Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0cd30a0d7 | ||
|
|
a351fc237c | ||
|
|
af7174e128 | ||
|
|
22077514fe | ||
|
|
6761f2d9ea | ||
|
|
18ff32b5ce | ||
|
|
67530d35e9 | ||
|
|
26ca1b90a2 | ||
|
|
36df4a46b9 | ||
|
|
c529b04ff0 | ||
|
|
51e90b6127 | ||
|
|
063ad8a3e1 | ||
|
|
68cd9fc4f9 | ||
|
|
c56046469e | ||
|
|
a0d1ec2feb | ||
|
|
3b21fc3aa6 | ||
|
|
1b4e153898 | ||
|
|
90e54ec295 | ||
|
|
df4d58a279 | ||
|
|
837367047c | ||
|
|
600373dc61 | ||
|
|
0966cdba89 | ||
|
|
30b0b0572f | ||
|
|
c22aa29c88 | ||
|
|
1a53f833e3 | ||
|
|
c9e41e2c91 | ||
|
|
28c36c7eae | ||
|
|
94a026093c | ||
|
|
134901098c | ||
|
|
acef6fd81f | ||
|
|
981445a797 | ||
|
|
da7ae49618 | ||
|
|
d7151f60e8 | ||
|
|
abc6c6c53e | ||
|
|
2b94a49352 | ||
|
|
e13132c202 | ||
|
|
989cb88e0a |
No files matched your search
@@ -9,6 +9,8 @@
|
||||
!compat/
|
||||
!agent/
|
||||
!patcher/
|
||||
!mod-tools/
|
||||
!gradle-plugin/
|
||||
!docker/
|
||||
**/build/
|
||||
**/.gradle/
|
||||
@@ -15,10 +15,13 @@ 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 v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Build and verify
|
||||
env:
|
||||
|
||||
@@ -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,11 +20,14 @@ 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 v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Log in to the registry
|
||||
env:
|
||||
@@ -36,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/
|
||||
|
||||
+60
-12
@@ -6,23 +6,34 @@
|
||||
# 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
|
||||
# server reports another one. Default: pz.version in gradle.properties
|
||||
# STEAMCLIENT bundled (default) or steamcmd: replace the server's steamclient.so
|
||||
# files with steamcmd's newer copies
|
||||
# FORGE_VERSION Image label only; set by ci/release.sh
|
||||
# STEAM_BUILDID Image label only; set by ci/release.sh
|
||||
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
|
||||
# Default: 0.0.0-prerelease
|
||||
# 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)
|
||||
|
||||
ARG PZ_BRANCH=public
|
||||
ARG PZ_VERSION=""
|
||||
ARG STEAMCLIENT=bundled
|
||||
ARG FORGE_VERSION=""
|
||||
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.
|
||||
@@ -33,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.
|
||||
@@ -48,17 +59,53 @@ 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.
|
||||
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
|
||||
# value (default 0.0.0-prerelease): this stage has no git, so the version cannot come from a tag.
|
||||
ARG PZ_VERSION
|
||||
ARG FORGE_VERSION
|
||||
ARG DISABLED_PATCHES=""
|
||||
RUN ./gradlew --no-daemon \
|
||||
-Ppz.jar=/pz/projectzomboid.jar \
|
||||
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
|
||||
build :patcher:patchServerJar
|
||||
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
|
||||
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
|
||||
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.
|
||||
@@ -68,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).
|
||||
@@ -15,13 +15,17 @@ 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` |
|
||||
|
||||
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
|
||||
|
||||
@@ -35,7 +39,7 @@ 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 |
|
||||
@@ -48,7 +52,7 @@ Unset variables keep the value in the server `.ini` (or the game default).
|
||||
| `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_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 |
|
||||
@@ -67,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
|
||||
@@ -78,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.
|
||||
+14
-4
@@ -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 {
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.agent;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -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,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
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));
|
||||
@@ -2,6 +2,22 @@ plugins {
|
||||
java
|
||||
}
|
||||
|
||||
// Version: -Pversion if given, else the newest v* git tag, else 0.0.0-prerelease.
|
||||
if (version == Project.DEFAULT_VERSION)
|
||||
{
|
||||
val latestTag = providers.exec {
|
||||
workingDir = layout.settingsDirectory.asFile
|
||||
commandLine("git", "describe", "--tags", "--abbrev=0", "--match", "v*")
|
||||
isIgnoreExitValue = true
|
||||
}
|
||||
|
||||
version = latestTag.standardOutput.asText
|
||||
.map { it.trim().removePrefix("v") }
|
||||
.orElse("")
|
||||
.get()
|
||||
.ifEmpty { "0.0.0-prerelease" }
|
||||
}
|
||||
|
||||
val projectZomboid = extensions.create<ProjectZomboidExtension>("projectZomboid")
|
||||
projectZomboid.serverJar.convention(
|
||||
layout.settingsDirectory.file(
|
||||
|
||||
@@ -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 "$@"
|
||||
+82
-23
@@ -1,19 +1,30 @@
|
||||
#!/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
|
||||
# <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
|
||||
#
|
||||
# Nothing is built when the immutable tag already exists in the registry.
|
||||
# <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).
|
||||
#
|
||||
# <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
|
||||
# PUBLISH true: push the tags. Default: false (build and verify only)
|
||||
# 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
|
||||
|
||||
@@ -26,7 +37,7 @@ readonly REPO_ROOT
|
||||
|
||||
readonly IMAGE="${IMAGE:?IMAGE is required}"
|
||||
readonly PZ_BRANCH="${PZ_BRANCH:-public}"
|
||||
readonly PUBLISH="${PUBLISH:-false}"
|
||||
readonly REQUESTED_PUBLISH="${PUBLISH:-false}"
|
||||
readonly LATEST="${LATEST:-false}"
|
||||
|
||||
log() {
|
||||
@@ -59,11 +70,40 @@ gradle_property() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# 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 --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
|
||||
}
|
||||
|
||||
image_exists() {
|
||||
local reference="$1"
|
||||
"$(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"
|
||||
@@ -104,35 +144,54 @@ push_as() {
|
||||
|
||||
main() {
|
||||
local forge_version
|
||||
local pz_version
|
||||
local publish="${REQUESTED_PUBLISH}"
|
||||
local pz_prefix
|
||||
local build_id
|
||||
local game_version
|
||||
|
||||
forge_version="$(gradle_property version)"
|
||||
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
|
||||
forge_version="$(release_tag_version)"
|
||||
if [[ -z "${forge_version}" ]]; then
|
||||
forge_version="0.0.0-prerelease"
|
||||
log "No v* git tag found (shallow clone without tags?); using version ${forge_version}."
|
||||
fi
|
||||
if [[ "${forge_version}" == *-* ]]; then
|
||||
publish=false
|
||||
log "${forge_version} is a pre-release version; nothing will be published."
|
||||
fi
|
||||
|
||||
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} (PUBLISH is not true; nothing pushed)"
|
||||
if [[ "${publish}" != true ]]; then
|
||||
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,13 @@ plugins {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":api"))
|
||||
implementation(project(":patcher"))
|
||||
implementation(libs.bundles.asm)
|
||||
|
||||
// Hook classes are read as class files to check that the patches' hooks exist.
|
||||
testImplementation(project(":compat:b42:runtime"))
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.compat.b42;
|
||||
|
||||
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;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Every build-time patch for Build 42, in application order. */
|
||||
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(),
|
||||
new IsoGameCharacterStateMachinePerformancePatch()
|
||||
);
|
||||
|
||||
@Override
|
||||
public int build() { return 42; }
|
||||
|
||||
@Override
|
||||
public @NotNull List<ClassPatch> patches() { return B42PatchSet.PATCHES; }
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import dev.overlord.zomboidforge.patcher.PatchSet;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Every build-time patch for Build 42, in application order. */
|
||||
public final class B42PatchSet implements PatchSet {
|
||||
private static final List<ClassPatch> PATCHES = List.of();
|
||||
|
||||
@Override
|
||||
public int build() {
|
||||
return 42;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ClassPatch> patches() {
|
||||
return PATCHES;
|
||||
}
|
||||
}
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
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.onServerStarted()} in {@code GameServer.main}, directly after
|
||||
* {@code UnitTests.runIfEnabled()} and before the {@code while (!done)} main loop: the world is
|
||||
* loaded, the network port is open, and RCON is initialized.
|
||||
*/
|
||||
public final class ServerStartedPatch extends HookInjectionPatch
|
||||
{
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("main", "([Ljava/lang/String;)V"),
|
||||
"zombie/UnitTests", "runIfEnabled", "()V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onServerStarted", "()V"
|
||||
);
|
||||
|
||||
public ServerStartedPatch() {
|
||||
super("zombie/network/GameServer", ServerStartedPatch.ANCHOR, ServerStartedPatch.HOOK);
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
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;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Stores the {@code StateMachineComponent} of an {@code IsoGameCharacter} in a field, so that
|
||||
* {@code getStateMachineComponent()} does not look it up in the entity's component map on every
|
||||
* call. The lookup walks the class hierarchy of the component class and reads a {@code HashMap}.
|
||||
*
|
||||
* <p>The method is {@code final} and its whole body is the lookup. Every access to the component
|
||||
* goes through it: the 12 call sites in {@code IsoGameCharacter}, among them
|
||||
* {@code getStateMachine()}, {@code getActionContext()} and {@code getAdvancedAnimator()}, which
|
||||
* zombies, players and animals call every frame.
|
||||
* The patched method returns the stored component only while the component's owner is this
|
||||
* character. {@code ECSEntity.setECSComponent} and {@code removeECSComponent} set the owner of a
|
||||
* replaced or removed component to {@code null}, and adding the component to another entity
|
||||
* changes its owner. In every other case the original lookup runs (and throws when the component
|
||||
* is missing, as before), and its result is stored.
|
||||
*/
|
||||
public final class IsoGameCharacterStateMachinePerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
|
||||
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
|
||||
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
|
||||
|
||||
private static final String FIELD_NAME = "zomboidForge$stateMachineComponent";
|
||||
private static final String FIELD_DESC = "L" + IsoGameCharacterStateMachinePerformancePatch.COMPONENT + ";";
|
||||
|
||||
private static final Anchor.Method GETTER = new Anchor.Method("getStateMachineComponent", "()" + IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC);
|
||||
|
||||
/** {@code return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);} */
|
||||
private static final Anchor.Sequence LOOKUP = new Anchor.Sequence(
|
||||
IsoGameCharacterStateMachinePerformancePatch.GETTER,
|
||||
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
|
||||
new Anchor.Instruction.Constant(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatch.COMPONENT)),
|
||||
new Anchor.Instruction.Invoke(
|
||||
IsoGameCharacterStateMachinePerformancePatch.CHARACTER, "getECSComponent",
|
||||
"(Ljava/lang/Class;)L" + IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT + ";"
|
||||
),
|
||||
new Anchor.Instruction.Opcode(Opcodes.CHECKCAST),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||
);
|
||||
|
||||
public IsoGameCharacterStateMachinePerformancePatch() {
|
||||
super(IsoGameCharacterStateMachinePerformancePatch.CHARACTER, IsoGameCharacterStateMachinePerformancePatch.LOOKUP, null);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
IsoGameCharacterStateMachinePerformancePatch.requireNoFieldNamed(node);
|
||||
|
||||
MethodNode method = IsoGameCharacterStateMachinePerformancePatch.GETTER.resolve(node);
|
||||
List<AbstractInsnNode> lookup = IsoGameCharacterStateMachinePerformancePatch.LOOKUP.resolve(node);
|
||||
|
||||
long instructions = Arrays.stream(method.instructions.toArray())
|
||||
.filter(instruction -> instruction.getOpcode() != -1)
|
||||
.count();
|
||||
|
||||
if (instructions != lookup.size())
|
||||
throw new IllegalStateException("'" + node.name + ".getStateMachineComponent' does more than the component lookup.");
|
||||
|
||||
node.fields.add(new FieldNode(
|
||||
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
|
||||
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
|
||||
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC,
|
||||
null, null
|
||||
));
|
||||
|
||||
method.instructions.insertBefore(lookup.getLast(), IsoGameCharacterStateMachinePerformancePatch.store());
|
||||
// The body is only the lookup, so the first slot after 'this' and the arguments is free.
|
||||
int stored = Type.getArgumentsAndReturnSizes(method.desc) >> 2;
|
||||
method.instructions.insert(IsoGameCharacterStateMachinePerformancePatch.returnStored(stored));
|
||||
}
|
||||
|
||||
/** The patch must not collide with a field of the game class, e.g. after an update. */
|
||||
private static void requireNoFieldNamed(ClassNode node)
|
||||
{
|
||||
boolean exists = node.fields.stream()
|
||||
.anyMatch(field -> field.name.equals(IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME));
|
||||
|
||||
if (exists) throw new IllegalStateException("'" + node.name + "' already has a field named '" + IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME + "'.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Placed at the start of the method:
|
||||
*
|
||||
* <pre>{@code
|
||||
* StateMachineComponent stored = this.zomboidForge$stateMachineComponent;
|
||||
* if (stored != null && stored.getECSOwnerEntity() == this) return stored;
|
||||
* }</pre>
|
||||
*/
|
||||
private static InsnList returnStored(int stored)
|
||||
{
|
||||
LabelNode lookup = new LabelNode();
|
||||
InsnList code = new InsnList();
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.GETFIELD));
|
||||
code.add(new VarInsnNode(Opcodes.ASTORE, stored));
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
|
||||
code.add(new JumpInsnNode(Opcodes.IFNULL, lookup));
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
|
||||
code.add(new MethodInsnNode(
|
||||
Opcodes.INVOKEVIRTUAL,
|
||||
IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT,
|
||||
"getECSOwnerEntity",
|
||||
"()Lzombie/characters/ecs/ECSEntity;",
|
||||
false
|
||||
));
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
code.add(new JumpInsnNode(Opcodes.IF_ACMPNE, lookup));
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
|
||||
code.add(new InsnNode(Opcodes.ARETURN));
|
||||
code.add(lookup);
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Placed before the {@code areturn} of the lookup, with the component on the operand stack:
|
||||
* {@code this.zomboidForge$stateMachineComponent = component}, leaving the component on the stack.
|
||||
*/
|
||||
private static InsnList store()
|
||||
{
|
||||
InsnList code = new InsnList();
|
||||
|
||||
code.add(new InsnNode(Opcodes.DUP));
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
code.add(new InsnNode(Opcodes.SWAP));
|
||||
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.PUTFIELD));
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
private static FieldInsnNode field(int opcode)
|
||||
{
|
||||
return new FieldInsnNode(
|
||||
opcode,
|
||||
IsoGameCharacterStateMachinePerformancePatch.CHARACTER,
|
||||
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
|
||||
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC
|
||||
);
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
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.LdcInsnNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.TypeInsnNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
/**
|
||||
* Stores the {@code NetworkZombieComponent} of an {@code IsoZombie} in a field instead of
|
||||
* looking it up in the entity's component map on every call.
|
||||
*
|
||||
* <p>Every call site in {@code IsoZombie} has the same shape:
|
||||
* {@code (NetworkZombieComponent) this.tryGetECSComponent(NetworkZombieComponent.class)}. The
|
||||
* lookup walks the class hierarchy of the component class and reads a {@code HashMap}. The
|
||||
* component is registered once by the {@code IsoObject} constructor and is never replaced or
|
||||
* removed, so a value read once stays valid for the life of the zombie.
|
||||
*
|
||||
* <p>The patch adds the field and a private method that fills it on first use, and replaces the
|
||||
* three instructions of each call site with a call to that method. A missing component is not
|
||||
* stored: the method then returns {@code null} like the lookup does.
|
||||
*/
|
||||
public final class IsoZombieNetworkComponentPerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final String ZOMBIE = "zombie/characters/IsoZombie";
|
||||
private static final String COMPONENT = "zombie/characters/component/NetworkZombieComponent";
|
||||
|
||||
private static final String LOOKUP_NAME = "tryGetECSComponent";
|
||||
private static final String LOOKUP_DESC = "(Ljava/lang/Class;)Lzombie/characters/ecs/ECSComponent;";
|
||||
|
||||
private static final String FIELD_NAME = "zomboidForge$networkComponent";
|
||||
private static final String FIELD_DESC = "L" + IsoZombieNetworkComponentPerformancePatch.COMPONENT + ";";
|
||||
|
||||
private static final String ACCESSOR_NAME = "zomboidForge$networkComponent";
|
||||
private static final String ACCESSOR_DESC = "()" + IsoZombieNetworkComponentPerformancePatch.FIELD_DESC;
|
||||
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("getOwner", "()Lzombie/core/raknet/UdpConnection;"),
|
||||
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
|
||||
IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME,
|
||||
IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC
|
||||
);
|
||||
|
||||
public IsoZombieNetworkComponentPerformancePatch() {
|
||||
super(IsoZombieNetworkComponentPerformancePatch.ZOMBIE, IsoZombieNetworkComponentPerformancePatch.ANCHOR, null);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
IsoZombieNetworkComponentPerformancePatch.requireNoMemberNamed(node);
|
||||
|
||||
node.fields.add(new FieldNode(Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC, IsoZombieNetworkComponentPerformancePatch.FIELD_NAME, IsoZombieNetworkComponentPerformancePatch.FIELD_DESC, null, null));
|
||||
node.methods.add(IsoZombieNetworkComponentPerformancePatch.accessor());
|
||||
|
||||
for (MethodNode method : node.methods) {
|
||||
IsoZombieNetworkComponentPerformancePatch.replaceLookups(method);
|
||||
}
|
||||
}
|
||||
|
||||
/** The patch must not collide with a member of the game class, e.g. after an update. */
|
||||
private static void requireNoMemberNamed(ClassNode node)
|
||||
{
|
||||
boolean fieldExists = node.fields.stream()
|
||||
.anyMatch(field -> field.name.equals(IsoZombieNetworkComponentPerformancePatch.FIELD_NAME));
|
||||
boolean methodExists = node.methods.stream()
|
||||
.anyMatch(method -> method.name.equals(IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME));
|
||||
|
||||
if (fieldExists || methodExists)
|
||||
throw new IllegalStateException("'" + node.name + "' already has a member named '" + IsoZombieNetworkComponentPerformancePatch.FIELD_NAME + "'.");
|
||||
}
|
||||
|
||||
/**
|
||||
* <pre>{@code
|
||||
* private NetworkZombieComponent zomboidForge$networkComponent()
|
||||
* {
|
||||
* NetworkZombieComponent component = this.zomboidForge$networkComponent;
|
||||
*
|
||||
* if (component == null) {
|
||||
* component = (NetworkZombieComponent) this.tryGetECSComponent(NetworkZombieComponent.class);
|
||||
* this.zomboidForge$networkComponent = component;
|
||||
* }
|
||||
*
|
||||
* return component;
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
private static MethodNode accessor()
|
||||
{
|
||||
MethodNode method = new MethodNode(
|
||||
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
|
||||
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME,
|
||||
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_DESC,
|
||||
null, null
|
||||
);
|
||||
LabelNode filled = new LabelNode();
|
||||
InsnList code = method.instructions;
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
code.add(new FieldInsnNode(
|
||||
Opcodes.GETFIELD,
|
||||
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
|
||||
IsoZombieNetworkComponentPerformancePatch.FIELD_NAME,
|
||||
IsoZombieNetworkComponentPerformancePatch.FIELD_DESC
|
||||
));
|
||||
code.add(new VarInsnNode(Opcodes.ASTORE, 1));
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
|
||||
code.add(new JumpInsnNode(Opcodes.IFNONNULL, filled));
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
code.add(new LdcInsnNode(Type.getObjectType(IsoZombieNetworkComponentPerformancePatch.COMPONENT)));
|
||||
code.add(new MethodInsnNode(
|
||||
Opcodes.INVOKEVIRTUAL,
|
||||
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
|
||||
IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME,
|
||||
IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC,
|
||||
false
|
||||
));
|
||||
code.add(new TypeInsnNode(Opcodes.CHECKCAST, IsoZombieNetworkComponentPerformancePatch.COMPONENT));
|
||||
code.add(new VarInsnNode(Opcodes.ASTORE, 1));
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
|
||||
code.add(new FieldInsnNode(
|
||||
Opcodes.PUTFIELD,
|
||||
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
|
||||
IsoZombieNetworkComponentPerformancePatch.FIELD_NAME,
|
||||
IsoZombieNetworkComponentPerformancePatch.FIELD_DESC
|
||||
));
|
||||
|
||||
code.add(filled);
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
|
||||
code.add(new InsnNode(Opcodes.ARETURN));
|
||||
|
||||
return method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces {@code ldc NetworkZombieComponent; invokevirtual tryGetECSComponent; checkcast
|
||||
* NetworkZombieComponent} with {@code invokespecial zomboidForge$networkComponent}. The
|
||||
* receiver is on the operand stack before and after, and the component instead of the
|
||||
* {@code Class} leaves it, so the stack stays the same. The accessor itself is skipped: it
|
||||
* contains the same three instructions.
|
||||
*/
|
||||
private static void replaceLookups(MethodNode method)
|
||||
{
|
||||
if (method.name.equals(IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME)) return;
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions.toArray())
|
||||
{
|
||||
if (!IsoZombieNetworkComponentPerformancePatch.isLookup(instruction)) continue;
|
||||
|
||||
@Nullable AbstractInsnNode load = IsoZombieNetworkComponentPerformancePatch.previousInstruction(instruction);
|
||||
@Nullable AbstractInsnNode cast = IsoZombieNetworkComponentPerformancePatch.nextInstruction(instruction);
|
||||
|
||||
if (!IsoZombieNetworkComponentPerformancePatch.isComponentClassLiteral(load)) continue;
|
||||
if (!IsoZombieNetworkComponentPerformancePatch.isComponentCast(cast)) continue;
|
||||
|
||||
method.instructions.remove(load);
|
||||
method.instructions.remove(cast);
|
||||
method.instructions.set(
|
||||
instruction, new MethodInsnNode(
|
||||
Opcodes.INVOKESPECIAL,
|
||||
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
|
||||
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME,
|
||||
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_DESC,
|
||||
false
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static boolean isLookup(AbstractInsnNode instruction)
|
||||
{
|
||||
return instruction instanceof MethodInsnNode call
|
||||
&& call.getOpcode() == Opcodes.INVOKEVIRTUAL
|
||||
&& call.owner.equals(IsoZombieNetworkComponentPerformancePatch.ZOMBIE)
|
||||
&& call.name.equals(IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME)
|
||||
&& call.desc.equals(IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC);
|
||||
}
|
||||
|
||||
private static boolean isComponentClassLiteral(@Nullable AbstractInsnNode instruction)
|
||||
{
|
||||
return instruction instanceof LdcInsnNode ldc
|
||||
&& ldc.cst instanceof Type type
|
||||
&& type.getInternalName().equals(IsoZombieNetworkComponentPerformancePatch.COMPONENT);
|
||||
}
|
||||
|
||||
private static boolean isComponentCast(@Nullable AbstractInsnNode instruction)
|
||||
{
|
||||
return instruction instanceof TypeInsnNode cast
|
||||
&& cast.getOpcode() == Opcodes.CHECKCAST
|
||||
&& cast.desc.equals(IsoZombieNetworkComponentPerformancePatch.COMPONENT);
|
||||
}
|
||||
|
||||
/** The closest earlier instruction that is not a label, line number, or frame; {@code null} at the start of the method. */
|
||||
private static @Nullable AbstractInsnNode previousInstruction(AbstractInsnNode instruction)
|
||||
{
|
||||
AbstractInsnNode previous = instruction.getPrevious();
|
||||
while (previous != null && previous.getOpcode() == -1) previous = previous.getPrevious();
|
||||
|
||||
return previous;
|
||||
}
|
||||
|
||||
/** The closest later instruction that is not a label, line number, or frame; {@code null} at the end of the method. */
|
||||
private static @Nullable AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
|
||||
{
|
||||
AbstractInsnNode next = instruction.getNext();
|
||||
while (next != null && next.getOpcode() == -1) next = next.getNext();
|
||||
|
||||
return next;
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
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.MethodNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skips the spot-chance modifiers in {@code IsoZombie.spottedNew} when the chance is already 0.
|
||||
*
|
||||
* <p>Between {@code if (bForced) chance = 1000000F} and {@code chance = (float)
|
||||
* PZMath.fastfloor(chance)} the method only multiplies or divides {@code chance}: bonus spot
|
||||
* time, sight, inactivity, traits of the player, shelter ({@code getObstacleMod}),
|
||||
* {@code isVehicleBetween}, worn items, eating. A chance of 0 stays 0, or becomes NaN when divided
|
||||
* by 0, and the roll {@code Rand.Next(10000) / 100F < chance} fails for both. The chance is 0 when
|
||||
* the player is outside the zombie's vision radius or behind it, and is never 0 for a forced spot.
|
||||
*
|
||||
* <p>The patch inserts {@code if (chance == 0F) goto rounding} after the forced-spot assignment.
|
||||
* The rounding, the roll (with its {@code Rand.Next} draw) and the failed-roll branch run as in
|
||||
* vanilla. The early return for a nearer current target comes before the jump. The skipped code
|
||||
* writes no field or local that is read after the jump; it writes the shared scratch vector
|
||||
* {@code IsoGameCharacter.tempo}, which other code sets before reading, except client debug drawing.
|
||||
*/
|
||||
public final class IsoZombieSpotChancePerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final Anchor.Method SPOTTED_NEW = new Anchor.Method("spottedNew", "(Lzombie/iso/IsoMovingObject;Z)V");
|
||||
|
||||
/** {@code if (bForced) chance = 1000000F;}: the store of the forced chance. */
|
||||
private static final Anchor.Sequence FORCED_CHANCE = new Anchor.Sequence(
|
||||
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
|
||||
new Anchor.Instruction.Constant(1000000.0F),
|
||||
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
|
||||
);
|
||||
|
||||
/** {@code chance = (float) PZMath.fastfloor(chance);}: the rounding before the roll. */
|
||||
private static final Anchor.Sequence ROUNDING = new Anchor.Sequence(
|
||||
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
|
||||
new Anchor.Instruction.Opcode(Opcodes.FLOAD),
|
||||
new Anchor.Instruction.Invoke("zombie/core/math/PZMath", "fastfloor", "(F)I"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.I2F),
|
||||
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
|
||||
);
|
||||
|
||||
public IsoZombieSpotChancePerformancePatch() {
|
||||
super("zombie/characters/IsoZombie", IsoZombieSpotChancePerformancePatch.FORCED_CHANCE, null);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode method = IsoZombieSpotChancePerformancePatch.SPOTTED_NEW.resolve(node);
|
||||
List<AbstractInsnNode> forced = IsoZombieSpotChancePerformancePatch.FORCED_CHANCE.resolve(node);
|
||||
List<AbstractInsnNode> rounding = IsoZombieSpotChancePerformancePatch.ROUNDING.resolve(node);
|
||||
|
||||
AbstractInsnNode forcedStore = forced.getLast();
|
||||
AbstractInsnNode roundingLoad = rounding.getFirst();
|
||||
int chance = ((VarInsnNode) forcedStore).var;
|
||||
|
||||
IsoZombieSpotChancePerformancePatch.requireVariable(roundingLoad, chance);
|
||||
IsoZombieSpotChancePerformancePatch.requireVariable(rounding.getLast(), chance);
|
||||
|
||||
if (method.instructions.indexOf(roundingLoad) < method.instructions.indexOf(forcedStore))
|
||||
throw new IllegalStateException("'" + node.name + ".spottedNew': the rounding of 'chance' comes before the forced-spot assignment.");
|
||||
|
||||
// The check goes after the label that the 'if (bForced)' jump targets, so both paths run it.
|
||||
// Inserting it before the new label keeps it ahead of that label if both precede the same instruction.
|
||||
LabelNode roundingLabel = new LabelNode();
|
||||
|
||||
method.instructions.insertBefore(
|
||||
IsoZombieSpotChancePerformancePatch.nextInstruction(forcedStore),
|
||||
IsoZombieSpotChancePerformancePatch.jumpIfZero(chance, roundingLabel)
|
||||
);
|
||||
method.instructions.insertBefore(roundingLoad, roundingLabel);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code if (chance == 0F) goto target}. {@code fcmpl} pushes -1 for NaN, so NaN does not
|
||||
* jump; -0F does.
|
||||
*/
|
||||
private static InsnList jumpIfZero(int chance, LabelNode target)
|
||||
{
|
||||
InsnList code = new InsnList();
|
||||
|
||||
code.add(new VarInsnNode(Opcodes.FLOAD, chance));
|
||||
code.add(new InsnNode(Opcodes.FCONST_0));
|
||||
code.add(new InsnNode(Opcodes.FCMPL));
|
||||
code.add(new JumpInsnNode(Opcodes.IFEQ, target));
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
private static void requireVariable(AbstractInsnNode instruction, int chance)
|
||||
{
|
||||
int variable = ((VarInsnNode) instruction).var;
|
||||
|
||||
if (variable != chance)
|
||||
throw new IllegalStateException("'IsoZombie.spottedNew': the rounding uses local " + variable + ", the forced-spot assignment local " + chance + ".");
|
||||
}
|
||||
|
||||
/** The closest later instruction that is not a label, line number, or frame. */
|
||||
private static AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
|
||||
{
|
||||
AbstractInsnNode next = instruction.getNext();
|
||||
while (next != null && next.getOpcode() == -1) next = next.getNext();
|
||||
|
||||
if (next == null) throw new IllegalStateException("'IsoZombie.spottedNew' ends after the forced-spot assignment.");
|
||||
|
||||
return next;
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.FieldInsnNode;
|
||||
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;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
/**
|
||||
* Makes {@code IsoZombie.isVehicleBetween} cheaper without changing its result, in two steps:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Returns {@code false} at the start of the method when the cell has no vehicles. The
|
||||
* loop would not run, but the three pooled vectors are allocated and released first.</li>
|
||||
* <li>Replaces the call to {@code BaseVehicle.getIntersectPoint} with
|
||||
* {@code ZombieVehicleHooks.getIntersectPoint}, which skips vehicles that the segment
|
||||
* cannot reach.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class IsoZombieVehiclePerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("isVehicleBetween", "(FFF)Z"),
|
||||
"zombie/vehicles/BaseVehicle", "getIntersectPoint",
|
||||
"(Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", "getIntersectPoint",
|
||||
"(Lzombie/vehicles/BaseVehicle;Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
|
||||
);
|
||||
|
||||
public IsoZombieVehiclePerformancePatch() {
|
||||
super("zombie/characters/IsoZombie", IsoZombieVehiclePerformancePatch.ANCHOR, IsoZombieVehiclePerformancePatch.HOOK);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode method = IsoZombieVehiclePerformancePatch.ANCHOR.in().resolve(node);
|
||||
MethodInsnNode call = IsoZombieVehiclePerformancePatch.ANCHOR.resolve(node);
|
||||
|
||||
// The hook takes the receiver as its first argument, so the operand stack is the same
|
||||
// as for the virtual call it replaces: vehicle, start, end, result -> Vector3f.
|
||||
method.instructions.set(call, new MethodInsnNode(
|
||||
Opcodes.INVOKESTATIC,
|
||||
IsoZombieVehiclePerformancePatch.HOOK.owner(),
|
||||
IsoZombieVehiclePerformancePatch.HOOK.name(),
|
||||
IsoZombieVehiclePerformancePatch.HOOK.desc(),
|
||||
false
|
||||
));
|
||||
|
||||
method.instructions.insert(IsoZombieVehiclePerformancePatch.returnFalseWithoutVehicles());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code if (IsoWorld.instance.currentCell.getVehicles().isEmpty()) return false;}, the same
|
||||
* expression the method iterates over. The method starts with an empty operand stack, so the
|
||||
* stack map frame at the jump target is the one of the method entry; the class writer
|
||||
* computes it.
|
||||
*/
|
||||
private static InsnList returnFalseWithoutVehicles()
|
||||
{
|
||||
LabelNode hasVehicles = new LabelNode();
|
||||
InsnList code = new InsnList();
|
||||
|
||||
code.add(new FieldInsnNode(Opcodes.GETSTATIC, "zombie/iso/IsoWorld", "instance", "Lzombie/iso/IsoWorld;"));
|
||||
code.add(new FieldInsnNode(Opcodes.GETFIELD, "zombie/iso/IsoWorld", "currentCell", "Lzombie/iso/IsoCell;"));
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "zombie/iso/IsoCell", "getVehicles", "()Ljava/util/Set;", false));
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "java/util/Set", "isEmpty", "()Z", true));
|
||||
code.add(new JumpInsnNode(Opcodes.IFEQ, hasVehicles));
|
||||
code.add(new InsnNode(Opcodes.ICONST_0));
|
||||
code.add(new InsnNode(Opcodes.IRETURN));
|
||||
code.add(hasVehicles);
|
||||
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+1
-1
@@ -1 +1 @@
|
||||
dev.overlord.zomboidforge.compat.b42.patches.B42PatchSet
|
||||
dev.overlord.zomboidforge.compat.b42.B42PatchSet
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The patcher does not check that a hook exists; a missing one fails only when the patched
|
||||
* game code runs, with a {@code NoSuchMethodError}. The hook classes are read as class files
|
||||
* because their signatures may mention game classes, which are not on this class path.
|
||||
*/
|
||||
class HookExistenceTest
|
||||
{
|
||||
@Test
|
||||
void everyHookOfThePatchSetExistsAsPublicStaticMethod() throws IOException
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (ClassPatch patch : new B42PatchSet().patches())
|
||||
{
|
||||
Hook hook = patch.hook();
|
||||
if (hook == null) continue;
|
||||
|
||||
String problem = HookExistenceTest.problemWith(hook);
|
||||
if (problem != null) problems.add("'" + patch.getClass().getSimpleName() + "': " + problem);
|
||||
}
|
||||
|
||||
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsAnExistingPublicStaticMethod() throws IOException
|
||||
{
|
||||
assertNull(HookExistenceTest.problemWith(new Hook("java/lang/String", "valueOf", "(I)Ljava/lang/String;")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsMissingClass() throws IOException
|
||||
{
|
||||
assertEquals(
|
||||
"Hook class 't/Missing' not found on the class path",
|
||||
HookExistenceTest.problemWith(new Hook("t/Missing", "hook", "()V"))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsMissingMethodOrDescriptor() throws IOException
|
||||
{
|
||||
assertEquals(
|
||||
"Hook method 'java/lang/String.nope()V' not found",
|
||||
HookExistenceTest.problemWith(new Hook("java/lang/String", "nope", "()V"))
|
||||
);
|
||||
assertEquals(
|
||||
"Hook method 'java/lang/String.valueOf(Z)V' not found",
|
||||
HookExistenceTest.problemWith(new Hook("java/lang/String", "valueOf", "(Z)V"))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsMethodThatIsNotPublicStatic() throws IOException
|
||||
{
|
||||
assertEquals(
|
||||
"Hook method 'java/lang/String.length()I' is not public static",
|
||||
HookExistenceTest.problemWith(new Hook("java/lang/String", "length", "()I"))
|
||||
);
|
||||
}
|
||||
|
||||
/** @return a description of what is wrong with {@code hook}, or {@code null} if it is usable */
|
||||
private static String problemWith(Hook hook) throws IOException
|
||||
{
|
||||
try (InputStream in = ClassLoader.getSystemResourceAsStream(hook.owner() + ".class"))
|
||||
{
|
||||
if (in == null) return "Hook class '" + hook.owner() + "' not found on the class path";
|
||||
|
||||
ClassNode node = new ClassNode();
|
||||
new ClassReader(in).accept(node, ClassReader.SKIP_CODE);
|
||||
|
||||
String description = "Hook method '" + hook.owner() + "." + hook.name() + hook.desc() + "'";
|
||||
|
||||
for (MethodNode method : node.methods)
|
||||
{
|
||||
if (!method.name.equals(hook.name()) || !method.desc.equals(hook.desc())) continue;
|
||||
|
||||
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
|
||||
return publicStatic ? null : description + " is not public static";
|
||||
}
|
||||
|
||||
return description + " not found";
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Structure rules for Build 42 patches and hooks. Class names end in {@code Patch} and
|
||||
* {@code Hooks}, so a class is recognizable as one or the other from its name alone.
|
||||
*/
|
||||
class NamingRulesTest
|
||||
{
|
||||
private static final List<String> PATCH_PACKAGES = List.of(
|
||||
"dev/overlord/zomboidforge/compat/b42/patches",
|
||||
"dev/overlord/zomboidforge/compat/b42/perf"
|
||||
);
|
||||
private static final String HOOKS_PACKAGE = "dev/overlord/zomboidforge/compat/b42/hooks";
|
||||
|
||||
@Test
|
||||
void patchClassesEndInPatch() throws Exception
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (String patchPackage : NamingRulesTest.PATCH_PACKAGES)
|
||||
{
|
||||
List<String> names = PackageScan.topLevelClassNames(patchPackage);
|
||||
|
||||
assertFalse(names.isEmpty(), "No classes found in '" + patchPackage + "'.");
|
||||
|
||||
for (String name : names)
|
||||
{
|
||||
if (!name.endsWith("Patch")) problems.add("'" + patchPackage + "/" + name + "' must end in 'Patch'.");
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hookClassesEndInHooksAndExposeOnlyPublicStaticMethods() throws Exception
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
List<String> names = PackageScan.topLevelClassNames(NamingRulesTest.HOOKS_PACKAGE);
|
||||
|
||||
assertFalse(names.isEmpty(), "No classes found in '" + NamingRulesTest.HOOKS_PACKAGE + "'");
|
||||
|
||||
for (String name : names)
|
||||
{
|
||||
if (!name.endsWith("Hooks")) problems.add("'" + name + "' must end in 'Hooks'");
|
||||
|
||||
ClassNode node = PackageScan.read(NamingRulesTest.HOOKS_PACKAGE + "/" + name);
|
||||
if ((node.access & Opcodes.ACC_FINAL) == 0) problems.add("'" + name + "' must be final");
|
||||
|
||||
for (MethodNode method : node.methods)
|
||||
{
|
||||
if ((method.access & Opcodes.ACC_SYNTHETIC) != 0 || method.name.equals("<clinit>")) continue;
|
||||
|
||||
if (method.name.equals("<init>"))
|
||||
{
|
||||
if ((method.access & Opcodes.ACC_PRIVATE) == 0) problems.add("'" + name + "' constructor must be private");
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
|
||||
if (!publicStatic) problems.add("'" + name + "." + method.name + method.desc + "' must be public static");
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A patch class that is not in {@link B42PatchSet} is never applied. Patches are switched off
|
||||
* for debug builds with the {@code zf.disabledPatches} Gradle property, not by removing them
|
||||
* from the patch set.
|
||||
*/
|
||||
class PatchSetRegistrationTest
|
||||
{
|
||||
private static final List<String> PATCH_PACKAGES = List.of(
|
||||
"dev/overlord/zomboidforge/compat/b42/patches",
|
||||
"dev/overlord/zomboidforge/compat/b42/perf"
|
||||
);
|
||||
|
||||
@Test
|
||||
void everyPatchClassIsRegisteredExactlyOnce() throws Exception
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
Set<String> registered = new TreeSet<>();
|
||||
|
||||
for (ClassPatch patch : new B42PatchSet().patches())
|
||||
{
|
||||
String name = patch.getClass().getSimpleName();
|
||||
if (!registered.add(name)) problems.add("'" + name + "' is registered more than once.");
|
||||
}
|
||||
|
||||
for (String patchPackage : PatchSetRegistrationTest.PATCH_PACKAGES)
|
||||
{
|
||||
for (String name : PackageScan.topLevelClassNames(patchPackage))
|
||||
{
|
||||
boolean abstractClass = (PackageScan.read(patchPackage + "/" + name).access & Opcodes.ACC_ABSTRACT) != 0;
|
||||
|
||||
if (name.endsWith("Patch") && !abstractClass && !registered.contains(name)) {
|
||||
problems.add("'" + name + "' is not registered in 'B42PatchSet'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
|
||||
}
|
||||
}
|
||||
+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 + "'.");
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches.support;
|
||||
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
|
||||
/**
|
||||
* Class loader that defines classes from {@link ClassNode}s, so patched test classes can be loaded
|
||||
* and run. Lives in a subpackage so that the scanned packages do not contain it.
|
||||
*/
|
||||
public final class ClassDefiner extends ClassLoader
|
||||
{
|
||||
public ClassDefiner() { super(ClassDefiner.class.getClassLoader()); }
|
||||
|
||||
/**
|
||||
* Writes {@code node} with computed frames and defines it. Classes that the frame computation
|
||||
* needs (common superclasses) must be defined first.
|
||||
*/
|
||||
public Class<?> define(ClassNode node)
|
||||
{
|
||||
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES)
|
||||
{
|
||||
@Override
|
||||
protected ClassLoader getClassLoader() { return ClassDefiner.this; }
|
||||
};
|
||||
node.accept(writer);
|
||||
|
||||
byte[] bytes = writer.toByteArray();
|
||||
return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches.support;
|
||||
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.JarURLConnection;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Lists and reads the classes of a package on the test class path, without loading them. Lives in
|
||||
* a subpackage so that the scanned packages do not contain it.
|
||||
*/
|
||||
public final class PackageScan
|
||||
{
|
||||
private PackageScan() {}
|
||||
|
||||
/** Simple names of the top-level non-test classes in {@code packagePath}, from a directory or a jar on the class path. */
|
||||
public static List<String> topLevelClassNames(String packagePath) throws IOException, URISyntaxException
|
||||
{
|
||||
List<String> names = new ArrayList<>();
|
||||
|
||||
for (URL url : Collections.list(ClassLoader.getSystemResources(packagePath)))
|
||||
{
|
||||
if (url.getProtocol().equals("file"))
|
||||
{
|
||||
try (Stream<Path> files = Files.list(Path.of(url.toURI()))) {
|
||||
files.map(file -> file.getFileName().toString()).forEach(names::add);
|
||||
}
|
||||
}
|
||||
else if (url.getProtocol().equals("jar"))
|
||||
{
|
||||
JarURLConnection connection = (JarURLConnection) url.openConnection();
|
||||
connection.getJarFile().stream()
|
||||
.map(entry -> entry.getName())
|
||||
.filter(entry -> entry.startsWith(packagePath + "/") && entry.indexOf('/', packagePath.length() + 1) < 0)
|
||||
.map(entry -> entry.substring(packagePath.length() + 1))
|
||||
.forEach(names::add);
|
||||
}
|
||||
}
|
||||
|
||||
return names.stream()
|
||||
.filter(file -> file.endsWith(".class") && !file.contains("$") && !file.equals("package-info.class"))
|
||||
.filter(file -> !file.endsWith("Test.class"))
|
||||
.map(file -> file.substring(0, file.length() - ".class".length()))
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static ClassNode read(String internalName) throws IOException
|
||||
{
|
||||
try (InputStream in = ClassLoader.getSystemResourceAsStream(internalName + ".class"))
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
new ClassReader(in).accept(node, ClassReader.SKIP_CODE);
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.patches.support;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
|
||||
import static org.objectweb.asm.Opcodes.ACC_FINAL;
|
||||
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
|
||||
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.ARETURN;
|
||||
import static org.objectweb.asm.Opcodes.CHECKCAST;
|
||||
import static org.objectweb.asm.Opcodes.GETFIELD;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.IADD;
|
||||
import static org.objectweb.asm.Opcodes.ICONST_1;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.NOP;
|
||||
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class IsoGameCharacterStateMachinePerformancePatchTest
|
||||
{
|
||||
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
|
||||
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
|
||||
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
|
||||
private static final String ECS_ENTITY = "zombie/characters/ecs/ECSEntity";
|
||||
|
||||
private Class<?> characterClass = Object.class;
|
||||
private Class<?> componentClass = Object.class;
|
||||
|
||||
/**
|
||||
* {@code IsoGameCharacter} whose lookup counts its calls and returns the field {@code current}:
|
||||
*
|
||||
* <pre>{@code
|
||||
* public static int lookups;
|
||||
* public ECSComponent current;
|
||||
*
|
||||
* public ECSComponent getECSComponent(Class type) { lookups++; return this.current; }
|
||||
*
|
||||
* public final StateMachineComponent getStateMachineComponent() {
|
||||
* return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
private static ClassNode character()
|
||||
{
|
||||
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
|
||||
IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "java/lang/Object", IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY
|
||||
);
|
||||
String component = "L" + IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT + ";";
|
||||
String ecsComponent = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT + ";";
|
||||
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "lookups", "I", null, null);
|
||||
node.visitField(ACC_PUBLIC, "current", ecsComponent, null, null);
|
||||
|
||||
MethodVisitor lookup = node.visitMethod(ACC_PUBLIC, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, null, null);
|
||||
lookup.visitFieldInsn(GETSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
|
||||
lookup.visitInsn(ICONST_1);
|
||||
lookup.visitInsn(IADD);
|
||||
lookup.visitFieldInsn(PUTSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
|
||||
lookup.visitVarInsn(ALOAD, 0);
|
||||
lookup.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "current", ecsComponent);
|
||||
lookup.visitInsn(ARETURN);
|
||||
lookup.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor getter = node.visitMethod(ACC_PUBLIC | ACC_FINAL, "getStateMachineComponent", "()" + component, null, null);
|
||||
getter.visitVarInsn(ALOAD, 0);
|
||||
getter.visitLdcInsn(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT));
|
||||
getter.visitMethodInsn(INVOKEVIRTUAL, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, false);
|
||||
getter.visitTypeInsn(CHECKCAST, IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT);
|
||||
getter.visitInsn(ARETURN);
|
||||
getter.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** {@code ECSComponent} with a public field {@code owner} that {@code getECSOwnerEntity()} returns. */
|
||||
private static ClassNode ecsComponent()
|
||||
{
|
||||
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "java/lang/Object", null);
|
||||
String owner = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY + ";";
|
||||
|
||||
node.visitField(ACC_PUBLIC, "owner", owner, null, null);
|
||||
|
||||
MethodVisitor getter = node.visitMethod(ACC_PUBLIC, "getECSOwnerEntity", "()" + owner, null, null);
|
||||
getter.visitVarInsn(ALOAD, 0);
|
||||
getter.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "owner", owner);
|
||||
getter.visitInsn(ARETURN);
|
||||
getter.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static ClassNode ecsEntity()
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY, null, "java/lang/Object", null);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Public class with a public no-argument constructor. */
|
||||
private static ClassNode emptyClass(String name, String superName, @Nullable String interfaceName)
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, name, null, superName, interfaceName == null ? null : new String[] { interfaceName });
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||
init.visitVarInsn(ALOAD, 0);
|
||||
init.visitMethodInsn(INVOKESPECIAL, superName, "<init>", "()V", false);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static ClassNode patched()
|
||||
{
|
||||
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
|
||||
new IsoGameCharacterStateMachinePerformancePatch().apply(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void loadPatchedClasses()
|
||||
{
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsEntity());
|
||||
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsComponent());
|
||||
|
||||
this.componentClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
|
||||
IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, null
|
||||
));
|
||||
this.characterClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.patched());
|
||||
}
|
||||
|
||||
private Object newCharacter() throws ReflectiveOperationException { return this.characterClass.getConstructor().newInstance(); }
|
||||
|
||||
/** A component owned by {@code owner} and registered as its {@code current} component. */
|
||||
private Object addComponent(Object owner) throws ReflectiveOperationException
|
||||
{
|
||||
Object component = this.componentClass.getConstructor().newInstance();
|
||||
|
||||
this.componentClass.getField("owner").set(component, owner);
|
||||
this.characterClass.getField("current").set(owner, component);
|
||||
|
||||
return component;
|
||||
}
|
||||
|
||||
private Object stateMachineComponent(Object character) throws ReflectiveOperationException
|
||||
{
|
||||
return this.characterClass.getMethod("getStateMachineComponent").invoke(character);
|
||||
}
|
||||
|
||||
private int lookups() throws ReflectiveOperationException { return this.characterClass.getField("lookups").getInt(null); }
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new IsoGameCharacterStateMachinePerformancePatch().anchor().verify(IsoGameCharacterStateMachinePerformancePatchTest.character());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTheStoredComponentWithoutALookup() throws ReflectiveOperationException
|
||||
{
|
||||
Object character = this.newCharacter();
|
||||
Object component = this.addComponent(character);
|
||||
|
||||
assertSame(component, this.stateMachineComponent(character));
|
||||
assertSame(component, this.stateMachineComponent(character));
|
||||
assertEquals(1, this.lookups());
|
||||
}
|
||||
|
||||
@Test
|
||||
void looksUpAgainAfterTheComponentWasReplaced() throws ReflectiveOperationException
|
||||
{
|
||||
Object character = this.newCharacter();
|
||||
Object first = this.addComponent(character);
|
||||
|
||||
assertSame(first, this.stateMachineComponent(character));
|
||||
|
||||
// ECSEntity.setECSComponent removes the old component, which sets its owner to null.
|
||||
this.componentClass.getField("owner").set(first, null);
|
||||
Object second = this.addComponent(character);
|
||||
|
||||
assertSame(second, this.stateMachineComponent(character));
|
||||
assertSame(second, this.stateMachineComponent(character));
|
||||
assertEquals(2, this.lookups());
|
||||
}
|
||||
|
||||
@Test
|
||||
void looksUpAgainAfterTheComponentMovedToAnotherCharacter() throws ReflectiveOperationException
|
||||
{
|
||||
Object character = this.newCharacter();
|
||||
Object component = this.addComponent(character);
|
||||
|
||||
assertSame(component, this.stateMachineComponent(character));
|
||||
|
||||
this.componentClass.getField("owner").set(component, this.newCharacter());
|
||||
this.characterClass.getField("current").set(character, null);
|
||||
|
||||
assertNull(this.stateMachineComponent(character));
|
||||
assertEquals(2, this.lookups());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheGetterDoesMoreThanTheLookup()
|
||||
{
|
||||
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
|
||||
MethodNode getter = node.methods.stream().filter(method -> method.name.equals("getStateMachineComponent")).findFirst().orElseThrow();
|
||||
getter.instructions.insert(new InsnNode(NOP));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheGameClassAlreadyHasTheField()
|
||||
{
|
||||
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.patched();
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
IsoGameCharacterStateMachinePerformancePatch patch = new IsoGameCharacterStateMachinePerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.FieldInsnNode;
|
||||
import org.objectweb.asm.tree.LdcInsnNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
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.ACONST_NULL;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.ARETURN;
|
||||
import static org.objectweb.asm.Opcodes.CHECKCAST;
|
||||
import static org.objectweb.asm.Opcodes.GETFIELD;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.POP;
|
||||
import static org.objectweb.asm.Opcodes.PUTFIELD;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class IsoZombieNetworkComponentPerformancePatchTest
|
||||
{
|
||||
private static final String ZOMBIE = "zombie/characters/IsoZombie";
|
||||
private static final String COMPONENT = "zombie/characters/component/NetworkZombieComponent";
|
||||
private static final String OTHER = "zombie/characters/component/OtherComponent";
|
||||
private static final String LOOKUP = "(Ljava/lang/Class;)Lzombie/characters/ecs/ECSComponent;";
|
||||
|
||||
/** {@code this.tryGetECSComponent(component.class)} cast to {@code component}, result dropped. */
|
||||
private static void lookup(MethodVisitor method, String component)
|
||||
{
|
||||
method.visitVarInsn(ALOAD, 0);
|
||||
method.visitLdcInsn(Type.getObjectType(component));
|
||||
method.visitMethodInsn(INVOKEVIRTUAL, IsoZombieNetworkComponentPerformancePatchTest.ZOMBIE, "tryGetECSComponent", IsoZombieNetworkComponentPerformancePatchTest.LOOKUP, false);
|
||||
method.visitTypeInsn(CHECKCAST, component);
|
||||
method.visitInsn(POP);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code IsoZombie} with {@code getOwner()} and {@code setOwner()}, each looking up the
|
||||
* network component, and {@code other()}, which looks up an unrelated component.
|
||||
*/
|
||||
private static ClassNode target()
|
||||
{
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
|
||||
cw.visit(V25, ACC_PUBLIC, IsoZombieNetworkComponentPerformancePatchTest.ZOMBIE, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor getOwner = cw.visitMethod(ACC_PUBLIC, "getOwner", "()Lzombie/core/raknet/UdpConnection;", null, null);
|
||||
IsoZombieNetworkComponentPerformancePatchTest.lookup(getOwner, IsoZombieNetworkComponentPerformancePatchTest.COMPONENT);
|
||||
getOwner.visitInsn(ACONST_NULL);
|
||||
getOwner.visitInsn(ARETURN);
|
||||
getOwner.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor setOwner = cw.visitMethod(ACC_PUBLIC, "setOwner", "()V", null, null);
|
||||
IsoZombieNetworkComponentPerformancePatchTest.lookup(setOwner, IsoZombieNetworkComponentPerformancePatchTest.COMPONENT);
|
||||
setOwner.visitInsn(RETURN);
|
||||
setOwner.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor other = cw.visitMethod(ACC_PUBLIC, "other", "()V", null, null);
|
||||
IsoZombieNetworkComponentPerformancePatchTest.lookup(other, IsoZombieNetworkComponentPerformancePatchTest.OTHER);
|
||||
other.visitInsn(RETURN);
|
||||
other.visitMaxs(0, 0);
|
||||
|
||||
cw.visitEnd();
|
||||
|
||||
ClassNode node = new ClassNode();
|
||||
new ClassReader(cw.toByteArray()).accept(node, 0);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static MethodNode method(ClassNode node, String name)
|
||||
{
|
||||
return node.methods.stream().filter(method -> method.name.equals(name)).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private static List<MethodInsnNode> calls(MethodNode method, String name)
|
||||
{
|
||||
List<MethodInsnNode> calls = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction instanceof MethodInsnNode call && call.name.equals(name)) calls.add(call);
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
private static ClassNode patched()
|
||||
{
|
||||
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.target();
|
||||
new IsoZombieNetworkComponentPerformancePatch().apply(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new IsoZombieNetworkComponentPerformancePatch().anchor().verify(IsoZombieNetworkComponentPerformancePatchTest.target());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsAPrivateFieldAndAnAccessor()
|
||||
{
|
||||
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
|
||||
|
||||
assertEquals(1, node.fields.size());
|
||||
assertEquals("zomboidForge$networkComponent", node.fields.getFirst().name);
|
||||
assertEquals("L" + IsoZombieNetworkComponentPerformancePatchTest.COMPONENT + ";", node.fields.getFirst().desc);
|
||||
assertTrue((node.fields.getFirst().access & ACC_PRIVATE) != 0);
|
||||
|
||||
MethodNode accessor = IsoZombieNetworkComponentPerformancePatchTest.method(node, "zomboidForge$networkComponent");
|
||||
assertTrue((accessor.access & ACC_PRIVATE) != 0);
|
||||
assertEquals("()L" + IsoZombieNetworkComponentPerformancePatchTest.COMPONENT + ";", accessor.desc);
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessorFillsTheFieldOnceFromTheLookup()
|
||||
{
|
||||
MethodNode accessor = IsoZombieNetworkComponentPerformancePatchTest.method(IsoZombieNetworkComponentPerformancePatchTest.patched(), "zomboidForge$networkComponent");
|
||||
|
||||
assertEquals(1, IsoZombieNetworkComponentPerformancePatchTest.calls(accessor, "tryGetECSComponent").size());
|
||||
|
||||
int reads = 0;
|
||||
int writes = 0;
|
||||
for (AbstractInsnNode instruction : accessor.instructions)
|
||||
{
|
||||
if (instruction instanceof FieldInsnNode field && field.getOpcode() == GETFIELD) reads++;
|
||||
if (instruction instanceof FieldInsnNode field && field.getOpcode() == PUTFIELD) writes++;
|
||||
}
|
||||
|
||||
assertEquals(1, reads);
|
||||
assertEquals(1, writes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesEveryLookupOfTheNetworkComponentWithTheAccessor()
|
||||
{
|
||||
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
|
||||
|
||||
for (String name : List.of("getOwner", "setOwner"))
|
||||
{
|
||||
MethodNode method = IsoZombieNetworkComponentPerformancePatchTest.method(node, name);
|
||||
|
||||
assertTrue(IsoZombieNetworkComponentPerformancePatchTest.calls(method, "tryGetECSComponent").isEmpty(), name);
|
||||
|
||||
List<MethodInsnNode> accessors = IsoZombieNetworkComponentPerformancePatchTest.calls(method, "zomboidForge$networkComponent");
|
||||
assertEquals(1, accessors.size(), name);
|
||||
assertEquals(INVOKESPECIAL, accessors.getFirst().getOpcode(), name);
|
||||
|
||||
// No class literal and no cast remain: the accessor returns the component itself.
|
||||
for (AbstractInsnNode instruction : method.instructions)
|
||||
{
|
||||
assertFalse(instruction instanceof LdcInsnNode, name);
|
||||
assertFalse(instruction.getOpcode() == CHECKCAST, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesLookupsOfOtherComponentsAlone()
|
||||
{
|
||||
MethodNode other = IsoZombieNetworkComponentPerformancePatchTest.method(IsoZombieNetworkComponentPerformancePatchTest.patched(), "other");
|
||||
|
||||
assertEquals(1, IsoZombieNetworkComponentPerformancePatchTest.calls(other, "tryGetECSComponent").size());
|
||||
assertTrue(IsoZombieNetworkComponentPerformancePatchTest.calls(other, "zomboidForge$networkComponent").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchedClassIsWrittenWithComputedFrames()
|
||||
{
|
||||
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
|
||||
IsoZombieNetworkComponentPerformancePatchTest.patched().accept(writer);
|
||||
|
||||
assertTrue(writer.toByteArray().length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheGameClassAlreadyHasTheMember()
|
||||
{
|
||||
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> new IsoZombieNetworkComponentPerformancePatch().apply(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
IsoZombieNetworkComponentPerformancePatch patch = new IsoZombieNetworkComponentPerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
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.tree.ClassNode;
|
||||
|
||||
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_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.F2I;
|
||||
import static org.objectweb.asm.Opcodes.FLOAD;
|
||||
import static org.objectweb.asm.Opcodes.FMUL;
|
||||
import static org.objectweb.asm.Opcodes.FSTORE;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.I2F;
|
||||
import static org.objectweb.asm.Opcodes.IADD;
|
||||
import static org.objectweb.asm.Opcodes.ICONST_1;
|
||||
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||
import static org.objectweb.asm.Opcodes.ILOAD;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.IRETURN;
|
||||
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class IsoZombieSpotChancePerformancePatchTest
|
||||
{
|
||||
private static final String ZOMBIE = "zombie/characters/IsoZombie";
|
||||
private static final String MOVING = "zombie/iso/IsoMovingObject";
|
||||
private static final String MATH = "zombie/core/math/PZMath";
|
||||
|
||||
private static final int CHANCE = 5;
|
||||
|
||||
private record Result(int modifierRuns, float rounded) {}
|
||||
|
||||
/**
|
||||
* {@code IsoZombie} with the shape of {@code spottedNew} around the patched range:
|
||||
*
|
||||
* <pre>{@code
|
||||
* public static float input;
|
||||
* public static int modifierRuns;
|
||||
* public static float rounded;
|
||||
*
|
||||
* public void spottedNew(IsoMovingObject other, boolean bForced)
|
||||
* {
|
||||
* float chance = input; // local 5
|
||||
* if (bForced) chance = 1000000F;
|
||||
* modifierRuns++; // stands for the modifiers
|
||||
* chance *= 2F;
|
||||
* chance = (float) PZMath.fastfloor(chance); // local roundingLocal
|
||||
* rounded = chance;
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
private static ClassNode zombie(int roundingLocal)
|
||||
{
|
||||
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.ZOMBIE);
|
||||
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "input", "F", null, null);
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "modifierRuns", "I", null, null);
|
||||
node.visitField(ACC_PUBLIC | ACC_STATIC, "rounded", "F", null, null);
|
||||
|
||||
MethodVisitor method = node.visitMethod(ACC_PUBLIC, "spottedNew", "(L" + IsoZombieSpotChancePerformancePatchTest.MOVING + ";Z)V", null, null);
|
||||
Label notForced = new Label();
|
||||
|
||||
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "input", "F");
|
||||
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
|
||||
|
||||
method.visitVarInsn(ILOAD, 2);
|
||||
method.visitJumpInsn(IFEQ, notForced);
|
||||
method.visitLdcInsn(1000000.0F);
|
||||
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
|
||||
method.visitLabel(notForced);
|
||||
|
||||
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
|
||||
method.visitInsn(ICONST_1);
|
||||
method.visitInsn(IADD);
|
||||
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
|
||||
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
|
||||
method.visitLdcInsn(2.0F);
|
||||
method.visitInsn(FMUL);
|
||||
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
|
||||
|
||||
method.visitVarInsn(FLOAD, roundingLocal);
|
||||
method.visitMethodInsn(INVOKESTATIC, IsoZombieSpotChancePerformancePatchTest.MATH, "fastfloor", "(F)I", false);
|
||||
method.visitInsn(I2F);
|
||||
method.visitVarInsn(FSTORE, roundingLocal);
|
||||
|
||||
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
|
||||
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "rounded", "F");
|
||||
method.visitInsn(RETURN);
|
||||
method.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/** {@code PZMath} with {@code fastfloor} as {@code (int) value}, which equals it for the values used here. */
|
||||
private static ClassNode math()
|
||||
{
|
||||
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MATH);
|
||||
MethodVisitor fastfloor = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "fastfloor", "(F)I", null, null);
|
||||
|
||||
fastfloor.visitVarInsn(FLOAD, 0);
|
||||
fastfloor.visitInsn(F2I);
|
||||
fastfloor.visitInsn(IRETURN);
|
||||
fastfloor.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;
|
||||
}
|
||||
|
||||
/** Loads the patched {@code IsoZombie} and runs {@code spottedNew(null, forced)} with {@code input} as the chance. */
|
||||
private static Result run(float input, boolean forced) throws ReflectiveOperationException
|
||||
{
|
||||
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE);
|
||||
new IsoZombieSpotChancePerformancePatch().apply(zombie);
|
||||
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(IsoZombieSpotChancePerformancePatchTest.math());
|
||||
|
||||
Class<?> moving = definer.define(IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MOVING));
|
||||
Class<?> loaded = definer.define(zombie);
|
||||
|
||||
loaded.getField("input").setFloat(null, input);
|
||||
loaded.getMethod("spottedNew", moving, boolean.class).invoke(loaded.getConstructor().newInstance(), null, forced);
|
||||
|
||||
return new Result(loaded.getField("modifierRuns").getInt(null), loaded.getField("rounded").getFloat(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new IsoZombieSpotChancePerformancePatch().anchor().verify(IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroChanceSkipsTheModifiersAndStillRounds() throws ReflectiveOperationException
|
||||
{
|
||||
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, false));
|
||||
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(-0.0F, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherChancesRunTheModifiers() throws ReflectiveOperationException
|
||||
{
|
||||
assertEquals(new Result(1, 6.0F), IsoZombieSpotChancePerformancePatchTest.run(3.0F, false));
|
||||
assertEquals(new Result(1, 2000000.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, true));
|
||||
assertEquals(1, IsoZombieSpotChancePerformancePatchTest.run(Float.NaN, false).modifierRuns());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheRoundingUsesAnotherLocal()
|
||||
{
|
||||
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(6);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> new IsoZombieSpotChancePerformancePatch().apply(zombie));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
IsoZombieSpotChancePerformancePatch patch = new IsoZombieSpotChancePerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.JumpInsnNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
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.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACONST_NULL;
|
||||
import static org.objectweb.asm.Opcodes.CHECKCAST;
|
||||
import static org.objectweb.asm.Opcodes.GETFIELD;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.ICONST_0;
|
||||
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||
import static org.objectweb.asm.Opcodes.ILOAD;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.IRETURN;
|
||||
import static org.objectweb.asm.Opcodes.ISTORE;
|
||||
import static org.objectweb.asm.Opcodes.POP;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class IsoZombieVehiclePerformancePatchTest
|
||||
{
|
||||
private static final String VECTOR = "org/joml/Vector3f";
|
||||
private static final String CALL = "(L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";";
|
||||
|
||||
/**
|
||||
* {@code IsoZombie} with a reduced {@code isVehicleBetween}: one call to
|
||||
* {@code BaseVehicle.getIntersectPoint}, result ignored, then {@code return intersect}.
|
||||
*/
|
||||
private static ClassNode target()
|
||||
{
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
|
||||
cw.visit(V25, ACC_PUBLIC, "zombie/characters/IsoZombie", null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor m = cw.visitMethod(ACC_PRIVATE, "isVehicleBetween", "(FFF)Z", null, null);
|
||||
m.visitInsn(ICONST_0);
|
||||
m.visitVarInsn(ISTORE, 4);
|
||||
m.visitInsn(ACONST_NULL);
|
||||
m.visitTypeInsn(CHECKCAST, "zombie/vehicles/BaseVehicle");
|
||||
m.visitInsn(ACONST_NULL);
|
||||
m.visitInsn(ACONST_NULL);
|
||||
m.visitInsn(ACONST_NULL);
|
||||
m.visitMethodInsn(INVOKEVIRTUAL, "zombie/vehicles/BaseVehicle", "getIntersectPoint", IsoZombieVehiclePerformancePatchTest.CALL, false);
|
||||
m.visitInsn(POP);
|
||||
m.visitVarInsn(ILOAD, 4);
|
||||
m.visitInsn(IRETURN);
|
||||
m.visitMaxs(0, 0);
|
||||
|
||||
cw.visitEnd();
|
||||
|
||||
ClassNode node = new ClassNode();
|
||||
new ClassReader(cw.toByteArray()).accept(node, 0);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static MethodNode isVehicleBetween(ClassNode node)
|
||||
{
|
||||
return node.methods.stream().filter(method -> method.name.equals("isVehicleBetween")).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
/** Opcodes of the real instructions: no labels, line numbers, or frames. */
|
||||
private static List<Integer> opcodes(MethodNode method)
|
||||
{
|
||||
List<Integer> opcodes = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction.getOpcode() != -1) opcodes.add(instruction.getOpcode());
|
||||
}
|
||||
|
||||
return opcodes;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new IsoZombieVehiclePerformancePatch().anchor().verify(IsoZombieVehiclePerformancePatchTest.target());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseFirstWhenTheCellHasNoVehicles()
|
||||
{
|
||||
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
|
||||
new IsoZombieVehiclePerformancePatch().apply(node);
|
||||
|
||||
List<Integer> opcodes = IsoZombieVehiclePerformancePatchTest.opcodes(IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node));
|
||||
|
||||
assertEquals(
|
||||
List.of(GETSTATIC, GETFIELD, INVOKEVIRTUAL, INVOKEINTERFACE, IFEQ, ICONST_0, IRETURN),
|
||||
opcodes.subList(0, 7)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void jumpsOverTheEarlyReturnToTheOriginalCode()
|
||||
{
|
||||
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
|
||||
new IsoZombieVehiclePerformancePatch().apply(node);
|
||||
|
||||
MethodNode method = IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node);
|
||||
JumpInsnNode jump = Arrays.stream(method.instructions.toArray())
|
||||
.filter(JumpInsnNode.class::isInstance)
|
||||
.map(JumpInsnNode.class::cast)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
// The label sits directly before the original first instruction, iconst_0 of "intersectVision = false".
|
||||
AbstractInsnNode firstOriginal = jump.label.getNext();
|
||||
while (firstOriginal.getOpcode() == -1) firstOriginal = firstOriginal.getNext();
|
||||
|
||||
assertEquals(ICONST_0, firstOriginal.getOpcode());
|
||||
assertEquals(ISTORE, firstOriginal.getNext().getOpcode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesTheVirtualCallWithTheHook()
|
||||
{
|
||||
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
|
||||
new IsoZombieVehiclePerformancePatch().apply(node);
|
||||
|
||||
List<MethodInsnNode> calls = new ArrayList<>();
|
||||
for (AbstractInsnNode instruction : IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node).instructions) {
|
||||
if (instruction instanceof MethodInsnNode call && call.name.equals("getIntersectPoint")) calls.add(call);
|
||||
}
|
||||
|
||||
assertEquals(1, calls.size());
|
||||
MethodInsnNode call = calls.getFirst();
|
||||
|
||||
assertEquals(INVOKESTATIC, call.getOpcode());
|
||||
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", call.owner);
|
||||
assertEquals("(Lzombie/vehicles/BaseVehicle;L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";", call.desc);
|
||||
assertFalse(call.itf);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
IsoZombieVehiclePerformancePatch patch = new IsoZombieVehiclePerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
@@ -9,4 +9,10 @@ dependencies {
|
||||
implementation(project(":core"))
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +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;
|
||||
|
||||
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()
|
||||
{
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.util.SegmentReach;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
import zombie.core.physics.WorldSimulation;
|
||||
import zombie.scripting.objects.VehicleScript;
|
||||
import zombie.vehicles.BaseVehicle;
|
||||
|
||||
/** Hooks called by patched {@code zombie.characters.IsoZombie} code. */
|
||||
public final class ZombieVehicleHooks
|
||||
{
|
||||
/**
|
||||
* World units added to the bounding radius. Float resolution near the world coordinates
|
||||
* (about 10000) is 0.001, so this covers rounding differences to the vanilla test.
|
||||
*/
|
||||
private static final float MARGIN = 0.1F;
|
||||
|
||||
private ZombieVehicleHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces the call {@code vehicle.getIntersectPoint(start, end, result)} in
|
||||
* {@code IsoZombie.isVehicleBetween}. Returns what that call returns.
|
||||
*
|
||||
* <p>The vanilla test is 2-dimensional: {@code getLocalPos} drops the height of both
|
||||
* points, and the vehicle's box is centered on its physics origin with the half extents
|
||||
* {@code extents * 0.5 + centerOfMassOffset}. Whatever its rotation, the box lies inside
|
||||
* the circle around that origin with the radius of its half diagonal. A segment that stays
|
||||
* outside the circle cannot hit the box, so the vanilla call returns {@code null} for it
|
||||
* and is skipped here.
|
||||
*/
|
||||
public static @Nullable Vector3f getIntersectPoint(
|
||||
BaseVehicle vehicle, Vector3f start,
|
||||
Vector3f end, @Nullable Vector3f result
|
||||
) {
|
||||
VehicleScript script = vehicle.getScript();
|
||||
Vector3f extents = script.getExtents();
|
||||
Vector3f centerOfMass = script.getCenterOfMassOffset();
|
||||
|
||||
float halfX = extents.x * 0.5F + centerOfMass.x;
|
||||
float halfZ = extents.z * 0.5F + centerOfMass.z;
|
||||
float radius = (float) Math.sqrt(halfX * halfX + halfZ * halfZ) + ZombieVehicleHooks.MARGIN;
|
||||
|
||||
// Same position that BaseVehicle.getWorldPos and getLocalPos use for the physics origin.
|
||||
float centerX = vehicle.jniTransform.origin.x + WorldSimulation.instance.offsetX;
|
||||
float centerY = vehicle.jniTransform.origin.z + WorldSimulation.instance.offsetY;
|
||||
|
||||
if (SegmentReach.missesCircle(start.x, start.y, end.x, end.y, centerX, centerY, radius)) return null;
|
||||
|
||||
return vehicle.getIntersectPoint(start, end, result);
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+5
@@ -1,5 +1,10 @@
|
||||
/**
|
||||
* Build 42 runtime code: hooks that patched game classes call, and adapters between
|
||||
* game classes and the version-independent {@code core} and {@code api}.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
/** Distance checks in the XY plane. Uses no game classes, so it can be tested on its own. */
|
||||
public final class SegmentReach
|
||||
{
|
||||
private SegmentReach() {}
|
||||
|
||||
/**
|
||||
* Whether every point of the segment from ({@code startX}, {@code startY}) to
|
||||
* ({@code endX}, {@code endY}) is farther than {@code radius} from
|
||||
* ({@code centerX}, {@code centerY}).
|
||||
*
|
||||
* <p>False when any input is NaN. A caller that skips work only on {@code true} therefore
|
||||
* still runs the full computation for such input.
|
||||
*/
|
||||
public static boolean missesCircle(
|
||||
float startX, float startY, float endX, float endY,
|
||||
float centerX, float centerY, float radius
|
||||
) {
|
||||
float directionX = endX - startX;
|
||||
float directionY = endY - startY;
|
||||
float lengthSquared = directionX * directionX + directionY * directionY;
|
||||
|
||||
// Position of the point on the segment closest to the center, from 0 (start) to 1 (end).
|
||||
// A segment of length 0 is its start. NaN passes through every comparison unchanged.
|
||||
float along = lengthSquared == 0.0F
|
||||
? 0.0F
|
||||
: ((centerX - startX) * directionX + (centerY - startY) * directionY) / lengthSquared;
|
||||
|
||||
if (along < 0.0F) along = 0.0F;
|
||||
else if (along > 1.0F) along = 1.0F;
|
||||
|
||||
float offsetX = startX + along * directionX - centerX;
|
||||
float offsetY = startY + along * directionY - centerY;
|
||||
|
||||
return offsetX * offsetX + offsetY * offsetY > radius * radius;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+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");
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SegmentReachTest
|
||||
{
|
||||
@Test
|
||||
void segmentFarFromTheCircleMisses()
|
||||
{
|
||||
assertTrue(SegmentReach.missesCircle(0, 10, 20, 10, 10, 0, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentThroughTheCenterDoesNotMiss()
|
||||
{
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 0, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentThatEndsBeforeTheCircleMissesEvenWhenItsLineWouldHit()
|
||||
{
|
||||
// The line y = 0 passes through the circle at (10, 0); the segment stops at x = 5.
|
||||
assertTrue(SegmentReach.missesCircle(0, 0, 5, 0, 10, 0, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentThatStartsAfterTheCircleMissesEvenWhenItsLineWouldHit()
|
||||
{
|
||||
assertTrue(SegmentReach.missesCircle(15, 0, 30, 0, 10, 0, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentThatTouchesTheCircleEdgeDoesNotMiss()
|
||||
{
|
||||
assertFalse(SegmentReach.missesCircle(0, 5, 20, 5, 10, 0, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentJustOutsideTheCircleMisses()
|
||||
{
|
||||
assertTrue(SegmentReach.missesCircle(0, 5.001F, 20, 5.001F, 10, 0, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentStartingInsideTheCircleDoesNotMiss()
|
||||
{
|
||||
assertFalse(SegmentReach.missesCircle(10, 1, 100, 100, 10, 0, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentOfLengthZeroIsItsStart()
|
||||
{
|
||||
assertFalse(SegmentReach.missesCircle(10, 1, 10, 1, 10, 0, 2));
|
||||
assertTrue(SegmentReach.missesCircle(50, 50, 50, 50, 10, 0, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void diagonalSegmentIsMeasuredToItsClosestPoint()
|
||||
{
|
||||
// Closest point of (0,0)-(10,10) to (10,0) is (5,5), distance sqrt(50) = 7.07.
|
||||
assertTrue(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.0F));
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.2F));
|
||||
}
|
||||
|
||||
@Test
|
||||
void worksAtWorldCoordinates()
|
||||
{
|
||||
assertFalse(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10196, 2));
|
||||
assertTrue(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10210, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void neverMissesOnNaN()
|
||||
{
|
||||
float nan = Float.NaN;
|
||||
|
||||
assertFalse(SegmentReach.missesCircle(nan, 0, 20, 0, 10, 100, 1));
|
||||
assertFalse(SegmentReach.missesCircle(0, nan, 20, 0, 10, 100, 1));
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, nan, 0, 10, 100, 1));
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, 20, nan, 10, 100, 1));
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, nan, 100, 1));
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, nan, 1));
|
||||
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 100, nan));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user