Compare commits
20
Commits
v0.2.0
..
a0cd30a0d7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0cd30a0d7 | ||
|
|
a351fc237c | ||
|
|
af7174e128 | ||
|
|
22077514fe | ||
|
|
6761f2d9ea | ||
|
|
18ff32b5ce | ||
|
|
67530d35e9 | ||
|
|
26ca1b90a2 | ||
|
|
36df4a46b9 | ||
|
|
c529b04ff0 | ||
|
|
51e90b6127 | ||
|
|
063ad8a3e1 | ||
|
|
68cd9fc4f9 | ||
|
|
c56046469e | ||
|
|
a0d1ec2feb | ||
|
|
3b21fc3aa6 | ||
|
|
90e54ec295 | ||
|
|
df4d58a279 | ||
|
|
837367047c | ||
|
|
600373dc61 |
No files matched your search
@@ -9,6 +9,8 @@
|
||||
!compat/
|
||||
!agent/
|
||||
!patcher/
|
||||
!mod-tools/
|
||||
!gradle-plugin/
|
||||
!docker/
|
||||
**/build/
|
||||
**/.gradle/
|
||||
@@ -15,12 +15,12 @@ jobs:
|
||||
include:
|
||||
# One entry per supported version; add older Steam version branches
|
||||
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
|
||||
- pz_version: "42.21"
|
||||
- pz_version: "42"
|
||||
steam_branch: public
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# release.sh derives the version from the newest v* tag
|
||||
# release.sh derives the version from the v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Build and verify
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Publishes the mod API, the mod tools, and the Gradle plugin to the Gitea Maven registry
|
||||
# (https://git.security-command.org/api/packages/overlord/maven) for every release tag.
|
||||
# Pre-release tags (containing "-") are tested but not published (see ci/publish.sh).
|
||||
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with package
|
||||
# write access), the same as the image release.
|
||||
name: publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
maven:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# publish.sh derives the version from the v* tag on HEAD
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "25"
|
||||
|
||||
# The tests run without the registry credentials; only the publish step gets them.
|
||||
- name: Test
|
||||
run: ci/publish.sh test
|
||||
|
||||
- name: Publish
|
||||
env:
|
||||
ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }}
|
||||
ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: ci/publish.sh publish
|
||||
@@ -1,12 +1,16 @@
|
||||
# Publishes an image for every new Steam build of each supported Project Zomboid
|
||||
# version. Immutable tags are never overwritten (see ci/release.sh).
|
||||
# Publishes an image for every new Project Zomboid version (hotfixes included) of each
|
||||
# matrix entry and every new ZomboidForge release; full version tags are never overwritten
|
||||
# (see ci/release.sh).
|
||||
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
|
||||
# package write access) and a runner with a Docker (or Podman) CLI.
|
||||
name: release
|
||||
|
||||
on:
|
||||
# Every 2.5 hours; cron cannot divide a day into 2.5-hour steps, so the gap
|
||||
# from 22:30 to 00:00 is 1.5 hours.
|
||||
schedule:
|
||||
- cron: "0 */6 * * *"
|
||||
- cron: "0 0,5,10,15,20 * * *"
|
||||
- cron: "30 2,7,12,17,22 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -16,13 +20,13 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- pz_version: "42.21"
|
||||
- pz_version: "42"
|
||||
steam_branch: public
|
||||
latest: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# release.sh derives the version from the newest v* tag
|
||||
# release.sh derives the version from the v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Log in to the registry
|
||||
@@ -39,3 +43,8 @@ jobs:
|
||||
PUBLISH: "true"
|
||||
LATEST: ${{ matrix.latest }}
|
||||
run: ci/release.sh
|
||||
|
||||
# Removes the stored registry token, also when a step failed, in case the runner is reused.
|
||||
- name: Log out of the registry
|
||||
if: always()
|
||||
run: docker logout git.security-command.org
|
||||
@@ -1,5 +1,6 @@
|
||||
*.md
|
||||
!README.md
|
||||
!MOD_DEVELOPMENT.md
|
||||
lib
|
||||
.*/
|
||||
!.gitea/
|
||||
|
||||
+49
-9
@@ -6,6 +6,10 @@
|
||||
# podman build --platform linux/amd64 -t zomboidforge .
|
||||
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
|
||||
#
|
||||
# The stage game-version (--target game-version) downloads only the server jar of
|
||||
# PZ_BRANCH and writes its game version to /game-version; ci/release.sh uses it to
|
||||
# name the image before the full build.
|
||||
#
|
||||
# Build arguments:
|
||||
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
|
||||
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
|
||||
@@ -14,7 +18,8 @@
|
||||
# files with steamcmd's newer copies
|
||||
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
|
||||
# Default: 0.0.0-prerelease
|
||||
# STEAM_BUILDID Image label only; set by ci/release.sh
|
||||
# STEAM_BUILDID Image label; in the stage game-version it keeps the cached result until
|
||||
# Steam publishes a new build. Set by ci/release.sh
|
||||
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
|
||||
# (debug builds only; ci/release.sh never sets it)
|
||||
|
||||
@@ -24,8 +29,11 @@ ARG STEAMCLIENT=bundled
|
||||
ARG FORGE_VERSION="0.0.0-prerelease"
|
||||
ARG STEAM_BUILDID=""
|
||||
|
||||
# Base images are pinned by digest; the tag in front of the digest is for readers only.
|
||||
# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame.
|
||||
|
||||
# --- Stage 1: vanilla dedicated server -----------------------------------------
|
||||
FROM docker.io/steamcmd/steamcmd:debian-13 AS server
|
||||
FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server
|
||||
|
||||
# steamcmd updates itself on its first run. This runs in its own layer so the
|
||||
# update is cached and separate from the app installation.
|
||||
@@ -36,8 +44,8 @@ ARG STEAMCLIENT
|
||||
COPY docker/install-server.sh /usr/local/bin/install-server
|
||||
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
|
||||
|
||||
# --- Stage 2: ZomboidForge build and server jar patching -----------------------
|
||||
FROM docker.io/library/eclipse-temurin:25-jdk AS build
|
||||
# --- Stage 2: ZomboidForge sources and Gradle -----------------------------------
|
||||
FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources
|
||||
WORKDIR /src
|
||||
|
||||
# Gradle distribution download, cached independently of the sources.
|
||||
@@ -51,6 +59,37 @@ COPY core core
|
||||
COPY compat compat
|
||||
COPY agent agent
|
||||
COPY patcher patcher
|
||||
COPY mod-tools mod-tools
|
||||
COPY gradle-plugin gradle-plugin
|
||||
|
||||
# --- Game version of a Steam branch, from its server jar alone ------------------
|
||||
# Not part of the image; built on its own by ci/release.sh.
|
||||
FROM sources AS game-version
|
||||
|
||||
# DepotDownloader downloads single files of a depot; steamcmd only whole apps.
|
||||
ADD --checksum=sha256:a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53 \
|
||||
https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip \
|
||||
/opt/depotdownloader/depotdownloader.zip
|
||||
RUN cd /opt/depotdownloader \
|
||||
&& jar xf depotdownloader.zip \
|
||||
&& chmod +x DepotDownloader \
|
||||
&& rm depotdownloader.zip
|
||||
|
||||
# FORGE_VERSION only keeps Gradle from asking git (not in this stage) for the version.
|
||||
ARG PZ_BRANCH
|
||||
ARG STEAM_BUILDID
|
||||
ARG FORGE_VERSION
|
||||
RUN echo java/projectzomboid.jar > /tmp/files \
|
||||
&& /opt/depotdownloader/DepotDownloader \
|
||||
-app 380870 -depot 380871 -branch "${PZ_BRANCH}" -filelist /tmp/files -dir /pz \
|
||||
&& ./gradlew --no-daemon --quiet \
|
||||
-Ppz.jar=/pz/java/projectzomboid.jar \
|
||||
-Pversion=${FORGE_VERSION} \
|
||||
:patcher:printGameVersion > /game-version
|
||||
|
||||
# --- Stage 3: ZomboidForge build and server jar patching -----------------------
|
||||
FROM sources AS build
|
||||
|
||||
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
|
||||
|
||||
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
|
||||
@@ -63,10 +102,10 @@ RUN ./gradlew --no-daemon \
|
||||
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
|
||||
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
|
||||
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
|
||||
build :patcher:patchServerJar
|
||||
build -x :gradle-plugin:test :patcher:patchServerJar
|
||||
|
||||
# --- Stage 3: runtime ------------------------------------------------------------
|
||||
FROM docker.io/library/debian:trixie-slim
|
||||
# --- Stage 4: runtime ------------------------------------------------------------
|
||||
FROM docker.io/library/debian:trixie-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a
|
||||
|
||||
# ca-certificates: required by steamclient.so to connect to Steam.
|
||||
# sqlite3: the entrypoint checks the admin account in the server database.
|
||||
@@ -76,9 +115,10 @@ RUN apt-get update \
|
||||
&& apt-get install --yes --no-install-recommends ca-certificates sqlite3 \
|
||||
&& rm --recursive --force /var/lib/apt/lists/*
|
||||
|
||||
# /forge/mods holds Java mods (one folder per mod); usually a mounted directory.
|
||||
RUN useradd --create-home --uid 1000 pz \
|
||||
&& mkdir /data \
|
||||
&& chown pz:pz /data
|
||||
&& mkdir --parents /data /forge/mods \
|
||||
&& chown --recursive pz:pz /data /forge
|
||||
|
||||
COPY --from=server /server /opt/pz
|
||||
COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/projectzomboid.jar
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
# Mod development
|
||||
|
||||
How to write a server-side Java mod for ZomboidForge. Installing mods on a server is
|
||||
described in the [README](README.md#mods).
|
||||
|
||||
## Project setup
|
||||
|
||||
A mod is a normal Gradle project with the ZomboidForge plugin. It needs JDK 25 (Project
|
||||
Zomboid's runtime); the plugin sets the Java toolchain to 25.
|
||||
|
||||
`settings.gradle.kts`:
|
||||
|
||||
```kotlin
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "shop"
|
||||
```
|
||||
|
||||
`build.gradle.kts`:
|
||||
|
||||
```kotlin
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge.mod") version "0.3.0" // the plugin's version is the API version
|
||||
}
|
||||
|
||||
version = "1.2.0"
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
game("42") // only when the mod uses game classes
|
||||
dependsOn("economy", "2.1") // other mods: id and minimum version
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/
|
||||
forgeMods("com.example:economy:2.1") // other mods to compile against
|
||||
}
|
||||
```
|
||||
|
||||
The plugin adds the API (`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the
|
||||
game jar for mods that declare `game` versions. Default settings go into
|
||||
`src/main/resources/META-INF/zomboidforge/config.toml`.
|
||||
|
||||
### `zomboidForge { }`
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
|--------------------------|------------------------------------------|-----------------------------------------------------------------------------------|
|
||||
| `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters |
|
||||
| `entrypoint` | (required) | the class that extends `Mod` |
|
||||
| `name` | the id | display name |
|
||||
| `version` | the project version | the mod's version |
|
||||
| `api` | the plugin's version | ZomboidForge API version the mod is built against |
|
||||
| `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` |
|
||||
| `dependsOn(id, version)` | none | another mod this one needs, with its minimum version |
|
||||
| `previousIds(...)` | none | earlier ids of the mod; their storage moves to the current id |
|
||||
| `gameJar` | see below | the `projectzomboid.jar` to compile and check against |
|
||||
| `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` |
|
||||
| `serverImage` | the ZomboidForge image, `latest` | image for `runServer` |
|
||||
| `adminPassword` | random, generated once per volume | admin password of the `runServer` server (see below) |
|
||||
| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network |
|
||||
| `dataVolume` | `zomboidforge-<id>` | volume for the `runServer` world and server config |
|
||||
| `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download |
|
||||
| `deployDirectory` | none | a server's mods directory for `deployMod` |
|
||||
|
||||
The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one
|
||||
fails the build.
|
||||
|
||||
Declare a minor version in `game(...)` only when the mod needs it. A mod declaring `"42.21"`
|
||||
stops the server after an update to 42.22, while the server checks every game member a mod uses
|
||||
against the running jar anyway.
|
||||
|
||||
### The game jar
|
||||
|
||||
Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be
|
||||
published. The plugin uses the first of:
|
||||
|
||||
1. `zomboidForge.gameJar`, or the Gradle property `zomboidforge.gameJar` (for example in
|
||||
`~/.gradle/gradle.properties`);
|
||||
2. a local Steam installation of the dedicated server or the game, in any Steam library;
|
||||
3. a download of the dedicated server with steamcmd (`steamcmd` if installed, otherwise its
|
||||
container image with podman or docker), once per Steam branch, into the Gradle user home.
|
||||
It is a few gigabytes.
|
||||
|
||||
The game jar has to be one of the declared `game` versions; the check below fails otherwise.
|
||||
|
||||
### Tasks
|
||||
|
||||
| Task | Does |
|
||||
|----------------|---------------------------------------------------------------------------------------------|
|
||||
| `build` | compiles, runs `checkMod`, and assembles the mod |
|
||||
| `checkMod` | the server's load checks, at build time (see [Checks at startup](#checks-at-startup)) |
|
||||
| `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
|
||||
| `modZip` | the same as `build/distributions/<id>-<version>.zip` |
|
||||
| `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world |
|
||||
| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod |
|
||||
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
|
||||
|
||||
`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without
|
||||
`adminPassword`, the first run generates a random admin password for the volume, prints it, and
|
||||
keeps it in `<Gradle user home>/zomboidforge/admin-passwords/<volume>`. The server uses the
|
||||
password only when it creates the admin account, on the volume's first start; a later change
|
||||
needs a new volume (`dataVolume`, or remove the old one).
|
||||
|
||||
### Working on ZomboidForge itself
|
||||
|
||||
To build a mod against a local ZomboidForge checkout instead of a published version, include it
|
||||
in `settings.gradle.kts`; Gradle then builds the plugin, the API, and the mod tools from the
|
||||
checkout:
|
||||
|
||||
```kotlin
|
||||
pluginManagement {
|
||||
includeBuild("../ZomboidForge")
|
||||
}
|
||||
|
||||
includeBuild("../ZomboidForge")
|
||||
```
|
||||
|
||||
## Entry point
|
||||
|
||||
The entry point extends `dev.overlord.zomboidforge.api.Mod`:
|
||||
|
||||
```java
|
||||
public final class ShopMod extends Mod
|
||||
{
|
||||
record Settings(String greeting, long maxBalance) {}
|
||||
|
||||
private final Settings settings = this.config().bind(Settings.class); // max_balance in config.toml
|
||||
|
||||
@Override
|
||||
public void onLoad() // main thread, registration only
|
||||
{
|
||||
this.events().onMain(TickEvent.class, event -> { /* every frame, on the main thread */ });
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServerStarted() // world loaded, port open
|
||||
{
|
||||
this.modThread().scheduleAtFixedRate(() -> {
|
||||
// on zf-mod-shop: slow work, no game objects
|
||||
this.main().submit(GameServer::getPlayerCount) // game objects only on the main thread
|
||||
.thenAcceptAsync(players -> this.logger().log(INFO, players + " online"), this.modThread());
|
||||
}, Duration.ZERO, Duration.ofMinutes(1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStopping() {} // before the world is saved
|
||||
}
|
||||
```
|
||||
|
||||
## Services
|
||||
|
||||
Methods of `Mod`, usable from the constructor on (also in field initializers):
|
||||
|
||||
| Method | Returns | Use |
|
||||
|--------------------|------------------|---------------------------------------------------------------|
|
||||
| `id()` | `String` | the mod's id from `mod.toml` |
|
||||
| `version()` | `String` | the mod's version from `mod.toml` |
|
||||
| `gameVersion()` | `GameVersion` | the running Project Zomboid version |
|
||||
| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path |
|
||||
| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id |
|
||||
| `directory()` | `Path` | the mod's folder, `<forge>/mods/<id>` |
|
||||
| `events()` | `Events` | event listeners |
|
||||
| `main()` | `MainThread` | code that touches game objects |
|
||||
| `modThread()` | `ModThread` | the mod's own work, one task at a time |
|
||||
| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O |
|
||||
| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` |
|
||||
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
|
||||
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
|
||||
|
||||
## Threads
|
||||
|
||||
Game objects belong to the server's main thread. Everything else should stay off it, because
|
||||
it also runs the game: the main loop runs about 10 frames per second.
|
||||
|
||||
| Executor | Thread | A task runs |
|
||||
|---------------|-------------------------------------|-------------------------------------------------------------------------|
|
||||
| `main()` | `main` | immediately when called on the main thread, otherwise in the next ticks |
|
||||
| `modThread()` | `zf-mod-<id>` | one at a time, in the order submitted |
|
||||
| `async()` | virtual threads `zf-async-<id>-<n>` | at once, each on its own thread |
|
||||
|
||||
Three rules follow from that:
|
||||
|
||||
1. Touch game objects only on the main thread; hand results over with `main().execute(...)`
|
||||
or `main().submit(...)`.
|
||||
2. Never wait on the main thread for another thread (`get()`, `join()`). Continue with
|
||||
`thenAcceptAsync(..., modThread())` instead.
|
||||
3. Keep main-thread work short. Queued tasks share a time budget per tick
|
||||
(`forge.toml`, `main_thread.budget_ms`); the rest waits for the next tick.
|
||||
|
||||
## Events
|
||||
|
||||
```java
|
||||
this.events().onMain(TickEvent.class, event -> ...); // main thread, while the event is posted
|
||||
this.events().onModThread(SomeEvent.class, event -> ...); // later, on zf-mod-<id>
|
||||
```
|
||||
|
||||
Listeners are matched by the event's exact class. Events that carry live game objects, such as
|
||||
`TickEvent`, can only be received on the main thread. A listener that keeps throwing is
|
||||
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
|
||||
it earlier.
|
||||
|
||||
## Commands
|
||||
|
||||
Admin commands work wherever Project Zomboid's own commands work: in the in-game chat
|
||||
(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the
|
||||
mod declares `game` versions. In Build 42 a command is a subclass of
|
||||
`zombie.commands.CommandBase`:
|
||||
|
||||
```java
|
||||
@CommandName(name = "zfhello")
|
||||
@CommandArgs(optional = "(.+)")
|
||||
@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false)
|
||||
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||
public class HelloCommand extends CommandBase
|
||||
{
|
||||
public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||
|
||||
@Override
|
||||
protected String Command()
|
||||
{
|
||||
String name = this.getCommandArg(0);
|
||||
return "Hello " + (name == null ? this.getExecutorUsername() : name);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
@Override
|
||||
public void onLoad() { this.commands().register(HelloCommand.class); }
|
||||
```
|
||||
|
||||
- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw.
|
||||
`register` checks the class and throws `IllegalArgumentException` listing every problem,
|
||||
which stops the server like any other exception in `onLoad()`.
|
||||
- **The class** is public and not abstract, with one public constructor
|
||||
`(String, Role, String, UdpConnection)`.
|
||||
- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and
|
||||
differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands.
|
||||
A name matches when it is the first word of the input, ignoring case.
|
||||
- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one.
|
||||
RCON and the server console run commands with the default admin role.
|
||||
- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become
|
||||
`getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with
|
||||
`shouldTranslated = false` the text is used as written) are optional.
|
||||
- **`Command()`** runs on the main thread, for every use on a new instance; its return value
|
||||
is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms
|
||||
that the work started.
|
||||
- Project Zomboid's commands are looked up first; mods' commands follow in load order.
|
||||
|
||||
## Client commands
|
||||
|
||||
A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk
|
||||
through Project Zomboid's command channel, so players keep the official client.
|
||||
|
||||
Client to server: the Lua mod calls `sendClientCommand`, and the server posts
|
||||
`ClientCommandEvent` on the main thread.
|
||||
|
||||
```lua
|
||||
sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 })
|
||||
```
|
||||
|
||||
```java
|
||||
this.events().onMain(ClientCommandEvent.class, event ->
|
||||
{
|
||||
if (!event.module().equals("Shop")) return;
|
||||
event.cancel(); // Lua's OnClientCommand does not see it
|
||||
|
||||
String item = (String) event.args().get("item");
|
||||
int count = ((Double) event.args().get("count")).intValue();
|
||||
// ...
|
||||
this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count));
|
||||
});
|
||||
```
|
||||
|
||||
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
|
||||
receives them in `Events.OnServerCommand`.
|
||||
|
||||
```lua
|
||||
Events.OnServerCommand.Add(function(module, command, args)
|
||||
if module == "Shop" and command == "bought" then print(args.item, args.count) end
|
||||
end)
|
||||
```
|
||||
|
||||
- **Every** client command is posted, including those of Project Zomboid (`vehicle`,
|
||||
`player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`.
|
||||
- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`.
|
||||
Every listener still runs; `isCancelled()` tells whether another one cancelled.
|
||||
- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua
|
||||
arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number),
|
||||
`Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is
|
||||
empty when the client sent no table.
|
||||
- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other
|
||||
threads and after the player left. Sending to a player who left sends nothing.
|
||||
- **Sending** works from any thread. The arguments are copied and checked at once
|
||||
(`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua
|
||||
numbers, lists become Lua arrays. The command is sent on the main thread: at once when
|
||||
called there, otherwise as one of the mod's queued main-thread tasks.
|
||||
- Client commands come from players and can be forged by a modified client. Check every
|
||||
argument and the player's rights before acting on it.
|
||||
|
||||
## Storage
|
||||
|
||||
Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's
|
||||
save folder. Vanilla backups include it, and deleting the world deletes it. Through the API,
|
||||
each mod only reaches its own tables.
|
||||
|
||||
A record declares a table's columns; each row has a `String` key:
|
||||
|
||||
```java
|
||||
record Balance(long coins, @Nullable Instant lastPaid) {}
|
||||
|
||||
Table<Balance> balances = this.storage().table("balances", Balance.class);
|
||||
|
||||
balances.set("player1", new Balance(250, Instant.now()));
|
||||
Optional<Balance> balance = balances.get("player1");
|
||||
balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null));
|
||||
|
||||
this.storage().transaction(() -> { // all or nothing, also when nested
|
||||
balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null));
|
||||
balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null));
|
||||
});
|
||||
```
|
||||
|
||||
| Component type | Stored as |
|
||||
|-----------------------------------|-------------------------|
|
||||
| `long`, `int`, `boolean` | integer, never null |
|
||||
| `double`, `float` | real number, never null |
|
||||
| `Long`, `Integer`, `Boolean`, ... | the same, may be null |
|
||||
| `String`, `UUID`, enums | text (enums by name) |
|
||||
| `Instant` | ISO-8601 text |
|
||||
| `byte[]` | blob |
|
||||
|
||||
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`.
|
||||
|
||||
When the record changes between versions of the mod:
|
||||
|
||||
| Change | What happens |
|
||||
|--------------------------------|-------------------------------------------|
|
||||
| new component that may be null | added; existing rows read `null` |
|
||||
| new primitive component | needs a migration |
|
||||
| removed component | the column and its data stay; logged once |
|
||||
| component with another type | needs a migration |
|
||||
|
||||
```java
|
||||
Table<Balance> balances = this.storage().define("balances", Balance.class)
|
||||
.version(2)
|
||||
.migrate(1, row -> new Balance(row.getLong("coins"), null)) // from stored version 1
|
||||
.open();
|
||||
```
|
||||
|
||||
Things to know:
|
||||
|
||||
1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the
|
||||
server runs they throw, so use `modThread()` or `async()`.
|
||||
2. Writes commit immediately, while the world is saved periodically. After a crash, the
|
||||
world goes back to its last save, but the mod data keeps later writes.
|
||||
3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables
|
||||
move to the new id once.
|
||||
4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits.
|
||||
These callbacks must not wait for other threads, for example with
|
||||
`main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs
|
||||
without pausing storage, so its copy of `zomboidforge.db` may be incomplete.
|
||||
|
||||
## Checks at startup
|
||||
|
||||
`checkMod` runs these checks when the mod is built, so a mod that would not load fails its
|
||||
build instead. On the server, before any mod code runs, ZomboidForge reads every class of the
|
||||
mod and its libraries. The server does not start when a mod
|
||||
|
||||
1. uses game classes without declaring `game` versions in `mod.toml`,
|
||||
2. uses a game class, field, or method that does not exist in the running version,
|
||||
3. uses ZomboidForge classes outside the API, or
|
||||
4. contains classes in a ZomboidForge package, or a class with the name of a game class.
|
||||
|
||||
Every problem of every mod is listed in the log.
|
||||
|
||||
## What a mod can see
|
||||
|
||||
| Source | Visible |
|
||||
|----------------------------------------------------|-----------------------------------------------|
|
||||
| JDK | yes |
|
||||
| ZomboidForge API (`dev.overlord.zomboidforge.api`) | yes |
|
||||
| the mod's own jar and `lib/*.jar` | yes; own libraries win over the game's copies |
|
||||
| own jars of declared dependencies | yes (not their libraries) |
|
||||
| game jar (game code and its bundled libraries) | only with `game` declared |
|
||||
| ZomboidForge internals | no |
|
||||
|
||||
These rules keep mods from linking against the wrong classes by accident. They are not a
|
||||
sandbox: a mod runs with the full privileges of the server process. Through reflection or the
|
||||
file system it can reach anything the server can, including other mods' data in
|
||||
`zomboidforge.db`.
|
||||
|
||||
## Profiling
|
||||
|
||||
Main-thread tasks and event listener calls appear in JFR recordings as the event
|
||||
`zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the
|
||||
event class).
|
||||
@@ -14,16 +14,18 @@ version in `gradle.properties` (`pz.version`).
|
||||
podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
|
||||
```
|
||||
|
||||
| Build argument | Default | |
|
||||
|---|---|---|
|
||||
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
|
||||
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
|
||||
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
|
||||
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
|
||||
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
|
||||
| Build argument | Default | |
|
||||
|--------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
|
||||
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
|
||||
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
|
||||
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
|
||||
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
|
||||
|
||||
Published images are tagged `<forge>-pz<pz>-build<steam buildid>` (immutable),
|
||||
`<forge>-pz<pz>`, and `latest`.
|
||||
Published images are tagged `<forge>-pz<major.minor.build>` (never overwritten),
|
||||
`<forge>-pz<major.minor>` (the newest hotfix of that minor version), and `latest`. A new image
|
||||
is built for every ZomboidForge release and every Project Zomboid version, hotfixes included:
|
||||
the server only admits clients with the same version.
|
||||
|
||||
## Running
|
||||
|
||||
@@ -36,24 +38,24 @@ podman run -d --name zomboidforge \
|
||||
|
||||
Unset variables keep the value in the server `.ini` (or the game default).
|
||||
|
||||
| Variable | Default | |
|
||||
|---|---|---|
|
||||
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
||||
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
||||
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
||||
| `PUBLIC_NAME` | | Name in the server browser |
|
||||
| `PORT` | `16261` | Game port (`-port`) |
|
||||
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
|
||||
| `ADMIN_USERNAME` | `admin` | First start only |
|
||||
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
|
||||
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
|
||||
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
|
||||
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
|
||||
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
|
||||
| `JVM_MIN_HEAP` | | `-Xms` |
|
||||
| `JVM_MAX_HEAP` | `8g` | `-Xmx` |
|
||||
| `STEAM` | `1` | `0` runs the server without Steam |
|
||||
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
||||
| Variable | Default | |
|
||||
|-------------------|----------------|-----------------------------------------------------------------------------------------------------|
|
||||
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
||||
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
||||
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
||||
| `PUBLIC_NAME` | | Name in the server browser |
|
||||
| `PORT` | `16261` | Game port (`-port`) |
|
||||
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
|
||||
| `ADMIN_USERNAME` | `admin` | First start only |
|
||||
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
|
||||
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
|
||||
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
|
||||
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
|
||||
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
|
||||
| `JVM_MIN_HEAP` | `JVM_MAX_HEAP` | `-Xms` |
|
||||
| `JVM_MAX_HEAP` | `8g` | `-Xmx` |
|
||||
| `STEAM` | `1` | `0` runs the server without Steam |
|
||||
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -69,6 +71,64 @@ Notes:
|
||||
|
||||
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
||||
|
||||
## Mods
|
||||
|
||||
ZomboidForge loads server-side Java mods. They run only on the server, so players keep the
|
||||
official, unmodified client. Project Zomboid's own Lua and Workshop mods are configured as
|
||||
usual with `MODS` and `WORKSHOP_ITEMS`.
|
||||
|
||||
### Installing mods
|
||||
|
||||
Mount a directory at `/forge` with one folder per mod:
|
||||
|
||||
```
|
||||
forge/
|
||||
├── forge.toml optional global settings
|
||||
└── mods/
|
||||
└── <id>/
|
||||
├── <id>.jar the mod
|
||||
├── lib/*.jar libraries of the mod (optional)
|
||||
└── config.toml settings of the mod (optional)
|
||||
```
|
||||
|
||||
```sh
|
||||
podman run ... -v ./forge:/forge zomboidforge
|
||||
```
|
||||
|
||||
Mods are trusted code. They run inside the server process with its full privileges: they can
|
||||
read and write any file the server can, open network connections, and stop the server. The
|
||||
class loader isolation and the startup checks catch mistakes; they do not contain a malicious
|
||||
mod. Install only mods whose authors you trust.
|
||||
|
||||
A mod's settings live in its `config.toml`. When the file is missing, it is created from the
|
||||
mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a
|
||||
file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]`
|
||||
table switches the mod off; mods that depend on it then fail to load.
|
||||
|
||||
Mods keep their data in `zomboidforge.db` in the world's save folder
|
||||
(`/data/Saves/Multiplayer/<server>/`). Vanilla backups include it, and deleting the world
|
||||
deletes it.
|
||||
|
||||
A mod that cannot be loaded stops the server with exit code 1, and the log lists every
|
||||
problem: a missing or too old dependency, an unsupported game version, game classes or methods
|
||||
that do not exist in the running version, invalid settings, or an exception in the mod's
|
||||
startup code. Changes to mods and their settings take effect when the server restarts.
|
||||
|
||||
`forge.toml`, every key optional:
|
||||
|
||||
```toml
|
||||
[main_thread]
|
||||
budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
|
||||
[shutdown]
|
||||
timeout_s = 10 # time the mods' threads get to finish when the server stops
|
||||
```
|
||||
|
||||
### Mod development
|
||||
|
||||
Writing a mod (descriptor, entry point, threads, events, settings, startup checks):
|
||||
[MOD_DEVELOPMENT.md](MOD_DEVELOPMENT.md).
|
||||
|
||||
## Development
|
||||
|
||||
Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla
|
||||
@@ -80,4 +140,8 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
|
||||
```
|
||||
|
||||
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
|
||||
`pz.version` in `gradle.properties` selects the targeted version.
|
||||
`pz.version` in `gradle.properties` selects the targeted version. `mod-tools` (the build-time
|
||||
mod checks) and `gradle-plugin` (the plugin for mod authors) are for mod builds, not the server.
|
||||
|
||||
Release tags publish `api`, `mod-tools`, and the Gradle plugin to the Gitea Maven registry
|
||||
(`.gitea/workflows/publish.yml`, `ci/publish.sh`); tags with a `-` are only tested.
|
||||
+15
-5
@@ -2,6 +2,7 @@
|
||||
|
||||
plugins {
|
||||
id("zomboidforge.java-conventions")
|
||||
alias(libs.plugins.shadow)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -11,10 +12,19 @@ dependencies {
|
||||
compileOnly(files(projectZomboid.serverJar))
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
archiveBaseName = "zomboidforge-agent"
|
||||
// The agent jar is appended to the system class path behind the game jar and includes api,
|
||||
// core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same
|
||||
// library in the game jar cannot replace them.
|
||||
tasks.shadowJar {
|
||||
archiveBaseName = "zomboidforge-agent"
|
||||
archiveClassifier = ""
|
||||
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
|
||||
// The agent jar is appended to the system class path and includes api, core and compat runtime.
|
||||
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
|
||||
relocate("org.objectweb.asm", "dev.overlord.zomboidforge.shaded.asm")
|
||||
relocate("com.electronwill.nightconfig", "dev.overlord.zomboidforge.shaded.nightconfig")
|
||||
}
|
||||
|
||||
// Only the shadow jar is used; the plain jar would match the same file name pattern.
|
||||
tasks.jar {
|
||||
enabled = false
|
||||
}
|
||||
@@ -1,5 +1,38 @@
|
||||
// API for custom Java mods. Version-independent: no references to game classes.
|
||||
// Published as dev.overlord.zomboidforge:api; mods compile against it.
|
||||
|
||||
plugins {
|
||||
id("zomboidforge.java-conventions")
|
||||
id("zomboidforge.publishing")
|
||||
`java-library`
|
||||
}
|
||||
|
||||
java {
|
||||
withSourcesJar()
|
||||
withJavadocJar()
|
||||
}
|
||||
|
||||
tasks.javadoc {
|
||||
// api.internal connects the API to the runtime and is not part of the documented API.
|
||||
exclude("dev/overlord/zomboidforge/api/internal/**")
|
||||
|
||||
(options as StandardJavadocDocletOptions).apply {
|
||||
// IntelliJ's @noinspection in package-info.java is not a Javadoc tag.
|
||||
tags("noinspection:X")
|
||||
addStringOption("Xdoclint:all,-missing", "-quiet")
|
||||
}
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
create<MavenPublication>("api") {
|
||||
from(components["java"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* Virtual threads for a mod's blocking work, such as HTTP calls or file I/O: one thread per
|
||||
* task, named {@code zf-async-<id>-<n>}. ZomboidForge shuts it down when the server stops; tasks
|
||||
* submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}.
|
||||
*/
|
||||
public interface AsyncExecutor extends Executor
|
||||
{
|
||||
/** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */
|
||||
@Override
|
||||
void execute(Runnable task);
|
||||
|
||||
/** Runs {@code task} on a new virtual thread; the future completes with its result or exception. */
|
||||
<T> CompletableFuture<T> submit(Callable<T> task);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/**
|
||||
* An event whose default action, what Project Zomboid does after the event, can be prevented.
|
||||
* Only listeners on the main thread can cancel: the default action runs once every main-thread
|
||||
* listener returned. Every listener is called, also after one cancelled.
|
||||
*/
|
||||
public interface Cancellable
|
||||
{
|
||||
/** Prevents the default action. */
|
||||
void cancel();
|
||||
|
||||
boolean isCancelled();
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A client command arrived: a client called Lua's {@code sendClientCommand(module, command, args)}.
|
||||
* Posted on the main thread for every client command, including those of Project Zomboid and of
|
||||
* Lua mods, so listeners filter by {@link #module()}.
|
||||
*
|
||||
* <p>Default action: Project Zomboid passes the command to Lua's {@code Events.OnClientCommand}.
|
||||
* {@link #cancel()} prevents that, for example when a Java mod handles the module itself.
|
||||
*
|
||||
* <p>{@link #args()} is the Lua table converted to Java: keys are {@code String} or
|
||||
* {@code Double} (Lua arrays have the keys {@code 1.0}, {@code 2.0}, ...), values are
|
||||
* {@code String}, {@code Double}, {@code Boolean}, a nested {@code Map} of the same kind, or a
|
||||
* game object that Project Zomboid sends with commands (in Build 42 an inventory item, an
|
||||
* {@code IsoDirections}, or a dead body). The maps cannot be modified.
|
||||
*/
|
||||
public final class ClientCommandEvent implements MainThreadEvent, Cancellable
|
||||
{
|
||||
private final PlayerRef player;
|
||||
private final String module;
|
||||
private final String command;
|
||||
private final Map<Object, Object> args;
|
||||
|
||||
private boolean cancelled;
|
||||
|
||||
/** @param args the converted arguments; empty when the client sent none */
|
||||
public ClientCommandEvent(PlayerRef player, String module, String command, Map<Object, Object> args)
|
||||
{
|
||||
this.player = Objects.requireNonNull(player, "player");
|
||||
this.module = Objects.requireNonNull(module, "module");
|
||||
this.command = Objects.requireNonNull(command, "command");
|
||||
this.args = Objects.requireNonNull(args, "args");
|
||||
}
|
||||
|
||||
/** The player who sent the command. */
|
||||
public PlayerRef player() { return this.player; }
|
||||
|
||||
public String module() { return this.module; }
|
||||
|
||||
public String command() { return this.command; }
|
||||
|
||||
public Map<Object, Object> args() { return this.args; }
|
||||
|
||||
@Override
|
||||
public void cancel() { this.cancelled = true; }
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() { return this.cancelled; }
|
||||
|
||||
@Override
|
||||
public String toString() { return "ClientCommandEvent[" + this.player + ", " + this.module + "." + this.command + ", " + this.args + (this.cancelled ? ", cancelled" : "") + "]"; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Server commands to clients, the reply channel to {@link ClientCommandEvent}: a client receives
|
||||
* them in Lua's {@code Events.OnServerCommand(module, command, args)}. Together, a Java mod on the
|
||||
* server and a Lua mod on the client exchange commands while players keep the official client.
|
||||
*
|
||||
* <p>{@code args} becomes a Lua table: keys are {@code String} or a {@code Number} (sent as a
|
||||
* Lua number), values are {@code String}, {@code Number}, {@code Boolean}, a nested {@code Map}, a
|
||||
* {@code List} (a Lua array, indexed from 1), or a game object that Project Zomboid sends with
|
||||
* commands (see {@link ClientCommandEvent}). {@code null} keys or values, and cycles, are not
|
||||
* allowed. An empty map sends no arguments; the client then receives {@code nil}.
|
||||
*
|
||||
* <p>The methods can be called on any thread. The arguments are checked at once; the command is
|
||||
* sent on the main thread, at once when called there, otherwise with the mod's queued
|
||||
* main-thread tasks.
|
||||
*/
|
||||
public interface ClientCommands
|
||||
{
|
||||
/**
|
||||
* Sends a command to {@code player}. Nothing is sent when the player is no longer connected.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
|
||||
*/
|
||||
void send(PlayerRef player, String module, String command, Map<?, ?> args);
|
||||
|
||||
/**
|
||||
* Sends a command to every connected client.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
|
||||
*/
|
||||
void sendToAll(String module, String command, Map<?, ?> args);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/**
|
||||
* Registration of admin commands. A registered command works wherever Project Zomboid's own
|
||||
* admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It
|
||||
* is looked up after the commands of Project Zomboid and runs on the main thread.
|
||||
*
|
||||
* <p>A command is a class of the running Project Zomboid version's command framework, so a mod
|
||||
* that registers commands declares {@code game} versions in {@code mod.toml}. In Build 42 it is
|
||||
* a public, non-abstract subclass of {@code zombie.commands.CommandBase} with:
|
||||
* <ul>
|
||||
* <li>one public constructor {@code (String username, Role role, String command, UdpConnection connection)},
|
||||
* which passes its arguments to {@code super};</li>
|
||||
* <li>at least one {@code @CommandName}; names consist of letters, digits, and {@code _}, and
|
||||
* differ (ignoring case) from every name of Project Zomboid and of other mods;</li>
|
||||
* <li>at least one {@code @RequiredCapability}; Project Zomboid refuses to run a command
|
||||
* without one;</li>
|
||||
* <li>optionally {@code @CommandArgs} (argument patterns) and {@code @CommandHelp}
|
||||
* ({@code help <name>} and the {@code help} list).</li>
|
||||
* </ul>
|
||||
* Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose
|
||||
* result is the reply.
|
||||
*/
|
||||
public interface Commands
|
||||
{
|
||||
/**
|
||||
* Registers {@code command}. Only on the main thread while the mod loads: in the entry point's
|
||||
* constructor or {@link Mod#onLoad()}.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code command} does not meet the rules above, or is
|
||||
* registered already
|
||||
* @throws IllegalStateException when called later or on another thread
|
||||
*/
|
||||
void register(Class<?> command);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/**
|
||||
* Something that happened in the server, delivered to listeners registered with
|
||||
* {@link Events}. Listeners are matched by the event's exact class.
|
||||
*/
|
||||
public interface Event {}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Registration of event listeners. Listeners of one event run in registration order. A listener
|
||||
* that throws is logged with the mod's id; one that throws repeatedly is removed.
|
||||
*/
|
||||
public interface Events
|
||||
{
|
||||
/**
|
||||
* {@code listener} runs on the main thread while the event is posted. It may touch game
|
||||
* objects and must return quickly: it runs inside the tick.
|
||||
*/
|
||||
<E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener);
|
||||
|
||||
/**
|
||||
* {@code listener} runs later on the mod's own thread. It must not touch game objects;
|
||||
* main-thread work goes through {@code main()}.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
|
||||
*/
|
||||
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Project Zomboid version, e.g. 42.21.0 ({@code Core.getGameAndBuildVersion()}). */
|
||||
public record GameVersion(int major, int minor, int build) implements Comparable<GameVersion>
|
||||
{
|
||||
// At most 9 digits per number, so every number fits an int.
|
||||
private static final Pattern VERSION = Pattern.compile("(\\d{1,9})\\.(\\d{1,9})(?:\\.(\\d{1,9}))?");
|
||||
private static final Pattern PREFIX = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9})(?:\\.(\\d{1,9}))?)?");
|
||||
|
||||
private static final Comparator<GameVersion> ORDER = Comparator
|
||||
.comparingInt(GameVersion::major)
|
||||
.thenComparingInt(GameVersion::minor)
|
||||
.thenComparingInt(GameVersion::build);
|
||||
|
||||
/** Parses "42.21.0", or "42.21" as 42.21.0. */
|
||||
public static GameVersion parse(String text)
|
||||
{
|
||||
Matcher matcher = GameVersion.VERSION.matcher(text.trim());
|
||||
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version: '" + text + "'.");
|
||||
|
||||
int build = matcher.group(3) == null
|
||||
? 0
|
||||
: Integer.parseInt(matcher.group(3));
|
||||
|
||||
return new GameVersion(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), build);
|
||||
}
|
||||
|
||||
/** Whether {@code text} is a version prefix for {@link #matches}: "42", "42.21", or "42.21.0". */
|
||||
public static boolean isPrefix(String text) { return GameVersion.PREFIX.matcher(text.trim()).matches(); }
|
||||
|
||||
/**
|
||||
* Whether this version starts with {@code prefix}: "42" matches every 42.x.y, "42.21" every
|
||||
* 42.21.x, "42.21.0" only 42.21.0.
|
||||
*/
|
||||
public boolean matches(String prefix)
|
||||
{
|
||||
Matcher matcher = GameVersion.PREFIX.matcher(prefix.trim());
|
||||
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version prefix: '" + prefix + "'.");
|
||||
|
||||
return GameVersion.partMatches(matcher.group(1), this.major)
|
||||
&& GameVersion.partMatches(matcher.group(2), this.minor)
|
||||
&& GameVersion.partMatches(matcher.group(3), this.build);
|
||||
}
|
||||
|
||||
public boolean isAtLeast(int major, int minor) { return this.compareTo(new GameVersion(major, minor, 0)) >= 0; }
|
||||
|
||||
public boolean isBefore(int major, int minor) { return this.compareTo(new GameVersion(major, minor, 0)) < 0; }
|
||||
|
||||
@Override
|
||||
public int compareTo(GameVersion other) { return GameVersion.ORDER.compare(this, other); }
|
||||
|
||||
@Override
|
||||
public String toString() { return this.major + "." + this.minor + "." + this.build; }
|
||||
|
||||
/** A missing part of a prefix matches any value. */
|
||||
private static boolean partMatches(@Nullable String part, int value) { return part == null || Integer.parseInt(part) == value; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* Runs a mod's code on the server's main thread, which owns every game object. Tasks from other
|
||||
* threads are queued and run during the next ticks, within a time budget per tick
|
||||
* ({@code forge.toml}); a task is never interrupted. Called on the main thread itself,
|
||||
* {@link #execute} and {@link #submit} run the task immediately.
|
||||
*
|
||||
* <p>Callbacks of the returned futures run on the thread that completes them, which is the
|
||||
* main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the
|
||||
* follow-up work back. The main thread must never wait for another thread's result.
|
||||
*/
|
||||
public interface MainThread extends Executor
|
||||
{
|
||||
/**
|
||||
* Runs {@code task} on the main thread. An exception it throws is logged with the mod's id.
|
||||
*
|
||||
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
|
||||
*/
|
||||
@Override
|
||||
void execute(Runnable task);
|
||||
|
||||
/**
|
||||
* Runs {@code task} on the main thread; the future completes with its result or exception.
|
||||
*
|
||||
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
|
||||
*/
|
||||
<T> CompletableFuture<T> submit(Callable<T> task);
|
||||
|
||||
/**
|
||||
* Queues {@code task} to run on the main thread {@code ticks} frames from now, also when
|
||||
* called on the main thread.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code ticks} is less than 1
|
||||
*/
|
||||
void runLater(int ticks, Runnable task);
|
||||
|
||||
/** Whether the calling thread is the main thread. */
|
||||
boolean isMainThread();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/**
|
||||
* An event that carries live game state or only makes sense during the tick. Listeners for it
|
||||
* run on the main thread only; {@link Events#onModThread} rejects it.
|
||||
*/
|
||||
public interface MainThreadEvent extends Event {}
|
||||
@@ -0,0 +1,93 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import dev.overlord.zomboidforge.api.internal.ModBinding;
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Base class of every mod. The class named as {@code entrypoint} in {@code mod.toml} extends it
|
||||
* and has a public constructor without parameters.
|
||||
*
|
||||
* <p>ZomboidForge creates one instance per mod on the main thread, in dependency order, while
|
||||
* the server starts. The methods of this class work from the constructor on, so field
|
||||
* initializers may use them.
|
||||
*
|
||||
* <p>Lifecycle, in this order:
|
||||
* <ol>
|
||||
* <li>{@link #onLoad()}: registration and setup. The server database, Lua, and the world do
|
||||
* not exist yet.</li>
|
||||
* <li>{@link #onServerStarted()}: the world is loaded and the network port is open.</li>
|
||||
* <li>{@link #onStopping()}: the server stops; the world has not been saved yet.</li>
|
||||
* </ol>
|
||||
* An exception thrown by the constructor or {@link #onLoad()} stops the server.
|
||||
*/
|
||||
public abstract class Mod
|
||||
{
|
||||
private final ModContext context;
|
||||
|
||||
/** @throws IllegalStateException when the instance is not created by ZomboidForge */
|
||||
protected Mod()
|
||||
{
|
||||
if (!ModBinding.CONTEXT.isBound())
|
||||
throw new IllegalStateException("'" + this.getClass().getName() + "' can only be created by ZomboidForge.");
|
||||
|
||||
this.context = ModBinding.CONTEXT.get();
|
||||
}
|
||||
|
||||
/** The id from {@code mod.toml}. */
|
||||
public final String id() { return this.context.id(); }
|
||||
|
||||
/** The version from {@code mod.toml}. */
|
||||
public final String version() { return this.context.version(); }
|
||||
|
||||
/** Called once on the main thread, after the instance is created. */
|
||||
@SuppressWarnings("RedundantThrows")
|
||||
public void onLoad() throws Exception {}
|
||||
|
||||
/**
|
||||
* Called once on the main thread, after the world is loaded, the network port is open, and
|
||||
* RCON is initialized; directly before the main loop starts.
|
||||
*/
|
||||
public void onServerStarted() {}
|
||||
|
||||
/**
|
||||
* Called once on the shutdown thread when the server stops, before the world is saved.
|
||||
* The main thread may still be finishing a tick. Mods are stopped in reverse load order.
|
||||
*/
|
||||
public void onStopping() {}
|
||||
|
||||
/** The running Project Zomboid version. */
|
||||
protected final GameVersion gameVersion() { return this.context.gameVersion(); }
|
||||
|
||||
/** Logger whose messages go into the Project Zomboid log, marked with the mod's id. */
|
||||
protected final System.Logger logger() { return this.context.logger(); }
|
||||
|
||||
/** The mod's folder, {@code <forge>/mods/<id>}. */
|
||||
protected final Path directory() { return this.context.directory(); }
|
||||
|
||||
/** The mod's settings from {@code config.toml}. */
|
||||
protected final ModConfig config() { return this.context.config(); }
|
||||
|
||||
/** Event listener registration. */
|
||||
protected final Events events() { return this.context.events(); }
|
||||
|
||||
/** The server's main thread, for everything that touches game objects. */
|
||||
@SuppressWarnings("ConfusingMainMethod")
|
||||
protected final MainThread main() { return this.context.main(); }
|
||||
|
||||
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
|
||||
protected final ModThread modThread() { return this.context.modThread(); }
|
||||
|
||||
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
|
||||
protected final AsyncExecutor async() { return this.context.async(); }
|
||||
|
||||
/** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */
|
||||
protected final ModStorage storage() { return this.context.storage(); }
|
||||
|
||||
/** Admin command registration. */
|
||||
protected final Commands commands() { return this.context.commands(); }
|
||||
|
||||
/** Server commands to clients, received by their Lua mods. */
|
||||
protected final ClientCommands clientCommands() { return this.context.clientCommands(); }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Settings of one mod: {@code <forge>/mods/<id>/config.toml}, over the defaults in the mod's
|
||||
* jar ({@code META-INF/zomboidforge/config.toml}). A key missing from the file takes the
|
||||
* default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings.
|
||||
*
|
||||
* <p>Keys are {@code snake_case}; record components and paths use the same names converted
|
||||
* from {@code camelCase} ({@code maxBalance} reads {@code max_balance}).
|
||||
*/
|
||||
public interface ModConfig
|
||||
{
|
||||
/**
|
||||
* Creates a record from the settings. Supported component types: {@code String},
|
||||
* {@code boolean}, {@code int}, {@code long}, {@code float}, {@code double} (and their
|
||||
* wrappers), enums (by constant name), records (TOML tables), {@code List<T>},
|
||||
* {@code Map<String, T>} (tables with free keys), and {@code Optional<T>} for values that
|
||||
* may be missing. Every other component must have a value. Keys without a component are
|
||||
* logged as warnings.
|
||||
*
|
||||
* @throws IllegalStateException listing every missing or mistyped value
|
||||
*/
|
||||
<T extends Record> T bind(Class<T> type);
|
||||
|
||||
/**
|
||||
* The value at a dotted path, e.g. {@code "features.max_balance"}, converted like a record
|
||||
* component of {@code type}. Primitive values use the wrapper types ({@code Long.class}).
|
||||
*
|
||||
* @throws IllegalStateException when the value exists but has another type
|
||||
*/
|
||||
<T> Optional<T> get(String path, Class<T> type);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* What ZomboidForge provides to one mod. Mods reach it through the methods of {@link Mod};
|
||||
* ZomboidForge implements it.
|
||||
*/
|
||||
public interface ModContext
|
||||
{
|
||||
/** The mod's id from {@code mod.toml}. */
|
||||
String id();
|
||||
|
||||
/** The mod's version from {@code mod.toml}. */
|
||||
String version();
|
||||
|
||||
/** The running Project Zomboid version. */
|
||||
GameVersion gameVersion();
|
||||
|
||||
/** Logger whose messages go into the Project Zomboid log, marked with the mod's id. */
|
||||
System.Logger logger();
|
||||
|
||||
/** The mod's folder, {@code <forge>/mods/<id>}. */
|
||||
Path directory();
|
||||
|
||||
/** The mod's settings from {@code config.toml}. */
|
||||
ModConfig config();
|
||||
|
||||
/** Event listener registration. */
|
||||
Events events();
|
||||
|
||||
/** The server's main thread, for everything that touches game objects. */
|
||||
MainThread main();
|
||||
|
||||
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
|
||||
ModThread modThread();
|
||||
|
||||
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
|
||||
AsyncExecutor async();
|
||||
|
||||
/** The mod's tables in the world's {@code zomboidforge.db}. */
|
||||
ModStorage storage();
|
||||
|
||||
/** Admin command registration. */
|
||||
Commands commands();
|
||||
|
||||
/** Server commands to clients, received by their Lua mods. */
|
||||
ClientCommands clientCommands();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
|
||||
/**
|
||||
* The mod's own platform thread, {@code zf-mod-<id>}: runs one task at a time, in the order
|
||||
* they were submitted. ZomboidForge shuts it down when the server stops; tasks submitted after
|
||||
* that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not
|
||||
* touch game objects; that goes through {@code main()}.
|
||||
*/
|
||||
public interface ModThread extends Executor
|
||||
{
|
||||
/** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */
|
||||
@Override
|
||||
void execute(Runnable task);
|
||||
|
||||
/** Runs {@code task} on the mod thread; the future completes with its result or exception. */
|
||||
<T> CompletableFuture<T> submit(Callable<T> task);
|
||||
|
||||
/** Runs {@code task} once after {@code delay}. An exception it throws is logged. */
|
||||
ScheduledFuture<?> schedule(Runnable task, Duration delay);
|
||||
|
||||
/**
|
||||
* Runs {@code task} after {@code initialDelay}, then every {@code period}, measured from the
|
||||
* start of each run. A run that throws is logged and ends the schedule.
|
||||
*/
|
||||
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period);
|
||||
|
||||
/**
|
||||
* Runs {@code task} after {@code initialDelay}, then again {@code delay} after each run
|
||||
* finished. A run that throws is logged and ends the schedule.
|
||||
*/
|
||||
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay);
|
||||
|
||||
/** Whether the calling thread is this mod thread. */
|
||||
boolean isModThread();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A connected player, by value: usable on any thread and after the player left. Project
|
||||
* Zomboid reuses online ids of players who left, so ZomboidForge matches both the id and the
|
||||
* username before it acts on a player.
|
||||
*
|
||||
* @param onlineId the player's online id while connected
|
||||
* @param username the player's account name
|
||||
*/
|
||||
public record PlayerRef(int onlineId, String username)
|
||||
{
|
||||
public PlayerRef
|
||||
{
|
||||
Objects.requireNonNull(username, "username");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/** A registered event listener. */
|
||||
public interface Subscription
|
||||
{
|
||||
/** Removes the listener; it receives no further events. Calling it again has no effect. */
|
||||
void cancel();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/**
|
||||
* Posted on the main thread once per frame of the main loop, before the queued main-thread
|
||||
* tasks run.
|
||||
*
|
||||
* @param tick number of the frame, counted from 1 at the first frame after the server started
|
||||
*/
|
||||
public record TickEvent(long tick) implements MainThreadEvent {}
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.overlord.zomboidforge.api.internal;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ModContext;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus.Internal;
|
||||
|
||||
/**
|
||||
* The context of the mod being created. ZomboidForge binds it while it calls a mod's
|
||||
* constructor; the {@code Mod} constructor reads it.
|
||||
*/
|
||||
@Internal
|
||||
public final class ModBinding
|
||||
{
|
||||
public static final ScopedValue<ModContext> CONTEXT = ScopedValue.newInstance();
|
||||
|
||||
private ModBinding() {}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Connection between the API and the ZomboidForge runtime. Not part of the mod API.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.api.internal;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to
|
||||
* the mod; this interface gives no access to the tables of other mods. It is not a security
|
||||
* boundary: mod code runs with the server's privileges and can open the file directly.
|
||||
*
|
||||
* <p>A record declares a table's columns: {@code String}, {@code long}/{@code int},
|
||||
* {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant},
|
||||
* and enums. Primitive components cannot be null. Table and column names are {@code snake_case}
|
||||
* ({@code lastPaid} is stored as {@code last_paid}).
|
||||
*
|
||||
* <p>Calls block. On the main thread they are only allowed during startup ({@code onLoad});
|
||||
* once the server runs they throw an {@link IllegalStateException}, so database I/O never costs
|
||||
* tick time. Use {@code modThread()} or {@code async()}.
|
||||
*/
|
||||
public interface ModStorage
|
||||
{
|
||||
/** Opens the table {@code name} with schema version 1 and no migrations. */
|
||||
<R extends Record> Table<R> table(String name, Class<R> type);
|
||||
|
||||
/** A table with a schema version and migrations; see {@link TableDefinition}. */
|
||||
<R extends Record> TableDefinition<R> define(String name, Class<R> type);
|
||||
|
||||
/**
|
||||
* Runs {@code work} in one transaction: writes of this thread inside it are committed
|
||||
* together, or not at all when {@code work} throws.
|
||||
*
|
||||
* <p>Storage of every mod waits while {@code work} runs, so {@code work} must not wait for
|
||||
* other threads, for example with {@code main().submit(...).join()}. A backup waits at most
|
||||
* 10 seconds for it and then runs without pausing storage.
|
||||
*/
|
||||
void transaction(Runnable work);
|
||||
|
||||
/** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */
|
||||
<T> T transaction(Supplier<T> work);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* One row of a table in its stored form, given to migrations: the key and the columns by
|
||||
* their {@code snake_case} names. Integers and booleans are stored as {@code Long}, other
|
||||
* numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as
|
||||
* {@code String}, bytes as {@code byte[]}.
|
||||
*/
|
||||
public interface Row
|
||||
{
|
||||
String key();
|
||||
|
||||
/** The names of the stored columns. */
|
||||
Set<String> columns();
|
||||
|
||||
/** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */
|
||||
@Nullable Object get(String column);
|
||||
|
||||
@Nullable String getString(String column);
|
||||
|
||||
/** @throws IllegalStateException when the value is null */
|
||||
long getLong(String column);
|
||||
|
||||
/** @throws IllegalStateException when the value is null */
|
||||
double getDouble(String column);
|
||||
|
||||
/** @throws IllegalStateException when the value is null */
|
||||
boolean getBoolean(String column);
|
||||
|
||||
byte @Nullable [] getBytes(String column);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/** A storage operation failed: a database error, or a table that does not match its record. */
|
||||
public final class StorageException extends RuntimeException
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public StorageException(String message) { super(message); }
|
||||
|
||||
public StorageException(String message, Throwable cause) { super(message, cause); }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
* Rows of type {@code R}, each under a {@code String} key. Every write commits immediately,
|
||||
* unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they
|
||||
* are only allowed during startup.
|
||||
*/
|
||||
public interface Table<R extends Record>
|
||||
{
|
||||
/** Stores {@code value} under {@code key}, replacing an existing row. */
|
||||
void set(String key, R value);
|
||||
|
||||
/** Stores every entry in one transaction. */
|
||||
void setAll(Map<String, R> values);
|
||||
|
||||
Optional<R> get(String key);
|
||||
|
||||
/** The rows of the given keys that exist. */
|
||||
Map<String, R> getAll(Collection<String> keys);
|
||||
|
||||
boolean contains(String key);
|
||||
|
||||
/** @return whether a row was removed */
|
||||
boolean delete(String key);
|
||||
|
||||
/** @return the number of rows removed */
|
||||
int deleteAll(Collection<String> keys);
|
||||
|
||||
/** Every key, sorted. */
|
||||
List<String> keys();
|
||||
|
||||
/**
|
||||
* Calls {@code action} for every row, sorted by key, without loading all rows at once.
|
||||
* Storage of every mod waits until it returns, so {@code action} must not wait for other
|
||||
* threads.
|
||||
*/
|
||||
void forEach(BiConsumer<String, R> action);
|
||||
|
||||
long count();
|
||||
|
||||
/**
|
||||
* Replaces the row under {@code key} with {@code change} applied to it, or to
|
||||
* {@code initial} when there is none, in one transaction: no other write comes in between.
|
||||
* As in {@link ModStorage#transaction}, {@code change} and {@code initial} must not wait for
|
||||
* other threads.
|
||||
*
|
||||
* @return the stored value
|
||||
*/
|
||||
R update(String key, UnaryOperator<R> change, Supplier<R> initial);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A table to open with a schema version and migrations:
|
||||
*
|
||||
* <pre>{@code
|
||||
* Table<Balance> balances = this.storage().define("balances", Balance.class)
|
||||
* .version(2)
|
||||
* .migrate(1, row -> new Balance(row.getLong("coins"), null))
|
||||
* .open();
|
||||
* }</pre>
|
||||
*/
|
||||
public interface TableDefinition<R extends Record>
|
||||
{
|
||||
/** Schema version of the record, at least 1. Default: 1. */
|
||||
TableDefinition<R> version(int version);
|
||||
|
||||
/**
|
||||
* How to turn a row stored with schema version {@code from} into the current record. Needed
|
||||
* when the stored version is older than {@link #version} or the record changed in a way that
|
||||
* cannot be applied without data.
|
||||
*/
|
||||
TableDefinition<R> migrate(int from, Function<Row, R> migration);
|
||||
|
||||
/**
|
||||
* Creates the table, or checks the stored one against the record and migrates it.
|
||||
*
|
||||
* @throws StorageException when the stored table does not match and no migration applies
|
||||
*/
|
||||
Table<R> open();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Per-world storage for mods: record tables in a SQLite database next to the save, kept
|
||||
* apart by mod id.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+35
-6
@@ -1,4 +1,4 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -7,9 +7,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class GameVersionTest {
|
||||
class GameVersionTest
|
||||
{
|
||||
@Test
|
||||
void parsesTwoAndThreePartVersions() {
|
||||
void parsesTwoAndThreePartVersions()
|
||||
{
|
||||
assertEquals(new GameVersion(42, 21, 0), GameVersion.parse("42.21"));
|
||||
assertEquals(new GameVersion(42, 21, 3), GameVersion.parse("42.21.3"));
|
||||
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42"));
|
||||
@@ -17,17 +19,44 @@ class GameVersionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoPartExpectationMatchesEveryBuild() {
|
||||
void prefixMatchesEveryMissingPart()
|
||||
{
|
||||
GameVersion version = new GameVersion(42, 21, 3);
|
||||
|
||||
assertTrue(version.matches("42"));
|
||||
assertTrue(version.matches("42.21"));
|
||||
assertTrue(version.matches("42.21.3"));
|
||||
assertFalse(version.matches("42.21.0"));
|
||||
assertFalse(version.matches("41"));
|
||||
assertFalse(version.matches("42.20"));
|
||||
assertFalse(version.matches("42.21.0"));
|
||||
assertFalse(version.matches("4"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void comparesNumerically() {
|
||||
void rejectsMalformedPrefixes()
|
||||
{
|
||||
GameVersion version = new GameVersion(42, 21, 3);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> version.matches(""));
|
||||
assertThrows(IllegalArgumentException.class, () -> version.matches("42."));
|
||||
assertThrows(IllegalArgumentException.class, () -> version.matches("42.21.3.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNumbersOutsideTheIntRange()
|
||||
{
|
||||
GameVersion version = new GameVersion(42, 21, 3);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42.99999999999"));
|
||||
assertThrows(IllegalArgumentException.class, () -> version.matches("99999999999"));
|
||||
assertFalse(GameVersion.isPrefix("42.99999999999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void comparesNumerically()
|
||||
{
|
||||
GameVersion version = new GameVersion(42, 21, 0);
|
||||
|
||||
assertTrue(version.isAtLeast(42, 9));
|
||||
assertTrue(version.isAtLeast(42, 21));
|
||||
assertFalse(version.isAtLeast(42, 22));
|
||||
@@ -0,0 +1,23 @@
|
||||
// Publishing to the Maven registry of the ZomboidForge Gitea. Credentials come from the Gradle
|
||||
// properties giteaUsername and giteaPassword (or ORG_GRADLE_PROJECT_giteaUsername and
|
||||
// ORG_GRADLE_PROJECT_giteaPassword), and are only read when a publish task runs.
|
||||
|
||||
plugins {
|
||||
`maven-publish`
|
||||
}
|
||||
|
||||
publishing {
|
||||
repositories {
|
||||
maven {
|
||||
name = "gitea"
|
||||
url = uri("https://git.security-command.org/api/packages/overlord/maven")
|
||||
credentials(PasswordCredentials::class)
|
||||
}
|
||||
|
||||
// build/repo of the root project: for the Gradle plugin's functional tests.
|
||||
maven {
|
||||
name = "build"
|
||||
url = uri(layout.settingsDirectory.dir("build/repo"))
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the
|
||||
# Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea,
|
||||
# in the version of the v* git tag on HEAD, without the "v".
|
||||
#
|
||||
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
|
||||
# published. Without a v* tag on HEAD nothing is published.
|
||||
#
|
||||
# Usage:
|
||||
# ci/publish.sh test runs the checks of the published modules; needs no credentials
|
||||
# ci/publish.sh publish publishes them without running the checks again
|
||||
#
|
||||
# Environment (publish only):
|
||||
# ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access
|
||||
# ORG_GRADLE_PROJECT_giteaPassword Token of that user
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
set -o pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
readonly REPO_ROOT
|
||||
|
||||
readonly MODULES=(
|
||||
api
|
||||
mod-tools
|
||||
gradle-plugin
|
||||
)
|
||||
|
||||
log() {
|
||||
echo "[publish] $*" >&2
|
||||
}
|
||||
|
||||
# Prints the v* tag on HEAD without its "v", or nothing.
|
||||
release_tag_version() {
|
||||
local tag
|
||||
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Gradle tasks for every module, e.g. ":api:check".
|
||||
module_tasks() {
|
||||
local task="$1"
|
||||
local module
|
||||
|
||||
for module in "${MODULES[@]}"; do
|
||||
echo ":${module}:${task}"
|
||||
done
|
||||
}
|
||||
|
||||
run_gradle() {
|
||||
local version="$1"
|
||||
shift
|
||||
|
||||
"${REPO_ROOT}/gradlew" \
|
||||
--no-daemon \
|
||||
--project-dir "${REPO_ROOT}" \
|
||||
"-Pversion=${version}" \
|
||||
"$@"
|
||||
}
|
||||
|
||||
run_tests() {
|
||||
local version="$1"
|
||||
local check_tasks
|
||||
|
||||
mapfile -t check_tasks < <(module_tasks check)
|
||||
|
||||
log "Testing ZomboidForge ${version}: ${MODULES[*]}"
|
||||
run_gradle "${version}" :core:check "${check_tasks[@]}"
|
||||
}
|
||||
|
||||
publish() {
|
||||
local version="$1"
|
||||
local publish_tasks
|
||||
|
||||
if [[ "${version}" == *-* ]]; then
|
||||
log "${version} is a pre-release version; nothing is published."
|
||||
return
|
||||
fi
|
||||
|
||||
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
|
||||
|
||||
log "Publishing ZomboidForge ${version}"
|
||||
run_gradle "${version}" "${publish_tasks[@]}"
|
||||
log "Published ${MODULES[*]} ${version}"
|
||||
}
|
||||
|
||||
main() {
|
||||
local step="${1:-}"
|
||||
local version
|
||||
|
||||
version="$(release_tag_version)"
|
||||
if [[ -z "${version}" ]]; then
|
||||
log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "${step}" in
|
||||
test)
|
||||
run_tests "${version}"
|
||||
;;
|
||||
publish)
|
||||
publish "${version}"
|
||||
;;
|
||||
*)
|
||||
log "Usage: ci/publish.sh test|publish"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
+61
-26
@@ -1,22 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Builds the ZomboidForge image for one Project Zomboid version and optionally
|
||||
# Builds the ZomboidForge image for the current build of a Steam branch and optionally
|
||||
# publishes it. Published tags:
|
||||
#
|
||||
# <forge>-pz<pz>-build<steam_buildid> immutable; never overwritten
|
||||
# <forge>-pz<pz> moves to the newest Steam build of that version
|
||||
# latest only with LATEST=true
|
||||
# <forge>-pz<major.minor.build> written once per ZomboidForge and Project Zomboid version
|
||||
# <forge>-pz<major.minor> moves to the newest hotfix of that minor version
|
||||
# latest only with LATEST=true
|
||||
#
|
||||
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0).
|
||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never
|
||||
# published. Without any v* tag the version is "0.0.0-prerelease".
|
||||
# <major.minor.build> is the version the branch's server jar reports, read before the full
|
||||
# build (Dockerfile stage game-version, which downloads only the jar).
|
||||
#
|
||||
# Nothing is built when the immutable tag already exists in the registry.
|
||||
# <forge> is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such
|
||||
# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0).
|
||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and
|
||||
# verified but never published. Without any v* tag the version is "0.0.0-prerelease".
|
||||
#
|
||||
# Nothing is built when <forge>-pz<major.minor.build> already exists in the registry. The
|
||||
# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 ->
|
||||
# 42.21.2) gets an image; a new Steam build with an unchanged version does not.
|
||||
#
|
||||
# Environment:
|
||||
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
|
||||
# PZ_BRANCH Steam branch. Default: public
|
||||
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties
|
||||
# PZ_VERSION Accepted Project Zomboid versions ("42": every Build 42 version).
|
||||
# Default: pz.version in gradle.properties
|
||||
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
|
||||
# LATEST true: also push "latest". Default: false
|
||||
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
|
||||
@@ -63,12 +70,15 @@ gradle_property() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Prints the forge version: the newest v* tag reachable from HEAD without its "v",
|
||||
# or nothing when the repository has no such tag.
|
||||
# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
|
||||
# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the
|
||||
# repository has no such tag.
|
||||
release_tag_version() {
|
||||
local tag
|
||||
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
fi
|
||||
}
|
||||
@@ -78,6 +88,22 @@ image_exists() {
|
||||
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
|
||||
}
|
||||
|
||||
# Prints the game version of the branch's current server jar, e.g. 42.21.0. Downloads only
|
||||
# the jar; the result stays cached until the build ID changes.
|
||||
read_game_version() {
|
||||
local build_id="$1"
|
||||
local image
|
||||
|
||||
image="$("$(container_engine)" build --quiet \
|
||||
--platform linux/amd64 \
|
||||
--target game-version \
|
||||
--build-arg "PZ_BRANCH=${PZ_BRANCH}" \
|
||||
--build-arg "STEAM_BUILDID=${build_id}" \
|
||||
"${REPO_ROOT}")"
|
||||
|
||||
"$(container_engine)" run --rm --entrypoint cat "${image}" /game-version
|
||||
}
|
||||
|
||||
build_image() {
|
||||
local reference="$1"
|
||||
local forge_version="$2"
|
||||
@@ -119,8 +145,9 @@ push_as() {
|
||||
main() {
|
||||
local forge_version
|
||||
local publish="${REQUESTED_PUBLISH}"
|
||||
local pz_version
|
||||
local pz_prefix
|
||||
local build_id
|
||||
local game_version
|
||||
|
||||
forge_version="$(release_tag_version)"
|
||||
if [[ -z "${forge_version}" ]]; then
|
||||
@@ -132,31 +159,39 @@ main() {
|
||||
log "${forge_version} is a pre-release version; nothing will be published."
|
||||
fi
|
||||
|
||||
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
|
||||
pz_prefix="${PZ_VERSION:-$(gradle_property pz.version)}"
|
||||
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
|
||||
game_version="$(read_game_version "${build_id}")"
|
||||
log "ZomboidForge ${forge_version}, Project Zomboid ${game_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
|
||||
|
||||
local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}"
|
||||
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}"
|
||||
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
|
||||
# Checked here as well as by the patcher, to fail before the full download.
|
||||
if [[ "${game_version}" != "${pz_prefix}" && "${game_version}" != "${pz_prefix}."* ]]; then
|
||||
log "Steam branch ${PZ_BRANCH} has Project Zomboid ${game_version}; the build accepts ${pz_prefix}."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${publish}" == true ]] && image_exists "${immutable_tag}"; then
|
||||
log "${immutable_tag} is already published; nothing to do."
|
||||
local version_tag="${IMAGE}:${forge_version}-pz${game_version}"
|
||||
# 42.21.2 -> 42.21
|
||||
local minor_tag="${IMAGE}:${forge_version}-pz${game_version%.*}"
|
||||
|
||||
if [[ "${publish}" == true ]] && image_exists "${version_tag}"; then
|
||||
log "${version_tag} is already published; nothing to do."
|
||||
return
|
||||
fi
|
||||
|
||||
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}"
|
||||
verify_build_id "${immutable_tag}" "${build_id}"
|
||||
build_image "${version_tag}" "${forge_version}" "${game_version}" "${build_id}"
|
||||
verify_build_id "${version_tag}" "${build_id}"
|
||||
|
||||
if [[ "${publish}" != true ]]; then
|
||||
log "Built ${immutable_tag} (not published)"
|
||||
log "Built ${version_tag} (not published)"
|
||||
return
|
||||
fi
|
||||
|
||||
"$(container_engine)" push "${immutable_tag}"
|
||||
log "Pushed ${immutable_tag}"
|
||||
push_as "${immutable_tag}" "${version_tag}"
|
||||
"$(container_engine)" push "${version_tag}"
|
||||
log "Pushed ${version_tag}"
|
||||
push_as "${version_tag}" "${minor_tag}"
|
||||
if [[ "${LATEST}" == true ]]; then
|
||||
push_as "${immutable_tag}" "${IMAGE}:latest"
|
||||
push_as "${version_tag}" "${IMAGE}:latest"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ set -o nounset
|
||||
set -o pipefail
|
||||
|
||||
readonly APP_ID="380870"
|
||||
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13"
|
||||
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d"
|
||||
|
||||
readonly BRANCH="$1"
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ plugins {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":api"))
|
||||
implementation(project(":patcher"))
|
||||
implementation(libs.bundles.asm)
|
||||
|
||||
|
||||
+9
-5
@@ -1,10 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch;
|
||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch;
|
||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch;
|
||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch;
|
||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieVehiclePerformancePatch;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.*;
|
||||
import dev.overlord.zomboidforge.compat.b42.perf.*;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import dev.overlord.zomboidforge.patcher.PatchSet;
|
||||
|
||||
@@ -16,7 +13,14 @@ import java.util.List;
|
||||
public final class B42PatchSet implements PatchSet
|
||||
{
|
||||
private static final List<ClassPatch> PATCHES = List.of(
|
||||
new ServerLoadPatch(),
|
||||
new ServerStartedPatch(),
|
||||
new ServerTickPatch(),
|
||||
new ServerStoppingPatch(),
|
||||
new BackupStoragePatch(),
|
||||
new CommandLookupPatch(),
|
||||
new CommandListPatch(),
|
||||
new ClientCommandPatch(),
|
||||
new IsoZombieVehiclePerformancePatch(),
|
||||
new IsoZombieNetworkComponentPerformancePatch(),
|
||||
new IsoZombieSpotChancePerformancePatch(),
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.LabelNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.TryCatchBlockNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
/**
|
||||
* Wraps {@code ZipBackup.makeBackupFile(String, BackupTypes)}, which zips the save folder
|
||||
* including {@code zomboidforge.db}, so that storage writes wait during a backup:
|
||||
*
|
||||
* <pre>{@code
|
||||
* private static void makeBackupFile(String serverName, BackupTypes type)
|
||||
* {
|
||||
* StorageHooks.backupRunning(true);
|
||||
* try { zomboidForge$makeBackupFile(serverName, type); }
|
||||
* finally { StorageHooks.backupRunning(false); }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The vanilla method is renamed to {@code zomboidForge$makeBackupFile} and stays unchanged. It
|
||||
* reads the zipped files until {@code ParallelScatterZipCreator.writeTo} returns and catches its
|
||||
* own exceptions, so only a wrapper around the whole method covers the entire backup.
|
||||
*/
|
||||
public final class BackupStoragePatch implements ClassPatch
|
||||
{
|
||||
private static final String TARGET = "zombie/core/backup/ZipBackup";
|
||||
private static final String RENAMED = "zomboidForge$makeBackupFile";
|
||||
|
||||
private static final Anchor.Method ANCHOR = new Anchor.Method(
|
||||
"makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks", "backupRunning", "(Z)V"
|
||||
);
|
||||
|
||||
@Override
|
||||
public String target() { return BackupStoragePatch.TARGET; }
|
||||
@Override
|
||||
public Anchor.Method anchor() { return BackupStoragePatch.ANCHOR; }
|
||||
@Override
|
||||
public Hook hook() { return BackupStoragePatch.HOOK; }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode original = BackupStoragePatch.ANCHOR.resolve(node);
|
||||
|
||||
if ((original.access & Opcodes.ACC_STATIC) == 0)
|
||||
throw new IllegalStateException("'" + node.name + "." + original.name + original.desc + "' is not static.");
|
||||
|
||||
boolean taken = node.methods.stream().anyMatch(method -> method.name.equals(BackupStoragePatch.RENAMED));
|
||||
if (taken) throw new IllegalStateException("'" + node.name + "' already has a method '" + BackupStoragePatch.RENAMED + "'.");
|
||||
|
||||
MethodNode wrapper = new MethodNode(original.access, original.name, original.desc, original.signature, original.exceptions.toArray(String[]::new));
|
||||
original.name = BackupStoragePatch.RENAMED;
|
||||
|
||||
BackupStoragePatch.wrap(node.name, original.desc, wrapper);
|
||||
node.methods.add(wrapper);
|
||||
}
|
||||
|
||||
/** {@code hook(true); try { renamed(args); } finally { hook(false); }} */
|
||||
private static void wrap(String owner, String desc, MethodNode wrapper)
|
||||
{
|
||||
Type[] arguments = Type.getArgumentTypes(desc);
|
||||
int thrown = arguments.length;
|
||||
LabelNode start = new LabelNode();
|
||||
LabelNode end = new LabelNode();
|
||||
LabelNode handler = new LabelNode();
|
||||
InsnList code = wrapper.instructions;
|
||||
|
||||
for (Type argument : arguments) {
|
||||
if (argument.getSize() != 1) throw new IllegalStateException("'" + owner + "." + BackupStoragePatch.ANCHOR.name() + desc + "' has a wide argument; the wrapper only passes one-slot arguments.");
|
||||
}
|
||||
|
||||
code.add(BackupStoragePatch.hook(true));
|
||||
code.add(start);
|
||||
|
||||
for (int i = 0; i < arguments.length; i++) code.add(new VarInsnNode(arguments[i].getOpcode(Opcodes.ILOAD), i));
|
||||
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, owner, BackupStoragePatch.RENAMED, desc, false));
|
||||
code.add(end);
|
||||
code.add(BackupStoragePatch.hook(false));
|
||||
code.add(new InsnNode(Opcodes.RETURN));
|
||||
|
||||
code.add(handler);
|
||||
code.add(new VarInsnNode(Opcodes.ASTORE, thrown));
|
||||
code.add(BackupStoragePatch.hook(false));
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, thrown));
|
||||
code.add(new InsnNode(Opcodes.ATHROW));
|
||||
|
||||
wrapper.tryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, null));
|
||||
}
|
||||
|
||||
private static InsnList hook(boolean running)
|
||||
{
|
||||
InsnList code = new InsnList();
|
||||
|
||||
code.add(new InsnNode(running ? Opcodes.ICONST_1 : Opcodes.ICONST_0));
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, BackupStoragePatch.HOOK.owner(), BackupStoragePatch.HOOK.name(), BackupStoragePatch.HOOK.desc(), false));
|
||||
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Makes the Lua event {@code OnClientCommand} in {@code GameServer.receiveClientCommand} depend on
|
||||
* {@code ClientCommandHooks.onClientCommand(module, command, player, tbl)}:
|
||||
*
|
||||
* <pre>{@code
|
||||
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
|
||||
* LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
|
||||
* }</pre>
|
||||
*
|
||||
* The arguments are the method's local variables of these names.
|
||||
*/
|
||||
public final class ClientCommandPatch extends CancellableHookPatch
|
||||
{
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("receiveClientCommand", "(Lzombie/core/network/ByteBufferReader;Lzombie/core/raknet/UdpConnection;S)V"),
|
||||
"zombie/Lua/LuaEventManager", "triggerEvent", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks", "onClientCommand",
|
||||
"(Ljava/lang/String;Ljava/lang/String;Lzombie/characters/IsoPlayer;Lse/krka/kahlua/vm/KahluaTable;)Z"
|
||||
);
|
||||
|
||||
private static final List<HookArgument> ARGUMENTS = List.of(
|
||||
new HookArgument.Local("module"),
|
||||
new HookArgument.Local("command"),
|
||||
new HookArgument.Local("player"),
|
||||
new HookArgument.Local("tbl")
|
||||
);
|
||||
|
||||
public ClientCommandPatch() {
|
||||
super("zombie/network/GameServer", ClientCommandPatch.ANCHOR, ClientCommandPatch.HOOK, ClientCommandPatch.ARGUMENTS);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Makes {@code CommandBase.getSubClasses()} return
|
||||
* {@code CommandHooks.listCommands(childrenClasses)}: Project Zomboid's command classes followed
|
||||
* by the mods'. The {@code help} command lists commands through this method.
|
||||
*/
|
||||
public final class CommandListPatch extends ReturnHookPatch
|
||||
{
|
||||
/** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "listCommands", "([Ljava/lang/Class;)[Ljava/lang/Class;"
|
||||
);
|
||||
|
||||
public CommandListPatch() {
|
||||
super("zombie/commands/CommandBase", CommandListPatch.ANCHOR, CommandListPatch.HOOK, List.of());
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Makes {@code CommandBase.findCommandCls(command)} return
|
||||
* {@code CommandHooks.findCommand(null, command)} where it returns {@code null}: when no command
|
||||
* of Project Zomboid matches, the mods' commands are searched. The server console, RCON, chat
|
||||
* commands, and {@code help <name>} look commands up through this method.
|
||||
*/
|
||||
public final class CommandLookupPatch extends ReturnHookPatch
|
||||
{
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("findCommandCls", "(Ljava/lang/String;)Ljava/lang/Class;"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ACONST_NULL),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "findCommand", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;"
|
||||
);
|
||||
|
||||
public CommandLookupPatch() {
|
||||
super("zombie/commands/CommandBase", CommandLookupPatch.ANCHOR, CommandLookupPatch.HOOK, List.of(new HookArgument.Parameter(0)));
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.FieldInsnNode;
|
||||
import org.objectweb.asm.tree.FieldNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.JumpInsnNode;
|
||||
import org.objectweb.asm.tree.LabelNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
|
||||
/**
|
||||
* Calls {@code ServerHooks.onLoad()} in {@code GameServer.main}, directly after
|
||||
* {@code ServerOptions.instance.init()}, and stops the server when it returns {@code false}:
|
||||
*
|
||||
* <pre>{@code
|
||||
* if (!ServerHooks.onLoad()) {
|
||||
* Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||
* System.exit(1);
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The vanilla shutdown hook saves the map on every JVM exit; before the world is loaded that
|
||||
* save fails with a {@code NullPointerException} in {@code IsoMetaGrid.save()}. The inserted
|
||||
* code is part of {@code GameServer}, so it reads the private field {@code shutdownHook}
|
||||
* directly.
|
||||
*/
|
||||
public final class ServerLoadPatch implements ClassPatch
|
||||
{
|
||||
private static final String TARGET = "zombie/network/GameServer";
|
||||
|
||||
private static final String SHUTDOWN_HOOK = "shutdownHook";
|
||||
private static final String SHUTDOWN_HOOK_DESC = "Ljava/lang/Thread;";
|
||||
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("main", "([Ljava/lang/String;)V"),
|
||||
"zombie/network/ServerOptions", "init", "()V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onLoad", "()Z"
|
||||
);
|
||||
|
||||
@Override
|
||||
public String target() { return ServerLoadPatch.TARGET; }
|
||||
@Override
|
||||
public Anchor.Call anchor() { return ServerLoadPatch.ANCHOR; }
|
||||
@Override
|
||||
public Hook hook() { return ServerLoadPatch.HOOK; }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
ServerLoadPatch.requireShutdownHookField(node);
|
||||
|
||||
MethodInsnNode init = ServerLoadPatch.ANCHOR.resolve(node);
|
||||
ServerLoadPatch.ANCHOR.in().resolve(node).instructions.insert(init, ServerLoadPatch.abortUnlessLoaded());
|
||||
}
|
||||
|
||||
/** The abort path runs only when a mod fails, so a missing field would otherwise go unnoticed until then. */
|
||||
private static void requireShutdownHookField(ClassNode node)
|
||||
{
|
||||
boolean found = node.fields.stream().anyMatch(ServerLoadPatch::isShutdownHook);
|
||||
|
||||
if (!found) throw new IllegalStateException("Expected the static field '" + node.name + "." + ServerLoadPatch.SHUTDOWN_HOOK + " " + ServerLoadPatch.SHUTDOWN_HOOK_DESC + "'.");
|
||||
}
|
||||
|
||||
private static boolean isShutdownHook(FieldNode field)
|
||||
{
|
||||
return field.name.equals(ServerLoadPatch.SHUTDOWN_HOOK)
|
||||
&& field.desc.equals(ServerLoadPatch.SHUTDOWN_HOOK_DESC)
|
||||
&& (field.access & Opcodes.ACC_STATIC) != 0;
|
||||
}
|
||||
|
||||
private static InsnList abortUnlessLoaded()
|
||||
{
|
||||
InsnList code = new InsnList();
|
||||
LabelNode loaded = new LabelNode();
|
||||
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ServerLoadPatch.HOOK.owner(), ServerLoadPatch.HOOK.name(), ServerLoadPatch.HOOK.desc(), false));
|
||||
code.add(new JumpInsnNode(Opcodes.IFNE, loaded));
|
||||
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false));
|
||||
code.add(new FieldInsnNode(Opcodes.GETSTATIC, ServerLoadPatch.TARGET, ServerLoadPatch.SHUTDOWN_HOOK, ServerLoadPatch.SHUTDOWN_HOOK_DESC));
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Runtime", "removeShutdownHook", "(Ljava/lang/Thread;)Z", false));
|
||||
code.add(new InsnNode(Opcodes.POP));
|
||||
|
||||
code.add(new InsnNode(Opcodes.ICONST_1));
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "exit", "(I)V", false));
|
||||
|
||||
code.add(loaded);
|
||||
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.FieldInsnNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Calls {@code ServerHooks.onStopping()} in the vanilla shutdown hook {@code GameServer$1.run()},
|
||||
* between {@code GameServer.done = true} and {@code ServerMap.instance.QueuedQuit()}, which saves
|
||||
* the world.
|
||||
*
|
||||
* <p>{@code GameServer$1} is the only caller of {@code QueuedQuit()}. The {@code quit} command
|
||||
* only sets {@code ServerMap.queuedQuit}; {@code ServerMap.preupdate()} then calls
|
||||
* {@code System.exit(0)}, so the save runs in the shutdown hook as it does for SIGTERM and SIGINT.
|
||||
*/
|
||||
public final class ServerStoppingPatch implements ClassPatch
|
||||
{
|
||||
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||
|
||||
/** {@code GameServer.done = true; ServerMap.instance.QueuedQuit();} */
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("run", "()V"),
|
||||
new Anchor.Instruction.Constant(1),
|
||||
new Anchor.Instruction.Opcode(Opcodes.PUTSTATIC),
|
||||
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||
new Anchor.Instruction.Invoke("zombie/network/ServerMap", "QueuedQuit", "()V")
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onStopping", "()V"
|
||||
);
|
||||
|
||||
@Override
|
||||
public String target() { return ServerStoppingPatch.GAME_SERVER + "$1"; }
|
||||
@Override
|
||||
public Anchor.Sequence anchor() { return ServerStoppingPatch.ANCHOR; }
|
||||
@Override
|
||||
public Hook hook() { return ServerStoppingPatch.HOOK; }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
List<AbstractInsnNode> matched = ServerStoppingPatch.ANCHOR.resolve(node);
|
||||
FieldInsnNode done = (FieldInsnNode) matched.get(1);
|
||||
|
||||
if (!done.owner.equals(ServerStoppingPatch.GAME_SERVER) || !done.name.equals("done"))
|
||||
throw new IllegalStateException("'" + node.name + ".run()V' sets '" + done.owner + "." + done.name + "' before 'QueuedQuit()', expected '" + ServerStoppingPatch.GAME_SERVER + ".done'.");
|
||||
|
||||
ServerStoppingPatch.ANCHOR.in().resolve(node).instructions.insert(
|
||||
done, new MethodInsnNode(
|
||||
Opcodes.INVOKESTATIC,
|
||||
ServerStoppingPatch.HOOK.owner(),
|
||||
ServerStoppingPatch.HOOK.name(),
|
||||
ServerStoppingPatch.HOOK.desc(),
|
||||
false
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
|
||||
|
||||
/**
|
||||
* Calls {@code ServerHooks.onTick()} in the main loop of {@code GameServer.main}, directly after
|
||||
* {@code ServerMap.instance.preupdate()} at the start of the frame branch. The {@code while (!done)}
|
||||
* loop itself also iterates while the update limiter skips a frame; the frame branch runs once
|
||||
* per game frame.
|
||||
*/
|
||||
public final class ServerTickPatch extends HookInjectionPatch
|
||||
{
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("main", "([Ljava/lang/String;)V"),
|
||||
"zombie/network/ServerMap", "preupdate", "()V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onTick", "()V"
|
||||
);
|
||||
|
||||
public ServerTickPatch() {
|
||||
super("zombie/network/GameServer", ServerTickPatch.ANCHOR, ServerTickPatch.HOOK);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.ATHROW;
|
||||
import static org.objectweb.asm.Opcodes.DUP;
|
||||
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.NEW;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class BackupStoragePatchTest
|
||||
{
|
||||
private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup";
|
||||
private static final String TYPES = "zombie/core/backup/ZipBackup$BackupTypes";
|
||||
private static final String DESC = "(Ljava/lang/String;L" + BackupStoragePatchTest.TYPES + ";)V";
|
||||
private static final String CALLS = Type.getInternalName(BackupStoragePatchTest.Calls.class);
|
||||
|
||||
/** Stands in for {@code StorageHooks.backupRunning(boolean)} and records the calls. */
|
||||
public static final class Calls
|
||||
{
|
||||
public static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
private Calls() {}
|
||||
|
||||
public static void record(String call) { Calls.LOG.add(call); }
|
||||
|
||||
public static void backupRunning(boolean running) { Calls.LOG.add("backupRunning " + running); }
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code ZipBackup} with the vanilla method's shape:
|
||||
*
|
||||
* <pre>{@code
|
||||
* private static void makeBackupFile(String serverName, BackupTypes type)
|
||||
* {
|
||||
* if (serverName.equals("fail")) throw new IllegalStateException("zip failed");
|
||||
* Calls.record("backup " + serverName);
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
private static ClassNode zipBackup()
|
||||
{
|
||||
ClassNode node = BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.ZIP_BACKUP);
|
||||
|
||||
MethodVisitor method = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", BackupStoragePatchTest.DESC, null, null);
|
||||
Label normal = new Label();
|
||||
|
||||
method.visitVarInsn(ALOAD, 0);
|
||||
method.visitLdcInsn("fail");
|
||||
method.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false);
|
||||
method.visitJumpInsn(IFEQ, normal);
|
||||
method.visitTypeInsn(NEW, "java/lang/IllegalStateException");
|
||||
method.visitInsn(DUP);
|
||||
method.visitLdcInsn("zip failed");
|
||||
method.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalStateException", "<init>", "(Ljava/lang/String;)V", false);
|
||||
method.visitInsn(ATHROW);
|
||||
|
||||
method.visitLabel(normal);
|
||||
method.visitVarInsn(ALOAD, 0);
|
||||
method.visitMethodInsn(INVOKESTATIC, BackupStoragePatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||
method.visitInsn(RETURN);
|
||||
method.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static ClassNode emptyClass(String name)
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||
init.visitVarInsn(ALOAD, 0);
|
||||
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Patches {@code ZipBackup}, points the hook at {@link Calls}, and returns {@code makeBackupFile}. */
|
||||
private static Method patched() throws ReflectiveOperationException
|
||||
{
|
||||
BackupStoragePatch patch = new BackupStoragePatch();
|
||||
ClassNode zipBackup = BackupStoragePatchTest.zipBackup();
|
||||
|
||||
patch.apply(zipBackup);
|
||||
CallRedirect.redirect(zipBackup, patch.hook().owner(), patch.hook().name(), BackupStoragePatchTest.CALLS);
|
||||
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
Class<?> types = definer.define(BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.TYPES));
|
||||
Class<?> loaded = definer.define(zipBackup);
|
||||
|
||||
Method method = loaded.getDeclaredMethod("makeBackupFile", String.class, types);
|
||||
method.setAccessible(true);
|
||||
|
||||
BackupStoragePatchTest.Calls.LOG.clear();
|
||||
return method;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new BackupStoragePatch().anchor().verify(BackupStoragePatchTest.zipBackup());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsTheHookAroundTheBackup() throws ReflectiveOperationException
|
||||
{
|
||||
BackupStoragePatchTest.patched().invoke(null, "server", null);
|
||||
|
||||
assertEquals(List.of("backupRunning true", "server", "backupRunning false"), BackupStoragePatchTest.Calls.LOG);
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsTheHookAfterAFailedBackupToo() throws ReflectiveOperationException
|
||||
{
|
||||
Method method = BackupStoragePatchTest.patched();
|
||||
|
||||
InvocationTargetException e = assertThrows(InvocationTargetException.class, () -> method.invoke(null, "fail", null));
|
||||
|
||||
assertInstanceOf(IllegalStateException.class, e.getCause());
|
||||
assertEquals(List.of("backupRunning true", "backupRunning false"), BackupStoragePatchTest.Calls.LOG);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheRenamedMethodExists()
|
||||
{
|
||||
ClassNode zipBackup = BackupStoragePatchTest.zipBackup();
|
||||
zipBackup.visitMethod(ACC_PRIVATE | ACC_STATIC, "zomboidForge$makeBackupFile", "()V", null, null);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BackupStoragePatch().apply(zipBackup));
|
||||
assertEquals("'zombie/core/backup/ZipBackup' already has a method 'zomboidForge$makeBackupFile'.", e.getMessage());
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.DUP;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.NEW;
|
||||
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class ServerLoadPatchTest
|
||||
{
|
||||
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||
private static final String SERVER_OPTIONS = "zombie/network/ServerOptions";
|
||||
private static final String CALLS = Type.getInternalName(ServerLoadPatchTest.Calls.class);
|
||||
|
||||
/** Stands in for {@code ServerHooks.onLoad()} and {@code System.exit}, and records the calls. */
|
||||
public static final class Calls
|
||||
{
|
||||
public static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
public static boolean loaded;
|
||||
|
||||
private Calls() {}
|
||||
|
||||
public static void record(String call) { Calls.LOG.add(call); }
|
||||
|
||||
public static boolean onLoad()
|
||||
{
|
||||
Calls.LOG.add("onLoad");
|
||||
return Calls.loaded;
|
||||
}
|
||||
|
||||
public static void exit(int status) { Calls.LOG.add("exit " + status); }
|
||||
}
|
||||
|
||||
private record Run(List<String> calls, Thread shutdownHook) {}
|
||||
|
||||
/**
|
||||
* {@code GameServer} with the parts of {@code main} the patch depends on:
|
||||
*
|
||||
* <pre>{@code
|
||||
* private static Thread shutdownHook = new Thread(); // only with withShutdownHook
|
||||
*
|
||||
* static { Runtime.getRuntime().addShutdownHook(shutdownHook); }
|
||||
*
|
||||
* public static void main(String[] args)
|
||||
* {
|
||||
* ServerOptions.instance.init();
|
||||
* Calls.record("after");
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
private static ClassNode gameServer(boolean withShutdownHook)
|
||||
{
|
||||
ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.GAME_SERVER);
|
||||
|
||||
if (withShutdownHook) {
|
||||
node.visitField(ACC_PRIVATE | ACC_STATIC, "shutdownHook", "Ljava/lang/Thread;", null, null);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||
init.visitTypeInsn(NEW, "java/lang/Thread");
|
||||
init.visitInsn(DUP);
|
||||
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Thread", "<init>", "()V", false);
|
||||
init.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;");
|
||||
init.visitMethodInsn(INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false);
|
||||
init.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;");
|
||||
init.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Runtime", "addShutdownHook", "(Ljava/lang/Thread;)V", false);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
}
|
||||
|
||||
MethodVisitor main = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
|
||||
main.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";");
|
||||
main.visitMethodInsn(INVOKEVIRTUAL, ServerLoadPatchTest.SERVER_OPTIONS, "init", "()V", false);
|
||||
main.visitLdcInsn("after");
|
||||
main.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||
main.visitInsn(RETURN);
|
||||
main.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** {@code ServerOptions} with {@code public static ServerOptions instance} and {@code init()} recording {@code "init"}. */
|
||||
private static ClassNode serverOptions()
|
||||
{
|
||||
ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.SERVER_OPTIONS);
|
||||
String desc = "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";";
|
||||
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null);
|
||||
|
||||
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||
clinit.visitTypeInsn(NEW, ServerLoadPatchTest.SERVER_OPTIONS);
|
||||
clinit.visitInsn(DUP);
|
||||
clinit.visitMethodInsn(INVOKESPECIAL, ServerLoadPatchTest.SERVER_OPTIONS, "<init>", "()V", false);
|
||||
clinit.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", desc);
|
||||
clinit.visitInsn(RETURN);
|
||||
clinit.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "init", "()V", null, null);
|
||||
init.visitLdcInsn("init");
|
||||
init.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Public class with a public no-argument constructor. */
|
||||
private static ClassNode emptyClass(String name)
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||
init.visitVarInsn(ALOAD, 0);
|
||||
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Patches {@code GameServer}, points the hook and {@code System.exit} at {@link Calls}, and runs {@code main}. */
|
||||
private static Run run(boolean loaded) throws ReflectiveOperationException
|
||||
{
|
||||
ServerLoadPatch patch = new ServerLoadPatch();
|
||||
ClassNode gameServer = ServerLoadPatchTest.gameServer(true);
|
||||
|
||||
patch.apply(gameServer);
|
||||
CallRedirect.redirect(gameServer, patch.hook().owner(), patch.hook().name(), ServerLoadPatchTest.CALLS);
|
||||
CallRedirect.redirect(gameServer, "java/lang/System", "exit", ServerLoadPatchTest.CALLS);
|
||||
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(ServerLoadPatchTest.serverOptions());
|
||||
Class<?> loadedClass = definer.define(gameServer);
|
||||
|
||||
ServerLoadPatchTest.Calls.LOG.clear();
|
||||
ServerLoadPatchTest.Calls.loaded = loaded;
|
||||
|
||||
loadedClass.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
|
||||
|
||||
Field shutdownHook = loadedClass.getDeclaredField("shutdownHook");
|
||||
shutdownHook.setAccessible(true);
|
||||
|
||||
return new Run(List.copyOf(ServerLoadPatchTest.Calls.LOG), (Thread) shutdownHook.get(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new ServerLoadPatch().anchor().verify(ServerLoadPatchTest.gameServer(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuesWhenTheHookReturnsTrue() throws ReflectiveOperationException
|
||||
{
|
||||
Run run = ServerLoadPatchTest.run(true);
|
||||
|
||||
assertEquals(List.of("init", "onLoad", "after"), run.calls());
|
||||
assertTrue(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook is still registered.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void removesTheShutdownHookAndExitsWhenTheHookReturnsFalse() throws ReflectiveOperationException
|
||||
{
|
||||
Run run = ServerLoadPatchTest.run(false);
|
||||
|
||||
// The test double for System.exit returns, so "after" still runs.
|
||||
assertEquals(List.of("init", "onLoad", "exit 1", "after"), run.calls());
|
||||
assertFalse(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook was not removed.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWithoutTheShutdownHookField()
|
||||
{
|
||||
ClassNode gameServer = ServerLoadPatchTest.gameServer(false);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerLoadPatch().apply(gameServer));
|
||||
assertEquals("Expected the static field 'zombie/network/GameServer.shutdownHook Ljava/lang/Thread;'.", e.getMessage());
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.DUP;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.ICONST_1;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.NEW;
|
||||
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class ServerStoppingPatchTest
|
||||
{
|
||||
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||
private static final String SHUTDOWN_HOOK = "zombie/network/GameServer$1";
|
||||
private static final String SERVER_MAP = "zombie/network/ServerMap";
|
||||
private static final String CALLS = Type.getInternalName(ServerStoppingPatchTest.Calls.class);
|
||||
|
||||
/** Stands in for {@code ServerHooks.onStopping()} and records the calls. */
|
||||
public static final class Calls
|
||||
{
|
||||
public static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
/** {@code GameServer.done} of the class under test. */
|
||||
public static Field done;
|
||||
|
||||
private Calls() {}
|
||||
|
||||
public static void record(String call) { Calls.LOG.add(call); }
|
||||
|
||||
public static void onStopping() throws IllegalAccessException { Calls.LOG.add("onStopping done=" + Calls.done.getBoolean(null)); }
|
||||
}
|
||||
|
||||
/** {@code GameServer} with {@code public static boolean done} and {@code other}. */
|
||||
private static ClassNode gameServer()
|
||||
{
|
||||
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.GAME_SERVER);
|
||||
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "done", "Z", null, null);
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "other", "Z", null, null);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** {@code ServerMap} with {@code public static ServerMap instance} and {@code QueuedQuit()} recording {@code "QueuedQuit"}. */
|
||||
private static ClassNode serverMap()
|
||||
{
|
||||
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SERVER_MAP);
|
||||
String desc = "L" + ServerStoppingPatchTest.SERVER_MAP + ";";
|
||||
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null);
|
||||
|
||||
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||
clinit.visitTypeInsn(NEW, ServerStoppingPatchTest.SERVER_MAP);
|
||||
clinit.visitInsn(DUP);
|
||||
clinit.visitMethodInsn(INVOKESPECIAL, ServerStoppingPatchTest.SERVER_MAP, "<init>", "()V", false);
|
||||
clinit.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", desc);
|
||||
clinit.visitInsn(RETURN);
|
||||
clinit.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor quit = node.visitMethod(ACC_PUBLIC, "QueuedQuit", "()V", null, null);
|
||||
quit.visitLdcInsn("QueuedQuit");
|
||||
quit.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||
quit.visitInsn(RETURN);
|
||||
quit.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code GameServer$1} with the part of {@code run()} the patch depends on:
|
||||
*
|
||||
* <pre>{@code
|
||||
* public void run()
|
||||
* {
|
||||
* GameServer.<field> = true;
|
||||
* ServerMap.instance.QueuedQuit();
|
||||
* Calls.record("after");
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
private static ClassNode shutdownHook(String field)
|
||||
{
|
||||
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SHUTDOWN_HOOK);
|
||||
MethodVisitor run = node.visitMethod(ACC_PUBLIC, "run", "()V", null, null);
|
||||
|
||||
run.visitInsn(ICONST_1);
|
||||
run.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.GAME_SERVER, field, "Z");
|
||||
run.visitFieldInsn(GETSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", "L" + ServerStoppingPatchTest.SERVER_MAP + ";");
|
||||
run.visitMethodInsn(INVOKEVIRTUAL, ServerStoppingPatchTest.SERVER_MAP, "QueuedQuit", "()V", false);
|
||||
run.visitLdcInsn("after");
|
||||
run.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||
run.visitInsn(RETURN);
|
||||
run.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Public class with a public no-argument constructor. */
|
||||
private static ClassNode emptyClass(String name)
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||
init.visitVarInsn(ALOAD, 0);
|
||||
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new ServerStoppingPatch().anchor().verify(ServerStoppingPatchTest.shutdownHook("done"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsTheHookAfterDoneIsSetAndBeforeTheSave() throws ReflectiveOperationException
|
||||
{
|
||||
ServerStoppingPatch patch = new ServerStoppingPatch();
|
||||
ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("done");
|
||||
|
||||
patch.apply(shutdownHook);
|
||||
CallRedirect.redirect(shutdownHook, patch.hook().owner(), patch.hook().name(), ServerStoppingPatchTest.CALLS);
|
||||
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(ServerStoppingPatchTest.serverMap());
|
||||
|
||||
Class<?> gameServer = definer.define(ServerStoppingPatchTest.gameServer());
|
||||
Class<?> loaded = definer.define(shutdownHook);
|
||||
|
||||
ServerStoppingPatchTest.Calls.LOG.clear();
|
||||
ServerStoppingPatchTest.Calls.done = gameServer.getField("done");
|
||||
|
||||
loaded.getMethod("run").invoke(loaded.getConstructor().newInstance());
|
||||
|
||||
assertEquals(List.of("onStopping done=true", "QueuedQuit", "after"), ServerStoppingPatchTest.Calls.LOG);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenAnotherFieldIsSetBeforeTheSave()
|
||||
{
|
||||
ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("other");
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerStoppingPatch().apply(shutdownHook));
|
||||
assertEquals(
|
||||
"'zombie/network/GameServer$1.run()V' sets 'zombie/network/GameServer.other' before 'QueuedQuit()', expected 'zombie/network/GameServer.done'.",
|
||||
e.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches.support;
|
||||
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
/**
|
||||
* Points calls in a patched test class at a test double, e.g. a hook or {@code System.exit}, so
|
||||
* the patched code can run inside a test.
|
||||
*/
|
||||
public final class CallRedirect
|
||||
{
|
||||
private CallRedirect() {}
|
||||
|
||||
/**
|
||||
* Changes the owner of every call to {@code owner.name} in {@code node} to {@code newOwner}.
|
||||
* Fails when {@code node} contains no such call.
|
||||
*/
|
||||
public static void redirect(ClassNode node, String owner, String name, String newOwner)
|
||||
{
|
||||
int redirected = 0;
|
||||
|
||||
for (MethodNode method : node.methods) {
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction instanceof MethodInsnNode call && call.owner.equals(owner) && call.name.equals(name)) {
|
||||
call.owner = newOwner;
|
||||
redirected++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (redirected == 0) throw new IllegalStateException("No call to '" + owner + "." + name + "' in '" + node.name + "'.");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.Label;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
|
||||
@@ -10,6 +10,8 @@ dependencies {
|
||||
implementation(project(":api"))
|
||||
compileOnly(files(projectZomboid.serverJar))
|
||||
|
||||
// ModCommandsTest checks command classes against the game's command framework.
|
||||
testImplementation(files(projectZomboid.serverJar))
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package dev.overlord.zomboidforge.compat.b42;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
|
||||
import dev.overlord.zomboidforge.core.Forge;
|
||||
|
||||
/** The one {@link Forge} of the server, shared by the hook classes. */
|
||||
public final class ForgeInstance
|
||||
{
|
||||
public static final Forge FORGE = Forge.fromSystemProperties(
|
||||
ModCommands::check, ClientCommandChannel::prepare
|
||||
);
|
||||
|
||||
private ForgeInstance() {}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import dev.overlord.zomboidforge.api.PlayerRef;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
|
||||
import zombie.Lua.LuaManager;
|
||||
import zombie.characters.IsoPlayer;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Client commands in Build 42: players as {@link PlayerRef}s, and server commands to clients. */
|
||||
public final class ClientCommandChannel
|
||||
{
|
||||
private ClientCommandChannel() {}
|
||||
|
||||
public static PlayerRef ref(IsoPlayer player) { return new PlayerRef(player.getOnlineID(), player.getUsername()); }
|
||||
|
||||
/**
|
||||
* Copies {@code args} at once and returns the action that sends the command with
|
||||
* {@code GameServer.sendServerCommand}, to every connection when {@code player} is
|
||||
* {@code null}. The action runs on the main thread and sends nothing when the player is no
|
||||
* longer connected.
|
||||
*
|
||||
* @throws IllegalArgumentException naming a key or value that cannot be sent
|
||||
*/
|
||||
public static Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args)
|
||||
{
|
||||
Map<Object, Object> copy = LuaTables.copy(args);
|
||||
|
||||
return () ->
|
||||
{
|
||||
KahluaTable table = copy.isEmpty() ? null : LuaTables.toLua(copy, LuaManager.platform::newTable);
|
||||
|
||||
if (player == null) {
|
||||
GameServer.sendServerCommand(module, command, table);
|
||||
return;
|
||||
}
|
||||
|
||||
IsoPlayer target = ClientCommandChannel.find(player);
|
||||
if (target != null) GameServer.sendServerCommand(target, module, command, table);
|
||||
};
|
||||
}
|
||||
|
||||
/** The connected player with the online id and the username of {@code player}, or {@code null}. Main thread. */
|
||||
private static @Nullable IsoPlayer find(PlayerRef player)
|
||||
{
|
||||
Object connected = GameServer.IDToPlayerMap.get((short) player.onlineId());
|
||||
|
||||
return connected instanceof IsoPlayer target && player.username().equals(target.getUsername()) ? target : null;
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
import se.krka.kahlua.vm.KahluaTableIterator;
|
||||
|
||||
import zombie.inventory.InventoryItem;
|
||||
import zombie.iso.IsoDirections;
|
||||
import zombie.iso.objects.IsoDeadBody;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Conversion between the Kahlua tables of command arguments and the Java maps of the API. The
|
||||
* types are those {@code TableNetworkUtils} sends: {@code String} and {@code Double} keys;
|
||||
* {@code String}, {@code Double}, {@code Boolean}, table, {@code InventoryItem},
|
||||
* {@code IsoDirections}, and {@code IsoDeadBody} values.
|
||||
*/
|
||||
public final class LuaTables
|
||||
{
|
||||
private LuaTables() {}
|
||||
|
||||
/** {@code table} as an unmodifiable map, nested tables as nested maps; empty for {@code null}. */
|
||||
public static Map<Object, Object> toJava(@Nullable KahluaTable table)
|
||||
{
|
||||
if (table == null) return Map.of();
|
||||
|
||||
Map<Object, Object> map = new LinkedHashMap<>();
|
||||
KahluaTableIterator iterator = table.iterator();
|
||||
|
||||
while (iterator.advance())
|
||||
{
|
||||
Object value = iterator.getValue();
|
||||
map.put(iterator.getKey(), value instanceof KahluaTable nested ? LuaTables.toJava(nested) : value);
|
||||
}
|
||||
|
||||
return Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* A deep, unmodifiable copy of {@code args} in Lua's types: number keys and values become
|
||||
* {@code Double}, lists become maps with the keys {@code 1.0}, {@code 2.0}, ....
|
||||
*
|
||||
* @throws IllegalArgumentException naming the first key or value that cannot be sent, or a
|
||||
* map or list that contains itself
|
||||
*/
|
||||
public static Map<Object, Object> copy(Map<?, ?> args) { return LuaTables.copy(args, "args", Collections.newSetFromMap(new IdentityHashMap<>())); }
|
||||
|
||||
/** A new table with the entries of {@code args}, a result of {@link #copy}; nested maps become nested tables. */
|
||||
public static KahluaTable toLua(Map<Object, Object> args, Supplier<KahluaTable> newTable)
|
||||
{
|
||||
KahluaTable table = newTable.get();
|
||||
|
||||
for (Map.Entry<Object, Object> entry : args.entrySet())
|
||||
{
|
||||
Object value = entry.getValue();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Object luaValue = value instanceof Map<?, ?> nested ? LuaTables.toLua((Map<Object, Object>) nested, newTable) : value;
|
||||
|
||||
table.rawset(entry.getKey(), luaValue);
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static Map<Object, Object> copy(Map<?, ?> map, String path, Set<Object> open)
|
||||
{
|
||||
if (!open.add(map)) throw new IllegalArgumentException("'" + path + "' contains itself.");
|
||||
|
||||
Map<Object, Object> copy = new LinkedHashMap<>();
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet())
|
||||
{
|
||||
Object key = LuaTables.key(entry.getKey(), path);
|
||||
String here = path + "[" + key + "]";
|
||||
|
||||
copy.put(key, LuaTables.value(entry.getValue(), here, open));
|
||||
}
|
||||
|
||||
open.remove(map);
|
||||
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
private static Map<Object, Object> copy(List<?> list, String path, Set<Object> open)
|
||||
{
|
||||
if (!open.add(list)) throw new IllegalArgumentException("'" + path + "' contains itself.");
|
||||
|
||||
Map<Object, Object> copy = new LinkedHashMap<>();
|
||||
|
||||
for (int i = 0; i < list.size(); i++) copy.put((double) (i + 1), LuaTables.value(list.get(i), path + "[" + (i + 1) + "]", open));
|
||||
|
||||
open.remove(list);
|
||||
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
private static Object key(@Nullable Object key, String path)
|
||||
{
|
||||
if (key instanceof String) return key;
|
||||
if (key instanceof Number number) return number.doubleValue();
|
||||
|
||||
throw new IllegalArgumentException("'" + path + "' has the key '" + key + "'" + LuaTables.typeOf(key) + "; keys are strings or numbers.");
|
||||
}
|
||||
|
||||
private static Object value(@Nullable Object value, String path, Set<Object> open)
|
||||
{
|
||||
return switch (value)
|
||||
{
|
||||
case String string -> string;
|
||||
case Boolean bool -> bool;
|
||||
case Number number -> number.doubleValue();
|
||||
case Map<?, ?> map -> LuaTables.copy(map, path, open);
|
||||
case List<?> list -> LuaTables.copy(list, path, open);
|
||||
case InventoryItem item -> item;
|
||||
case IsoDirections direction -> direction;
|
||||
case IsoDeadBody body -> body;
|
||||
case null -> throw new IllegalArgumentException("'" + path + "' is null.");
|
||||
default -> throw new IllegalArgumentException(
|
||||
"'" + path + "' is a '" + value.getClass().getName() + "'; values are strings, numbers, booleans, maps, lists, inventory items, directions, or dead bodies."
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
private static String typeOf(@Nullable Object value) { return value == null ? "" : " ('" + value.getClass().getName() + "')"; }
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import zombie.characters.Role;
|
||||
import zombie.commands.CommandBase;
|
||||
import zombie.commands.CommandName;
|
||||
import zombie.commands.RequiredCapability;
|
||||
import zombie.core.raknet.UdpConnection;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Command classes of mods in Build 42: subclasses of {@code CommandBase}, which
|
||||
* {@code GameServer.handleServerCommand} creates through {@code getConstructors()[0]} with
|
||||
* {@code (username, role, command, connection)}.
|
||||
*/
|
||||
public final class ModCommands
|
||||
{
|
||||
private static final Class<?>[] CONSTRUCTOR = {String.class, Role.class, String.class, UdpConnection.class};
|
||||
|
||||
/**
|
||||
* Names are inserted into a regular expression by {@code findCommandCls}, so they are limited
|
||||
* to word characters. With such names, {@code ^name\b} matches the input exactly when its first
|
||||
* word equals the name, ignoring case.
|
||||
*/
|
||||
private static final Pattern NAME = Pattern.compile("\\w+");
|
||||
|
||||
private ModCommands() {}
|
||||
|
||||
/**
|
||||
* Fails unless {@code command} is a usable Build 42 command whose names are not taken by
|
||||
* Project Zomboid's commands or by {@code registered}.
|
||||
*
|
||||
* @throws IllegalArgumentException listing every problem
|
||||
*/
|
||||
public static void check(Class<?> command, List<Class<?>> registered)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
int modifiers = command.getModifiers();
|
||||
|
||||
if (!CommandBase.class.isAssignableFrom(command)) problems.add("it does not extend '" + CommandBase.class.getName() + "'");
|
||||
if (!Modifier.isPublic(modifiers)) problems.add("it is not public");
|
||||
if (Modifier.isAbstract(modifiers)) problems.add("it is abstract");
|
||||
|
||||
Constructor<?>[] constructors = command.getConstructors();
|
||||
if (constructors.length != 1 || !Arrays.equals(constructors[0].getParameterTypes(), ModCommands.CONSTRUCTOR))
|
||||
problems.add("it needs exactly one public constructor '(String, Role, String, UdpConnection)'");
|
||||
|
||||
if (command.getAnnotationsByType(RequiredCapability.class).length == 0)
|
||||
problems.add("it has no @RequiredCapability, and Project Zomboid runs no command without one");
|
||||
|
||||
CommandName[] names = command.getAnnotationsByType(CommandName.class);
|
||||
if (names.length == 0) problems.add("it has no @CommandName");
|
||||
|
||||
for (CommandName name : names)
|
||||
{
|
||||
if (!ModCommands.NAME.matcher(name.name()).matches()) {
|
||||
problems.add("the name '" + name.name() + "' contains characters other than letters, digits, and '_'");
|
||||
continue;
|
||||
}
|
||||
|
||||
Class<?> owner = ModCommands.owner(name.name(), registered);
|
||||
if (owner != null) problems.add("the name '" + name.name() + "' is taken by '" + owner.getName() + "'");
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException("'" + command.getName() + "' cannot be a command: " + String.join("; ", problems) + ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* The first class of {@code commands} that is not disabled and has a name that {@code input}
|
||||
* starts with, matched like {@code CommandBase.findCommandCls} matches Project Zomboid's
|
||||
* commands; {@code null} when there is none.
|
||||
*/
|
||||
public static @Nullable Class<?> find(List<Class<?>> commands, String input)
|
||||
{
|
||||
for (Class<?> command : commands)
|
||||
{
|
||||
if (CommandBase.isDisabled(command)) continue;
|
||||
|
||||
for (CommandName name : command.getAnnotationsByType(CommandName.class)) {
|
||||
if (Pattern.compile("^" + name.name() + "\\b", Pattern.CASE_INSENSITIVE).matcher(input).find()) return command;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The class among Project Zomboid's commands and {@code registered} that has {@code name}, ignoring case. */
|
||||
private static @Nullable Class<?> owner(String name, List<Class<?>> registered)
|
||||
{
|
||||
Set<Class<?>> taken = new LinkedHashSet<>(Arrays.<Class<?>>asList(CommandBase.getSubClasses()));
|
||||
taken.addAll(registered);
|
||||
|
||||
for (Class<?> command : taken)
|
||||
{
|
||||
for (CommandName existing : command.getAnnotationsByType(CommandName.class)) {
|
||||
if (existing.name().equalsIgnoreCase(name)) return command;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Commands of mods in Build 42: checks for registered admin command classes and the lookup that
|
||||
* mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion
|
||||
* of their Lua tables.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ClientCommandEvent;
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.LuaTables;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
|
||||
import zombie.characters.IsoPlayer;
|
||||
|
||||
/**
|
||||
* Hooks called by patched {@code zombie.network.GameServer.receiveClientCommand} code, on the main
|
||||
* thread (client commands are queued for the main loop). Exceptions are caught here; the command
|
||||
* then reaches Lua as in vanilla.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public final class ClientCommandHooks
|
||||
{
|
||||
private ClientCommandHooks() {}
|
||||
|
||||
/**
|
||||
* Called directly before {@code LuaEventManager.triggerEvent("OnClientCommand", module, command, player, args)},
|
||||
* after the vanilla checks (the player exists; {@code vehicle.remove} only with permission).
|
||||
* Posts {@link ClientCommandEvent} when a mod listens for it.
|
||||
*
|
||||
* @param args {@code null} when the client sent no arguments
|
||||
* @return {@code true} when a listener cancelled the event, which skips the Lua event
|
||||
*/
|
||||
public static boolean onClientCommand(String module, String command, IsoPlayer player, @Nullable KahluaTable args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ForgeInstance.FORGE.hasListeners(ClientCommandEvent.class)) return false;
|
||||
|
||||
ClientCommandEvent event = new ClientCommandEvent(
|
||||
ClientCommandChannel.ref(player),
|
||||
module, command,
|
||||
LuaTables.toJava(args)
|
||||
);
|
||||
|
||||
ForgeInstance.FORGE.post(event);
|
||||
|
||||
return event.isCancelled();
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
t.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Hooks called by patched {@code zombie.commands.CommandBase} code, on the main thread: the
|
||||
* server console, RCON, and chat commands all run there. Exceptions are caught here, and the
|
||||
* vanilla value is returned.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public final class CommandHooks
|
||||
{
|
||||
private CommandHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces the {@code null} that {@code CommandBase.findCommandCls} returns when no command of
|
||||
* Project Zomboid matches {@code command}: the mods' command class for it, or {@code null}.
|
||||
*/
|
||||
public static @Nullable Class<?> findCommand(@Nullable Class<?> vanilla, String command)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ModCommands.find(ForgeInstance.FORGE.commands(), command);
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
t.printStackTrace();
|
||||
return vanilla;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the array that {@code CommandBase.getSubClasses} returns: Project Zomboid's
|
||||
* command classes followed by the mods', in registration order. Without mod commands, the
|
||||
* vanilla array itself.
|
||||
*/
|
||||
public static Class<?>[] listCommands(Class<?>[] vanilla)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<Class<?>> mods = ForgeInstance.FORGE.commands();
|
||||
if (mods.isEmpty()) return vanilla;
|
||||
|
||||
Class<?>[] all = Arrays.copyOf(vanilla, vanilla.length + mods.size());
|
||||
for (int i = 0; i < mods.size(); i++) all[vanilla.length + i] = mods.get(i);
|
||||
|
||||
return all;
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
t.printStackTrace();
|
||||
return vanilla;
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
-3
@@ -1,17 +1,110 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.api.ZomboidForge;
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.storage.StorageDatabase;
|
||||
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||
|
||||
/** Hooks called by patched {@code zombie.network.GameServer} code. */
|
||||
import zombie.ZomboidFileSystem;
|
||||
import zombie.core.Core;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Hooks called by patched {@code zombie.network.GameServer} code and its shutdown hook
|
||||
* {@code GameServer$1}. Exceptions are caught here: the main loop logs repeated exceptions only
|
||||
* a limited number of times, and an exception in the shutdown hook would skip the world save.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public final class ServerHooks
|
||||
{
|
||||
private ServerHooks() {}
|
||||
|
||||
/**
|
||||
* Called once on the main thread in {@code GameServer.main}, directly after
|
||||
* {@code ServerOptions.instance.init()}: logging is set up, and the server name and cache
|
||||
* directory are known. The Workshop download, the server database, Lua, and the world come
|
||||
* later. Loads the mods.
|
||||
*
|
||||
* @return {@code false} to stop the server; the patched code then removes the vanilla
|
||||
* shutdown hook and exits with code 1
|
||||
*/
|
||||
public static boolean onLoad()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.out.println("[ZomboidForge] " + ZomboidForge.VERSION + " loading mods.");
|
||||
|
||||
GameVersion game = GameVersion.parse(Core.getInstance().getGameAndBuildVersion());
|
||||
Path gameJar = Path.of(Core.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
|
||||
// The save folder ZipBackup zips. getCurrentSaveDir() depends on Core.gameMode, which GameServer.main sets to "Multiplayer" only later.
|
||||
Path storage = Path.of(ZomboidFileSystem.instance.getCacheDir(), "Saves", "Multiplayer", GameServer.serverName, StorageDatabase.FILE);
|
||||
|
||||
ForgeInstance.FORGE.load(game, gameJar, ServerHooks.class.getClassLoader(), storage);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (ModLoadException e)
|
||||
{
|
||||
System.out.println("[ZomboidForge] Cannot load the mods, stopping the server:");
|
||||
e.problems().forEach(problem -> System.out.println("[ZomboidForge] " + problem));
|
||||
if (e.getCause() != null) e.getCause().printStackTrace();
|
||||
|
||||
return false;
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
System.out.println("[ZomboidForge] Startup failed, stopping the server.");
|
||||
t.printStackTrace();
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called once on the main thread, after the world is loaded, the network port is open, and
|
||||
* RCON is initialized; directly before the main loop starts.
|
||||
*/
|
||||
public static void onServerStarted() {
|
||||
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
|
||||
public static void onServerStarted()
|
||||
{
|
||||
try
|
||||
{
|
||||
ForgeInstance.FORGE.started();
|
||||
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
|
||||
}
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Called on the main thread for every frame of the main loop, directly after
|
||||
* {@code ServerMap.instance.preupdate()}, inside the {@code frameStep} profiling probe. Not
|
||||
* called while the update limiter skips a frame. Posts the tick event and runs the mods'
|
||||
* queued main-thread tasks.
|
||||
*/
|
||||
public static void onTick()
|
||||
{
|
||||
try { ForgeInstance.FORGE.tick(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Called once on the shutdown hook thread ({@code GameServer$1}), after
|
||||
* {@code GameServer.done = true} and before {@code ServerMap.instance.QueuedQuit()} saves the
|
||||
* world. Both ways the server stops lead here: the {@code quit} command makes
|
||||
* {@code ServerMap.preupdate()} call {@code System.exit(0)}, and SIGTERM or SIGINT start the
|
||||
* JVM shutdown directly. In the second case the main thread may still be inside a frame. Not
|
||||
* called in soft-reset mode.
|
||||
*/
|
||||
public static void onStopping()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.out.println("[ZomboidForge] Server stopping.");
|
||||
ForgeInstance.FORGE.stopping();
|
||||
}
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
|
||||
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public final class StorageHooks
|
||||
{
|
||||
private StorageHooks() {}
|
||||
|
||||
/**
|
||||
* Called by the patched {@code ZipBackup.makeBackupFile} on the thread that makes the backup:
|
||||
* with {@code true} before the vanilla method, with {@code false} after it, also when it threw.
|
||||
* Storage writes wait in between, so the zipped {@code zomboidforge.db} is complete.
|
||||
*/
|
||||
public static void backupRunning(boolean running)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (running) ForgeInstance.FORGE.backupStarted();
|
||||
else ForgeInstance.FORGE.backupFinished();
|
||||
}
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -33,10 +33,8 @@ public final class ZombieVehicleHooks
|
||||
* and is skipped here.
|
||||
*/
|
||||
public static @Nullable Vector3f getIntersectPoint(
|
||||
@NotNull BaseVehicle vehicle,
|
||||
@NotNull Vector3f start,
|
||||
@NotNull Vector3f end,
|
||||
@Nullable Vector3f result
|
||||
BaseVehicle vehicle, Vector3f start,
|
||||
Vector3f end, @Nullable Vector3f result
|
||||
) {
|
||||
VehicleScript script = vehicle.getScript();
|
||||
Vector3f extents = script.getExtents();
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import se.krka.kahlua.j2se.KahluaTableImpl;
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
|
||||
import zombie.iso.IsoDirections;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Runs against the Kahlua classes of the server jar; {@code LuaManager.platform} is not used. */
|
||||
class LuaTablesTest
|
||||
{
|
||||
private static final Supplier<KahluaTable> NEW_TABLE = () -> new KahluaTableImpl(new HashMap<>());
|
||||
|
||||
@Test
|
||||
void convertsTablesToUnmodifiableMaps()
|
||||
{
|
||||
KahluaTable items = LuaTablesTest.NEW_TABLE.get();
|
||||
items.rawset(1.0, "Base.Axe");
|
||||
items.rawset(2.0, "Base.Saw");
|
||||
|
||||
KahluaTable table = LuaTablesTest.NEW_TABLE.get();
|
||||
table.rawset("count", 3.0);
|
||||
table.rawset("gift", true);
|
||||
table.rawset("facing", IsoDirections.N);
|
||||
table.rawset("items", items);
|
||||
|
||||
Map<Object, Object> args = LuaTables.toJava(table);
|
||||
|
||||
assertEquals(Map.of("count", 3.0, "gift", true, "facing", IsoDirections.N, "items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw")), args);
|
||||
assertThrows(UnsupportedOperationException.class, () -> args.put("x", "y"));
|
||||
assertThrows(UnsupportedOperationException.class, () -> ((Map<?, ?>) args.get("items")).clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertsMissingArgumentsToAnEmptyMap()
|
||||
{
|
||||
assertEquals(Map.of(), LuaTables.toJava(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void copiesJavaValuesInLuaTypes()
|
||||
{
|
||||
Map<String, Object> args = new LinkedHashMap<>();
|
||||
args.put("count", 3);
|
||||
args.put("price", 2.5F);
|
||||
args.put("items", List.of("Base.Axe", "Base.Saw"));
|
||||
args.put("seller", Map.of("name", "alice", 7, false));
|
||||
|
||||
assertEquals(
|
||||
Map.of(
|
||||
"count", 3.0,
|
||||
"price", 2.5,
|
||||
"items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw"),
|
||||
"seller", Map.of("name", "alice", 7.0, false)
|
||||
),
|
||||
LuaTables.copy(args)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void copiesAtOnceSoLaterChangesAreNotSent()
|
||||
{
|
||||
Map<String, Object> args = new HashMap<>(Map.of("count", 1));
|
||||
Map<Object, Object> copy = LuaTables.copy(args);
|
||||
|
||||
args.put("count", 2);
|
||||
|
||||
assertEquals(Map.of("count", 1.0), copy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildsNestedTablesFromACopy()
|
||||
{
|
||||
KahluaTable table = LuaTables.toLua(LuaTables.copy(Map.of("count", 3, "items", List.of("Base.Axe"))), LuaTablesTest.NEW_TABLE);
|
||||
|
||||
assertEquals(3.0, table.rawget("count"));
|
||||
|
||||
KahluaTable items = (KahluaTable) table.rawget("items");
|
||||
assertEquals("Base.Axe", items.rawget(1.0));
|
||||
assertNull(items.rawget(2.0));
|
||||
assertEquals(1, items.len());
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesTheFirstValueThatCannotBeSent()
|
||||
{
|
||||
IllegalArgumentException e = assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> LuaTables.copy(Map.of("seller", Map.of("since", new Object())))
|
||||
);
|
||||
|
||||
assertTrue(e.getMessage().startsWith("'args[seller][since]' is a 'java.lang.Object'; values are strings, numbers, booleans,"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNullValuesOtherKeysAndCycles()
|
||||
{
|
||||
Map<Object, Object> withNull = new HashMap<>();
|
||||
withNull.put("name", null);
|
||||
|
||||
Map<Object, Object> withObjectKey = new HashMap<>();
|
||||
withObjectKey.put(true, "yes");
|
||||
|
||||
List<Object> cycle = new ArrayList<>();
|
||||
cycle.add(cycle);
|
||||
|
||||
assertEquals("'args[name]' is null.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withNull)).getMessage());
|
||||
assertEquals(
|
||||
"'args' has the key 'true' ('java.lang.Boolean'); keys are strings or numbers.",
|
||||
assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withObjectKey)).getMessage()
|
||||
);
|
||||
assertEquals("'args[list][1]' contains itself.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(Map.of("list", cycle))).getMessage());
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.characters.Capability;
|
||||
import zombie.characters.Role;
|
||||
import zombie.commands.CommandBase;
|
||||
import zombie.commands.CommandName;
|
||||
import zombie.commands.DisabledCommand;
|
||||
import zombie.commands.RequiredCapability;
|
||||
import zombie.core.raknet.UdpConnection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** Runs against the classes of the server jar that the module compiles against. */
|
||||
class ModCommandsTest
|
||||
{
|
||||
@CommandName(name = "zfshop")
|
||||
@CommandName(name = "zfbuy")
|
||||
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||
public static final class ShopCommand extends CommandBase
|
||||
{
|
||||
public ShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||
|
||||
@Override
|
||||
protected String Command() { return "shop"; }
|
||||
}
|
||||
|
||||
@CommandName(name = "ZFSHOP")
|
||||
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||
public static final class OtherShopCommand extends CommandBase
|
||||
{
|
||||
public OtherShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||
|
||||
@Override
|
||||
protected String Command() { return "other shop"; }
|
||||
}
|
||||
|
||||
@CommandName(name = "Save")
|
||||
@CommandName(name = "zf-save")
|
||||
@RequiredCapability(requiredCapability = Capability.SaveWorld)
|
||||
public static final class SaveCommand extends CommandBase
|
||||
{
|
||||
public SaveCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||
|
||||
@Override
|
||||
protected String Command() { return "save"; }
|
||||
}
|
||||
|
||||
@DisabledCommand
|
||||
@CommandName(name = "zfoff")
|
||||
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||
public static final class DisabledShopCommand extends CommandBase
|
||||
{
|
||||
public DisabledShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||
|
||||
@Override
|
||||
protected String Command() { return "off"; }
|
||||
}
|
||||
|
||||
/** Neither a command nor annotated; its constructor has no parameters. */
|
||||
public static final class NotACommand {}
|
||||
|
||||
@Test
|
||||
void acceptsAUsableCommand()
|
||||
{
|
||||
assertDoesNotThrow(() -> ModCommands.check(ModCommandsTest.ShopCommand.class, List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsEveryProblemOfAClassThatIsNoCommand()
|
||||
{
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.NotACommand.class, List.of()));
|
||||
|
||||
assertEquals(
|
||||
"'" + ModCommandsTest.NotACommand.class.getName() + "' cannot be a command: it does not extend 'zombie.commands.CommandBase';"
|
||||
+ " it needs exactly one public constructor '(String, Role, String, UdpConnection)';"
|
||||
+ " it has no @RequiredCapability, and Project Zomboid runs no command without one; it has no @CommandName.",
|
||||
e.getMessage()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNamesOfProjectZomboidIgnoringCaseAndNamesWithOtherCharacters()
|
||||
{
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.SaveCommand.class, List.of()));
|
||||
|
||||
assertEquals(
|
||||
"'" + ModCommandsTest.SaveCommand.class.getName() + "' cannot be a command:"
|
||||
+ " the name 'Save' is taken by 'zombie.commands.serverCommands.SaveCommand';"
|
||||
+ " the name 'zf-save' contains characters other than letters, digits, and '_'.",
|
||||
e.getMessage()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNamesOfRegisteredCommands()
|
||||
{
|
||||
IllegalArgumentException e = assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> ModCommands.check(ModCommandsTest.OtherShopCommand.class, List.of(ModCommandsTest.ShopCommand.class))
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
"'" + ModCommandsTest.OtherShopCommand.class.getName() + "' cannot be a command: the name 'ZFSHOP' is taken by '" + ModCommandsTest.ShopCommand.class.getName() + "'.",
|
||||
e.getMessage()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsCommandsByTheirFirstWordIgnoringCase()
|
||||
{
|
||||
List<Class<?>> commands = List.of(ModCommandsTest.DisabledShopCommand.class, ModCommandsTest.ShopCommand.class);
|
||||
|
||||
assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "zfshop"));
|
||||
assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "ZFBuy apple 3"));
|
||||
assertNull(ModCommands.find(commands, "zfshopping"));
|
||||
assertNull(ModCommands.find(commands, "zfoff"), "disabled commands are skipped, like Project Zomboid's");
|
||||
}
|
||||
}
|
||||
@@ -6,4 +6,18 @@ plugins {
|
||||
|
||||
dependencies {
|
||||
implementation(project(":api"))
|
||||
implementation(libs.night.config.toml)
|
||||
implementation(libs.asm)
|
||||
|
||||
testImplementation(libs.bundles.asm)
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
// At runtime the game jar provides the driver.
|
||||
testRuntimeOnly(libs.sqlite.jdbc)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// The SQLite JDBC driver loads a native library; the server runs with the same flag.
|
||||
jvmArgs("--enable-native-access=ALL-UNNAMED")
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package dev.overlord.zomboidforge.core;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
/**
|
||||
* {@link System.Logger} that prints {@code [<name>] message} to standard output, which the
|
||||
* Project Zomboid log captures. Levels below {@code INFO} are dropped; other levels than
|
||||
* {@code INFO} are written before the message.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public final class ConsoleLogger implements System.Logger
|
||||
{
|
||||
private final String name;
|
||||
|
||||
public ConsoleLogger(String name) { this.name = name; }
|
||||
|
||||
@Override
|
||||
public String getName() { return this.name; }
|
||||
|
||||
@Override
|
||||
public boolean isLoggable(Level level) { return level != Level.OFF && level.getSeverity() >= Level.INFO.getSeverity(); }
|
||||
|
||||
@Override
|
||||
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String message, @Nullable Throwable thrown)
|
||||
{
|
||||
if (!this.isLoggable(level)) return;
|
||||
|
||||
String prefix = level == Level.INFO ? "" : level.getName() + ": ";
|
||||
System.out.println("[" + this.name + "] " + prefix + message);
|
||||
|
||||
if (thrown != null) thrown.printStackTrace();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(
|
||||
Level level,
|
||||
@Nullable ResourceBundle bundle,
|
||||
@Nullable String format,
|
||||
@Nullable Object @Nullable ... parameters
|
||||
) {
|
||||
String message = format == null || parameters == null || parameters.length == 0
|
||||
? format
|
||||
: MessageFormat.format(format, parameters);
|
||||
|
||||
this.log(level, bundle, message, (Throwable) null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package dev.overlord.zomboidforge.core;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Event;
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.api.MainThread;
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.TickEvent;
|
||||
import dev.overlord.zomboidforge.api.ZomboidForge;
|
||||
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||
import dev.overlord.zomboidforge.core.commands.ClientCommandSender;
|
||||
import dev.overlord.zomboidforge.core.commands.CommandRegistry;
|
||||
import dev.overlord.zomboidforge.core.commands.ModClientCommands;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||
import dev.overlord.zomboidforge.core.mods.ModLoader;
|
||||
import dev.overlord.zomboidforge.core.mods.ModResolver;
|
||||
import dev.overlord.zomboidforge.core.mods.ModServices;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVerifier;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||
import dev.overlord.zomboidforge.core.runtime.EventBus;
|
||||
import dev.overlord.zomboidforge.core.runtime.MainThreadQueue;
|
||||
import dev.overlord.zomboidforge.core.runtime.ModThreads;
|
||||
import dev.overlord.zomboidforge.core.storage.ModTables;
|
||||
import dev.overlord.zomboidforge.core.storage.StorageDatabase;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* ZomboidForge inside a running server: the lifecycle phase, the loaded mods, and their threads
|
||||
* and events. The compat hooks call {@link #load}, {@link #started()}, {@link #tick()}, and
|
||||
* {@link #stopping()}.
|
||||
*/
|
||||
public final class Forge
|
||||
{
|
||||
/** System property with the ZomboidForge directory, which contains {@code mods/}. */
|
||||
public static final String DIRECTORY_PROPERTY = "zomboidforge.dir";
|
||||
public static final String DEFAULT_DIRECTORY = "/forge";
|
||||
|
||||
private static final String MODS = "mods";
|
||||
|
||||
private final Lifecycle lifecycle = new Lifecycle();
|
||||
private final System.Logger logger = new ConsoleLogger("ZomboidForge");
|
||||
private final MainThreadQueue queue = new MainThreadQueue(ForgeSettings.DEFAULTS.mainThreadBudget());
|
||||
private final EventBus events = new EventBus();
|
||||
private final ModThreads threads = new ModThreads();
|
||||
|
||||
private final Path directory;
|
||||
private final @Nullable ModVersion api;
|
||||
private final CommandRegistry commands;
|
||||
private final ClientCommandSender clientCommands;
|
||||
|
||||
private volatile List<ModLoader.LoadedMod> mods = List.of();
|
||||
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
|
||||
private volatile @Nullable StorageDatabase storage;
|
||||
|
||||
/**
|
||||
* @param directory the ZomboidForge directory
|
||||
* @param api the API version mods are checked against, or {@code null} to skip the
|
||||
* check
|
||||
* @param commands checks the command classes that mods register against the running
|
||||
* game version
|
||||
* @param clientCommands sends the mods' server commands to clients in the running game version
|
||||
*/
|
||||
public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands, ClientCommandSender clientCommands)
|
||||
{
|
||||
this.directory = directory;
|
||||
this.api = api;
|
||||
this.commands = new CommandRegistry(commands, this::commandsOpen);
|
||||
this.clientCommands = clientCommands;
|
||||
}
|
||||
|
||||
/**
|
||||
* Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API
|
||||
* version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev},
|
||||
* {@code 0.0.0-...}) skip the API check.
|
||||
*
|
||||
* @param commands checks the command classes that mods register against the running
|
||||
* game version
|
||||
* @param clientCommands sends the mods' server commands to clients in the running game version
|
||||
*/
|
||||
public static Forge fromSystemProperties(CommandRegistry.Validator commands, ClientCommandSender clientCommands)
|
||||
{
|
||||
Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY));
|
||||
ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION)
|
||||
.filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0)
|
||||
.orElse(null);
|
||||
|
||||
return new Forge(directory, api, commands, clientCommands);
|
||||
}
|
||||
|
||||
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
||||
|
||||
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
||||
|
||||
/** The admin command classes that mods registered, in registration order. */
|
||||
public List<Class<?>> commands() { return this.commands.classes(); }
|
||||
|
||||
/**
|
||||
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
|
||||
* {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
|
||||
* {@code main()}. When a mod fails, the threads of the mods created so far are stopped.
|
||||
*
|
||||
* @param gameJar the Project Zomboid jar the server runs
|
||||
* @param parent parent of the mods' class loaders; loads the game, the API, and ZomboidForge
|
||||
* @param storageFile the world's {@code zomboidforge.db}; created when a mod first uses storage
|
||||
* @throws ModLoadException listing every problem found
|
||||
*/
|
||||
public void load(GameVersion game, Path gameJar, ClassLoader parent, Path storageFile) throws ModLoadException
|
||||
{
|
||||
Path modsDirectory = this.directory.resolve(Forge.MODS);
|
||||
|
||||
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); }
|
||||
|
||||
this.queue.budget(this.settings.mainThreadBudget());
|
||||
this.queue.bindToCurrentThread();
|
||||
|
||||
if (this.api == null) this.logger.log(System.Logger.Level.WARNING, "ZomboidForge " + ZomboidForge.VERSION + " is not a release; the API versions of mods are not checked.");
|
||||
|
||||
List<ModDiscovery.Candidate> candidates = Files.isDirectory(modsDirectory)
|
||||
? ModDiscovery.discover(modsDirectory, this.logger)
|
||||
: List.of();
|
||||
|
||||
List<String> disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).toList();
|
||||
if (!disabled.isEmpty()) this.logger.log(System.Logger.Level.INFO, "Disabled in config.toml: " + String.join(", ", disabled) + ".");
|
||||
|
||||
List<ModDiscovery.Candidate> ordered = ModResolver.resolve(candidates, game, this.api);
|
||||
List<String> installed = candidates.stream().map(ModDiscovery.Candidate::id).toList();
|
||||
StorageDatabase storage = new StorageDatabase(storageFile, this::storageForbidden);
|
||||
|
||||
this.storage = storage;
|
||||
|
||||
try (GameClasses gameClasses = GameClasses.open(gameJar))
|
||||
{
|
||||
ModVerifier.verify(ordered, gameClasses, game);
|
||||
|
||||
for (ModDiscovery.Candidate candidate : ordered) ModTables.adoptPreviousIds(storage, candidate.id(), candidate.descriptor().previousIds(), installed);
|
||||
|
||||
this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
this.stopMods(Duration.ZERO);
|
||||
throw new ModLoadException("Cannot read the Project Zomboid jar '" + gameJar + "': " + e.getMessage(), e);
|
||||
}
|
||||
catch (StorageException e)
|
||||
{
|
||||
this.stopMods(Duration.ZERO);
|
||||
throw new ModLoadException(e.getMessage() == null ? e.toString() : e.getMessage(), e);
|
||||
}
|
||||
catch (ModLoadException | RuntimeException e)
|
||||
{
|
||||
this.stopMods(Duration.ZERO);
|
||||
throw e;
|
||||
}
|
||||
|
||||
this.lifecycle.loaded();
|
||||
|
||||
this.logger.log(System.Logger.Level.INFO, this.mods.isEmpty()
|
||||
? "No mods in '" + modsDirectory + "'."
|
||||
: "Loaded " + this.mods.size() + " mod(s): " + this.mods.stream().map(mod -> mod.descriptor().id() + " " + mod.descriptor().version()).collect(Collectors.joining(", ")) + "."
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. Anything a
|
||||
* mod throws is logged, and the next mod is called.
|
||||
*/
|
||||
public void started()
|
||||
{
|
||||
this.lifecycle.started();
|
||||
|
||||
for (ModLoader.LoadedMod mod : this.mods) {
|
||||
try { mod.mod().onServerStarted(); }
|
||||
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts {@link TickEvent} (only when a listener exists), then runs queued main-thread tasks
|
||||
* within the budget. Main thread, once per frame of the main loop.
|
||||
*/
|
||||
public void tick()
|
||||
{
|
||||
if (this.events.hasListeners(TickEvent.class)) this.events.post(new TickEvent(this.queue.tick() + 1));
|
||||
|
||||
this.queue.drain();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers {@code event} to the mods' listeners: main listeners run now on the calling
|
||||
* thread, which must be the main thread; mod-thread listeners get a task on their mod's
|
||||
* thread.
|
||||
*/
|
||||
public void post(Event event) { this.events.post(event); }
|
||||
|
||||
/** Whether any mod listens for {@code type}, so a hook can skip creating the event. */
|
||||
public boolean hasListeners(Class<? extends Event> type) { return this.events.hasListeners(type); }
|
||||
|
||||
/**
|
||||
* Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}).
|
||||
* Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup.
|
||||
*/
|
||||
public void backupStarted()
|
||||
{
|
||||
StorageDatabase storage = this.storage;
|
||||
if (storage == null) return;
|
||||
|
||||
String problem = storage.backupStarted();
|
||||
if (problem != null) this.logger.log(System.Logger.Level.WARNING, problem);
|
||||
}
|
||||
|
||||
/** Resumes storage after {@link #backupStarted()}; same thread. */
|
||||
public void backupFinished()
|
||||
{
|
||||
StorageDatabase storage = this.storage;
|
||||
if (storage != null) storage.backupFinished();
|
||||
}
|
||||
|
||||
/**
|
||||
* Once: calls {@link Mod#onStopping()} of every mod in reverse load order, then stops the
|
||||
* mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread,
|
||||
* before the world is saved, so nothing a mod throws leaves this method.
|
||||
*/
|
||||
public void stopping()
|
||||
{
|
||||
if (!this.lifecycle.stopping()) return;
|
||||
|
||||
try
|
||||
{
|
||||
for (ModLoader.LoadedMod mod : this.mods.reversed()) {
|
||||
try { mod.mod().onStopping(); }
|
||||
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", t); }
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.stopMods(this.settings.shutdownTimeout());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects further main-thread tasks and cancels the queued ones, stops event delivery, gives
|
||||
* the mods' threads {@code timeout} to finish before they are interrupted, and closes the
|
||||
* storage.
|
||||
*/
|
||||
private void stopMods(Duration timeout)
|
||||
{
|
||||
this.queue.close();
|
||||
this.events.close();
|
||||
this.threads.shutdown(timeout, this.logger);
|
||||
|
||||
StorageDatabase storage = this.storage;
|
||||
if (storage == null) return;
|
||||
|
||||
try { storage.close(); }
|
||||
catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); }
|
||||
}
|
||||
|
||||
/** Mods register commands on the main thread while they load. */
|
||||
private boolean commandsOpen() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.BOOTING; }
|
||||
|
||||
/** The main thread may use storage only before the main loop runs. */
|
||||
private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; }
|
||||
|
||||
private ModServices services(String id, System.Logger logger)
|
||||
{
|
||||
ModThreads.ModExecutors executors = this.threads.create(id, logger);
|
||||
|
||||
StorageDatabase storage = Objects.requireNonNull(this.storage, "storage");
|
||||
MainThread main = this.queue.forMod(id, logger);
|
||||
|
||||
return new ModServices(
|
||||
this.events.forMod(id, executors.modThread(), logger),
|
||||
main,
|
||||
executors.modThread(),
|
||||
executors.async(),
|
||||
new ModTables(id, storage, logger),
|
||||
this.commands.forMod(logger),
|
||||
new ModClientCommands(this.clientCommands, main)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package dev.overlord.zomboidforge.core;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Phase of a server run, advanced by the hooks in the patched game code. {@link #loaded()} and
|
||||
* {@link #started()} each happen once and in this order; {@link #stopping()} can follow any phase,
|
||||
* because the JVM can be stopped at any time.
|
||||
*/
|
||||
public final class Lifecycle
|
||||
{
|
||||
public enum Phase
|
||||
{
|
||||
/** The JVM runs; mods are not loaded yet. */
|
||||
BOOTING,
|
||||
/** Mods are loaded; the game still loads the world and opens the network port. */
|
||||
LOADED,
|
||||
/** The main loop runs. */
|
||||
RUNNING,
|
||||
/** The shutdown started; the world is about to be saved. */
|
||||
STOPPING
|
||||
}
|
||||
|
||||
private final AtomicReference<Phase> phase = new AtomicReference<>(Phase.BOOTING);
|
||||
|
||||
public Phase phase() { return this.phase.get(); }
|
||||
|
||||
/** {@link Phase#BOOTING} to {@link Phase#LOADED}. */
|
||||
public void loaded() { this.advance(Phase.BOOTING, Phase.LOADED); }
|
||||
|
||||
/** {@link Phase#LOADED} to {@link Phase#RUNNING}. */
|
||||
public void started() { this.advance(Phase.LOADED, Phase.RUNNING); }
|
||||
|
||||
/**
|
||||
* Any phase to {@link Phase#STOPPING}.
|
||||
*
|
||||
* @return {@code false} when the phase already was {@link Phase#STOPPING}
|
||||
*/
|
||||
public boolean stopping() { return this.phase.getAndSet(Phase.STOPPING) != Phase.STOPPING; }
|
||||
|
||||
private void advance(Phase from, Phase to)
|
||||
{
|
||||
Phase current = this.phase.compareAndExchange(from, to);
|
||||
|
||||
if (current != from) throw new IllegalStateException("Cannot enter phase '" + to + "' from '" + current + "', only from '" + from + "'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.overlord.zomboidforge.core.commands;
|
||||
|
||||
import dev.overlord.zomboidforge.api.PlayerRef;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Sends server commands to clients; implemented by the compat module of the running game version. */
|
||||
@FunctionalInterface
|
||||
public interface ClientCommandSender
|
||||
{
|
||||
/**
|
||||
* Checks {@code args} on the calling thread and returns the action that converts and sends
|
||||
* the command, which runs on the main thread.
|
||||
*
|
||||
* @param player the receiving player, or {@code null} for every connected client
|
||||
* @throws IllegalArgumentException naming a key or value that cannot be sent
|
||||
*/
|
||||
Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package dev.overlord.zomboidforge.core.commands;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* The admin command classes that mods registered, in registration order. What a command class
|
||||
* has to look like depends on the Project Zomboid version, so a {@link Validator} from the compat
|
||||
* module checks every class. Registration happens only while the mods load, on the main thread;
|
||||
* the compat hooks read {@link #classes()} on the main thread afterwards.
|
||||
*/
|
||||
public final class CommandRegistry
|
||||
{
|
||||
/** Checks a command class against the command framework of the running game version. */
|
||||
@FunctionalInterface
|
||||
public interface Validator
|
||||
{
|
||||
/**
|
||||
* @param registered the classes registered before, by any mod
|
||||
* @throws IllegalArgumentException naming what is wrong with {@code command}
|
||||
*/
|
||||
void check(Class<?> command, List<Class<?>> registered);
|
||||
}
|
||||
|
||||
private final Validator validator;
|
||||
private final BooleanSupplier open;
|
||||
|
||||
private volatile List<Class<?>> classes = List.of();
|
||||
|
||||
/** @param open whether registration is allowed now, on the calling thread */
|
||||
public CommandRegistry(Validator validator, BooleanSupplier open)
|
||||
{
|
||||
this.validator = Objects.requireNonNull(validator);
|
||||
this.open = Objects.requireNonNull(open);
|
||||
}
|
||||
|
||||
/** Every registered class, in registration order. */
|
||||
public List<Class<?>> classes() { return this.classes; }
|
||||
|
||||
/**
|
||||
* Registration for one mod; registered classes are logged with {@code logger}. Exceptions do
|
||||
* not name the mod: one thrown in the mod's {@code onLoad()} is reported with its id.
|
||||
*/
|
||||
public Commands forMod(System.Logger logger)
|
||||
{
|
||||
return command ->
|
||||
{
|
||||
this.register(command);
|
||||
logger.log(System.Logger.Level.INFO, "Registered the command class '" + command.getName() + "'.");
|
||||
};
|
||||
}
|
||||
|
||||
private synchronized void register(Class<?> command)
|
||||
{
|
||||
Objects.requireNonNull(command, "command");
|
||||
|
||||
if (!this.open.getAsBoolean())
|
||||
throw new IllegalStateException("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).");
|
||||
|
||||
if (this.classes.contains(command))
|
||||
throw new IllegalArgumentException("The command class '" + command.getName() + "' is registered already.");
|
||||
|
||||
this.validator.check(command, this.classes);
|
||||
|
||||
List<Class<?>> updated = new ArrayList<>(this.classes);
|
||||
updated.add(command);
|
||||
|
||||
this.classes = List.copyOf(updated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.overlord.zomboidforge.core.commands;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ClientCommands;
|
||||
import dev.overlord.zomboidforge.api.MainThread;
|
||||
import dev.overlord.zomboidforge.api.PlayerRef;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The {@link ClientCommands} of one mod: checks on the calling thread, sends through the mod's
|
||||
* {@link MainThread}, so a command sent off the main thread is one of the mod's queued tasks.
|
||||
*/
|
||||
public final class ModClientCommands implements ClientCommands
|
||||
{
|
||||
private final ClientCommandSender sender;
|
||||
private final MainThread main;
|
||||
|
||||
public ModClientCommands(ClientCommandSender sender, MainThread main)
|
||||
{
|
||||
this.sender = Objects.requireNonNull(sender);
|
||||
this.main = Objects.requireNonNull(main);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(PlayerRef player, String module, String command, Map<?, ?> args)
|
||||
{
|
||||
Objects.requireNonNull(player, "player");
|
||||
|
||||
this.main.execute(this.sender.prepare(player, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToAll(String module, String command, Map<?, ?> args)
|
||||
{
|
||||
this.main.execute(this.sender.prepare(null, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args")));
|
||||
}
|
||||
|
||||
private static String require(String value, String name)
|
||||
{
|
||||
if (Objects.requireNonNull(value, name).isEmpty()) throw new IllegalArgumentException("'" + name + "' is empty.");
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Commands of loaded mods: the registry of admin commands that the compat hooks consult, and
|
||||
* server commands to clients.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.core.commands;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -0,0 +1,70 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Global settings from {@code <forge>/forge.toml}. Every key is optional:
|
||||
*
|
||||
* <pre>
|
||||
* [main_thread]
|
||||
* budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
*
|
||||
* [shutdown]
|
||||
* timeout_s = 10 # how long mod threads get to finish when the server stops
|
||||
* </pre>
|
||||
*
|
||||
* @param mainThreadBudget at least 1 ms
|
||||
* @param shutdownTimeout 0 or more
|
||||
*/
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
{
|
||||
public static final String FILE = "forge.toml";
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
|
||||
private record MainThread(Optional<Long> budgetMs) {}
|
||||
private record Shutdown(Optional<Long> timeoutS) {}
|
||||
|
||||
/**
|
||||
* The settings in {@code file}, or {@link #DEFAULTS} when it does not exist.
|
||||
*
|
||||
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
|
||||
* of the wrong type or out of range
|
||||
*/
|
||||
public static ForgeSettings read(Path file)
|
||||
{
|
||||
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
|
||||
|
||||
Map<String, Object> values;
|
||||
|
||||
try { values = TomlTree.parse(Files.readString(file)); }
|
||||
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
|
||||
|
||||
RecordBinder binder = new RecordBinder();
|
||||
@Nullable Document document = binder.record(values, Document.class, "");
|
||||
List<String> problems = new ArrayList<>(binder.problems());
|
||||
|
||||
for (String key : binder.unknownKeys()) problems.add("Unknown key '" + key + "'.");
|
||||
|
||||
if (document == null || !problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
long budget = document.mainThread().flatMap(MainThread::budgetMs).orElse(ForgeSettings.DEFAULTS.mainThreadBudget().toMillis());
|
||||
long timeout = document.shutdown().flatMap(Shutdown::timeoutS).orElse(ForgeSettings.DEFAULTS.shutdownTimeout().toSeconds());
|
||||
|
||||
if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + ".");
|
||||
if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + ".");
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.RecordComponent;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Converts {@link TomlTree} values to records and other Java types. Collects every problem
|
||||
* instead of stopping at the first one, and records the keys no component reads.
|
||||
*/
|
||||
public final class RecordBinder
|
||||
{
|
||||
private final List<String> problems = new ArrayList<>();
|
||||
private final Set<String> unknownKeys = new TreeSet<>();
|
||||
|
||||
public List<String> problems() { return List.copyOf(this.problems); }
|
||||
|
||||
/** Dotted paths of keys that no record component reads, sorted. */
|
||||
public List<String> unknownKeys() { return List.copyOf(this.unknownKeys); }
|
||||
|
||||
/** Record component name to TOML key: {@code maxBalance} to {@code max_balance}, {@code httpPort} to {@code http_port}. */
|
||||
public static String key(String component)
|
||||
{
|
||||
StringBuilder key = new StringBuilder(component.length() + 4);
|
||||
|
||||
for (int i = 0; i < component.length(); i++)
|
||||
{
|
||||
char c = component.charAt(i);
|
||||
boolean upper = Character.isUpperCase(c);
|
||||
boolean afterLower = i > 0 && !Character.isUpperCase(component.charAt(i - 1));
|
||||
boolean wordStart = i > 0 && i + 1 < component.length() && Character.isUpperCase(component.charAt(i - 1)) && Character.isLowerCase(component.charAt(i + 1));
|
||||
|
||||
if (upper && (afterLower || wordStart)) key.append('_');
|
||||
key.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return key.toString();
|
||||
}
|
||||
|
||||
/** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */
|
||||
public <T extends Record> @Nullable T record(Map<String, Object> table, Class<T> type, String path)
|
||||
{
|
||||
RecordComponent[] components = type.getRecordComponents();
|
||||
@Nullable Object[] arguments = new Object[components.length];
|
||||
Set<String> keys = new TreeSet<>(table.keySet());
|
||||
int before = this.problems.size();
|
||||
|
||||
for (int i = 0; i < components.length; i++)
|
||||
{
|
||||
String key = RecordBinder.key(components[i].getName());
|
||||
keys.remove(key);
|
||||
|
||||
arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key));
|
||||
}
|
||||
|
||||
for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key));
|
||||
|
||||
// value() returns null only after recording a problem, so past this check no argument is null.
|
||||
if (this.problems.size() > before) return null;
|
||||
|
||||
try
|
||||
{
|
||||
Constructor<T> constructor = type.getDeclaredConstructor(Arrays.stream(components).map(RecordComponent::getType).toArray(Class<?>[]::new));
|
||||
constructor.setAccessible(true);
|
||||
|
||||
return constructor.newInstance(arguments);
|
||||
}
|
||||
catch (InvocationTargetException e)
|
||||
{
|
||||
this.problems.add("'" + (path.isEmpty() ? "<root>" : path) + "': " + type.getSimpleName() + " rejected the values: " + e.getCause() + ".");
|
||||
return null;
|
||||
}
|
||||
catch (ReflectiveOperationException e)
|
||||
{
|
||||
throw new IllegalStateException("Cannot create record '" + type.getName() + "'.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code raw} converted to {@code target}, or {@code null} after recording a problem.
|
||||
* {@code raw == null} means the key is missing.
|
||||
*/
|
||||
public @Nullable Object value(@Nullable Object raw, Type target, String path)
|
||||
{
|
||||
Class<?> type = RecordBinder.rawType(target);
|
||||
|
||||
if (type == Optional.class)
|
||||
{
|
||||
if (raw == null) return Optional.empty();
|
||||
|
||||
Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path);
|
||||
return element == null ? null : Optional.of(element);
|
||||
}
|
||||
|
||||
if (raw == null) return this.problem(path, "is missing");
|
||||
|
||||
if (type == String.class) return raw instanceof String ? raw : this.mistyped(path, "a string", raw);
|
||||
if (type == boolean.class || type == Boolean.class) return raw instanceof Boolean ? raw : this.mistyped(path, "true or false", raw);
|
||||
if (type == long.class || type == Long.class) return raw instanceof Long ? raw : this.mistyped(path, "an integer", raw);
|
||||
if (type == int.class || type == Integer.class) return this.integer(raw, path);
|
||||
if (type == double.class || type == Double.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw);
|
||||
if (type == float.class || type == Float.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw);
|
||||
if (type.isEnum()) return this.constant(raw, type, path);
|
||||
if (type.isRecord()) return raw instanceof Map<?, ?> table ? this.record(TomlTree.cast(table), type.asSubclass(Record.class), path) : this.mistyped(path, "a table", raw);
|
||||
if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path);
|
||||
if (type == Map.class) return this.map(raw, target, path);
|
||||
|
||||
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have.");
|
||||
}
|
||||
|
||||
private @Nullable Object integer(Object raw, String path)
|
||||
{
|
||||
if (!(raw instanceof Long number)) return this.mistyped(path, "an integer", raw);
|
||||
if (number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) return this.problem(path, "must be between " + Integer.MIN_VALUE + " and " + Integer.MAX_VALUE + ", found " + number);
|
||||
|
||||
return number.intValue();
|
||||
}
|
||||
|
||||
private @Nullable Object constant(Object raw, Class<?> type, String path)
|
||||
{
|
||||
Object[] constants = type.getEnumConstants();
|
||||
|
||||
if (raw instanceof String name) {
|
||||
for (Object constant : constants) {
|
||||
if (((Enum<?>) constant).name().equalsIgnoreCase(name)) return constant;
|
||||
}
|
||||
}
|
||||
|
||||
String allowed = Arrays.stream(constants).map(constant -> "\"" + ((Enum<?>) constant).name().toLowerCase(Locale.ROOT) + "\"").collect(Collectors.joining(", "));
|
||||
return this.mistyped(path, "one of " + allowed, raw);
|
||||
}
|
||||
|
||||
private @Nullable Object list(Object raw, Type element, String path)
|
||||
{
|
||||
if (!(raw instanceof List<?> list)) return this.mistyped(path, "a list", raw);
|
||||
|
||||
List<Object> values = new ArrayList<>(list.size());
|
||||
int before = this.problems.size();
|
||||
|
||||
for (int i = 0; i < list.size(); i++)
|
||||
{
|
||||
Object value = this.value(list.get(i), element, path + "[" + i + "]");
|
||||
if (value != null) values.add(value);
|
||||
}
|
||||
|
||||
return this.problems.size() > before ? null : List.copyOf(values);
|
||||
}
|
||||
|
||||
private @Nullable Object map(Object raw, Type target, String path)
|
||||
{
|
||||
if (RecordBinder.typeArgument(target, 0) != String.class)
|
||||
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys.");
|
||||
|
||||
if (!(raw instanceof Map<?, ?> table)) return this.mistyped(path, "a table", raw);
|
||||
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
int before = this.problems.size();
|
||||
|
||||
for (Map.Entry<String, Object> entry : TomlTree.cast(table).entrySet())
|
||||
{
|
||||
Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()));
|
||||
if (value != null) values.put(entry.getKey(), value);
|
||||
}
|
||||
|
||||
return this.problems.size() > before ? null : Map.copyOf(values);
|
||||
}
|
||||
|
||||
private @Nullable Object mistyped(String path, String expected, Object raw)
|
||||
{
|
||||
String found = raw instanceof Map<?, ?> ? "a table" : raw instanceof List<?> ? "a list" : raw instanceof String text ? "\"" + text + "\"" : String.valueOf(raw);
|
||||
return this.problem(path, "must be " + expected + ", found " + found);
|
||||
}
|
||||
|
||||
private @Nullable Object problem(String path, String message)
|
||||
{
|
||||
this.problems.add("'" + path + "' " + message + ".");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Class<?> rawType(Type type)
|
||||
{
|
||||
return switch (type)
|
||||
{
|
||||
case Class<?> clazz -> clazz;
|
||||
case ParameterizedType parameters -> (Class<?>) parameters.getRawType();
|
||||
default -> throw new IllegalArgumentException("Configuration values cannot have the type '" + type.getTypeName() + "'.");
|
||||
};
|
||||
}
|
||||
|
||||
private static Type typeArgument(Type type, int index)
|
||||
{
|
||||
if (type instanceof ParameterizedType parameters) return parameters.getActualTypeArguments()[index];
|
||||
|
||||
throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records.");
|
||||
}
|
||||
|
||||
private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ModConfig;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/** {@link ModConfig} over the merged {@link TomlTree} of a mod's {@code config.toml}. */
|
||||
public final class TomlModConfig implements ModConfig
|
||||
{
|
||||
private final Map<String, Object> values;
|
||||
private final System.Logger logger;
|
||||
|
||||
/**
|
||||
* @param values the settings without the {@code [forge]} table
|
||||
* @param logger receives warnings about keys no record component reads
|
||||
*/
|
||||
public TomlModConfig(Map<String, Object> values, System.Logger logger)
|
||||
{
|
||||
this.values = Map.copyOf(values);
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Record> T bind(Class<T> type)
|
||||
{
|
||||
RecordBinder binder = new RecordBinder();
|
||||
T record = binder.record(this.values, type, "");
|
||||
|
||||
if (record == null || !binder.problems().isEmpty())
|
||||
throw new IllegalStateException("config.toml does not match '" + type.getSimpleName() + "': " + String.join(" ", binder.problems()));
|
||||
|
||||
for (String key : binder.unknownKeys()) this.logger.log(System.Logger.Level.WARNING, "config.toml: unknown key '" + key + "'.");
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> get(String path, Class<T> type)
|
||||
{
|
||||
Object value = this.values;
|
||||
|
||||
for (String key : path.split("\\."))
|
||||
{
|
||||
if (!(value instanceof Map<?, ?> table)) return Optional.empty();
|
||||
|
||||
value = table.get(key);
|
||||
if (value == null) return Optional.empty();
|
||||
}
|
||||
|
||||
RecordBinder binder = new RecordBinder();
|
||||
Object converted = binder.value(value, type, path);
|
||||
|
||||
if (converted == null) throw new IllegalStateException("config.toml: " + String.join(" ", binder.problems()));
|
||||
|
||||
return Optional.of(type.cast(converted));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
||||
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||
import com.electronwill.nightconfig.toml.TomlParser;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* TOML documents as plain Java values: tables become {@code Map<String, Object>}, arrays
|
||||
* {@code List<Object>}, integers {@code Long}, floats {@code Double}; strings and booleans stay
|
||||
* as they are. Dates and times keep the types of the parser.
|
||||
*/
|
||||
public final class TomlTree
|
||||
{
|
||||
private TomlTree() {}
|
||||
|
||||
/** @throws IllegalArgumentException when {@code toml} is not valid TOML */
|
||||
public static Map<String, Object> parse(String toml)
|
||||
{
|
||||
try { return TomlTree.table(new TomlParser().parse(toml)); }
|
||||
catch (ParsingException e) { throw new IllegalArgumentException("Not valid TOML: " + e.getMessage(), e); }
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code overrides} over {@code defaults}: tables are merged key by key, every other value of
|
||||
* {@code overrides} replaces the default.
|
||||
*/
|
||||
public static Map<String, Object> merge(Map<String, Object> defaults, Map<String, Object> overrides)
|
||||
{
|
||||
Map<String, Object> merged = new LinkedHashMap<>(defaults);
|
||||
|
||||
for (Map.Entry<String, Object> entry : overrides.entrySet())
|
||||
{
|
||||
Object defaultValue = merged.get(entry.getKey());
|
||||
|
||||
if (defaultValue instanceof Map<?, ?> defaultTable && entry.getValue() instanceof Map<?, ?> table)
|
||||
merged.put(entry.getKey(), TomlTree.merge(TomlTree.cast(defaultTable), TomlTree.cast(table)));
|
||||
else
|
||||
merged.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
private static Map<String, Object> table(UnmodifiableConfig config)
|
||||
{
|
||||
Map<String, Object> table = new LinkedHashMap<>();
|
||||
|
||||
for (UnmodifiableConfig.Entry entry : config.entrySet()) table.put(entry.getKey(), TomlTree.value(entry.getRawValue()));
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static Object value(Object raw)
|
||||
{
|
||||
return switch (raw)
|
||||
{
|
||||
case UnmodifiableConfig config -> TomlTree.table(config);
|
||||
case List<?> list -> TomlTree.list(list);
|
||||
case Integer number -> number.longValue();
|
||||
case Float number -> number.doubleValue();
|
||||
default -> raw;
|
||||
};
|
||||
}
|
||||
|
||||
private static List<Object> list(List<?> raw)
|
||||
{
|
||||
List<Object> list = new ArrayList<>(raw.size());
|
||||
|
||||
for (Object element : raw) list.add(TomlTree.value(element));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> cast(Map<?, ?> table) { return (Map<String, Object>) table; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* TOML configuration: parsing into plain maps, merging over defaults, and binding to records.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -0,0 +1,92 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* The classes of the Project Zomboid jar (game code and the libraries it bundles). The names
|
||||
* stay available after {@link #close()}; the class files can be read until then.
|
||||
*/
|
||||
public final class GameClasses implements AutoCloseable
|
||||
{
|
||||
private static final String CLASS_SUFFIX = ".class";
|
||||
private static final Pattern VERSIONED = Pattern.compile("META-INF/versions/\\d+/(.+)");
|
||||
|
||||
private final @Nullable JarFile file;
|
||||
private final Set<String> classes;
|
||||
private final Set<String> packages;
|
||||
|
||||
private GameClasses(@Nullable JarFile file, Set<String> classes, Set<String> packages)
|
||||
{
|
||||
this.file = file;
|
||||
this.classes = Set.copyOf(classes);
|
||||
this.packages = Set.copyOf(packages);
|
||||
}
|
||||
|
||||
/** Indexes {@code jar}; multi-release entries count for their base name. */
|
||||
public static GameClasses open(Path jar) throws IOException
|
||||
{
|
||||
JarFile file = new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, Runtime.version());
|
||||
Set<String> classes = new HashSet<>();
|
||||
Set<String> packages = new HashSet<>();
|
||||
|
||||
for (JarEntry entry : file.stream().toList())
|
||||
{
|
||||
String name = entry.getName();
|
||||
Matcher versioned = GameClasses.VERSIONED.matcher(name);
|
||||
|
||||
if (versioned.matches()) name = versioned.group(1);
|
||||
if (!name.endsWith(GameClasses.CLASS_SUFFIX) || name.startsWith("META-INF/")) continue;
|
||||
|
||||
String internalName = name.substring(0, name.length() - GameClasses.CLASS_SUFFIX.length());
|
||||
classes.add(internalName);
|
||||
packages.add(GameClasses.packageOf(internalName));
|
||||
}
|
||||
|
||||
return new GameClasses(file, classes, packages);
|
||||
}
|
||||
|
||||
/** No game classes, for checking a mod that declares no {@code game} versions without a game jar. */
|
||||
public static GameClasses none() { return new GameClasses(null, Set.of(), Set.of()); }
|
||||
|
||||
/** Whether the jar contains the class with this internal name, e.g. {@code zombie/core/Core}. */
|
||||
public boolean contains(String internalName) { return this.classes.contains(internalName); }
|
||||
|
||||
/** Whether the jar contains classes in the package of this internal class name. */
|
||||
public boolean containsPackageOf(String internalName) { return this.packages.contains(GameClasses.packageOf(internalName)); }
|
||||
|
||||
/** The class file for the running Java version, or {@code null} when the jar has none. */
|
||||
byte @Nullable [] read(String internalName) throws IOException
|
||||
{
|
||||
JarFile file = this.file;
|
||||
if (file == null) return null;
|
||||
|
||||
JarEntry entry = file.getJarEntry(internalName + GameClasses.CLASS_SUFFIX);
|
||||
if (entry == null) return null;
|
||||
|
||||
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
JarFile file = this.file;
|
||||
if (file != null) file.close();
|
||||
}
|
||||
|
||||
static String packageOf(String internalName)
|
||||
{
|
||||
int slash = internalName.lastIndexOf('/');
|
||||
return slash < 0 ? "" : internalName.substring(0, slash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Packages of the modules in the boot layer (the JDK), with the class loader of each. */
|
||||
final class JdkPackages
|
||||
{
|
||||
private static final Map<String, ClassLoader> LOADERS = JdkPackages.loaders();
|
||||
|
||||
private JdkPackages() {}
|
||||
|
||||
/** The loader for a class of the JDK package {@code dottedPackage}, or {@code null} for other packages. */
|
||||
static @Nullable ClassLoader loader(String dottedPackage) { return JdkPackages.LOADERS.get(dottedPackage); }
|
||||
|
||||
/** Whether the class with this internal name, e.g. {@code java/util/List}, is in a JDK package. */
|
||||
static boolean contains(String internalName) { return JdkPackages.LOADERS.containsKey(GameClasses.packageOf(internalName).replace('/', '.')); }
|
||||
|
||||
private static Map<String, ClassLoader> loaders()
|
||||
{
|
||||
Map<String, ClassLoader> loaders = new HashMap<>();
|
||||
|
||||
for (Module module : ModuleLayer.boot().modules())
|
||||
{
|
||||
// Modules of the boot loader report null; the platform loader delegates to it.
|
||||
ClassLoader loader = module.getClassLoader() == null ? ClassLoader.getPlatformClassLoader() : module.getClassLoader();
|
||||
|
||||
for (String name : module.getPackages()) loaders.put(name, loader);
|
||||
}
|
||||
|
||||
return Map.copyOf(loaders);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Class loader of one mod, over its jar and its {@code lib/} jars. Lookup order:
|
||||
*
|
||||
* <ol>
|
||||
* <li>JDK classes, from the loader of their module;</li>
|
||||
* <li>the ZomboidForge API ({@code dev.overlord.zomboidforge.api}, without {@code .internal}),
|
||||
* from the parent;</li>
|
||||
* <li>the mod's own jar and libraries;</li>
|
||||
* <li>the own jars (not the libraries) of the mod's declared dependencies;</li>
|
||||
* <li>classes of the Project Zomboid jar, from the parent, only for mods that declare
|
||||
* {@code game} versions.</li>
|
||||
* </ol>
|
||||
*
|
||||
* Everything else on the parent's class path, such as ZomboidForge's own classes and libraries,
|
||||
* is not visible. A mod's own copy of a library that the game also bundles takes precedence.
|
||||
*
|
||||
* <p>The lookup order prevents accidental linkage only. It is not a security boundary: mod code
|
||||
* can still reach other classes through reflection or {@link ClassLoader#getSystemClassLoader()}.
|
||||
*/
|
||||
final class ModClassLoader extends URLClassLoader
|
||||
{
|
||||
private static final String API = "dev.overlord.zomboidforge.api.";
|
||||
private static final String API_INTERNAL = "dev.overlord.zomboidforge.api.internal.";
|
||||
|
||||
static { ClassLoader.registerAsParallelCapable(); }
|
||||
|
||||
private final String id;
|
||||
private final Set<String> ownClasses;
|
||||
private final List<ModClassLoader> dependencies;
|
||||
private final @Nullable GameClasses game;
|
||||
|
||||
/** @param game the game's classes, or {@code null} when the mod declares no {@code game} versions */
|
||||
ModClassLoader(String id, Path jar, List<Path> libraries, ClassLoader parent, List<ModClassLoader> dependencies, @Nullable GameClasses game)
|
||||
{
|
||||
super("mod:" + id, ModClassLoader.urls(jar, libraries), parent);
|
||||
|
||||
this.id = id;
|
||||
this.ownClasses = ModClassLoader.classNames(jar);
|
||||
this.dependencies = List.copyOf(dependencies);
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
/** Whether a class with this binary name is part of the mod API. */
|
||||
static boolean isApi(String name) { return name.startsWith(ModClassLoader.API) && !name.startsWith(ModClassLoader.API_INTERNAL); }
|
||||
|
||||
@Override
|
||||
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
|
||||
{
|
||||
synchronized (this.getClassLoadingLock(name))
|
||||
{
|
||||
Class<?> type = this.findLoadedClass(name);
|
||||
if (type == null) type = this.lookUp(name);
|
||||
if (resolve) this.resolveClass(type);
|
||||
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
/** Resources of the mod's own jars first, then the parent's. */
|
||||
@Override
|
||||
public @Nullable URL getResource(String name)
|
||||
{
|
||||
URL own = this.findResource(name);
|
||||
return own != null ? own : super.getResource(name);
|
||||
}
|
||||
|
||||
private Class<?> lookUp(String name) throws ClassNotFoundException
|
||||
{
|
||||
int dot = name.lastIndexOf('.');
|
||||
ClassLoader jdk = JdkPackages.loader(dot < 0 ? "" : name.substring(0, dot));
|
||||
|
||||
if (jdk != null) return jdk.loadClass(name);
|
||||
if (ModClassLoader.isApi(name)) return this.getParent().loadClass(name);
|
||||
|
||||
try { return this.findClass(name); }
|
||||
catch (ClassNotFoundException e) { /* not in the mod's own jars */ }
|
||||
|
||||
for (ModClassLoader dependency : this.dependencies) {
|
||||
if (dependency.ownClasses.contains(name)) return dependency.loadClass(name);
|
||||
}
|
||||
|
||||
if (this.game != null && this.game.contains(name.replace('.', '/'))) return this.getParent().loadClass(name);
|
||||
|
||||
throw new ClassNotFoundException(name + " (not visible to mod '" + this.id + "')");
|
||||
}
|
||||
|
||||
private static URL[] urls(Path jar, List<Path> libraries)
|
||||
{
|
||||
URL[] urls = new URL[libraries.size() + 1];
|
||||
urls[0] = ModClassLoader.url(jar);
|
||||
|
||||
for (int i = 0; i < libraries.size(); i++) urls[i + 1] = ModClassLoader.url(libraries.get(i));
|
||||
|
||||
return urls;
|
||||
}
|
||||
|
||||
private static URL url(Path path)
|
||||
{
|
||||
try { return path.toUri().toURL(); }
|
||||
catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
|
||||
}
|
||||
|
||||
/** Binary names of the classes in {@code jar}, e.g. {@code com.example.Mod$Inner}. */
|
||||
private static Set<String> classNames(Path jar)
|
||||
{
|
||||
try (JarFile file = new JarFile(jar.toFile()))
|
||||
{
|
||||
return file.stream()
|
||||
.map(JarEntry::getName)
|
||||
.filter(name -> name.endsWith(".class") && !name.startsWith("META-INF/"))
|
||||
.map(name -> name.substring(0, name.length() - ".class".length()).replace('/', '.'))
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
}
|
||||
catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
||||
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||
import com.electronwill.nightconfig.toml.TomlParser;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Contents of {@code META-INF/zomboidforge/mod.toml} in a mod's jar, written by the mod's author.
|
||||
*
|
||||
* @param game version prefixes of Project Zomboid the mod supports; empty when the mod
|
||||
* uses no game classes
|
||||
* @param previousIds earlier ids of the mod, whose storage moves to {@code id}
|
||||
* @param dependencies mod id to minimum version
|
||||
*/
|
||||
public record ModDescriptor(
|
||||
String id,
|
||||
String name,
|
||||
ModVersion version,
|
||||
String entrypoint,
|
||||
ModVersion api,
|
||||
List<String> game,
|
||||
List<String> previousIds,
|
||||
Map<String, ModVersion> dependencies
|
||||
)
|
||||
{
|
||||
/** Location of the descriptor inside a mod's jar. */
|
||||
public static final String PATH = "META-INF/zomboidforge/mod.toml";
|
||||
|
||||
/** No {@code __} and no trailing {@code _}: storage tables are named {@code <id>__<table>}. */
|
||||
private static final Pattern ID = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*");
|
||||
private static final int ID_MAX_LENGTH = 32;
|
||||
private static final Pattern CLASS_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
|
||||
|
||||
private static final Set<String> RESERVED_IDS = Set.of("forge", "zomboidforge", "core", "api", "game");
|
||||
private static final Set<String> KEYS = Set.of("id", "name", "version", "entrypoint", "api", "game", "previous_ids", "dependencies");
|
||||
|
||||
public ModDescriptor
|
||||
{
|
||||
game = List.copyOf(game);
|
||||
previousIds = List.copyOf(previousIds);
|
||||
dependencies = Map.copyOf(dependencies);
|
||||
}
|
||||
|
||||
/** Whether {@code id} is a valid mod id that is not reserved. */
|
||||
public static boolean isValidId(String id)
|
||||
{
|
||||
return id.length() <= ModDescriptor.ID_MAX_LENGTH
|
||||
&& ModDescriptor.ID.matcher(id).matches()
|
||||
&& !ModDescriptor.RESERVED_IDS.contains(id);
|
||||
}
|
||||
|
||||
/** @throws ModLoadException listing every problem of the descriptor */
|
||||
public static ModDescriptor parse(String toml) throws ModLoadException
|
||||
{
|
||||
UnmodifiableConfig config;
|
||||
|
||||
try { config = new TomlParser().parse(toml); }
|
||||
catch (ParsingException e) { throw new ModLoadException("Not valid TOML: " + e.getMessage(), e); }
|
||||
|
||||
Reader reader = new Reader(config);
|
||||
|
||||
for (UnmodifiableConfig.Entry entry : config.entrySet()) {
|
||||
if (!ModDescriptor.KEYS.contains(entry.getKey())) reader.problems.add("Unknown key '" + entry.getKey() + "'.");
|
||||
}
|
||||
|
||||
String id = reader.string("id", true);
|
||||
String name = reader.string("name", false);
|
||||
ModVersion version = reader.version("version");
|
||||
String entrypoint = reader.string("entrypoint", true);
|
||||
ModVersion api = reader.version("api");
|
||||
List<String> game = reader.stringList("game");
|
||||
List<String> previousIds = reader.stringList("previous_ids");
|
||||
|
||||
Map<String, ModVersion> dependencies = reader.dependencies();
|
||||
|
||||
if (id != null && !ModDescriptor.isValidId(id)) reader.problems.add("'id' = '" + id + "' is not a valid mod id (" + ModDescriptor.ID.pattern() + ", at most " + ModDescriptor.ID_MAX_LENGTH + " characters, not one of " + ModDescriptor.RESERVED_IDS + ").");
|
||||
if (entrypoint != null && !ModDescriptor.CLASS_NAME.matcher(entrypoint).matches()) reader.problems.add("'entrypoint' = '" + entrypoint + "' is not a class name.");
|
||||
|
||||
if (reader.has("game") && game.isEmpty()) reader.problems.add("'game' is empty; leave it out when the mod uses no game classes.");
|
||||
for (String prefix : game) {
|
||||
if (!GameVersion.isPrefix(prefix)) reader.problems.add("'game' contains '" + prefix + "', which is not a version prefix such as '42' or '42.21'.");
|
||||
}
|
||||
|
||||
for (String previousId : previousIds) {
|
||||
if (!ModDescriptor.isValidId(previousId) || previousId.equals(id)) reader.problems.add("'previous_ids' contains '" + previousId + "', which is not a valid earlier mod id.");
|
||||
}
|
||||
|
||||
if (id != null && dependencies.containsKey(id)) reader.problems.add("'dependencies' contains the mod itself.");
|
||||
|
||||
if (!reader.problems.isEmpty() || id == null || version == null || entrypoint == null || api == null)
|
||||
throw new ModLoadException(reader.problems);
|
||||
|
||||
return new ModDescriptor(id, name == null ? id : name, version, entrypoint, api, game, previousIds, dependencies);
|
||||
}
|
||||
|
||||
/** Reads typed values and collects a problem for each missing or mistyped one. */
|
||||
private static final class Reader
|
||||
{
|
||||
private final UnmodifiableConfig config;
|
||||
private final List<String> problems = new ArrayList<>();
|
||||
|
||||
private Reader(UnmodifiableConfig config) { this.config = config; }
|
||||
|
||||
private boolean has(String key) { return this.config.contains(key); }
|
||||
|
||||
private @Nullable String string(String key, boolean required)
|
||||
{
|
||||
Object value = this.config.get(key);
|
||||
|
||||
if (value == null) {
|
||||
if (required) this.problems.add("'" + key + "' is missing.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value instanceof String text && !text.isBlank()) return text.trim();
|
||||
|
||||
this.problems.add("'" + key + "' must be a non-empty string.");
|
||||
return null;
|
||||
}
|
||||
|
||||
private @Nullable ModVersion version(String key)
|
||||
{
|
||||
String text = this.string(key, true);
|
||||
if (text == null) return null;
|
||||
|
||||
ModVersion version = ModVersion.tryParse(text).orElse(null);
|
||||
if (version == null) this.problems.add("'" + key + "' = '" + text + "' is not a version such as '1.2.0'.");
|
||||
|
||||
return version;
|
||||
}
|
||||
|
||||
private List<String> stringList(String key)
|
||||
{
|
||||
Object value = this.config.get(key);
|
||||
if (value == null) return List.of();
|
||||
|
||||
List<String> strings = new ArrayList<>();
|
||||
|
||||
if (value instanceof List<?> list)
|
||||
{
|
||||
for (Object element : list) {
|
||||
if (element instanceof String text) strings.add(text.trim());
|
||||
else this.problems.add("'" + key + "' must contain only strings.");
|
||||
}
|
||||
}
|
||||
else this.problems.add("'" + key + "' must be a list of strings, e.g. [\"a\", \"b\"].");
|
||||
|
||||
return strings;
|
||||
}
|
||||
|
||||
private Map<String, ModVersion> dependencies()
|
||||
{
|
||||
Object value = this.config.get("dependencies");
|
||||
if (value == null) return Map.of();
|
||||
|
||||
if (!(value instanceof UnmodifiableConfig table)) {
|
||||
this.problems.add("'dependencies' must be a table of mod id = minimum version.");
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
Map<String, ModVersion> dependencies = new LinkedHashMap<>();
|
||||
|
||||
for (UnmodifiableConfig.Entry entry : table.entrySet())
|
||||
{
|
||||
String dependency = entry.getKey();
|
||||
ModVersion minimum = entry.getRawValue() instanceof String text ? ModVersion.tryParse(text).orElse(null) : null;
|
||||
|
||||
if (!ModDescriptor.isValidId(dependency)) this.problems.add("'dependencies' contains '" + dependency + "', which is not a valid mod id.");
|
||||
if (minimum == null) this.problems.add("'dependencies." + dependency + "' must be a version string such as \"1.2\".");
|
||||
else dependencies.put(dependency, minimum);
|
||||
}
|
||||
|
||||
return dependencies;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import dev.overlord.zomboidforge.core.config.TomlTree;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.ZipEntry;
|
||||
|
||||
/**
|
||||
* Finds the mods in {@code <forge>/mods}. Every mod is a folder named after its id:
|
||||
*
|
||||
* <pre>
|
||||
* mods/<id>/
|
||||
* <id>.jar the mod, with META-INF/zomboidforge/mod.toml
|
||||
* lib/*.jar libraries of the mod (optional)
|
||||
* config.toml settings of the mod (optional)
|
||||
* </pre>
|
||||
*/
|
||||
public final class ModDiscovery
|
||||
{
|
||||
/** Location of the default settings inside a mod's jar. */
|
||||
public static final String DEFAULT_CONFIG = "META-INF/zomboidforge/config.toml";
|
||||
public static final String CONFIG = "config.toml";
|
||||
|
||||
private static final String JAR_SUFFIX = ".jar";
|
||||
private static final String LIBRARIES = "lib";
|
||||
private static final String FORGE_TABLE = "forge";
|
||||
private static final String ENABLED = "enabled";
|
||||
|
||||
/**
|
||||
* A mod folder whose descriptor and settings were read.
|
||||
*
|
||||
* @param enabled {@code [forge] enabled} from the settings; {@code true} when missing
|
||||
* @param config the settings over the defaults from the jar, without the {@code [forge]} table
|
||||
*/
|
||||
public record Candidate(Path directory, Path jar, List<Path> libraries, ModDescriptor descriptor, boolean enabled, Map<String, Object> config)
|
||||
{
|
||||
public Candidate
|
||||
{
|
||||
libraries = List.copyOf(libraries);
|
||||
config = Map.copyOf(config);
|
||||
}
|
||||
|
||||
public String id() { return this.descriptor.id(); }
|
||||
}
|
||||
|
||||
private record JarContents(String descriptor, byte @Nullable [] defaultConfig) {}
|
||||
|
||||
private ModDiscovery() {}
|
||||
|
||||
/**
|
||||
* Reads every mod folder in {@code modsDirectory}, sorted by folder name. Writes the default
|
||||
* settings of a mod to {@code config.toml} when the folder has none and is writable.
|
||||
*
|
||||
* @param logger receives notes about written or unwritable default settings
|
||||
* @throws ModLoadException listing the problems of every folder
|
||||
*/
|
||||
public static List<Candidate> discover(Path modsDirectory, System.Logger logger) throws ModLoadException
|
||||
{
|
||||
List<Candidate> candidates = new ArrayList<>();
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (Path entry : ModDiscovery.sortedEntries(modsDirectory))
|
||||
{
|
||||
String name = entry.getFileName().toString();
|
||||
|
||||
if (name.startsWith(".")) continue;
|
||||
|
||||
if (!Files.isDirectory(entry)) {
|
||||
problems.add("'" + name + "': not a folder; every mod is a folder 'mods/<id>/' with '<id>.jar' inside.");
|
||||
continue;
|
||||
}
|
||||
|
||||
try { candidates.add(ModDiscovery.read(entry, logger)); }
|
||||
catch (ModLoadException e) { e.problems().forEach(problem -> problems.add("'" + name + "': " + problem)); }
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
private static Candidate read(Path directory, System.Logger logger) throws ModLoadException
|
||||
{
|
||||
String name = directory.getFileName().toString();
|
||||
Path jar = directory.resolve(name + ModDiscovery.JAR_SUFFIX);
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (Path entry : ModDiscovery.sortedEntries(directory)) {
|
||||
if (ModDiscovery.isJar(entry) && !entry.equals(jar)) problems.add("'" + entry.getFileName() + "' is not '" + jar.getFileName() + "'; the folder may contain only the mod's own jar (libraries go into 'lib/').");
|
||||
}
|
||||
|
||||
if (!Files.isRegularFile(jar)) problems.add("'" + jar.getFileName() + "' is missing.");
|
||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||
|
||||
JarContents contents = ModDiscovery.contents(jar);
|
||||
ModDescriptor descriptor = ModDiscovery.descriptor(contents.descriptor());
|
||||
if (!descriptor.id().equals(name)) throw new ModLoadException(List.of("The folder is named '" + name + "', but 'mod.toml' declares the id '" + descriptor.id() + "'."));
|
||||
|
||||
Path libraryDirectory = directory.resolve(ModDiscovery.LIBRARIES);
|
||||
List<Path> libraries = Files.isDirectory(libraryDirectory)
|
||||
? ModDiscovery.sortedEntries(libraryDirectory).stream().filter(ModDiscovery::isJar).toList()
|
||||
: List.of();
|
||||
|
||||
Map<String, Object> config = ModDiscovery.config(directory, contents.defaultConfig(), logger, problems);
|
||||
boolean enabled = ModDiscovery.enabled(config.remove(ModDiscovery.FORGE_TABLE), problems);
|
||||
|
||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||
|
||||
return new Candidate(directory, jar, libraries, descriptor, enabled, config);
|
||||
}
|
||||
|
||||
/** The folder's {@code config.toml} over the jar's defaults, as a mutable map. */
|
||||
private static Map<String, Object> config(Path directory, byte @Nullable [] defaultConfig, System.Logger logger, List<String> problems)
|
||||
{
|
||||
Path file = directory.resolve(ModDiscovery.CONFIG);
|
||||
Map<String, Object> defaults = Map.of();
|
||||
Map<String, Object> settings = Map.of();
|
||||
|
||||
if (defaultConfig != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
defaults = TomlTree.parse(new String(defaultConfig, StandardCharsets.UTF_8));
|
||||
}
|
||||
catch (IllegalArgumentException e)
|
||||
{
|
||||
// Invalid defaults are reported and never copied to the folder.
|
||||
problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "' in the jar: " + e.getMessage());
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
if (Files.isRegularFile(file))
|
||||
{
|
||||
try { settings = TomlTree.parse(Files.readString(file)); }
|
||||
catch (IOException e) { problems.add("Cannot read '" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
|
||||
catch (IllegalArgumentException e) { problems.add("'" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
|
||||
}
|
||||
else if (defaultConfig != null)
|
||||
{
|
||||
String id = directory.getFileName().toString();
|
||||
|
||||
try
|
||||
{
|
||||
Files.write(file, defaultConfig, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
|
||||
logger.log(System.Logger.Level.INFO, "'" + id + "': wrote the default settings to '" + file + "'.");
|
||||
}
|
||||
catch (IOException | UnsupportedOperationException e)
|
||||
{
|
||||
logger.log(System.Logger.Level.INFO, "'" + id + "': cannot write the default settings to '" + file + "' (" + e + "); using them without a file.");
|
||||
}
|
||||
}
|
||||
|
||||
return TomlTree.merge(defaults, settings);
|
||||
}
|
||||
|
||||
/** {@code [forge] enabled}; {@code true} without a {@code [forge]} table. */
|
||||
private static boolean enabled(@Nullable Object forge, List<String> problems)
|
||||
{
|
||||
if (forge == null) return true;
|
||||
|
||||
if (!(forge instanceof Map<?, ?> table)) {
|
||||
problems.add("'" + ModDiscovery.CONFIG + "': 'forge' must be a table ([forge]).");
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean enabled = true;
|
||||
|
||||
for (Map.Entry<?, ?> entry : table.entrySet())
|
||||
{
|
||||
if (!ModDiscovery.ENABLED.equals(entry.getKey()))
|
||||
problems.add("'" + ModDiscovery.CONFIG + "': unknown key 'forge." + entry.getKey() + "'; [forge] only has 'enabled'.");
|
||||
else if (entry.getValue() instanceof Boolean value)
|
||||
enabled = value;
|
||||
else
|
||||
problems.add("'" + ModDiscovery.CONFIG + "': 'forge.enabled' must be true or false.");
|
||||
}
|
||||
|
||||
return enabled;
|
||||
}
|
||||
|
||||
private static JarContents contents(Path jar) throws ModLoadException
|
||||
{
|
||||
try (JarFile file = new JarFile(jar.toFile()))
|
||||
{
|
||||
byte[] descriptor = ModDiscovery.entry(file, ModDescriptor.PATH);
|
||||
if (descriptor == null) throw new ModLoadException(List.of("'" + jar.getFileName() + "' contains no '" + ModDescriptor.PATH + "'."));
|
||||
|
||||
return new JarContents(new String(descriptor, StandardCharsets.UTF_8), ModDiscovery.entry(file, ModDiscovery.DEFAULT_CONFIG));
|
||||
}
|
||||
catch (IOException e) { throw new ModLoadException("Cannot read '" + jar.getFileName() + "': " + e.getMessage(), e); }
|
||||
}
|
||||
|
||||
private static byte @Nullable [] entry(JarFile file, String name) throws IOException
|
||||
{
|
||||
ZipEntry entry = file.getEntry(name);
|
||||
if (entry == null) return null;
|
||||
|
||||
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
|
||||
}
|
||||
|
||||
private static ModDescriptor descriptor(String toml) throws ModLoadException
|
||||
{
|
||||
try { return ModDescriptor.parse(toml); }
|
||||
catch (ModLoadException e) { throw new ModLoadException(e.problems().stream().map(problem -> "mod.toml: " + problem).toList()); }
|
||||
}
|
||||
|
||||
private static boolean isJar(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(ModDiscovery.JAR_SUFFIX); }
|
||||
|
||||
private static List<Path> sortedEntries(Path directory) throws ModLoadException
|
||||
{
|
||||
try (Stream<Path> entries = Files.list(directory)) { return entries.sorted().toList(); }
|
||||
catch (IOException e) { throw new ModLoadException("Cannot list '" + directory + "': " + e.getMessage(), e); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.List;
|
||||
|
||||
/** The mods cannot be loaded; {@link #problems()} lists every problem found, one line each. */
|
||||
public final class ModLoadException extends Exception
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** Not serialized; the exception is only used inside the server process. */
|
||||
private final transient List<String> problems;
|
||||
|
||||
public ModLoadException(List<String> problems)
|
||||
{
|
||||
super(String.join("\n", problems));
|
||||
|
||||
if (problems.isEmpty()) throw new IllegalArgumentException("A ModLoadException needs at least one problem.");
|
||||
|
||||
this.problems = List.copyOf(problems);
|
||||
}
|
||||
|
||||
public ModLoadException(String problem, Throwable cause)
|
||||
{
|
||||
super(problem, cause);
|
||||
|
||||
this.problems = List.of(problem);
|
||||
}
|
||||
|
||||
public List<String> problems() { return this.problems; }
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.AsyncExecutor;
|
||||
import dev.overlord.zomboidforge.api.ClientCommands;
|
||||
import dev.overlord.zomboidforge.api.Commands;
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.api.MainThread;
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.ModConfig;
|
||||
import dev.overlord.zomboidforge.api.ModContext;
|
||||
import dev.overlord.zomboidforge.api.ModThread;
|
||||
import dev.overlord.zomboidforge.api.internal.ModBinding;
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
import dev.overlord.zomboidforge.core.ConsoleLogger;
|
||||
import dev.overlord.zomboidforge.core.config.TomlModConfig;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Creates the class loaders and entry points of resolved mods, in order, and calls
|
||||
* {@link Mod#onLoad()} on each. Stops at the first mod that fails.
|
||||
*/
|
||||
public final class ModLoader
|
||||
{
|
||||
/** A mod whose entry point was created and whose {@link Mod#onLoad()} returned. */
|
||||
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
|
||||
|
||||
private record Context(
|
||||
String id,
|
||||
String version,
|
||||
GameVersion gameVersion,
|
||||
System.Logger logger,
|
||||
Path directory,
|
||||
ModConfig config,
|
||||
Events events,
|
||||
MainThread main,
|
||||
ModThread modThread,
|
||||
AsyncExecutor async,
|
||||
ModStorage storage,
|
||||
Commands commands,
|
||||
ClientCommands clientCommands
|
||||
) implements ModContext {}
|
||||
|
||||
private ModLoader() {}
|
||||
|
||||
/**
|
||||
* @param ordered mods in load order, as returned by {@link ModResolver#resolve} and checked
|
||||
* by {@link ModVerifier#verify}
|
||||
* @param parent parent of every mod's class loader
|
||||
* @param gameClasses classes of the Project Zomboid jar, visible to mods that declare
|
||||
* {@code game} versions
|
||||
* @param services creates each mod's threads and event registration
|
||||
* @throws ModLoadException naming the mod that failed and why
|
||||
*/
|
||||
public static List<LoadedMod> load(List<ModDiscovery.Candidate> ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services) throws ModLoadException
|
||||
{
|
||||
Map<String, ModClassLoader> loaders = new HashMap<>();
|
||||
List<LoadedMod> loaded = new ArrayList<>();
|
||||
|
||||
try
|
||||
{
|
||||
for (ModDiscovery.Candidate candidate : ordered)
|
||||
{
|
||||
ModDescriptor descriptor = candidate.descriptor();
|
||||
|
||||
List<ModClassLoader> dependencies = descriptor.dependencies().keySet().stream()
|
||||
.sorted()
|
||||
.map(dependency -> Objects.requireNonNull(loaders.get(dependency), "'" + dependency + "' is not loaded before '" + descriptor.id() + "'."))
|
||||
.toList();
|
||||
|
||||
@Nullable GameClasses visible = descriptor.game().isEmpty() ? null : gameClasses;
|
||||
ModClassLoader loader = new ModClassLoader(descriptor.id(), candidate.jar(), candidate.libraries(), parent, dependencies, visible);
|
||||
loaders.put(descriptor.id(), loader);
|
||||
|
||||
System.Logger logger = new ConsoleLogger("ZomboidForge/" + descriptor.id());
|
||||
ModServices provided = services.create(descriptor.id(), logger);
|
||||
Context context = new Context(
|
||||
descriptor.id(),
|
||||
descriptor.version().toString(),
|
||||
game,
|
||||
logger,
|
||||
candidate.directory(),
|
||||
new TomlModConfig(candidate.config(), logger),
|
||||
provided.events(),
|
||||
provided.main(),
|
||||
provided.modThread(),
|
||||
provided.async(),
|
||||
provided.storage(),
|
||||
provided.commands(),
|
||||
provided.clientCommands()
|
||||
);
|
||||
|
||||
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
|
||||
}
|
||||
|
||||
return List.copyOf(loaded);
|
||||
}
|
||||
catch (ModLoadException | RuntimeException e)
|
||||
{
|
||||
ModLoader.close(loaders.values());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context) throws ModLoadException
|
||||
{
|
||||
String id = descriptor.id();
|
||||
|
||||
Constructor<? extends Mod> constructor = ModLoader.constructor(descriptor, loader);
|
||||
|
||||
Mod mod;
|
||||
|
||||
try
|
||||
{
|
||||
mod = ScopedValue.where(ModBinding.CONTEXT, context).call(constructor::newInstance);
|
||||
}
|
||||
catch (InvocationTargetException e)
|
||||
{
|
||||
throw new ModLoadException(ModLoader.sentence("'" + id + "': the constructor of '" + descriptor.entrypoint() + "' threw " + e.getCause()), e.getCause());
|
||||
}
|
||||
catch (ReflectiveOperationException | LinkageError e)
|
||||
{
|
||||
throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e);
|
||||
}
|
||||
|
||||
try { mod.onLoad(); }
|
||||
catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); }
|
||||
catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); }
|
||||
|
||||
return mod;
|
||||
}
|
||||
|
||||
private static Constructor<? extends Mod> constructor(ModDescriptor descriptor, ClassLoader loader) throws ModLoadException
|
||||
{
|
||||
String id = descriptor.id();
|
||||
String entrypoint = descriptor.entrypoint();
|
||||
|
||||
Class<?> type;
|
||||
|
||||
try { type = Class.forName(entrypoint, false, loader); }
|
||||
catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': entry point '" + entrypoint + "' cannot be loaded: " + e), e); }
|
||||
|
||||
if (!Mod.class.isAssignableFrom(type))
|
||||
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' does not extend '" + Mod.class.getName() + "'."));
|
||||
|
||||
if (Modifier.isAbstract(type.getModifiers()))
|
||||
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' is abstract."));
|
||||
|
||||
try { return type.asSubclass(Mod.class).getConstructor(); }
|
||||
catch (NoSuchMethodException e) { throw new ModLoadException("'" + id + "': entry point '" + entrypoint + "' has no public constructor without parameters.", e); }
|
||||
}
|
||||
|
||||
/** {@code text} ending with a period; exception messages often have one already. */
|
||||
private static String sentence(String text) { return text.endsWith(".") ? text : text + "."; }
|
||||
|
||||
private static void close(Iterable<ModClassLoader> loaders)
|
||||
{
|
||||
for (ModClassLoader loader : loaders) {
|
||||
try { loader.close(); }
|
||||
catch (IOException e) { /* the server stops anyway */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Checks the API version, the game versions, and the dependencies of discovered mods, and orders
|
||||
* them so that every mod comes after its dependencies (otherwise by id).
|
||||
*/
|
||||
public final class ModResolver
|
||||
{
|
||||
private ModResolver() {}
|
||||
|
||||
/**
|
||||
* Returns the enabled mods in load order; disabled mods are left out.
|
||||
*
|
||||
* @param api the running ZomboidForge API version, or {@code null} to skip the API check
|
||||
* (development builds)
|
||||
* @throws ModLoadException listing every problem of every enabled mod
|
||||
*/
|
||||
public static List<ModDiscovery.Candidate> resolve(List<ModDiscovery.Candidate> candidates, GameVersion game, @Nullable ModVersion api) throws ModLoadException
|
||||
{
|
||||
Map<String, ModDiscovery.Candidate> byId = candidates.stream().filter(ModDiscovery.Candidate::enabled).collect(Collectors.toMap(ModDiscovery.Candidate::id, Function.identity(), (a, b) -> a, TreeMap::new));
|
||||
Set<String> disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).collect(Collectors.toSet());
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (ModDiscovery.Candidate candidate : byId.values())
|
||||
{
|
||||
ModDescriptor descriptor = candidate.descriptor();
|
||||
String id = descriptor.id();
|
||||
|
||||
if (api != null && !api.providesApi(descriptor.api()))
|
||||
problems.add("'" + id + "': built against ZomboidForge API " + descriptor.api() + ", the server provides " + api + ".");
|
||||
|
||||
for (String previous : descriptor.previousIds()) {
|
||||
if (byId.containsKey(previous)) problems.add("'" + id + "': 'previous_ids' contains '" + previous + "', which is installed as a mod.");
|
||||
}
|
||||
|
||||
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(game::matches))
|
||||
problems.add("'" + id + "': supports Project Zomboid " + descriptor.game() + ", the server runs " + game + ".");
|
||||
|
||||
for (Map.Entry<String, ModVersion> dependency : new TreeMap<>(descriptor.dependencies()).entrySet())
|
||||
{
|
||||
ModDiscovery.Candidate installed = byId.get(dependency.getKey());
|
||||
|
||||
if (installed == null && disabled.contains(dependency.getKey()))
|
||||
problems.add("'" + id + "': requires '" + dependency.getKey() + "', which is disabled in its config.toml.");
|
||||
else if (installed == null)
|
||||
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, which is not installed.");
|
||||
else if (installed.descriptor().version().compareTo(dependency.getValue()) < 0)
|
||||
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, " + installed.descriptor().version() + " is installed.");
|
||||
}
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||
|
||||
return new Order(byId).sorted();
|
||||
}
|
||||
|
||||
/** Depth-first ordering that reports dependency cycles. */
|
||||
private static final class Order
|
||||
{
|
||||
private final Map<String, ModDiscovery.Candidate> byId;
|
||||
private final Set<String> done = new HashSet<>();
|
||||
private final LinkedHashSet<String> visiting = new LinkedHashSet<>();
|
||||
private final List<ModDiscovery.Candidate> sorted = new ArrayList<>();
|
||||
private final List<String> problems = new ArrayList<>();
|
||||
|
||||
private Order(Map<String, ModDiscovery.Candidate> byId) { this.byId = byId; }
|
||||
|
||||
private List<ModDiscovery.Candidate> sorted() throws ModLoadException
|
||||
{
|
||||
for (String id : this.byId.keySet()) this.visit(id);
|
||||
|
||||
if (!this.problems.isEmpty()) throw new ModLoadException(this.problems);
|
||||
|
||||
return List.copyOf(this.sorted);
|
||||
}
|
||||
|
||||
private void visit(String id)
|
||||
{
|
||||
if (this.done.contains(id)) return;
|
||||
|
||||
if (!this.visiting.add(id))
|
||||
{
|
||||
List<String> path = new ArrayList<>(this.visiting);
|
||||
List<String> cycle = new ArrayList<>(path.subList(path.indexOf(id), path.size()));
|
||||
cycle.add(id);
|
||||
|
||||
this.problems.add("'" + id + "': dependency cycle " + cycle.stream().map(element -> "'" + element + "'").collect(Collectors.joining(" -> ")) + ".");
|
||||
return;
|
||||
}
|
||||
|
||||
ModDiscovery.Candidate candidate = Objects.requireNonNull(this.byId.get(id));
|
||||
for (String dependency : new TreeMap<>(candidate.descriptor().dependencies()).keySet()) this.visit(dependency);
|
||||
|
||||
this.visiting.remove(id);
|
||||
|
||||
if (this.done.add(id)) this.sorted.add(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.AsyncExecutor;
|
||||
import dev.overlord.zomboidforge.api.ClientCommands;
|
||||
import dev.overlord.zomboidforge.api.Commands;
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
import dev.overlord.zomboidforge.api.MainThread;
|
||||
import dev.overlord.zomboidforge.api.ModThread;
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
|
||||
/** The threads, event and command registration, storage, and client commands of one mod, created before its entry point. */
|
||||
public record ModServices(
|
||||
Events events,
|
||||
MainThread main,
|
||||
ModThread modThread,
|
||||
AsyncExecutor async,
|
||||
ModStorage storage,
|
||||
Commands commands,
|
||||
ClientCommands clientCommands
|
||||
) {
|
||||
/** Creates the services of one mod. */
|
||||
@FunctionalInterface
|
||||
public interface Factory
|
||||
{
|
||||
ModServices create(String id, System.Logger logger);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.FieldVisitor;
|
||||
import org.objectweb.asm.Handle;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.RecordComponentVisitor;
|
||||
import org.objectweb.asm.Type;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Checks the classes of resolved mods before any of them is loaded:
|
||||
*
|
||||
* <ul>
|
||||
* <li>no class in a ZomboidForge package, and no class in the mod's own jar with the name of a
|
||||
* game class;</li>
|
||||
* <li>no use of ZomboidForge classes outside the API;</li>
|
||||
* <li>a mod that uses classes of the Project Zomboid jar declares {@code game} versions;</li>
|
||||
* <li>every game class, field, and method such a mod uses exists in the running jar
|
||||
* (members are looked up through superclasses and interfaces).</li>
|
||||
* </ul>
|
||||
*
|
||||
* Annotations are not checked: the JVM does not load annotation types a class only carries.
|
||||
*/
|
||||
public final class ModVerifier
|
||||
{
|
||||
private static final String FORGE = "dev/overlord/zomboidforge/";
|
||||
private static final String API = "dev/overlord/zomboidforge/api/";
|
||||
private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/";
|
||||
private static final int EXAMPLES = 5;
|
||||
|
||||
/** A field or method that a mod's code uses. */
|
||||
private record Member(boolean method, String owner, String name, String desc) implements Comparable<Member>
|
||||
{
|
||||
@Override
|
||||
public int compareTo(Member other) { return this.toString().compareTo(other.toString()); }
|
||||
|
||||
@Override
|
||||
public String toString() { return this.owner.replace('/', '.') + "." + this.name + (this.method ? "" : ":") + this.desc; }
|
||||
}
|
||||
|
||||
private ModVerifier() {}
|
||||
|
||||
/**
|
||||
* @param ordered mods in load order, as returned by {@link ModResolver#resolve}
|
||||
* @param version the version of {@code game}, for messages; {@code null} with {@link GameClasses#none()}
|
||||
* @throws ModLoadException listing every problem of every mod
|
||||
*/
|
||||
public static void verify(List<ModDiscovery.Candidate> ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException
|
||||
{
|
||||
Hierarchy hierarchy = new Hierarchy(game);
|
||||
Map<String, Set<String>> ownByMod = new HashMap<>();
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (ModDiscovery.Candidate candidate : ordered)
|
||||
{
|
||||
String id = candidate.id();
|
||||
Map<String, byte[]> own = ModVerifier.classes(candidate.jar());
|
||||
Map<String, byte[]> libraries = new TreeMap<>();
|
||||
|
||||
for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library));
|
||||
|
||||
ownByMod.put(id, own.keySet());
|
||||
|
||||
Set<String> provided = new HashSet<>(own.keySet());
|
||||
provided.addAll(libraries.keySet());
|
||||
for (String dependency : candidate.descriptor().dependencies().keySet()) provided.addAll(ownByMod.getOrDefault(dependency, Set.of()));
|
||||
|
||||
Set<String> contained = new TreeSet<>(own.keySet());
|
||||
contained.addAll(libraries.keySet());
|
||||
|
||||
for (String name : contained) {
|
||||
if (name.startsWith(ModVerifier.FORGE)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is in a ZomboidForge package.");
|
||||
}
|
||||
|
||||
for (String name : new TreeSet<>(own.keySet())) {
|
||||
if (game.contains(name)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is a class of Project Zomboid.");
|
||||
}
|
||||
|
||||
References references = new References();
|
||||
for (byte[] bytes : own.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||
for (byte[] bytes : libraries.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||
|
||||
Set<String> gameTypes = new TreeSet<>();
|
||||
Set<String> missingTypes = new TreeSet<>();
|
||||
|
||||
for (String type : references.types)
|
||||
{
|
||||
if (JdkPackages.contains(type) || provided.contains(type)) continue;
|
||||
|
||||
if (type.startsWith(ModVerifier.FORGE) && (!type.startsWith(ModVerifier.API) || type.startsWith(ModVerifier.API_INTERNAL)))
|
||||
problems.add("'" + id + "': uses '" + ModVerifier.dotted(type) + "', which is internal to ZomboidForge.");
|
||||
else if (game.contains(type))
|
||||
gameTypes.add(type);
|
||||
else if (!type.startsWith(ModVerifier.FORGE) && game.containsPackageOf(type))
|
||||
missingTypes.add(type);
|
||||
}
|
||||
|
||||
boolean declaresGame = !candidate.descriptor().game().isEmpty();
|
||||
|
||||
if (!declaresGame && !(gameTypes.isEmpty() && missingTypes.isEmpty()))
|
||||
{
|
||||
Set<String> used = new TreeSet<>(gameTypes);
|
||||
used.addAll(missingTypes);
|
||||
|
||||
problems.add("'" + id + "': uses classes of the Project Zomboid jar (" + ModVerifier.examples(used) + ") but declares no 'game' versions in mod.toml.");
|
||||
continue;
|
||||
}
|
||||
|
||||
List<String> linkage = new ArrayList<>();
|
||||
|
||||
for (String type : missingTypes) linkage.add("'" + ModVerifier.dotted(type) + "'");
|
||||
|
||||
for (Member member : references.members) {
|
||||
if (gameTypes.contains(member.owner()) && !hierarchy.has(member)) linkage.add("'" + member + "'");
|
||||
}
|
||||
|
||||
if (!linkage.isEmpty())
|
||||
problems.add("'" + id + "': uses " + ModVerifier.examples(linkage) + ", which " + (linkage.size() == 1 ? "does" : "do") + " not exist in " + (version == null ? "the game jar" : "Project Zomboid " + version) + ".");
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||
}
|
||||
|
||||
/** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */
|
||||
private static Map<String, byte[]> classes(Path jar)
|
||||
{
|
||||
Map<String, byte[]> classes = new TreeMap<>();
|
||||
|
||||
try (JarFile file = new JarFile(jar.toFile()))
|
||||
{
|
||||
for (JarEntry entry : file.stream().toList())
|
||||
{
|
||||
String name = entry.getName();
|
||||
if (!name.endsWith(".class") || name.startsWith("META-INF/") || name.endsWith("module-info.class")) continue;
|
||||
|
||||
try (InputStream in = file.getInputStream(entry)) { classes.put(name.substring(0, name.length() - ".class".length()), in.readAllBytes()); }
|
||||
}
|
||||
}
|
||||
catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
/** The first {@value #EXAMPLES} elements, quoted unless already quoted, and how many more there are. */
|
||||
private static String examples(Iterable<String> elements)
|
||||
{
|
||||
List<String> all = new ArrayList<>();
|
||||
for (String element : elements) all.add(element.startsWith("'") ? element : "'" + ModVerifier.dotted(element) + "'");
|
||||
|
||||
String shown = all.stream().limit(ModVerifier.EXAMPLES).collect(Collectors.joining(", "));
|
||||
return all.size() > ModVerifier.EXAMPLES ? shown + " and " + (all.size() - ModVerifier.EXAMPLES) + " more" : shown;
|
||||
}
|
||||
|
||||
private static String dotted(String internalName) { return internalName.replace('/', '.'); }
|
||||
|
||||
/** Collects the classes and members that code uses; skips annotations and debug information. */
|
||||
private static final class References extends ClassVisitor
|
||||
{
|
||||
private final Set<String> types = new TreeSet<>();
|
||||
private final Set<Member> members = new TreeSet<>();
|
||||
|
||||
private References() { super(Opcodes.ASM9); }
|
||||
|
||||
@Override
|
||||
public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces)
|
||||
{
|
||||
if (superName != null) this.type(superName);
|
||||
if (interfaces != null) for (String type : interfaces) this.type(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
|
||||
{
|
||||
this.descriptor(descriptor);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable RecordComponentVisitor visitRecordComponent(String name, String descriptor, @Nullable String signature)
|
||||
{
|
||||
this.descriptor(descriptor);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
|
||||
{
|
||||
this.descriptor(descriptor);
|
||||
if (exceptions != null) for (String type : exceptions) this.type(type);
|
||||
|
||||
References references = this;
|
||||
|
||||
return new MethodVisitor(Opcodes.ASM9)
|
||||
{
|
||||
@Override
|
||||
public void visitTypeInsn(int opcode, String type) { references.type(type); }
|
||||
|
||||
@Override
|
||||
public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { references.member(false, owner, name, descriptor); }
|
||||
|
||||
@Override
|
||||
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) { references.member(true, owner, name, descriptor); }
|
||||
|
||||
@Override
|
||||
public void visitInvokeDynamicInsn(String name, String descriptor, Handle bootstrap, Object... arguments)
|
||||
{
|
||||
references.descriptor(descriptor);
|
||||
references.constant(bootstrap);
|
||||
|
||||
for (Object argument : arguments) references.constant(argument);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitLdcInsn(Object value) { references.constant(value); }
|
||||
|
||||
@Override
|
||||
public void visitMultiANewArrayInsn(String descriptor, int dimensions) { references.descriptor(descriptor); }
|
||||
|
||||
@Override
|
||||
public void visitTryCatchBlock(Label start, Label end, Label handler, @Nullable String type)
|
||||
{
|
||||
if (type != null) references.type(type);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void member(boolean method, String owner, String name, String descriptor)
|
||||
{
|
||||
this.type(owner);
|
||||
this.descriptor(descriptor);
|
||||
|
||||
if (!owner.startsWith("[")) this.members.add(new Member(method, owner, name, descriptor));
|
||||
}
|
||||
|
||||
private void constant(Object value)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case Handle handle -> this.member(handle.getTag() > Opcodes.H_PUTSTATIC, handle.getOwner(), handle.getName(), handle.getDesc());
|
||||
case Type type -> this.descriptor(type.getDescriptor());
|
||||
default -> { /* numbers, strings, dynamic constants */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** An internal class name, or an array descriptor as used by {@code anewarray} and {@code checkcast}. */
|
||||
private void type(String name)
|
||||
{
|
||||
if (name.startsWith("[")) this.descriptor(name);
|
||||
else this.types.add(name);
|
||||
}
|
||||
|
||||
private void descriptor(String descriptor)
|
||||
{
|
||||
Type type = Type.getType(descriptor);
|
||||
|
||||
if (type.getSort() == Type.METHOD)
|
||||
{
|
||||
for (Type argument : type.getArgumentTypes()) this.add(argument);
|
||||
this.add(type.getReturnType());
|
||||
}
|
||||
else this.add(type);
|
||||
}
|
||||
|
||||
private void add(Type type)
|
||||
{
|
||||
Type element = type.getSort() == Type.ARRAY ? type.getElementType() : type;
|
||||
if (element.getSort() == Type.OBJECT) this.types.add(element.getInternalName());
|
||||
}
|
||||
}
|
||||
|
||||
/** Fields and methods of game and JDK classes, read from their class files. */
|
||||
private static final class Hierarchy
|
||||
{
|
||||
private record Info(@Nullable String superName, List<String> interfaces, Set<String> fields, Set<String> methods) {}
|
||||
|
||||
private final GameClasses game;
|
||||
private final Map<String, @Nullable Info> cache = new HashMap<>();
|
||||
|
||||
private Hierarchy(GameClasses game) { this.game = game; }
|
||||
|
||||
/**
|
||||
* Whether {@code member} resolves in its owner, a superclass, or a superinterface.
|
||||
* Constructors only count in the owner. Supertypes whose class files cannot be read
|
||||
* count as having every member.
|
||||
*/
|
||||
private boolean has(Member member)
|
||||
{
|
||||
String key = member.name() + member.desc();
|
||||
Deque<String> pending = new ArrayDeque<>(List.of(member.owner()));
|
||||
Set<String> seen = new HashSet<>();
|
||||
|
||||
while (!pending.isEmpty())
|
||||
{
|
||||
String type = pending.pop();
|
||||
if (!seen.add(type)) continue;
|
||||
|
||||
Info info = this.info(type);
|
||||
if (info == null) return !type.equals(member.owner());
|
||||
|
||||
if ((member.method() ? info.methods() : info.fields()).contains(key)) return true;
|
||||
if (member.method() && member.name().equals("<init>")) return false;
|
||||
|
||||
if (info.superName() != null) pending.add(info.superName());
|
||||
pending.addAll(info.interfaces());
|
||||
}
|
||||
|
||||
// Interface methods may also be declared by java.lang.Object.
|
||||
return member.method() && !member.owner().equals("java/lang/Object") && this.has(new Member(true, "java/lang/Object", member.name(), member.desc()));
|
||||
}
|
||||
|
||||
private @Nullable Info info(String type)
|
||||
{
|
||||
if (this.cache.containsKey(type)) return this.cache.get(type);
|
||||
|
||||
Info info = null;
|
||||
|
||||
try
|
||||
{
|
||||
byte[] bytes = this.game.contains(type) ? this.game.read(type) : JdkPackages.contains(type) ? Hierarchy.jdkClass(type) : null;
|
||||
if (bytes != null) info = Hierarchy.read(bytes);
|
||||
}
|
||||
catch (IOException e) { throw new UncheckedIOException("Cannot read class '" + type + "'.", e); }
|
||||
|
||||
this.cache.put(type, info);
|
||||
return info;
|
||||
}
|
||||
|
||||
private static byte @Nullable [] jdkClass(String type) throws IOException
|
||||
{
|
||||
try (InputStream in = ClassLoader.getSystemResourceAsStream(type + ".class")) { return in == null ? null : in.readAllBytes(); }
|
||||
}
|
||||
|
||||
private static Info read(byte[] bytes)
|
||||
{
|
||||
ClassReader reader = new ClassReader(bytes);
|
||||
Set<String> fields = new HashSet<>();
|
||||
Set<String> methods = new HashSet<>();
|
||||
|
||||
reader.accept(new ClassVisitor(Opcodes.ASM9)
|
||||
{
|
||||
@Override
|
||||
public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
|
||||
{
|
||||
fields.add(name + descriptor);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
|
||||
{
|
||||
methods.add(name + descriptor);
|
||||
return null;
|
||||
}
|
||||
}, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||
|
||||
return new Info(reader.getSuperName(), List.of(reader.getInterfaces()), fields, methods);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Semantic version of a mod or of the ZomboidForge API: {@code major[.minor[.patch]][-pre-release]},
|
||||
* missing parts are 0. A pre-release sorts before the release with the same numbers.
|
||||
*/
|
||||
public record ModVersion(int major, int minor, int patch, @Nullable String preRelease) implements Comparable<ModVersion>
|
||||
{
|
||||
// At most 9 digits per number, so every number fits an int.
|
||||
private static final Pattern FORMAT = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9}))?(?:\\.(\\d{1,9}))?(?:-([0-9A-Za-z.-]+))?");
|
||||
|
||||
private static final Comparator<ModVersion> ORDER = Comparator
|
||||
.comparingInt(ModVersion::major)
|
||||
.thenComparingInt(ModVersion::minor)
|
||||
.thenComparingInt(ModVersion::patch)
|
||||
.thenComparing(ModVersion::preRelease, Comparator.nullsLast(Comparator.naturalOrder()));
|
||||
|
||||
public static ModVersion parse(String text)
|
||||
{
|
||||
return ModVersion.tryParse(text).orElseThrow(() -> new IllegalArgumentException("Not a version: '" + text + "'."));
|
||||
}
|
||||
|
||||
public static Optional<ModVersion> tryParse(String text)
|
||||
{
|
||||
Matcher matcher = ModVersion.FORMAT.matcher(text.trim());
|
||||
if (!matcher.matches()) return Optional.empty();
|
||||
|
||||
return Optional.of(new ModVersion(
|
||||
Integer.parseInt(matcher.group(1)),
|
||||
ModVersion.partOrZero(matcher.group(2)),
|
||||
ModVersion.partOrZero(matcher.group(3)),
|
||||
matcher.group(4)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a mod built against the API version {@code required} runs with this API version:
|
||||
* same major version and this version not older. Before 1.0 the minor version must match
|
||||
* as well, because 0.x releases may break the API.
|
||||
*/
|
||||
public boolean providesApi(ModVersion required)
|
||||
{
|
||||
if (this.major != required.major || this.compareTo(required) < 0) return false;
|
||||
|
||||
return this.major != 0 || this.minor == required.minor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(ModVersion other) { return ModVersion.ORDER.compare(this, other); }
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
String numbers = this.major + "." + this.minor + "." + this.patch;
|
||||
return this.preRelease == null ? numbers : numbers + "-" + this.preRelease;
|
||||
}
|
||||
|
||||
private static int partOrZero(@Nullable String part) { return part == null ? 0 : Integer.parseInt(part); }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Mod discovery, validation, and loading from {@code <forge>/mods}.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.core.mods;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -0,0 +1,173 @@
|
||||
package dev.overlord.zomboidforge.core.runtime;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Event;
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
import dev.overlord.zomboidforge.api.MainThreadEvent;
|
||||
import dev.overlord.zomboidforge.api.Subscription;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Event dispatch for every mod. Listeners are matched by the event's exact class and called in
|
||||
* registration order. Registration replaces the listener array of a class, so {@link #post}
|
||||
* iterates a snapshot without locks.
|
||||
*/
|
||||
public final class EventBus
|
||||
{
|
||||
/** Failures after which a listener is removed. */
|
||||
static final int MAX_FAILURES = 10;
|
||||
|
||||
private final Map<Class<?>, Listener[]> listeners = new ConcurrentHashMap<>();
|
||||
|
||||
private volatile boolean closed;
|
||||
|
||||
/** Registration for one mod; its listeners are tagged with {@code id}. */
|
||||
public Events forMod(String id, Executor modThread, System.Logger logger) { return new ModEvents(id, modThread, logger); }
|
||||
|
||||
/** Whether any listener is registered for exactly this class. */
|
||||
public boolean hasListeners(Class<? extends Event> type) { return this.listeners.containsKey(type); }
|
||||
|
||||
/**
|
||||
* Delivers {@code event}: main listeners run now, on the calling thread, which must be the
|
||||
* main thread; mod-thread listeners get a task on their mod's thread. A listener's exception
|
||||
* is logged and never reaches the caller.
|
||||
*/
|
||||
public void post(Event event)
|
||||
{
|
||||
if (this.closed) return;
|
||||
|
||||
Listener[] listeners = this.listeners.get(event.getClass());
|
||||
if (listeners == null) return;
|
||||
|
||||
for (Listener listener : listeners) listener.deliver(event);
|
||||
}
|
||||
|
||||
/** Stops delivering events. */
|
||||
public void close() { this.closed = true; }
|
||||
|
||||
private synchronized void add(Listener listener)
|
||||
{
|
||||
Listener[] current = this.listeners.getOrDefault(listener.type, new Listener[0]);
|
||||
Listener[] updated = Arrays.copyOf(current, current.length + 1);
|
||||
|
||||
updated[current.length] = listener;
|
||||
this.listeners.put(listener.type, updated);
|
||||
}
|
||||
|
||||
private synchronized void remove(Listener listener)
|
||||
{
|
||||
Listener[] current = this.listeners.get(listener.type);
|
||||
if (current == null) return;
|
||||
|
||||
Listener[] updated = Arrays.stream(current).filter(other -> other != listener).toArray(Listener[]::new);
|
||||
|
||||
if (updated.length == 0) this.listeners.remove(listener.type);
|
||||
else this.listeners.put(listener.type, updated);
|
||||
}
|
||||
|
||||
private final class ModEvents implements Events
|
||||
{
|
||||
private final String id;
|
||||
private final Executor modThread;
|
||||
private final System.Logger logger;
|
||||
|
||||
private ModEvents(String id, Executor modThread, System.Logger logger)
|
||||
{
|
||||
this.id = id;
|
||||
this.modThread = modThread;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener) { return this.register(type, listener, null); }
|
||||
|
||||
@Override
|
||||
public <E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener)
|
||||
{
|
||||
if (MainThreadEvent.class.isAssignableFrom(type))
|
||||
throw new IllegalArgumentException("'" + type.getName() + "' is a main-thread event; listen with onMain().");
|
||||
|
||||
return this.register(type, listener, this.modThread);
|
||||
}
|
||||
|
||||
private <E extends Event> Subscription register(Class<E> type, Consumer<? super E> listener, @Nullable Executor executor)
|
||||
{
|
||||
Objects.requireNonNull(type, "type");
|
||||
Objects.requireNonNull(listener, "listener");
|
||||
|
||||
Listener registered = new Listener(this.id, type, event -> listener.accept(type.cast(event)), executor, this.logger);
|
||||
EventBus.this.add(registered);
|
||||
|
||||
return registered;
|
||||
}
|
||||
}
|
||||
|
||||
private final class Listener implements Subscription
|
||||
{
|
||||
private final String mod;
|
||||
private final Class<?> type;
|
||||
private final String kind;
|
||||
private final Consumer<Object> action;
|
||||
private final @Nullable Executor executor;
|
||||
private final System.Logger logger;
|
||||
private final AtomicInteger failures = new AtomicInteger();
|
||||
|
||||
private volatile boolean active = true;
|
||||
|
||||
private Listener(String mod, Class<?> type, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
|
||||
{
|
||||
this.mod = mod;
|
||||
this.type = type;
|
||||
this.kind = "listener " + type.getSimpleName();
|
||||
this.action = action;
|
||||
this.executor = executor;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel()
|
||||
{
|
||||
this.active = false;
|
||||
EventBus.this.remove(this);
|
||||
}
|
||||
|
||||
private void deliver(Event event)
|
||||
{
|
||||
if (!this.active) return;
|
||||
|
||||
if (this.executor == null) {
|
||||
this.invoke(event);
|
||||
return;
|
||||
}
|
||||
|
||||
try { this.executor.execute(() -> this.invoke(event)); }
|
||||
catch (RejectedExecutionException e) { /* the mod's thread has been shut down */ }
|
||||
}
|
||||
|
||||
private void invoke(Event event)
|
||||
{
|
||||
if (!this.active) return;
|
||||
|
||||
Throwable failure = ModTaskEvent.run(this.mod, this.kind, () -> this.action.accept(event));
|
||||
if (failure == null) return;
|
||||
|
||||
int count = this.failures.incrementAndGet();
|
||||
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
|
||||
|
||||
if (count >= EventBus.MAX_FAILURES)
|
||||
{
|
||||
this.cancel();
|
||||
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' removed after " + EventBus.MAX_FAILURES + " failures.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user