32 Commits
Author SHA1 Message Date
Overlord 68f090061f Merge branch 'release/v0.5.0'
ci / image (42, public) (push) Successful in 28s
publish / maven (push) Failing after 2m6s
2026-10-07 07:57:27 +02:00
Overlord be08756c36 Add JVM_EXPERIMENTAL_PERFORMANCE configuration to enable compact object headers and transparent huge pages in the JVM. 2026-10-07 07:57:17 +02:00
Overlord 49af536786 qol: improve comments
ci / image (42, public) (push) Successful in 3m41s
2026-10-05 20:27:52 +02:00
Overlord 9178d36168 Refine exception messages in AssetLoadingHooks and RolesHooks for clarity during hook registration and transaction handling. 2026-10-05 19:46:18 +02:00
Overlord e61026a3d4 Add QuitHooks and ServerMapQuitSleepPerformancePatch for Build 42.21. Optimize server shutdown by replacing fixed sleep with client connection polling. Include hooks, unit tests, and integrate the patch into the performance patch set. 2026-10-05 19:45:28 +02:00
Overlord 99f4f49a7c Add AssetLoadingHooks and GameServerAssetLoadingPerformancePatch for Build 42.21. Optimize asset loading during startup by increasing loader threads and reducing main thread spinning. Include hooks, unit tests, and integrate the patch into the performance patch set. 2026-10-05 16:55:31 +02:00
OverlordandClaude Bot 43df96391c Update README
ci / image (42, public) (push) Successful in 3m23s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 15:32:34 +02:00
Overlord 607d5b2b32 Add Feature configuration and support for dynamic feature toggling in ForgeSettings with system property and config precedence. Add unit tests, documentation, and integrate feature handling across the project. 2026-10-05 15:31:29 +02:00
Overlord 07dc3f0fad Add BackupHooks and ParallelZip for Build 42.21. Implement optimized backup file creation with parallel processing. Include hooks, utilities, and unit tests for validation.
ci / image (42, public) (push) Successful in 3m38s
2026-10-05 13:38:08 +02:00
Overlord 7ffcbdbb06 Add @SuppressWarnings("unused") to hooks. 2026-10-05 12:25:37 +02:00
Overlord 9b721bfd45 Refactor Patches package to patches for consistency across project structure. Update imports in all related classes and tests. 2026-10-05 12:23:50 +02:00
Overlord 88cd68b5cb Add ThreadSleepPerformancePatch variants for Build 42.21 to optimize waiting loops. Replace Thread.sleep calls with hook-based alternatives. Include hooks, utility and tests. 2026-10-05 12:22:38 +02:00
Overlord 529e48ed5a Add RolesSavePerformancePatch to optimize role saving in Build 42.21. Use single SQLite transaction to reduce redundant database operations. Include hooks, tests, and integrate the patch into the performance patch set. 2026-10-05 11:24:59 +02:00
Overlord dd113961e6 Add IsoChunkSaveDirectoryPerformancePatch to remove redundant folder checks during chunk saves in Build 42.21. Include tests and integrate the patch into the performance patch set. 2026-10-05 01:20:10 +02:00
Overlord eb09a77941 Add BitHeaderPoolPerformancePatch for chunk serialization improvements in Build 42.21. Introduce PerThreadDeque for thread-local pooling with reduced contention and memory overhead. Include unit tests and integrate patch into the performance patch set. 2026-10-05 00:47:01 +02:00
Overlord 2081235433 Add MethodBody implementation for method delegation and TileRules utility for optimised tile rule matching and caching. Include patches for WorldGenChunk performance and corresponding tests. 2026-10-04 23:19:08 +02:00
Overlord e932c7401a qol: fix formatting 2026-10-04 20:16:59 +02:00
Overlord 56e01c5cbe Introduce FrameBudget utility and ServerMapCellBudgetPerformancePatch for frame-based workload distribution. 2026-10-04 20:16:38 +02:00
Overlord 38a15db299 Add performance improvements for ZomboidFileSystem.init: implement MediaScan and ZomboidFileSystemHooks for efficient file system traversal, and replace directory checks with a single-pass approach. Integrate new patch into the performance patch set, and include unit tests for behavior validation. 2026-10-04 19:34:09 +02:00
Overlord 05a4b9dbd9 Moved VoronoiNoise and its tests to vanilla package for improved organisation. 2026-10-04 19:30:37 +02:00
Overlord 900f65b591 Optimize ZombieVoronoi.evaluateNoise with a hook-based implementation for Build 42.21. Replace distance calculations with a single-pass method, avoiding boxed sorting. Add associated tests and integrate new patch into the performance patch set. 2026-10-04 16:45:31 +02:00
Overlord 05eed7e205 Updated server configuration; add UPnP and JVM memory options, and enhance startup behaviour with dynamic memory allocation and ZUncommitDelay settings. 2026-10-04 15:17:38 +02:00
Overlord a0cd30a0d7 Merge branch 'release/v0.4.0'
publish / maven (push) Successful in 2m59s
ci / image (42, public) (push) Successful in 16s
2026-10-03 13:40:26 +02:00
Overlord 151e1d459f Merge tag 'v0.4.0' into develop
ci / image (42, public) (push) Successful in 3m13s
Tagging version v0.4.0 v0.4.0
2026-10-03 13:40:26 +02:00
Overlord a351fc237c Add client command integration for Build 42: define APIs, event system, hooks, patches, and Lua table converters. Include tests, documentation, and mod support. 2026-10-03 13:22:47 +02:00
Overlord af7174e128 Add mod command integration for Build 42: command hooks, lookup extensions, registry, and validation mechanisms. Include corresponding tests and documentation. 2026-10-03 11:27:06 +02:00
Overlord 22077514fe Add CancellableHookPatch to allow call skipping based on hook return values. Introduce HookArgument to pass method parameters and locals to hooks. Add HookCall and supporting tests for hook behavior validation. Update HookInjectionPatch to support argument-based hooks.
ci / image (42, public) (push) Successful in 6m4s
2026-10-03 10:56:46 +02:00
Overlord 6761f2d9ea Add ModCheckTest to test runtime mod validations and entry point superclass checks. Include Gradle verification metadata for dependency integrity. 2026-10-03 09:59:47 +02:00
Overlord 18ff32b5ce Refine tag handling in CI/release workflows and publish script to use the v* tag on HEAD, improve error messaging, and update documentation for server configuration adjustments.
ci / image (42, public) (push) Successful in 3m3s
2026-10-03 01:11:44 +02:00
Overlord 67530d35e9 Enhance transactional support with savepoints, improve error handling for nested exceptions, and provide better rollback mechanisms. Update tests to validate savepoint behavior and add new test cases for mod errors, task execution, and server configuration. Expand Gradle tasks to generate admin passwords, preserve configs during deployment, and support custom server addresses. 2026-10-03 01:10:38 +02:00
Overlord 26ca1b90a2 Add support for precise Project Zomboid versioning in builds and images. Include printGameVersion task, improve image tagging, and enhance CI/release workflows for hotfix handling.
ci / image (42, public) (push) Successful in 3m17s
2026-10-02 17:53:58 +02:00
Overlord c529b04ff0 Merge tag 'v0.3.0' into develop
ci / image (42.21, public) (push) Successful in 2m38s
Tagging version v0.3.0 v0.3.0
2026-10-02 15:36:33 +02:00
158 changed files with 10970 additions and 372 deletions

No files matched your search

+3 -3
View File
@@ -15,12 +15,12 @@ jobs:
include:
# One entry per supported version; add older Steam version branches
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
- pz_version: "42.21"
- pz_version: "42"
steam_branch: public
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# release.sh derives the version from the newest v* tag
# release.sh derives the version from the v* tags
fetch-depth: 0
- name: Build and verify
+9 -7
View File
@@ -9,25 +9,27 @@ on:
push:
tags:
- "v*"
workflow_dispatch:
jobs:
maven:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# publish.sh derives the version from the newest v* tag
# publish.sh derives the version from the v* tag on HEAD
fetch-depth: 0
- uses: actions/setup-java@v4
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with:
distribution: temurin
java-version: "25"
- name: Test and publish
# 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 }}
PUBLISH: "true"
run: ci/publish.sh
run: ci/publish.sh publish
+15 -6
View File
@@ -1,12 +1,16 @@
# Publishes an image for every new Steam build of each supported Project Zomboid
# version. Immutable tags are never overwritten (see ci/release.sh).
# Publishes an image for every new Project Zomboid version (hotfixes included) of each
# matrix entry and every new ZomboidForge release; full version tags are never overwritten
# (see ci/release.sh).
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
# package write access) and a runner with a Docker (or Podman) CLI.
name: release
on:
# Every 2.5 hours; cron cannot divide a day into 2.5-hour steps, so the gap
# from 22:30 to 00:00 is 1.5 hours.
schedule:
- cron: "0 */6 * * *"
- cron: "0 0,5,10,15,20 * * *"
- cron: "30 2,7,12,17,22 * * *"
workflow_dispatch:
jobs:
@@ -16,13 +20,13 @@ jobs:
fail-fast: false
matrix:
include:
- pz_version: "42.21"
- pz_version: "42"
steam_branch: public
latest: "true"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# release.sh derives the version from the newest v* tag
# release.sh derives the version from the v* tags
fetch-depth: 0
- name: Log in to the registry
@@ -39,3 +43,8 @@ jobs:
PUBLISH: "true"
LATEST: ${{ matrix.latest }}
run: ci/release.sh
# Removes the stored registry token, also when a step failed, in case the runner is reused.
- name: Log out of the registry
if: always()
run: docker logout git.security-command.org
+43 -6
View File
@@ -6,6 +6,10 @@
# podman build --platform linux/amd64 -t zomboidforge .
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
#
# The stage game-version (--target game-version) downloads only the server jar of
# PZ_BRANCH and writes its game version to /game-version; ci/release.sh uses it to
# name the image before the full build.
#
# Build arguments:
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
@@ -14,7 +18,8 @@
# files with steamcmd's newer copies
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
# Default: 0.0.0-prerelease
# STEAM_BUILDID Image label only; set by ci/release.sh
# STEAM_BUILDID Image label; in the stage game-version it keeps the cached result until
# Steam publishes a new build. Set by ci/release.sh
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
# (debug builds only; ci/release.sh never sets it)
@@ -24,8 +29,11 @@ ARG STEAMCLIENT=bundled
ARG FORGE_VERSION="0.0.0-prerelease"
ARG STEAM_BUILDID=""
# Base images are pinned by digest; the tag in front of the digest is for readers only.
# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame.
# --- Stage 1: vanilla dedicated server -----------------------------------------
FROM docker.io/steamcmd/steamcmd:debian-13 AS server
FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server
# steamcmd updates itself on its first run. This runs in its own layer so the
# update is cached and separate from the app installation.
@@ -36,8 +44,8 @@ ARG STEAMCLIENT
COPY docker/install-server.sh /usr/local/bin/install-server
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
# --- Stage 2: ZomboidForge build and server jar patching -----------------------
FROM docker.io/library/eclipse-temurin:25-jdk AS build
# --- Stage 2: ZomboidForge sources and Gradle -----------------------------------
FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources
WORKDIR /src
# Gradle distribution download, cached independently of the sources.
@@ -53,6 +61,35 @@ COPY agent agent
COPY patcher patcher
COPY mod-tools mod-tools
COPY gradle-plugin gradle-plugin
# --- Game version of a Steam branch, from its server jar alone ------------------
# Not part of the image; built on its own by ci/release.sh.
FROM sources AS game-version
# DepotDownloader downloads single files of a depot; steamcmd only whole apps.
ADD --checksum=sha256:a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53 \
https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip \
/opt/depotdownloader/depotdownloader.zip
RUN cd /opt/depotdownloader \
&& jar xf depotdownloader.zip \
&& chmod +x DepotDownloader \
&& rm depotdownloader.zip
# FORGE_VERSION only keeps Gradle from asking git (not in this stage) for the version.
ARG PZ_BRANCH
ARG STEAM_BUILDID
ARG FORGE_VERSION
RUN echo java/projectzomboid.jar > /tmp/files \
&& /opt/depotdownloader/DepotDownloader \
-app 380870 -depot 380871 -branch "${PZ_BRANCH}" -filelist /tmp/files -dir /pz \
&& ./gradlew --no-daemon --quiet \
-Ppz.jar=/pz/java/projectzomboid.jar \
-Pversion=${FORGE_VERSION} \
:patcher:printGameVersion > /game-version
# --- Stage 3: ZomboidForge build and server jar patching -----------------------
FROM sources AS build
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
@@ -67,8 +104,8 @@ RUN ./gradlew --no-daemon \
${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.
+150 -23
View File
@@ -40,7 +40,7 @@ version = "1.2.0"
zomboidForge {
id = "shop"
entrypoint = "com.example.shop.ShopMod"
game("42.21") // only when the mod uses game classes
game("42") // only when the mod uses game classes
dependsOn("economy", "2.1") // other mods: id and minimum version
}
@@ -69,7 +69,8 @@ game jar for mods that declare `game` versions. Default settings go into
| `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` | `admin` | admin password of the `runServer` server |
| `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` |
@@ -77,6 +78,10 @@ game jar for mods that declare `game` versions. Default settings go into
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
@@ -100,9 +105,15 @@ The game jar has to be one of the declared `game` versions; the check below fail
| `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` |
| `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
@@ -131,7 +142,9 @@ public final class ShopMod extends Mod
@Override
public void onLoad() // main thread, registration only
{
this.events().onMain(TickEvent.class, event -> { /* every frame, on the main thread */ });
this.events().onMain(TickEvent.class, event -> {
/* every frame, on the main thread */
});
}
@Override
@@ -139,8 +152,12 @@ public final class ShopMod extends Mod
{
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());
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));
}
@@ -151,21 +168,23 @@ public final class ShopMod extends Mod
## Services
Methods of `Mod`, usable from the constructor on (also in field initializers):
Methods of `Mod`, usable from the constructor on, and 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` |
| 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
@@ -199,11 +218,110 @@ Listeners are matched by the event's exact class. Events that carry live game ob
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. Each mod only
reaches its own tables.
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:
@@ -216,7 +334,7 @@ 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
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));
});
@@ -257,6 +375,10 @@ Things to know:
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
@@ -282,6 +404,11 @@ Every problem of every mod is listed in the log.
| 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
+58 -33
View File
@@ -22,8 +22,10 @@ podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
| `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`.
> [!NOTE]
> Published images are tagged `<forge>-pz<major.minor.build>`, `<forge>-pz<major.minor>`, and `latest`. <br>
> A new image is built for every ZomboidForge release and every Project Zomboid version,
> hotfixes included, as the server only admits client with the exact same version.
## Running
@@ -36,24 +38,28 @@ podman run -d --name zomboidforge \
Unset variables keep the value in the server `.ini` (or the game default).
| Variable | Default | |
|-------------------|----------------|-----------------------------------------------------------------------------------------------------|
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
| `PUBLIC_NAME` | | Name in the server browser |
| `PORT` | `16261` | Game port (`-port`) |
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
| `ADMIN_USERNAME` | `admin` | First start only |
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
| `JVM_MIN_HEAP` | `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 |
| Variable | Default | |
|--------------------------------|--------------------------|-----------------------------------------------------------------------------------------------------------------------------|
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
| `PUBLIC_NAME` | | Name in the server browser |
| `PORT` | `16261` | Game port (`-port`) |
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
| `UPNP` | | `true`/`false`: UPnP port mapping on the router (`.ini` `UPnP`); `false` recommended (see below) |
| `ADMIN_USERNAME` | `admin` | First start only |
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
| `JVM_MIN_HEAP` | JVM default | `-Xms`; unused heap memory is returned to the system only down to this size |
| `JVM_MAX_HEAP` | 75 % of the memory limit | `-Xmx`; `8g` when the container has no memory limit |
| `JVM_UNCOMMIT_DELAY` | `60` | Seconds after which unused heap memory is returned to the system (`-XX:ZUncommitDelay`) |
| `JVM_EXPERIMENTAL_PERFORMANCE` | `false` | `true`/`false`: `-XX:+UseCompactObjectHeaders` and `-XX:+UseTransparentHugePages` (see below) |
| `STEAM` | `1` | `0` runs the server without Steam |
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
| `ZF_EXPERIMENTAL_PERFORMANCE` | `false` | `true`/`false`: performance changes that alter timing or resource use (more threads, shorter waits); overrides `forge.toml` |
Notes:
@@ -64,10 +70,19 @@ Notes:
items (`/data/steamapps`). The server runs as UID 1000. A bind-mounted host directory
must be writable by UID 1000 (`chown 1000:1000 <dir>`); with rootless Podman, use
`--userns=keep-id:uid=1000,gid=1000` to map it to your own user.
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large
worlds (`podman stop -t 120`, `stop_grace_period` in compose).
- **UPnP:** the game enables UPnP by default. In a container the server sees only its own
container address and cannot map the host's ports, and the router search delays every start
by about 12 s; set `UPNP=false` and publish the ports instead.
- **Memory:** with a memory limit (`--memory`, `mem_limit`), the heap gets 75 % of it and the
rest stays for native memory. The startup briefly needs a large heap; with 8 players
exploring, the heap held up to 4.4 GB of live data in tests. A limit below about 6 GB is
not recommended. Without a limit the heap is `8g`, as in vanilla.
- **Huge pages:** `JVM_EXPERIMENTAL_PERFORMANCE=true` maps the heap with transparent huge pages
only when the host's `/sys/kernel/mm/transparent_hugepage/shmem_enabled` is `advise` or
`always` (a container cannot change it); otherwise the JVM logs a warning and runs without them.
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large worlds.
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`).
For local testing use `compose.yaml` (`podman compose up --build`, settings from `.env`).
## Mods
@@ -93,19 +108,24 @@ forge/
podman run ... -v ./forge:/forge zomboidforge
```
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.
> [!WARNING]
> Mods are trusted code. <br>
> They run inside the server process with its full privileges, which means they can
> read and write any file the server can, open network connections, and stop the server. <br>
> The class loader isolation and the startup checks catch mistakes; they do not contain
> or restrict a malicious mod.
>
> Install only mods whose authors you trust, or whose code you can verify yourself!
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.
problem. For example, 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:
@@ -115,6 +135,9 @@ 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
[features]
experimental_performance = false # default false; ZF_EXPERIMENTAL_PERFORMANCE takes precedence when set
```
### Mod development
@@ -132,9 +155,11 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar
```
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
`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.
> [!IMPORTANT]
> Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent. <br>
> `pz.version` in `gradle.properties` selects the targeted version. <br>
> `mod-tools` (the build-time mod checks) and `gradle-plugin` (the plugin for mod authors)
> are for mod builds, not the server.
Release tags publish `api`, `mod-tools`, and the Gradle plugin to the Gitea Maven registry
(`.gitea/workflows/publish.yml`, `ci/publish.sh`); tags with a `-` are only tested.
+15 -7
View File
@@ -2,6 +2,7 @@
plugins {
id("zomboidforge.java-conventions")
alias(libs.plugins.shadow)
}
dependencies {
@@ -11,12 +12,19 @@ dependencies {
compileOnly(files(projectZomboid.serverJar))
}
tasks.jar {
archiveBaseName = "zomboidforge-agent"
// The agent jar is appended to the system class path behind the game jar and includes api,
// core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same
// library in the game jar cannot replace them.
tasks.shadowJar {
archiveBaseName = "zomboidforge-agent"
archiveClassifier = ""
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
// The agent jar is appended to the system class path and includes api, core and compat runtime.
// Mapping the classpath to zip trees loses its task dependencies; the input restores them.
inputs.files(configurations.runtimeClasspath)
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,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);
}
@@ -9,8 +9,9 @@ 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>
{
private static final Pattern VERSION = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?");
private static final Pattern PREFIX = Pattern.compile("(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?");
// 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)
@@ -84,4 +84,10 @@ public abstract class Mod
/** 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(); }
}
@@ -42,4 +42,10 @@ public interface ModContext
/** 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,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");
}
}
@@ -4,7 +4,8 @@ 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; other mods cannot reach it.
* 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},
@@ -26,6 +27,10 @@ public interface ModStorage
/**
* 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);
@@ -37,7 +37,11 @@ public interface Table<R extends Record>
/** Every key, sorted. */
List<String> keys();
/** Calls {@code action} for every row, sorted by key, without loading all rows at once. */
/**
* 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();
@@ -45,6 +49,8 @@ public interface Table<R extends Record>
/**
* 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
*/
@@ -42,6 +42,16 @@ class GameVersionTest
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()
{
+44 -25
View File
@@ -2,15 +2,18 @@
#
# 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 newest v* git tag reachable from HEAD, without the "v".
# 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 any v* tag nothing is published.
# published. Without a v* tag on HEAD nothing is published.
#
# Environment:
# 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
# PUBLISH true: publish after the tests. Default: false (test only)
set -o errexit
set -o nounset
@@ -19,8 +22,6 @@ set -o pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly REPO_ROOT
readonly REQUESTED_PUBLISH="${PUBLISH:-false}"
readonly MODULES=(
api
mod-tools
@@ -31,11 +32,11 @@ log() {
echo "[publish] $*" >&2
}
# Prints the newest v* tag reachable from HEAD without its "v", or nothing.
# Prints the v* tag on HEAD without its "v", or nothing.
release_tag_version() {
local tag
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
fi
}
@@ -61,36 +62,54 @@ run_gradle() {
"$@"
}
main() {
local version
local publish="${REQUESTED_PUBLISH}"
run_tests() {
local version="$1"
local check_tasks
local publish_tasks
version="$(release_tag_version)"
if [[ -z "${version}" ]]; then
log "No v* git tag found (shallow clone without tags?); nothing to publish."
exit 1
fi
if [[ "${version}" == *-* ]]; then
publish=false
log "${version} is a pre-release version; nothing will be published."
fi
mapfile -t check_tasks < <(module_tasks check)
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
log "Testing ZomboidForge ${version}: ${MODULES[*]}"
run_gradle "${version}" :core:check "${check_tasks[@]}"
}
if [[ "${publish}" != "true" ]]; then
log "Not publishing (PUBLISH=${REQUESTED_PUBLISH})."
publish() {
local version="$1"
local publish_tasks
if [[ "${version}" == *-* ]]; then
log "${version} is a pre-release version; nothing is published."
return
fi
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
log "Publishing ZomboidForge ${version}"
run_gradle "${version}" "${publish_tasks[@]}"
log "Published ${MODULES[*]} ${version}"
}
main() {
local step="${1:-}"
local version
version="$(release_tag_version)"
if [[ -z "${version}" ]]; then
log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish."
exit 1
fi
case "${step}" in
test)
run_tests "${version}"
;;
publish)
publish "${version}"
;;
*)
log "Usage: ci/publish.sh test|publish"
exit 2
;;
esac
}
main "$@"
+61 -26
View File
@@ -1,22 +1,29 @@
#!/usr/bin/env bash
#
# Builds the ZomboidForge image for one Project Zomboid version and optionally
# Builds the ZomboidForge image for the current build of a Steam branch and optionally
# publishes it. Published tags:
#
# <forge>-pz<pz>-build<steam_buildid> immutable; never overwritten
# <forge>-pz<pz> moves to the newest Steam build of that version
# latest only with LATEST=true
# <forge>-pz<major.minor.build> written once per ZomboidForge and Project Zomboid version
# <forge>-pz<major.minor> moves to the newest hotfix of that minor version
# latest only with LATEST=true
#
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0).
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never
# published. Without any v* tag the version is "0.0.0-prerelease".
# <major.minor.build> is the version the branch's server jar reports, read before the full
# build (Dockerfile stage game-version, which downloads only the jar).
#
# Nothing is built when the immutable tag already exists in the registry.
# <forge> is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such
# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0).
# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and
# verified but never published. Without any v* tag the version is "0.0.0-prerelease".
#
# Nothing is built when <forge>-pz<major.minor.build> already exists in the registry. The
# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 ->
# 42.21.2) gets an image; a new Steam build with an unchanged version does not.
#
# Environment:
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
# PZ_BRANCH Steam branch. Default: public
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties
# PZ_VERSION Accepted Project Zomboid versions ("42": every Build 42 version).
# Default: pz.version in gradle.properties
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
# LATEST true: also push "latest". Default: false
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
@@ -63,12 +70,15 @@ gradle_property() {
exit 1
}
# Prints the forge version: the newest v* tag reachable from HEAD without its "v",
# or nothing when the repository has no such tag.
# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the
# repository has no such tag.
release_tag_version() {
local tag
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
fi
}
@@ -78,6 +88,22 @@ image_exists() {
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
}
# Prints the game version of the branch's current server jar, e.g. 42.21.0. Downloads only
# the jar; the result stays cached until the build ID changes.
read_game_version() {
local build_id="$1"
local image
image="$("$(container_engine)" build --quiet \
--platform linux/amd64 \
--target game-version \
--build-arg "PZ_BRANCH=${PZ_BRANCH}" \
--build-arg "STEAM_BUILDID=${build_id}" \
"${REPO_ROOT}")"
"$(container_engine)" run --rm --entrypoint cat "${image}" /game-version
}
build_image() {
local reference="$1"
local forge_version="$2"
@@ -119,8 +145,9 @@ push_as() {
main() {
local forge_version
local publish="${REQUESTED_PUBLISH}"
local pz_version
local pz_prefix
local build_id
local game_version
forge_version="$(release_tag_version)"
if [[ -z "${forge_version}" ]]; then
@@ -132,31 +159,39 @@ main() {
log "${forge_version} is a pre-release version; nothing will be published."
fi
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
pz_prefix="${PZ_VERSION:-$(gradle_property pz.version)}"
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
game_version="$(read_game_version "${build_id}")"
log "ZomboidForge ${forge_version}, Project Zomboid ${game_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}"
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}"
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
# Checked here as well as by the patcher, to fail before the full download.
if [[ "${game_version}" != "${pz_prefix}" && "${game_version}" != "${pz_prefix}."* ]]; then
log "Steam branch ${PZ_BRANCH} has Project Zomboid ${game_version}; the build accepts ${pz_prefix}."
exit 1
fi
if [[ "${publish}" == true ]] && image_exists "${immutable_tag}"; then
log "${immutable_tag} is already published; nothing to do."
local version_tag="${IMAGE}:${forge_version}-pz${game_version}"
# 42.21.2 -> 42.21
local minor_tag="${IMAGE}:${forge_version}-pz${game_version%.*}"
if [[ "${publish}" == true ]] && image_exists "${version_tag}"; then
log "${version_tag} is already published; nothing to do."
return
fi
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}"
verify_build_id "${immutable_tag}" "${build_id}"
build_image "${version_tag}" "${forge_version}" "${game_version}" "${build_id}"
verify_build_id "${version_tag}" "${build_id}"
if [[ "${publish}" != true ]]; then
log "Built ${immutable_tag} (not published)"
log "Built ${version_tag} (not published)"
return
fi
"$(container_engine)" push "${immutable_tag}"
log "Pushed ${immutable_tag}"
push_as "${immutable_tag}" "${version_tag}"
"$(container_engine)" push "${version_tag}"
log "Pushed ${version_tag}"
push_as "${version_tag}" "${minor_tag}"
if [[ "${LATEST}" == true ]]; then
push_as "${immutable_tag}" "${IMAGE}:latest"
push_as "${version_tag}" "${IMAGE}:latest"
fi
}
+1 -1
View File
@@ -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"
@@ -17,11 +17,30 @@ public final class B42PatchSet implements PatchSet
new ServerStartedPatch(),
new ServerTickPatch(),
new ServerStoppingPatch(),
new ZipBackupSinglePassPerformancePatch(),
new BackupStoragePatch(),
new CommandLookupPatch(),
new CommandListPatch(),
new ClientCommandPatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch()
new IsoGameCharacterStateMachinePerformancePatch(),
new ZombieVoronoiPerformancePatch(),
new ZomboidFileSystemInitPerformancePatch(),
new ServerMapCellBudgetPerformancePatch(),
new WorldGenUtilsPlacementPerformancePatch(),
new WorldGenChunkRulesPerformancePatch(),
new BitHeaderPoolPerformancePatch(),
new IsoChunkSaveDirectoryPerformancePatch(),
new RolesSavePerformancePatch(),
new ServerChunkLoaderQuitPerformancePatch(),
new ZipBackupWaitPerformancePatch(),
new ServerPlayersVehiclesRoundPerformancePatch(),
new ServerPlayersVehiclesStopPerformancePatch(),
new ServerPlayerDBSaveWaitPerformancePatch(),
new GameServerAssetLoadingPerformancePatch(),
new ServerMapQuitSleepPerformancePatch()
);
@Override
@@ -0,0 +1,48 @@
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);
}
}
@@ -0,0 +1,31 @@
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
{
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());
}
}
@@ -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)));
}
}
@@ -2,7 +2,7 @@ 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;
import dev.overlord.zomboidforge.patcher.patches.HookInjectionPatch;
/**
* Calls {@code ServerHooks.onServerStarted()} in {@code GameServer.main}, directly after
@@ -2,7 +2,7 @@ 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;
import dev.overlord.zomboidforge.patcher.patches.HookInjectionPatch;
/**
* Calls {@code ServerHooks.onTick()} in the main loop of {@code GameServer.main}, directly after
@@ -0,0 +1,93 @@
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.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Creates the four header pools of {@code zombie.util.io.BitHeader} as {@code PerThreadDeque}s
* instead of {@code ConcurrentLinkedDeque}s:
*
* <pre>{@code
* // and short, int, long
* private static final ConcurrentLinkedDeque pool_byte = new PerThreadDeque();
* }</pre>
*
* Every square and object a chunk save writes takes a header from a pool and returns it, from the
* save worker threads at once; the shared deques were about a third of chunk serialization.
* {@code PerThreadDeque} answers {@code poll}, {@code offer} and {@code size}, the only methods
* {@code BitHeader} calls on the pools, from a pool per thread. A header is reset when it is
* returned and gets its buffer and mode when it is taken, so which header a thread gets does not
* change what is written.
*/
public final class BitHeaderPoolPerformancePatch extends PerformancePatch
{
private static final String DEQUE = "java/util/concurrent/ConcurrentLinkedDeque";
private static final String POOL = "dev/overlord/zomboidforge/compat/b42/util/PerThreadDeque";
private static final Set<String> POOL_FIELDS = Set.of("pool_byte", "pool_short", "pool_int", "pool_long");
private static final Anchor.Method ANCHOR = new Anchor.Method("<clinit>", "()V");
public BitHeaderPoolPerformancePatch() {
super("zombie/util/io/BitHeader", BitHeaderPoolPerformancePatch.ANCHOR, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = BitHeaderPoolPerformancePatch.ANCHOR.resolve(node);
Set<String> replaced = new TreeSet<>();
for (AbstractInsnNode instruction : method.instructions)
{
if (!(instruction instanceof TypeInsnNode creation) || creation.getOpcode() != Opcodes.NEW || !creation.desc.equals(BitHeaderPoolPerformancePatch.DEQUE)) continue;
// new ConcurrentLinkedDeque; dup; invokespecial <init>()V; putstatic pool_*
List<AbstractInsnNode> next = BitHeaderPoolPerformancePatch.following(creation, 3);
if (!(next.get(1) instanceof MethodInsnNode constructor) || constructor.getOpcode() != Opcodes.INVOKESPECIAL || !constructor.owner.equals(BitHeaderPoolPerformancePatch.DEQUE) || !constructor.desc.equals("()V"))
throw new IllegalStateException("'" + node.name + ".<clinit>': a 'ConcurrentLinkedDeque' is not created with its no-argument constructor.");
if (!(next.get(2) instanceof FieldInsnNode store) || store.getOpcode() != Opcodes.PUTSTATIC || !BitHeaderPoolPerformancePatch.POOL_FIELDS.contains(store.name))
throw new IllegalStateException("'" + node.name + ".<clinit>': a 'ConcurrentLinkedDeque' is created for something other than a header pool.");
creation.desc = BitHeaderPoolPerformancePatch.POOL;
constructor.owner = BitHeaderPoolPerformancePatch.POOL;
replaced.add(store.name);
}
if (!replaced.equals(BitHeaderPoolPerformancePatch.POOL_FIELDS))
throw new IllegalStateException("'" + node.name + ".<clinit>' creates the pools " + replaced + ", expected " + new TreeSet<>(BitHeaderPoolPerformancePatch.POOL_FIELDS) + ".");
}
/** The {@code count} real instructions after {@code instruction}: no labels, line numbers, or frames. */
private static List<AbstractInsnNode> following(AbstractInsnNode instruction, int count)
{
List<AbstractInsnNode> following = new ArrayList<>();
for (AbstractInsnNode next = instruction.getNext(); next != null && following.size() < count; next = next.getNext()) {
if (next.getOpcode() != -1) following.add(next);
}
if (following.size() < count) throw new IllegalStateException("'BitHeader.<clinit>' ends after a 'new ConcurrentLinkedDeque'.");
return following;
}
}
@@ -0,0 +1,62 @@
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.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Replaces the update call of the asset loop in {@code GameServer.doMinimumInit}:
*
* <pre>{@code
* while (GameWindow.fileSystem.hasWork()) {
* // GameWindow.fileSystem.updateAsyncTransactions()
* AssetLoadingHooks.updateAsyncTransactions(GameWindow.fileSystem);
* }
* }</pre>
*
* With the feature {@code experimental_performance} the hook grows the loader pool to one thread
* per CPU but one and parks the main thread between updates instead of spinning. The
* per-frame call in {@code GameServer.main} stays.
*/
public final class GameServerAssetLoadingPerformancePatch extends PerformancePatch
{
private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("doMinimumInit", "()V"),
GameServerAssetLoadingPerformancePatch.FILE_SYSTEM, "updateAsyncTransactions", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooks", "updateAsyncTransactions", "(L" + GameServerAssetLoadingPerformancePatch.FILE_SYSTEM + ";)V"
);
public GameServerAssetLoadingPerformancePatch() {
super("zombie/network/GameServer", GameServerAssetLoadingPerformancePatch.ANCHOR, GameServerAssetLoadingPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = GameServerAssetLoadingPerformancePatch.ANCHOR.in().resolve(node);
MethodInsnNode update = GameServerAssetLoadingPerformancePatch.ANCHOR.resolve(node);
if (update.getOpcode() != Opcodes.INVOKEVIRTUAL)
throw new IllegalStateException("'" + node.name + ".doMinimumInit': 'FileSystem.updateAsyncTransactions' is not called virtually.");
// The hook takes the receiver of the virtual call as its argument: the stack is unchanged.
method.instructions.set(update, new MethodInsnNode(Opcodes.INVOKESTATIC, GameServerAssetLoadingPerformancePatch.HOOK.owner(),
GameServerAssetLoadingPerformancePatch.HOOK.name(), GameServerAssetLoadingPerformancePatch.HOOK.desc(), false));
}
}
@@ -0,0 +1,85 @@
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.JumpInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.List;
/**
* Removes the folder check before every chunk save in {@code IsoChunk.Save(boolean)}:
*
* <pre>{@code
* File testDir = ChunkMapFilenames.instance.getDir(Core.gameSaveWorld);
* if (!testDir.exists()) { // removed
* testDir.mkdir();
* }
* }</pre>
*
* {@code getDir} returns {@code <cache>/map/<world>}, which nothing reads or writes; chunk files
* are saved under {@code <cache>/<world>/map/<x>/}, whose folders {@code getFilename} creates.
* {@code <cache>/map} does not exist, so the {@code mkdir} fails on every save: one {@code stat}
* and one failed {@code mkdir} per chunk. The {@code getDir} call stays; it initializes the cache
* folder of {@code ChunkMapFilenames} on first use.
*/
public final class IsoChunkSaveDirectoryPerformancePatch extends PerformancePatch
{
/** {@code testDir = ...getDir(world); if (!testDir.exists()) testDir.mkdir();} */
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
new Anchor.Method("Save", "(Z)V"),
new Anchor.Instruction.Invoke("zombie/ChunkMapFilenames", "getDir", "(Ljava/lang/String;)Ljava/io/File;"),
new Anchor.Instruction.Opcode(Opcodes.ASTORE),
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Invoke("java/io/File", "exists", "()Z"),
new Anchor.Instruction.Opcode(Opcodes.IFNE),
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Invoke("java/io/File", "mkdir", "()Z"),
new Anchor.Instruction.Opcode(Opcodes.POP)
);
public IsoChunkSaveDirectoryPerformancePatch() {
super("zombie/iso/IsoChunk", IsoChunkSaveDirectoryPerformancePatch.ANCHOR, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoChunkSaveDirectoryPerformancePatch.ANCHOR.in().resolve(node);
List<AbstractInsnNode> matched = IsoChunkSaveDirectoryPerformancePatch.ANCHOR.resolve(node);
int testDir = ((VarInsnNode) matched.get(1)).var;
JumpInsnNode skip = (JumpInsnNode) matched.get(4);
if (((VarInsnNode) matched.get(2)).var != testDir || ((VarInsnNode) matched.get(5)).var != testDir)
throw new IllegalStateException("'" + node.name + ".Save': the check does not use the folder that 'getDir' returned.");
if (IsoChunkSaveDirectoryPerformancePatch.nextInstruction(skip.label) != IsoChunkSaveDirectoryPerformancePatch.nextInstruction(matched.getLast()))
throw new IllegalStateException("'" + node.name + ".Save': the folder check does not jump to the end of its block.");
// The if-block: from loading testDir for exists() to the pop after mkdir(). Labels stay,
// so the jump target and the local variable table remain valid.
for (AbstractInsnNode instruction : matched.subList(2, matched.size())) method.instructions.remove(instruction);
}
/** 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("'IsoChunk.Save' ends after the folder check.");
return next;
}
}
@@ -2,7 +2,7 @@ package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
@@ -2,7 +2,7 @@ package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.jetbrains.annotations.Nullable;
@@ -2,7 +2,7 @@ package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
@@ -3,7 +3,7 @@ package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
@@ -0,0 +1,58 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Saves the roles in one SQLite transaction. {@code Roles.save()} is renamed to
* {@code zomboidForge$save} and wrapped:
*
* <pre>{@code
* public static void save()
* {
* RolesHooks.beginSave();
* try { zomboidForge$save(); }
* finally { RolesHooks.endSave(); }
* }
* }</pre>
*
* The vanilla method writes every role and capability with its own autocommitted statement
* ({@code ServerWorldDatabase.saveRole}, {@code saveDefaultRole}): about 250 transactions and
* 1,000 {@code fsync}s, 1.3 s of every shutdown on a fast disk.
*/
public final class RolesSavePerformancePatch extends PerformancePatch
{
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
private static final String RENAMED = "zomboidForge$save";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("save", "()V"),
"zombie/network/ServerWorldDatabase", "saveRole", "(Lzombie/characters/Role;)V"
);
private static final Hook HOOK = new Hook(RolesSavePerformancePatch.HOOKS, "beginSave", "()V");
private static final Hook END = new Hook(RolesSavePerformancePatch.HOOKS, "endSave", "()V");
public RolesSavePerformancePatch() {
super("zombie/characters/Roles", RolesSavePerformancePatch.ANCHOR, RolesSavePerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode save = RolesSavePerformancePatch.ANCHOR.in().resolve(node);
MethodBody.wrap(node, save, RolesSavePerformancePatch.RENAMED, RolesSavePerformancePatch.HOOK, RolesSavePerformancePatch.END);
}
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerChunkLoader.quit()} waits for the chunk loading thread, then for the chunk saving
* thread, each with {@code while (thread.isAlive()) Thread.sleep(500);}: at least 1 s of every
* shutdown although both threads end within milliseconds. The sleeps become
* {@code WaitHooks.pollSleep} (at most 5 ms).
*/
public final class ServerChunkLoaderQuitPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "pollSleep", "(J)V");
public ServerChunkLoaderQuitPerformancePatch() {
super("zombie/network/ServerChunkLoader", new Anchor.Method("quit", "()V"), 2, ServerChunkLoaderQuitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,90 @@
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.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Spreads the integration of finished cells in {@code ServerMap.preupdate} over frames:
*
* <pre>{@code
* // was ServerLOS.instance.suspend()
* ServerMapHooks.beginIntegration(ServerLOS.instance);
*
* for (int x = 0; x < ServerCell.loaded2.size(); ++x)
* {
* ServerCell cell = ServerCell.loaded2.get(x);
*
* if (ServerMapHooks.integrate(cell)) {
* // was cell.Load2()
* --x; this.toLoad.remove(cell);
* }
* }
* }</pre>
*
* Vanilla integrates every cell that finished loading since the last frame (70 to 300 ms each
* on new terrain), so cells that finish together make one long frame. The hooks integrate cells
* until 40 ms are used, at least one per frame; the others stay in {@code loaded2} for the next
* frames. The work per cell is the same; only the frame it runs in changes, which the
* asynchronous loader already varies.
*/
public final class ServerMapCellBudgetPerformancePatch extends PerformancePatch
{
private static final String OWNER = "zombie/network/ServerMap";
private static final String CELL = "zombie/network/ServerMap$ServerCell";
private static final String LOS = "zombie/network/ServerLOS";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ServerMapHooks";
private static final Anchor.Method PREUPDATE = new Anchor.Method("preupdate", "()V");
private static final Anchor.Call ANCHOR = new Anchor.Call(
ServerMapCellBudgetPerformancePatch.PREUPDATE, ServerMapCellBudgetPerformancePatch.CELL, "Load2", "()Z"
);
/** {@code ServerLOS.instance.suspend()} before the integration loop. */
private static final Anchor.Call SUSPEND = new Anchor.Call(
ServerMapCellBudgetPerformancePatch.PREUPDATE, ServerMapCellBudgetPerformancePatch.LOS, "suspend", "()V"
);
private static final Hook HOOK = new Hook(
ServerMapCellBudgetPerformancePatch.HOOKS, "integrate", "(L" + ServerMapCellBudgetPerformancePatch.CELL + ";)Z"
);
private static final Hook BEGIN = new Hook(
ServerMapCellBudgetPerformancePatch.HOOKS, "beginIntegration", "(L" + ServerMapCellBudgetPerformancePatch.LOS + ";)V"
);
public ServerMapCellBudgetPerformancePatch() {
super(ServerMapCellBudgetPerformancePatch.OWNER, ServerMapCellBudgetPerformancePatch.ANCHOR, ServerMapCellBudgetPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ServerMapCellBudgetPerformancePatch.PREUPDATE.resolve(node);
MethodInsnNode load2 = ServerMapCellBudgetPerformancePatch.ANCHOR.resolve(node);
MethodInsnNode suspend = ServerMapCellBudgetPerformancePatch.SUSPEND.resolve(node);
if (method.instructions.indexOf(suspend) > method.instructions.indexOf(load2))
throw new IllegalStateException("'" + node.name + ".preupdate': 'ServerLOS.suspend' comes after 'ServerCell.Load2'.");
// Both hooks take the receiver of the virtual call as their argument: the stack is unchanged.
method.instructions.set(suspend, ServerMapCellBudgetPerformancePatch.call(ServerMapCellBudgetPerformancePatch.BEGIN));
method.instructions.set(load2, ServerMapCellBudgetPerformancePatch.call(ServerMapCellBudgetPerformancePatch.HOOK));
}
private static MethodInsnNode call(Hook hook)
{
return new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false);
}
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerMap.QueuedQuit()} sleeps 5 s after the world save and the {@code ServerQuit}
* broadcast, so the clients can disconnect. The sleep becomes {@code QuitHooks.quitSleep}. With
* the feature {@code experimental_performance} enabled, the shutdown continues as soon as no
* client is connected, after at most 5s. With the feature disabled, it keeps the vanilla sleep.
*/
public final class ServerMapQuitSleepPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/QuitHooks", "quitSleep", "(J)V");
public ServerMapQuitSleepPerformancePatch() {
super("zombie/network/ServerMap", new Anchor.Method("QueuedQuit", "()V"), 1, ServerMapQuitSleepPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,27 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerPlayerDB.saveFinishWait()} waits until the {@code ServerPlayersVehicles} thread
* has saved the queued players: {@code while (!charactersToSave.isEmpty()) Thread.sleep(100);}.
* The thread saves them at the start of its next round, up to 500 ms later. The sleep becomes
* {@code WaitHooks.wakeVehiclesAndPoll}: it starts that round now
* ({@link ServerPlayersVehiclesRoundPerformancePatch}) and polls every 5 ms.
*/
public final class ServerPlayerDBSaveWaitPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "wakeVehiclesAndPoll", "(J)V");
public ServerPlayerDBSaveWaitPerformancePatch() {
super("zombie/savefile/ServerPlayerDB", new Anchor.Method("saveFinishWait", "()V"), 1, ServerPlayerDBSaveWaitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* The {@code ServerPlayersVehicles} thread saves queued players and streams vehicles, then sleeps
* 500 ms ({@code SPVThread.runInner}). The sleep becomes {@code WaitHooks.vehicleRoundSleep}: the
* same 500 ms, but {@link ServerPlayersVehiclesStopPerformancePatch} and
* {@link ServerPlayerDBSaveWaitPerformancePatch} can end it early.
*/
public final class ServerPlayersVehiclesRoundPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "vehicleRoundSleep", "(J)V");
public ServerPlayersVehiclesRoundPerformancePatch() {
super("zombie/network/ServerPlayersVehicles$SPVThread", new Anchor.Method("runInner", "()V"), 1, ServerPlayersVehiclesRoundPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerPlayersVehicles.stop()} sets the thread's stop flag and waits with
* {@code while (thread.isAlive()) Thread.sleep(100);}, while the thread may sleep up to 500 ms
* before it sees the flag. The sleep becomes {@code WaitHooks.wakeVehiclesAndPoll}: it ends the
* thread's round sleep ({@link ServerPlayersVehiclesRoundPerformancePatch}) and polls every 5 ms.
*/
public final class ServerPlayersVehiclesStopPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "wakeVehiclesAndPoll", "(J)V");
public ServerPlayersVehiclesStopPerformancePatch() {
super("zombie/network/ServerPlayersVehicles", new Anchor.Method("stop", "()V"), 1, ServerPlayersVehiclesStopPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,76 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* The tile rules of {@code WorldGenChunk} with cached compiled patterns, like
* {@link WorldGenUtilsPlacementPerformancePatch}:
*
* <ul>
* <li>the body of {@code isProtected(List, String)} becomes
* {@code return WorldGenHooks.isProtected(protectedTiles, tile);}</li>
* <li>in {@code cleanChunk(IsoChunk, String, String)}, {@code floorMaterial.matches(mat)}
* becomes {@code WorldGenHooks.matches(floorMaterial, mat)}.</li>
* </ul>
*/
public final class WorldGenChunkRulesPerformancePatch extends PerformancePatch
{
private static final String STRING = "java/lang/String";
private static final String MATCHES = "(Ljava/lang/String;)Z";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("isProtected", "(Ljava/util/List;Ljava/lang/String;)Z"),
WorldGenChunkRulesPerformancePatch.STRING, "matches", WorldGenChunkRulesPerformancePatch.MATCHES
);
private static final Anchor.Call CLEAN_CHUNK = new Anchor.Call(
new Anchor.Method("cleanChunk", "(Lzombie/iso/IsoChunk;Ljava/lang/String;Ljava/lang/String;)V"),
WorldGenChunkRulesPerformancePatch.STRING, "matches", WorldGenChunkRulesPerformancePatch.MATCHES
);
private static final Hook HOOK = new Hook(
WorldGenChunkRulesPerformancePatch.HOOKS, "isProtected", "(Ljava/util/List;Ljava/lang/String;)Z"
);
private static final Hook MATCHES_HOOK = new Hook(
WorldGenChunkRulesPerformancePatch.HOOKS, "matches", "(Ljava/lang/String;Ljava/lang/String;)Z"
);
public WorldGenChunkRulesPerformancePatch() {
super("zombie/iso/worldgen/WorldGenChunk", WorldGenChunkRulesPerformancePatch.ANCHOR, WorldGenChunkRulesPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode isProtected = WorldGenChunkRulesPerformancePatch.ANCHOR.in().resolve(node);
MethodNode cleanChunk = WorldGenChunkRulesPerformancePatch.CLEAN_CHUNK.in().resolve(node);
MethodInsnNode matches = WorldGenChunkRulesPerformancePatch.CLEAN_CHUNK.resolve(node);
MethodBody.delegate(node, isProtected, WorldGenChunkRulesPerformancePatch.HOOK);
// The hook takes the receiver as its first argument: the stack is unchanged.
cleanChunk.instructions.set(matches, new MethodInsnNode(
Opcodes.INVOKESTATIC,
WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.owner(),
WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.name(),
WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.desc(),
false
));
}
}
@@ -0,0 +1,56 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Replaces the body of {@code WorldGenUtils.canPlace(List, String)} with a call to
* {@code WorldGenHooks.canPlace}, which caches the compiled rules:
*
* <pre>{@code
* public boolean canPlace(List placement, String floorName)
* {
* return WorldGenHooks.canPlace(placement, floorName);
* }
* }</pre>
*
* Vanilla builds and compiles a regular expression per rule per call, for every square of a new
* chunk, on the chunk loader thread. Together with {@link WorldGenChunkRulesPerformancePatch}
* this halves the time to create a new chunk and removes most of the garbage the server
* produces while players explore; {@link ServerMapCellBudgetPerformancePatch} keeps the faster
* cells from bunching up on the main thread.
*/
public final class WorldGenUtilsPlacementPerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("canPlace", "(Ljava/util/List;Ljava/lang/String;)Z"),
"java/lang/String", "matches", "(Ljava/lang/String;)Z"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks", "canPlace", "(Ljava/util/List;Ljava/lang/String;)Z"
);
public WorldGenUtilsPlacementPerformancePatch() {
super("zombie/iso/worldgen/WorldGenUtils", WorldGenUtilsPlacementPerformancePatch.ANCHOR, WorldGenUtilsPlacementPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = WorldGenUtilsPlacementPerformancePatch.ANCHOR.in().resolve(node);
MethodBody.delegate(node, method, WorldGenUtilsPlacementPerformancePatch.HOOK);
}
}
@@ -0,0 +1,60 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)} with a call to
* {@code BackupHooks.makeBackupFile}, which writes the same zip in one pass:
*
* <pre>{@code
* private static void makeBackupFile(String serverName, BackupTypes type)
* {
* BackupHooks.makeBackupFile(serverName, type);
* }
* }</pre>
*
* Vanilla's {@code ParallelScatterZipCreator} copies every file into a temporary file per thread
* and then into the zip: about three times the size of the save written per backup. For an
* explored world of 880 MiB in 365,538 files, the startup backup takes 15.2 to 16.8 s and writes
* 2.9 GB; in one pass 7.5 s and 1.0 GB, with the same entries. The save folder is read under
* {@code IsoChunk.WriteLock}, as vanilla; chunk saves wait for it half as long.
*
* <p>Registered before {@code BackupStoragePatch}, which renames this method and wraps it: the
* anchor requires vanilla's body, and the storage hooks stay around the whole backup.
*/
public final class ZipBackupSinglePassPerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V"),
"org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator", "writeTo", "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveOutputStream;)V"
);
// BackupTypes is private: the hook takes it as Object.
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks", "makeBackupFile", "(Ljava/lang/String;Ljava/lang/Object;)V"
);
public ZipBackupSinglePassPerformancePatch() {
super("zombie/core/backup/ZipBackup", ZipBackupSinglePassPerformancePatch.ANCHOR, ZipBackupSinglePassPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ZipBackupSinglePassPerformancePatch.ANCHOR.in().resolve(node);
MethodBody.delegate(node, method, ZipBackupSinglePassPerformancePatch.HOOK);
}
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ZipBackup.waitFinish()}, called at the start of the shutdown, waits for a running
* periodic backup with {@code while (backupThread.isAlive()) Thread.sleep(500);}. The sleep
* becomes {@code WaitHooks.pollSleep} (at most 5 ms), so the shutdown continues when the backup
* ends instead of up to 500 ms later.
*/
public final class ZipBackupWaitPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "pollSleep", "(J)V");
public ZipBackupWaitPerformancePatch() {
super("zombie/core/backup/ZipBackup", new Anchor.Method("waitFinish", "()V"), 1, ZipBackupWaitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,121 @@
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.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Replaces the body of {@code ZombieVoronoi.evaluateNoise(double, double, Random, List)} with a
* call to {@code ZombieVoronoiHooks.evaluateNoise}, which returns the same values:
*
* <pre>{@code
* private double evaluateNoise(
* double x, double y, Random rng, List<Coord> points
* ) {
* return ZombieVoronoiHooks.evaluateNoise(
* this.closestPoint,
* this.seed,
* this.numberPoints,
* x, y, rng, points
* );
* }
* }</pre>
*
* The world generation evaluates it 1,024 times per cell at startup; each call creates 9
* {@code Coord}s and lets {@code ClosestSelectionType.getClosest} sort their boxed distances.
* The hook computes the distances in one pass.
*/
public final class ZombieVoronoiPerformancePatch extends PerformancePatch
{
private static final String SELECTION = "zombie/iso/worldgen/zombie/ClosestSelection";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("evaluateNoise", "(DDLjava/util/Random;Ljava/util/List;)D"),
ZombieVoronoiPerformancePatch.SELECTION, "getClosest", "(DDLjava/util/List;)D"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks", "evaluateNoise",
"(L" + ZombieVoronoiPerformancePatch.SELECTION + ";JIDDLjava/util/Random;Ljava/util/List;)D"
);
public ZombieVoronoiPerformancePatch() {
super("zombie/iso/worldgen/zombie/ZombieVoronoi", ZombieVoronoiPerformancePatch.ANCHOR, ZombieVoronoiPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ZombieVoronoiPerformancePatch.ANCHOR.in().resolve(node);
if ((method.access & Opcodes.ACC_STATIC) != 0)
throw new IllegalStateException("'" + node.name + "." + method.name + method.desc + "' is static.");
ZombieVoronoiPerformancePatch.requireField(node, "closestPoint", "L" + ZombieVoronoiPerformancePatch.SELECTION + ";");
ZombieVoronoiPerformancePatch.requireField(node, "seed", "J");
ZombieVoronoiPerformancePatch.requireField(node, "numberPoints", "I");
// The local variable table and annotations refer to labels of the old body.
method.instructions.clear();
method.tryCatchBlocks.clear();
method.localVariables = null;
method.visibleLocalVariableAnnotations = null;
method.invisibleLocalVariableAnnotations = null;
method.instructions.add(ZombieVoronoiPerformancePatch.callHook(node.name));
}
/**
* {@code return hook(this.closestPoint, this.seed, this.numberPoints, x, y, rng, points);}.
* Locals: {@code this} 0, {@code x} 1-2, {@code y} 3-4, {@code rng} 5, {@code points} 6.
*/
private static InsnList callHook(String owner)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "closestPoint", "L" + ZombieVoronoiPerformancePatch.SELECTION + ";"));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "seed", "J"));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "numberPoints", "I"));
code.add(new VarInsnNode(Opcodes.DLOAD, 1));
code.add(new VarInsnNode(Opcodes.DLOAD, 3));
code.add(new VarInsnNode(Opcodes.ALOAD, 5));
code.add(new VarInsnNode(Opcodes.ALOAD, 6));
code.add(new MethodInsnNode(
Opcodes.INVOKESTATIC,
ZombieVoronoiPerformancePatch.HOOK.owner(),
ZombieVoronoiPerformancePatch.HOOK.name(),
ZombieVoronoiPerformancePatch.HOOK.desc(),
false
));
code.add(new InsnNode(Opcodes.DRETURN));
return code;
}
private static void requireField(ClassNode node, String name, String desc)
{
for (FieldNode field : node.fields) {
if (field.name.equals(name) && field.desc.equals(desc) && (field.access & Opcodes.ACC_STATIC) == 0) return;
}
throw new IllegalStateException("Expected the instance field '" + node.name + "." + name + " " + desc + "'.");
}
}
@@ -0,0 +1,119 @@
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.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Replaces the call {@code this.searchFolders(workdir)} in {@code ZomboidFileSystem.init} with
* {@code ZomboidFileSystemHooks.searchAndIndex}, which also does the work of the loop after it:
*
* <pre>{@code
* ZomboidFileSystemHooks.searchAndIndex(
* this, this.workdir.canonicalFile,
* this.loadList, this.allAbsolutePaths
* );
*
* // loadList is empty now
* for (int n = 0; n < this.loadList.size(); ++n) { ... }
*
* this.loadList.clear();
* }</pre>
*
* Vanilla checks each of the ~39,000 entries under {@code media/} for being a folder twice, and
* builds two URIs per entry for its relative path; the hook walks the folder once.
*/
public final class ZomboidFileSystemInitPerformancePatch extends PerformancePatch
{
private static final String OWNER = "zombie/ZomboidFileSystem";
private static final Anchor.Method INIT = new Anchor.Method("init", "()V");
private static final Anchor.Call ANCHOR = new Anchor.Call(
ZomboidFileSystemInitPerformancePatch.INIT,
ZomboidFileSystemInitPerformancePatch.OWNER, "searchFolders", "(Ljava/io/File;)V"
);
/** The loop the hook takes over: the relative path of each entry. */
private static final Anchor.Call RELATIVE_PATH = new Anchor.Call(
ZomboidFileSystemInitPerformancePatch.INIT,
ZomboidFileSystemInitPerformancePatch.OWNER, "getRelativeFile", "(Ljava/lang/String;)Ljava/lang/String;"
);
/** {@code this.loadList.clear()} after the loop. */
private static final Anchor.Call CLEAR = new Anchor.Call(
ZomboidFileSystemInitPerformancePatch.INIT,
"java/util/List", "clear", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks", "searchAndIndex",
"(L" + ZomboidFileSystemInitPerformancePatch.OWNER + ";Ljava/io/File;Ljava/util/List;Ljava/util/Set;)V"
);
public ZomboidFileSystemInitPerformancePatch() {
super(ZomboidFileSystemInitPerformancePatch.OWNER, ZomboidFileSystemInitPerformancePatch.ANCHOR, ZomboidFileSystemInitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ZomboidFileSystemInitPerformancePatch.INIT.resolve(node);
MethodInsnNode call = ZomboidFileSystemInitPerformancePatch.ANCHOR.resolve(node);
ZomboidFileSystemInitPerformancePatch.RELATIVE_PATH.verify(node);
ZomboidFileSystemInitPerformancePatch.CLEAR.verify(node);
ZomboidFileSystemInitPerformancePatch.requireField(node, "loadList", "Ljava/util/List;");
ZomboidFileSystemInitPerformancePatch.requireField(node, "allAbsolutePaths", "Ljava/util/Set;");
int callIndex = method.instructions.indexOf(call);
if (callIndex > method.instructions.indexOf(ZomboidFileSystemInitPerformancePatch.RELATIVE_PATH.resolve(node)))
throw new IllegalStateException("'" + node.name + ".init': 'searchFolders' is called after 'getRelativeFile'.");
// The stack holds this and the folder for the virtual call; the hook takes both, then the two fields.
method.instructions.insertBefore(call, ZomboidFileSystemInitPerformancePatch.loadFields(node.name));
method.instructions.set(call, new MethodInsnNode(
Opcodes.INVOKESTATIC,
ZomboidFileSystemInitPerformancePatch.HOOK.owner(),
ZomboidFileSystemInitPerformancePatch.HOOK.name(),
ZomboidFileSystemInitPerformancePatch.HOOK.desc(),
false
));
}
/** {@code this.loadList, this.allAbsolutePaths}. */
private static InsnList loadFields(String owner)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "loadList", "Ljava/util/List;"));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "allAbsolutePaths", "Ljava/util/Set;"));
return code;
}
private static void requireField(ClassNode node, String name, String desc)
{
for (FieldNode field : node.fields) {
if (field.name.equals(name) && field.desc.equals(desc) && (field.access & Opcodes.ACC_STATIC) == 0) return;
}
throw new IllegalStateException("Expected the instance field '" + node.name + "." + name + " " + desc + "'.");
}
}
@@ -0,0 +1,138 @@
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.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;
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_FINAL;
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.DUP;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
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 BitHeaderPoolPerformancePatchTest
{
private static final String HEADER = "zombie/util/io/BitHeader";
private static final String DEQUE = "java/util/concurrent/ConcurrentLinkedDeque";
private static final String POOL = "dev/overlord/zomboidforge/compat/b42/util/PerThreadDeque";
/** {@code BitHeader} whose {@code <clinit>} creates a deque for each of {@code fields}. */
private static ClassNode bitHeader(List<String> fields)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_FINAL, BitHeaderPoolPerformancePatchTest.HEADER, null, "java/lang/Object", null);
for (String field : fields) node.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, field, "L" + BitHeaderPoolPerformancePatchTest.DEQUE + ";", null, null);
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
for (String field : fields)
{
clinit.visitTypeInsn(NEW, BitHeaderPoolPerformancePatchTest.DEQUE);
clinit.visitInsn(DUP);
clinit.visitMethodInsn(INVOKESPECIAL, BitHeaderPoolPerformancePatchTest.DEQUE, "<init>", "()V", false);
clinit.visitFieldInsn(PUTSTATIC, BitHeaderPoolPerformancePatchTest.HEADER, field, "L" + BitHeaderPoolPerformancePatchTest.DEQUE + ";");
}
clinit.visitInsn(RETURN);
clinit.visitMaxs(0, 0);
return node;
}
private static ClassNode bitHeader()
{
return BitHeaderPoolPerformancePatchTest.bitHeader(List.of("pool_byte", "pool_short", "pool_int", "pool_long"));
}
@Test
void anchorMatchesTheTarget()
{
new BitHeaderPoolPerformancePatch().anchor().verify(BitHeaderPoolPerformancePatchTest.bitHeader());
}
@Test
void createsThePoolsAsPerThreadDeques()
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader();
new BitHeaderPoolPerformancePatch().apply(node);
int creations = 0;
for (AbstractInsnNode instruction : node.methods.getFirst().instructions)
{
if (instruction instanceof TypeInsnNode creation && creation.getOpcode() == NEW)
{
assertEquals(BitHeaderPoolPerformancePatchTest.POOL, creation.desc);
creations++;
}
if (instruction instanceof MethodInsnNode call) assertEquals(BitHeaderPoolPerformancePatchTest.POOL, call.owner);
}
assertEquals(4, creations);
}
@Test
void patchedPoolsAreConcurrentLinkedDeques() throws ReflectiveOperationException
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader();
new BitHeaderPoolPerformancePatch().apply(node);
// Initializing runs <clinit>, which creates the runtime module's PerThreadDeques.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class<?> loaded = Class.forName(node.name.replace('/', '.'), true, definer);
Field pool = loaded.getDeclaredField("pool_int");
pool.setAccessible(true);
Object value = pool.get(null);
assertTrue(value instanceof ConcurrentLinkedDeque<?>);
assertEquals(BitHeaderPoolPerformancePatchTest.POOL.replace('/', '.'), value.getClass().getName());
}
@Test
void failsWhenADequeIsForAnotherField()
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader(List.of("pool_byte", "pool_short", "pool_int", "pool_long", "other"));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BitHeaderPoolPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("other than a header pool"), e.getMessage());
}
@Test
void failsWhenAPoolIsMissing()
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader(List.of("pool_byte", "pool_short", "pool_int"));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BitHeaderPoolPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("expected [pool_byte, pool_int, pool_long, pool_short]"), e.getMessage());
}
@Test
void appliesOnlyToVerifiedVersions()
{
BitHeaderPoolPerformancePatch patch = new BitHeaderPoolPerformancePatch();
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")));
}
}
@@ -0,0 +1,120 @@
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.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
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.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.GOTO;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class GameServerAssetLoadingPerformancePatchTest
{
private static final String GAME_SERVER = "zombie/network/GameServer";
private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
/**
* {@code GameServer} with the loop of {@code doMinimumInit} and the per-frame call of
* {@code main}: {@code while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();}
* and {@code GameWindow.fileSystem.updateAsyncTransactions();}.
*/
private static ClassNode gameServer()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, GameServerAssetLoadingPerformancePatchTest.GAME_SERVER, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "doMinimumInit", "()V", null, null);
Label check = new Label();
Label end = new Label();
init.visitLabel(check);
init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "hasWork", "()Z", false);
init.visitJumpInsn(IFEQ, end);
init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
init.visitJumpInsn(GOTO, check);
init.visitLabel(end);
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, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
main.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
main.visitInsn(RETURN);
main.visitMaxs(0, 0);
return node;
}
private static List<String> calls(ClassNode node, String name)
{
MethodNode method = node.methods.stream().filter(candidate -> candidate.name.equals(name)).findFirst().orElseThrow();
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name + call.desc);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new GameServerAssetLoadingPerformancePatch().anchor().verify(GameServerAssetLoadingPerformancePatchTest.gameServer());
}
@Test
void replacesTheUpdateInTheStartupLoopOnly()
{
ClassNode node = GameServerAssetLoadingPerformancePatchTest.gameServer();
new GameServerAssetLoadingPerformancePatch().apply(node);
assertEquals(
List.of("FileSystem.hasWork()Z", "AssetLoadingHooks.updateAsyncTransactions(Lzombie/fileSystem/FileSystem;)V"),
GameServerAssetLoadingPerformancePatchTest.calls(node, "doMinimumInit")
);
assertEquals(List.of("FileSystem.updateAsyncTransactions()V"), GameServerAssetLoadingPerformancePatchTest.calls(node, "main"));
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = GameServerAssetLoadingPerformancePatchTest.gameServer();
new GameServerAssetLoadingPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the changed loop.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void appliesOnlyToVerifiedVersions()
{
GameServerAssetLoadingPerformancePatch patch = new GameServerAssetLoadingPerformancePatch();
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")));
}
}
@@ -0,0 +1,193 @@
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.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import java.nio.file.Files;
import java.nio.file.Path;
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_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.ASTORE;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.IFNE;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoChunkSaveDirectoryPerformancePatchTest
{
private static final String CHUNK = "zombie/iso/IsoChunk";
private static final String FILENAMES = "zombie/ChunkMapFilenames";
/**
* {@code IsoChunk} with a reduced {@code Save(boolean)}:
*
* <pre>{@code
* public static String world;
*
* public void Save(boolean bPreventChunkReuse)
* {
* File testDir = new ChunkMapFilenames().getDir(world);
* if (!testDir.exists()) testDir.mkdir();
* }
* }</pre>
*/
private static ClassNode chunk()
{
return IsoChunkSaveDirectoryPerformancePatchTest.chunk(2);
}
/** {@link #chunk()} whose {@code mkdir} call uses the local {@code mkdirLocal} (the folder is in 2). */
private static ClassNode chunk(int mkdirLocal)
{
ClassNode node = IsoChunkSaveDirectoryPerformancePatchTest.emptyClass(IsoChunkSaveDirectoryPerformancePatchTest.CHUNK);
node.visitField(ACC_PUBLIC | ACC_STATIC, "world", "Ljava/lang/String;", null, null);
MethodVisitor save = node.visitMethod(ACC_PUBLIC, "Save", "(Z)V", null, null);
Label exists = new Label();
save.visitTypeInsn(NEW, IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES);
save.visitInsn(DUP);
save.visitMethodInsn(INVOKESPECIAL, IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES, "<init>", "()V", false);
save.visitFieldInsn(GETSTATIC, IsoChunkSaveDirectoryPerformancePatchTest.CHUNK, "world", "Ljava/lang/String;");
save.visitMethodInsn(INVOKEVIRTUAL, IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES, "getDir", "(Ljava/lang/String;)Ljava/io/File;", false);
save.visitVarInsn(ASTORE, 2);
save.visitVarInsn(ALOAD, 2);
save.visitMethodInsn(INVOKEVIRTUAL, "java/io/File", "exists", "()Z", false);
save.visitJumpInsn(IFNE, exists);
save.visitVarInsn(ALOAD, mkdirLocal);
save.visitMethodInsn(INVOKEVIRTUAL, "java/io/File", "mkdir", "()Z", false);
save.visitInsn(POP);
save.visitLabel(exists);
save.visitInsn(RETURN);
save.visitMaxs(0, 0);
return node;
}
/** {@code ChunkMapFilenames} whose {@code getDir(path)} is {@code new File(path)}. */
private static ClassNode filenames()
{
ClassNode node = IsoChunkSaveDirectoryPerformancePatchTest.emptyClass(IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES);
MethodVisitor getDir = node.visitMethod(ACC_PUBLIC, "getDir", "(Ljava/lang/String;)Ljava/io/File;", null, null);
getDir.visitTypeInsn(NEW, "java/io/File");
getDir.visitInsn(DUP);
getDir.visitVarInsn(ALOAD, 1);
getDir.visitMethodInsn(INVOKESPECIAL, "java/io/File", "<init>", "(Ljava/lang/String;)V", false);
getDir.visitInsn(ARETURN);
getDir.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;
}
/** Runs {@code Save(false)} of {@code chunk} with {@code folder} as the checked folder. */
private static void save(ClassNode chunk, Path folder) throws ReflectiveOperationException
{
ClassDefiner definer = new ClassDefiner();
definer.define(IsoChunkSaveDirectoryPerformancePatchTest.filenames());
Class<?> loaded = definer.define(chunk);
loaded.getField("world").set(null, folder.toString());
loaded.getMethod("Save", boolean.class).invoke(loaded.getConstructor().newInstance(), false);
}
@Test
void anchorMatchesTheTarget()
{
new IsoChunkSaveDirectoryPerformancePatch().anchor().verify(IsoChunkSaveDirectoryPerformancePatchTest.chunk());
}
@Test
void vanillaCreatesTheFolder(@TempDir Path temp) throws ReflectiveOperationException
{
Path folder = temp.resolve("map");
IsoChunkSaveDirectoryPerformancePatchTest.save(IsoChunkSaveDirectoryPerformancePatchTest.chunk(), folder);
assertTrue(Files.isDirectory(folder));
}
@Test
void patchedSaveKeepsGetDirAndDropsTheCheck(@TempDir Path temp) throws ReflectiveOperationException
{
ClassNode chunk = IsoChunkSaveDirectoryPerformancePatchTest.chunk();
new IsoChunkSaveDirectoryPerformancePatch().apply(chunk);
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : chunk.methods.getLast().instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.name);
}
assertEquals(List.of("<init>", "getDir"), calls);
Path folder = temp.resolve("map");
IsoChunkSaveDirectoryPerformancePatchTest.save(chunk, folder);
assertFalse(Files.exists(folder));
}
@Test
void failsWhenTheCheckUsesAnotherFolder()
{
ClassNode chunk = IsoChunkSaveDirectoryPerformancePatchTest.chunk(1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new IsoChunkSaveDirectoryPerformancePatch().apply(chunk));
assertTrue(e.getMessage().contains("does not use the folder"), e.getMessage());
}
@Test
void failsWithoutTheFolderCheck()
{
ClassNode chunk = IsoChunkSaveDirectoryPerformancePatchTest.emptyClass(IsoChunkSaveDirectoryPerformancePatchTest.CHUNK);
MethodVisitor save = chunk.visitMethod(ACC_PUBLIC, "Save", "(Z)V", null, null);
save.visitInsn(RETURN);
save.visitMaxs(0, 0);
assertThrows(IllegalStateException.class, () -> new IsoChunkSaveDirectoryPerformancePatch().apply(chunk));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoChunkSaveDirectoryPerformancePatch patch = new IsoChunkSaveDirectoryPerformancePatch();
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")));
}
}
@@ -0,0 +1,119 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
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.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class RolesSavePerformancePatchTest
{
private static final String ROLES = "zombie/characters/Roles";
private static final String DATABASE = "zombie/network/ServerWorldDatabase";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
/** {@code Roles} with a reduced {@code save()}: {@code ((ServerWorldDatabase) null).saveRole(null);} */
private static ClassNode roles()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, RolesSavePerformancePatchTest.ROLES, null, "java/lang/Object", null);
MethodVisitor save = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "save", "()V", null, null);
save.visitInsn(ACONST_NULL);
save.visitTypeInsn(CHECKCAST, RolesSavePerformancePatchTest.DATABASE);
save.visitInsn(ACONST_NULL);
save.visitTypeInsn(CHECKCAST, "zombie/characters/Role");
save.visitMethodInsn(INVOKEVIRTUAL, RolesSavePerformancePatchTest.DATABASE, "saveRole", "(Lzombie/characters/Role;)V", false);
save.visitInsn(RETURN);
save.visitMaxs(0, 0);
return node;
}
private static List<String> calls(MethodNode method)
{
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new RolesSavePerformancePatch().anchor().verify(RolesSavePerformancePatchTest.roles());
}
@Test
void wrapsSaveBetweenTheTransactionHooks()
{
ClassNode node = RolesSavePerformancePatchTest.roles();
new RolesSavePerformancePatch().apply(node);
MethodNode save = node.methods.stream().filter(method -> method.name.equals("save")).findFirst().orElseThrow();
MethodNode original = node.methods.stream().filter(method -> method.name.equals("zomboidForge$save")).findFirst().orElseThrow();
// The normal path and the exception path each end the transaction.
assertEquals(List.of("RolesHooks.beginSave", "Roles.zomboidForge$save", "RolesHooks.endSave", "RolesHooks.endSave"), RolesSavePerformancePatchTest.calls(save));
assertEquals(1, save.tryCatchBlocks.size());
assertEquals(List.of("ServerWorldDatabase.saveRole"), RolesSavePerformancePatchTest.calls(original));
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = RolesSavePerformancePatchTest.roles();
new RolesSavePerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the wrapper.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void endSaveHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(RolesSavePerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("endSave") && method.desc.equals("()V")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
RolesSavePerformancePatch patch = new RolesSavePerformancePatch();
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")));
}
}
@@ -0,0 +1,181 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
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_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
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.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ServerMapCellBudgetPerformancePatchTest
{
private static final String MAP = "zombie/network/ServerMap";
private static final String CELL = "zombie/network/ServerMap$ServerCell";
private static final String LOS = "zombie/network/ServerLOS";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ServerMapHooks";
/**
* {@code ServerMap} with a reduced {@code preupdate}:
*
* <pre>{@code
* public void preupdate()
* {
* ServerLOS.instance.suspend(); // when suspendFirst
* ((ServerCell) null).Load2();
* ServerLOS.instance.suspend(); // when suspendLast
* }
* }</pre>
*/
private static ClassNode serverMap(boolean suspendFirst, boolean suspendLast)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ServerMapCellBudgetPerformancePatchTest.MAP, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor preupdate = node.visitMethod(ACC_PUBLIC, "preupdate", "()V", null, null);
if (suspendFirst) ServerMapCellBudgetPerformancePatchTest.suspend(preupdate);
preupdate.visitInsn(ACONST_NULL);
preupdate.visitTypeInsn(CHECKCAST, ServerMapCellBudgetPerformancePatchTest.CELL);
preupdate.visitMethodInsn(INVOKEVIRTUAL, ServerMapCellBudgetPerformancePatchTest.CELL, "Load2", "()Z", false);
preupdate.visitInsn(POP);
if (suspendLast) ServerMapCellBudgetPerformancePatchTest.suspend(preupdate);
preupdate.visitInsn(RETURN);
preupdate.visitMaxs(0, 0);
return node;
}
private static void suspend(MethodVisitor method)
{
method.visitFieldInsn(GETSTATIC, ServerMapCellBudgetPerformancePatchTest.LOS, "instance", "L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";");
method.visitMethodInsn(INVOKEVIRTUAL, ServerMapCellBudgetPerformancePatchTest.LOS, "suspend", "()V", false);
}
private static ClassNode serverMap()
{
return ServerMapCellBudgetPerformancePatchTest.serverMap(true, false);
}
private static List<MethodInsnNode> calls(ClassNode node)
{
MethodNode preupdate = node.methods.stream().filter(method -> method.name.equals("preupdate")).findFirst().orElseThrow();
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : preupdate.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new ServerMapCellBudgetPerformancePatch().anchor().verify(ServerMapCellBudgetPerformancePatchTest.serverMap());
}
@Test
void redirectsSuspendAndLoad2ToTheHooks()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap();
new ServerMapCellBudgetPerformancePatch().apply(node);
List<MethodInsnNode> calls = ServerMapCellBudgetPerformancePatchTest.calls(node);
assertEquals(2, calls.size());
for (MethodInsnNode call : calls)
{
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals(ServerMapCellBudgetPerformancePatchTest.HOOKS, call.owner);
assertFalse(call.itf);
}
assertEquals("beginIntegration", calls.get(0).name);
assertEquals("(L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";)V", calls.get(0).desc);
assertEquals("integrate", calls.get(1).name);
assertEquals("(L" + ServerMapCellBudgetPerformancePatchTest.CELL + ";)Z", calls.get(1).desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap();
new ServerMapCellBudgetPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheSuspend()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap(false, false);
assertThrows(IllegalStateException.class, () -> new ServerMapCellBudgetPerformancePatch().apply(node));
}
@Test
void failsWhenTheSuspendComesAfterLoad2()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap(false, true);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerMapCellBudgetPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("comes after"), e.getMessage());
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void beginIntegrationHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(ServerMapCellBudgetPerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("beginIntegration")
&& method.desc.equals("(L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";)V")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ServerMapCellBudgetPerformancePatch patch = new ServerMapCellBudgetPerformancePatch();
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")));
}
}
@@ -0,0 +1,132 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.patches.ThreadSleepPerformancePatch;
import org.jspecify.annotations.NonNull;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
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.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.LCONST_1;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
/** The Build 42 patches that redirect {@code Thread.sleep}: each with its target, number of sleeps and hook. */
class ThreadSleepPatchesTest
{
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/";
/** Each patch with its target method, number of sleeps, hook class and hook. */
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, String hooks, String hook)
{
@Override
public @NonNull String toString() { return this.patch.getClass().getSimpleName(); }
}
private static Stream<Case> cases()
{
return Stream.of(
new Case(new ServerChunkLoaderQuitPerformancePatch(), "zombie/network/ServerChunkLoader", "quit", 2, "WaitHooks", "pollSleep"),
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "WaitHooks", "pollSleep"),
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "WaitHooks", "vehicleRoundSleep"),
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "WaitHooks", "wakeVehiclesAndPoll"),
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "WaitHooks", "wakeVehiclesAndPoll"),
new Case(new ServerMapQuitSleepPerformancePatch(), "zombie/network/ServerMap", "QueuedQuit", 1, "QuitHooks", "quitSleep")
);
}
/** The target class with {@code method()} calling {@code Thread.sleep(1L)} {@code sleeps} times. */
private static ClassNode target(Case test, int sleeps)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, test.target(), null, "java/lang/Object", null);
MethodVisitor method = node.visitMethod(ACC_PUBLIC, test.method(), "()V", null, null);
for (int i = 0; i < sleeps; i++)
{
method.visitInsn(LCONST_1);
method.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "sleep", "(J)V", false);
}
method.visitInsn(RETURN);
method.visitMaxs(0, 0);
return node;
}
private static List<MethodInsnNode> calls(ClassNode node)
{
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : node.methods.getFirst().instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@ParameterizedTest
@MethodSource("cases")
void anchorMatchesTheTarget(Case test)
{
test.patch().anchor().verify(ThreadSleepPatchesTest.target(test, test.sleeps()));
}
@ParameterizedTest
@MethodSource("cases")
void redirectsEverySleepToItsHook(Case test) throws ClassNotFoundException
{
ClassNode node = ThreadSleepPatchesTest.target(test, test.sleeps());
test.patch().apply(node);
List<MethodInsnNode> calls = ThreadSleepPatchesTest.calls(node);
assertEquals(test.sleeps(), calls.size());
for (MethodInsnNode call : calls)
{
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals(ThreadSleepPatchesTest.HOOKS + test.hooks(), call.owner);
assertEquals(test.hook(), call.name);
assertEquals("(J)V", call.desc);
}
assertEquals(test.hook(), test.patch().hook().name());
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@ParameterizedTest
@MethodSource("cases")
void failsForAnotherNumberOfSleeps(Case test)
{
ClassNode node = ThreadSleepPatchesTest.target(test, test.sleeps() + 1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> test.patch().apply(node));
assertTrue(e.getMessage().contains("found " + (test.sleeps() + 1)), e.getMessage());
}
@ParameterizedTest
@MethodSource("cases")
void appliesOnlyToVerifiedVersions(Case test)
{
assertTrue(test.patch().appliesTo(GameVersion.parse("42.21.0")));
assertTrue(test.patch().appliesTo(GameVersion.parse("42.21.3")));
assertFalse(test.patch().appliesTo(GameVersion.parse("42.20.3")));
assertFalse(test.patch().appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,160 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
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_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
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.IRETURN;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class WorldGenChunkRulesPerformancePatchTest
{
private static final String CHUNK = "zombie/iso/worldgen/WorldGenChunk";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks";
private static final String MATCHES = "(Ljava/lang/String;)Z";
/**
* {@code WorldGenChunk} with a reduced {@code isProtected} ({@code return tile.matches(null);})
* and, when {@code withCleanChunk}, a reduced {@code cleanChunk}
* ({@code material.matches(filter);}).
*/
private static ClassNode chunk(boolean withCleanChunk)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, WorldGenChunkRulesPerformancePatchTest.CHUNK, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor isProtected = node.visitMethod(ACC_PUBLIC, "isProtected", "(Ljava/util/List;Ljava/lang/String;)Z", null, null);
isProtected.visitVarInsn(ALOAD, 2);
isProtected.visitInsn(ACONST_NULL);
isProtected.visitTypeInsn(CHECKCAST, "java/lang/String");
isProtected.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", WorldGenChunkRulesPerformancePatchTest.MATCHES, false);
isProtected.visitInsn(IRETURN);
isProtected.visitMaxs(0, 0);
if (withCleanChunk)
{
MethodVisitor cleanChunk = node.visitMethod(ACC_PUBLIC, "cleanChunk", "(Lzombie/iso/IsoChunk;Ljava/lang/String;Ljava/lang/String;)V", null, null);
cleanChunk.visitVarInsn(ALOAD, 2);
cleanChunk.visitVarInsn(ALOAD, 3);
cleanChunk.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", WorldGenChunkRulesPerformancePatchTest.MATCHES, false);
cleanChunk.visitInsn(POP);
cleanChunk.visitInsn(RETURN);
cleanChunk.visitMaxs(0, 0);
}
return node;
}
private static List<MethodInsnNode> calls(ClassNode node, String methodName)
{
MethodNode method = node.methods.stream().filter(m -> m.name.equals(methodName)).findFirst().orElseThrow();
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new WorldGenChunkRulesPerformancePatch().anchor().verify(WorldGenChunkRulesPerformancePatchTest.chunk(true));
}
@Test
void replacesIsProtectedAndTheMatchesCallOfCleanChunk()
{
ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(true);
new WorldGenChunkRulesPerformancePatch().apply(node);
List<MethodInsnNode> isProtected = WorldGenChunkRulesPerformancePatchTest.calls(node, "isProtected");
assertEquals(1, isProtected.size());
assertEquals(INVOKESTATIC, isProtected.getFirst().getOpcode());
assertEquals(WorldGenChunkRulesPerformancePatchTest.HOOKS, isProtected.getFirst().owner);
assertEquals("isProtected", isProtected.getFirst().name);
List<MethodInsnNode> cleanChunk = WorldGenChunkRulesPerformancePatchTest.calls(node, "cleanChunk");
assertEquals(1, cleanChunk.size());
assertEquals(INVOKESTATIC, cleanChunk.getFirst().getOpcode());
assertEquals(WorldGenChunkRulesPerformancePatchTest.HOOKS, cleanChunk.getFirst().owner);
assertEquals("matches", cleanChunk.getFirst().name);
assertEquals("(Ljava/lang/String;Ljava/lang/String;)Z", cleanChunk.getFirst().desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(true);
new WorldGenChunkRulesPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on both changed methods.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutCleanChunk()
{
ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(false);
assertThrows(IllegalStateException.class, () -> new WorldGenChunkRulesPerformancePatch().apply(node));
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void matchesHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(WorldGenChunkRulesPerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("matches")
&& method.desc.equals("(Ljava/lang/String;Ljava/lang/String;)Z")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
WorldGenChunkRulesPerformancePatch patch = new WorldGenChunkRulesPerformancePatch();
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")));
}
}
@@ -0,0 +1,134 @@
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.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
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_PUBLIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
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.IRETURN;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class WorldGenUtilsPlacementPerformancePatchTest
{
private static final String UTILS = "zombie/iso/worldgen/WorldGenUtils";
/**
* {@code WorldGenUtils} with a reduced {@code canPlace}:
* {@code return floorName.matches((String) placement.get(0));}, reading {@code this} first
* when {@code usesThis}.
*/
private static ClassNode utils(boolean usesThis)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, WorldGenUtilsPlacementPerformancePatchTest.UTILS, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor canPlace = node.visitMethod(ACC_PUBLIC, "canPlace", "(Ljava/util/List;Ljava/lang/String;)Z", null, null);
if (usesThis)
{
canPlace.visitVarInsn(ALOAD, 0);
canPlace.visitInsn(POP);
}
canPlace.visitVarInsn(ALOAD, 2);
canPlace.visitVarInsn(ALOAD, 1);
canPlace.visitInsn(ICONST_0);
canPlace.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;", true);
canPlace.visitTypeInsn(CHECKCAST, "java/lang/String");
canPlace.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", "(Ljava/lang/String;)Z", false);
canPlace.visitInsn(IRETURN);
canPlace.visitMaxs(0, 0);
return node;
}
private static List<AbstractInsnNode> instructions(ClassNode node)
{
MethodNode canPlace = node.methods.stream().filter(method -> method.name.equals("canPlace")).findFirst().orElseThrow();
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : canPlace.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
@Test
void anchorMatchesTheTarget()
{
new WorldGenUtilsPlacementPerformancePatch().anchor().verify(WorldGenUtilsPlacementPerformancePatchTest.utils(false));
}
@Test
void replacesTheBodyWithTheHookCall()
{
ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(false);
new WorldGenUtilsPlacementPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = WorldGenUtilsPlacementPerformancePatchTest.instructions(node);
assertEquals(List.of(ALOAD, ALOAD, INVOKESTATIC, IRETURN), instructions.stream().map(AbstractInsnNode::getOpcode).toList());
MethodInsnNode call = (MethodInsnNode) instructions.get(2);
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks", call.owner);
assertEquals("canPlace", call.name);
assertEquals("(Ljava/util/List;Ljava/lang/String;)Z", call.desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(false);
new WorldGenUtilsPlacementPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the new body.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWhenTheBodyUsesThis()
{
ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(true);
assertThrows(IllegalStateException.class, () -> new WorldGenUtilsPlacementPerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
WorldGenUtilsPlacementPerformancePatch patch = new WorldGenUtilsPlacementPerformancePatch();
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")));
}
}
@@ -0,0 +1,157 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
import dev.overlord.zomboidforge.compat.b42.patches.BackupStoragePatch;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
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.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ZipBackupSinglePassPerformancePatchTest
{
private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup";
private static final String DESC = "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V";
private static final String SCATTER = "org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator";
private static final String STREAM = "org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream";
/** {@code ZipBackup} with a reduced {@code makeBackupFile}: {@code ((ParallelScatterZipCreator) null).writeTo(null);} */
private static ClassNode zipBackup()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ZipBackupSinglePassPerformancePatchTest.ZIP_BACKUP, null, "java/lang/Object", null);
MethodVisitor make = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", ZipBackupSinglePassPerformancePatchTest.DESC, null, null);
make.visitInsn(ACONST_NULL);
make.visitTypeInsn(CHECKCAST, ZipBackupSinglePassPerformancePatchTest.SCATTER);
make.visitInsn(ACONST_NULL);
make.visitTypeInsn(CHECKCAST, ZipBackupSinglePassPerformancePatchTest.STREAM);
make.visitMethodInsn(INVOKEVIRTUAL, ZipBackupSinglePassPerformancePatchTest.SCATTER, "writeTo", "(L" + ZipBackupSinglePassPerformancePatchTest.STREAM + ";)V", false);
make.visitInsn(RETURN);
make.visitMaxs(0, 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<String> calls(MethodNode method)
{
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new ZipBackupSinglePassPerformancePatch().anchor().verify(ZipBackupSinglePassPerformancePatchTest.zipBackup());
}
@Test
void replacesTheBodyWithTheHookCall()
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
new ZipBackupSinglePassPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : ZipBackupSinglePassPerformancePatchTest.method(node, "makeBackupFile").instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
assertEquals(List.of(ALOAD, ALOAD, INVOKESTATIC, RETURN), instructions.stream().map(AbstractInsnNode::getOpcode).toList());
MethodInsnNode call = (MethodInsnNode) instructions.get(2);
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks", call.owner);
assertEquals("makeBackupFile", call.name);
assertEquals("(Ljava/lang/String;Ljava/lang/Object;)V", call.desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
new ZipBackupSinglePassPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the new body.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
/** As in {@link B42PatchSet}: this patch first, then the storage wrapper around the hook call. */
@Test
void storagePatchWrapsTheReplacedBody()
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
BackupStoragePatch storage = new BackupStoragePatch();
new ZipBackupSinglePassPerformancePatch().apply(node);
storage.anchor().verify(node);
storage.apply(node);
assertEquals(List.of("StorageHooks.backupRunning", "ZipBackup.zomboidForge$makeBackupFile", "StorageHooks.backupRunning", "StorageHooks.backupRunning"),
ZipBackupSinglePassPerformancePatchTest.calls(ZipBackupSinglePassPerformancePatchTest.method(node, "makeBackupFile")));
assertEquals(List.of("BackupHooks.makeBackupFile"),
ZipBackupSinglePassPerformancePatchTest.calls(ZipBackupSinglePassPerformancePatchTest.method(node, "zomboidForge$makeBackupFile")));
}
@Test
void registeredBeforeTheStoragePatch()
{
List<String> names = new B42PatchSet().patches().stream().map(ClassPatch::getClass).map(Class::getSimpleName).toList();
assertTrue(names.indexOf("ZipBackupSinglePassPerformancePatch") >= 0);
assertTrue(names.indexOf("ZipBackupSinglePassPerformancePatch") < names.indexOf("BackupStoragePatch"));
}
/** After the storage patch, {@code makeBackupFile} is the wrapper, which the hook must not replace. */
@Test
void anchorFailsOnTheStorageWrapper()
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
new BackupStoragePatch().apply(node);
assertThrows(IllegalStateException.class, () -> new ZipBackupSinglePassPerformancePatch().anchor().verify(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ZipBackupSinglePassPerformancePatch patch = new ZipBackupSinglePassPerformancePatch();
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")));
}
}
@@ -0,0 +1,188 @@
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.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
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.DLOAD;
import static org.objectweb.asm.Opcodes.DRETURN;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ZombieVoronoiPerformancePatchTest
{
private static final String VORONOI = "zombie/iso/worldgen/zombie/ZombieVoronoi";
private static final String SELECTION = "zombie/iso/worldgen/zombie/ClosestSelection";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks";
private static final String NOISE = "(DDLjava/util/Random;Ljava/util/List;)D";
/**
* {@code ZombieVoronoi} with its three fields and a reduced {@code evaluateNoise}:
*
* <pre>{@code
* private double evaluateNoise(double x, double y, Random rng, List points)
* {
* long unused = this.seed; // a local beyond the parameters
* return this.closestPoint.getClosest(x, y, points);
* }
* }</pre>
*/
private static ClassNode voronoi(boolean withSeed, int noiseAccess)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ZombieVoronoiPerformancePatchTest.VORONOI, null, "java/lang/Object", null);
if (withSeed) node.visitField(ACC_PRIVATE | ACC_FINAL, "seed", "J", null, null);
node.visitField(ACC_PRIVATE | ACC_FINAL, "numberPoints", "I", null, null);
node.visitField(ACC_PRIVATE | ACC_FINAL, "closestPoint", "L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";", null, 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);
MethodVisitor noise = node.visitMethod(noiseAccess, "evaluateNoise", ZombieVoronoiPerformancePatchTest.NOISE, null, null);
Label start = new Label();
Label end = new Label();
noise.visitLabel(start);
noise.visitVarInsn(ALOAD, 0);
noise.visitFieldInsn(GETFIELD, ZombieVoronoiPerformancePatchTest.VORONOI, "closestPoint", "L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";");
noise.visitVarInsn(DLOAD, 1);
noise.visitVarInsn(DLOAD, 3);
noise.visitVarInsn(ALOAD, 6);
noise.visitMethodInsn(INVOKEINTERFACE, ZombieVoronoiPerformancePatchTest.SELECTION, "getClosest", "(DDLjava/util/List;)D", true);
noise.visitInsn(DRETURN);
noise.visitLabel(end);
noise.visitLocalVariable("unused", "J", null, start, end, 7);
noise.visitMaxs(0, 0);
return node;
}
private static ClassNode voronoi()
{
return ZombieVoronoiPerformancePatchTest.voronoi(true, ACC_PRIVATE);
}
private static MethodNode evaluateNoise(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("evaluateNoise")).findFirst().orElseThrow();
}
/** The real instructions: no labels, line numbers, or frames. */
private static List<AbstractInsnNode> instructions(MethodNode method)
{
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
@Test
void anchorMatchesTheTarget()
{
new ZombieVoronoiPerformancePatch().anchor().verify(ZombieVoronoiPerformancePatchTest.voronoi());
}
@Test
void replacesTheBodyWithTheHookCall()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi();
new ZombieVoronoiPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = ZombieVoronoiPerformancePatchTest.instructions(ZombieVoronoiPerformancePatchTest.evaluateNoise(node));
assertEquals(
List.of(ALOAD, GETFIELD, ALOAD, GETFIELD, ALOAD, GETFIELD, DLOAD, DLOAD, ALOAD, ALOAD, INVOKESTATIC, DRETURN),
instructions.stream().map(AbstractInsnNode::getOpcode).toList()
);
assertEquals(
List.of("closestPoint", "seed", "numberPoints"),
instructions.stream().filter(FieldInsnNode.class::isInstance).map(field -> ((FieldInsnNode) field).name).toList()
);
MethodInsnNode call = (MethodInsnNode) instructions.get(10);
assertEquals(ZombieVoronoiPerformancePatchTest.HOOKS, call.owner);
assertEquals("evaluateNoise", call.name);
assertEquals("(L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";JIDDLjava/util/Random;Ljava/util/List;)D", call.desc);
assertFalse(call.itf);
}
@Test
void dropsTheLocalVariablesOfTheOldBody()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi();
new ZombieVoronoiPerformancePatch().apply(node);
assertNull(ZombieVoronoiPerformancePatchTest.evaluateNoise(node).localVariables);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi();
new ZombieVoronoiPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the new body.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheSeedField()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(false, ACC_PRIVATE);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZombieVoronoiPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("'" + ZombieVoronoiPerformancePatchTest.VORONOI + ".seed J'"), e.getMessage());
}
@Test
void failsWhenTheMethodIsStatic()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(true, ACC_PRIVATE | ACC_STATIC);
assertThrows(IllegalStateException.class, () -> new ZombieVoronoiPerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ZombieVoronoiPerformancePatch patch = new ZombieVoronoiPerformancePatch();
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")));
}
}
@@ -0,0 +1,197 @@
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.MethodVisitor;
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 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_FINAL;
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.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
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.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ZomboidFileSystemInitPerformancePatchTest
{
private static final String FILE_SYSTEM = "zombie/ZomboidFileSystem";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks";
/**
* {@code ZomboidFileSystem} with a reduced {@code init}:
*
* <pre>{@code
* public void init()
* {
* this.searchFolders((File) null); // when search is true
* this.getRelativeFile((String) null); // when relative is true
* this.searchFolders((File) null); // when searchLast is true
* this.loadList.clear();
* }
* }</pre>
*/
private static ClassNode fileSystem(boolean withSets, boolean search, boolean relative, boolean searchLast)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_FINAL, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, null, "java/lang/Object", null);
node.visitField(ACC_PRIVATE | ACC_FINAL, "loadList", "Ljava/util/List;", null, null);
if (withSets) node.visitField(ACC_PRIVATE | ACC_FINAL, "allAbsolutePaths", "Ljava/util/Set;", null, null);
MethodVisitor constructor = node.visitMethod(ACC_PRIVATE, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "init", "()V", null, null);
if (search) ZomboidFileSystemInitPerformancePatchTest.callSearchFolders(init);
if (relative)
{
init.visitVarInsn(ALOAD, 0);
init.visitInsn(ACONST_NULL);
init.visitTypeInsn(CHECKCAST, "java/lang/String");
init.visitMethodInsn(INVOKEVIRTUAL, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, "getRelativeFile", "(Ljava/lang/String;)Ljava/lang/String;", false);
init.visitInsn(POP);
}
if (searchLast) ZomboidFileSystemInitPerformancePatchTest.callSearchFolders(init);
init.visitVarInsn(ALOAD, 0);
init.visitFieldInsn(GETFIELD, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, "loadList", "Ljava/util/List;");
init.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "clear", "()V", true);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
private static void callSearchFolders(MethodVisitor init)
{
init.visitVarInsn(ALOAD, 0);
init.visitInsn(ACONST_NULL);
init.visitTypeInsn(CHECKCAST, "java/io/File");
init.visitMethodInsn(INVOKEVIRTUAL, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, "searchFolders", "(Ljava/io/File;)V", false);
}
private static ClassNode fileSystem()
{
return ZomboidFileSystemInitPerformancePatchTest.fileSystem(true, true, true, false);
}
private static MethodNode init(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("init")).findFirst().orElseThrow();
}
/** The real instructions: no labels, line numbers, or frames. */
private static List<AbstractInsnNode> instructions(MethodNode method)
{
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
@Test
void anchorMatchesTheTarget()
{
new ZomboidFileSystemInitPerformancePatch().anchor().verify(ZomboidFileSystemInitPerformancePatchTest.fileSystem());
}
@Test
void replacesTheCallWithTheHookAndPassesBothFields()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem();
new ZomboidFileSystemInitPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = ZomboidFileSystemInitPerformancePatchTest.instructions(ZomboidFileSystemInitPerformancePatchTest.init(node));
assertEquals(
List.of(ALOAD, ACONST_NULL, CHECKCAST, ALOAD, GETFIELD, ALOAD, GETFIELD, INVOKESTATIC),
instructions.subList(0, 8).stream().map(AbstractInsnNode::getOpcode).toList()
);
assertEquals("loadList", ((FieldInsnNode) instructions.get(4)).name);
assertEquals("allAbsolutePaths", ((FieldInsnNode) instructions.get(6)).name);
MethodInsnNode call = (MethodInsnNode) instructions.get(7);
assertEquals(ZomboidFileSystemInitPerformancePatchTest.HOOKS, call.owner);
assertEquals("searchAndIndex", call.name);
assertEquals("(L" + ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM + ";Ljava/io/File;Ljava/util/List;Ljava/util/Set;)V", call.desc);
assertFalse(call.itf);
// The loop after the call stays as it is.
assertTrue(instructions.stream().anyMatch(instruction -> instruction instanceof MethodInsnNode m && m.name.equals("getRelativeFile")));
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem();
new ZomboidFileSystemInitPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheLoopAfterTheCall()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem(true, true, false, false);
assertThrows(IllegalStateException.class, () -> new ZomboidFileSystemInitPerformancePatch().apply(node));
}
@Test
void failsWhenTheCallComesAfterTheLoop()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem(true, false, true, true);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZomboidFileSystemInitPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("after 'getRelativeFile'"), e.getMessage());
}
@Test
void failsWithoutTheAbsolutePathsField()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem(false, true, true, false);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZomboidFileSystemInitPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("'" + ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM + ".allAbsolutePaths Ljava/util/Set;'"), e.getMessage());
}
@Test
void appliesOnlyToVerifiedVersions()
{
ZomboidFileSystemInitPerformancePatch patch = new ZomboidFileSystemInitPerformancePatch();
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")));
}
}
+2
View File
@@ -10,6 +10,8 @@ dependencies {
implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar))
// ModCommandsTest checks command classes against the game's command framework.
testImplementation(files(projectZomboid.serverJar))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
@@ -1,11 +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();
public static final Forge FORGE = Forge.fromSystemProperties(
ModCommands::check, ClientCommandChannel::prepare
);
private ForgeInstance() {}
}
@@ -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;
}
}
@@ -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() + "')"; }
}
@@ -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;
}
}
@@ -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;
@@ -0,0 +1,91 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.core.config.Feature;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.LockSupport;
import zombie.fileSystem.FileSystem;
import zombie.fileSystem.FileSystemImpl;
/**
* Hooks for the asset loading at startup ({@link Feature#EXPERIMENTAL_PERFORMANCE}): the loop
* in {@code GameServer.doMinimumInit}
*
* <pre>{@code
* while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();
* }</pre>
*
* hands file tasks (model and animation imports, 16 at most in flight) to the loader threads of
* {@code FileSystemImpl} and collects their results on the main thread. It spins: the main
* thread takes a CPU that the loaders could use. Vanilla has 2 loader threads with up to 4
* CPUs, 4 with more.
*/
@SuppressWarnings("unused")
public final class AssetLoadingHooks
{
/** Pause of the main thread after each update; one task takes about 8 ms of loader time. */
private static final long PARK_NANOS = 500_000L;
/** {@code FileSystemImpl.executor}, private; {@code null} when it cannot be reached. */
private static final @Nullable VarHandle EXECUTOR;
static
{
VarHandle executor = null;
try
{
executor = MethodHandles.privateLookupIn(FileSystemImpl.class, MethodHandles.lookup())
.findVarHandle(FileSystemImpl.class, "executor", ExecutorService.class);
}
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'AssetLoadingHooks.updateAsyncTransactions': 'FileSystemImpl.executor' not found: " + e); }
EXECUTOR = executor;
}
/** Whether the loader pool was checked; the main thread is the only caller. */
private static boolean poolChecked;
private AssetLoadingHooks() {}
/**
* Replaces {@code fileSystem.updateAsyncTransactions()} in that loop. With the feature off,
* only that call. On: the first call grows the loader pool to one thread per CPU but one (at
* least 2), and every call parks the main thread for 0.5 ms after the update instead of
* spinning. Fewer threads with a spinning main thread, or more threads alone, load slower.
* The pool keeps its size after startup; the loaders run the same tasks as in vanilla.
*/
public static void updateAsyncTransactions(FileSystem fileSystem)
{
if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE))
{
fileSystem.updateAsyncTransactions();
return;
}
if (!AssetLoadingHooks.poolChecked)
{
AssetLoadingHooks.poolChecked = true;
Object executor = AssetLoadingHooks.EXECUTOR != null && fileSystem instanceof FileSystemImpl ? AssetLoadingHooks.EXECUTOR.get(fileSystem) : null;
int threads = Math.max(2, Runtime.getRuntime().availableProcessors() - 1);
// A fixed pool: maximum first, the core size may not exceed it.
if (executor instanceof ThreadPoolExecutor pool && pool.getMaximumPoolSize() < threads)
{
System.out.println("[ZomboidForge] Loader threads: " + pool.getMaximumPoolSize() + " -> " + threads + ".");
pool.setMaximumPoolSize(threads);
pool.setCorePoolSize(threads);
}
}
fileSystem.updateAsyncTransactions();
LockSupport.parkNanos(AssetLoadingHooks.PARK_NANOS);
}
}
@@ -0,0 +1,114 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.ParallelZip;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import zombie.ZomboidFileSystem;
import zombie.core.backup.ZipBackup;
import zombie.debug.DebugLog;
import zombie.debug.DebugType;
import zombie.debug.LogSeverity;
import zombie.iso.IsoChunk;
import zombie.network.CoopSlave;
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
@SuppressWarnings("unused")
public final class BackupHooks
{
/** {@code ZipBackup.rotateBackupFile(BackupTypes)}, private, taking the enum as {@code Object}. */
private static final MethodHandle ROTATE;
/** {@code ZipBackup.getBackupReadme(String)}, private. */
private static final MethodHandle README;
/** The files of the cache folder that vanilla adds, each when it exists. */
private static final String[] FILES = {
"options.ini", "popman-options.ini", "latestSave.ini", "debug-options.ini", "sounds.ini", "gamepadBinding.config"
};
/** The folders of the cache folder whose top-level files vanilla adds. */
private static final String[] TOP_LEVEL_FOLDERS = { "mods", "Lua", "db", "Server" };
static
{
try
{
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(ZipBackup.class, MethodHandles.lookup());
Class<?> types = Class.forName("zombie.core.backup.ZipBackup$BackupTypes");
ROTATE = lookup.findStatic(ZipBackup.class, "rotateBackupFile", MethodType.methodType(void.class, types))
.asType(MethodType.methodType(void.class, Object.class));
README = lookup.findStatic(ZipBackup.class, "getBackupReadme", MethodType.methodType(String.class, String.class));
}
catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
}
private BackupHooks() {}
/**
* Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)}; {@code type} is
* the {@code BackupTypes} constant, a private enum. Writes the same entries into
* {@code backups/<type>/backup_1.zip} as vanilla, after the same rotation: {@code readme.txt},
* the files of {@link #FILES}, the top-level files of {@link #TOP_LEVEL_FOLDERS} (vanilla's
* {@code zipDir(String, String)} skips every subfolder), and the save folder without the
* folders named {@code blam}, read under {@code IsoChunk.WriteLock}. {@link ParallelZip}
* writes them in one pass instead of vanilla's three. As vanilla, the backup logs its
* failures and does not throw.
*/
public static void makeBackupFile(String serverName, Object type)
{
String backupDir = ZomboidFileSystem.instance.getCacheDir() + File.separator + "backups" + File.separator + ((Enum<?>) type).name();
long startTime = System.currentTimeMillis();
DebugType.General.println("Start making backup");
DebugType.DetailedInfo.println("backup dir: " + backupDir);
CoopSlave.status("UI_ServerStatus_CreateBackup");
try
{
//noinspection ResultOfMethodCallIgnored
new File(backupDir).mkdirs();
BackupHooks.ROTATE.invokeExact(type);
Path zipFile = Paths.get(backupDir + File.separator + "backup_1.zip");
try { Files.deleteIfExists(zipFile); }
catch (IOException e) { DebugType.General.printException(e, LogSeverity.Error); }
String readme = (String) BackupHooks.README.invokeExact(serverName);
String saveDir = "Saves" + File.separator + "Multiplayer" + File.separator + serverName;
int threads = Runtime.getRuntime().availableProcessors();
try (ParallelZip zip = new ParallelZip(zipFile, readme, threads, e -> DebugType.General.printException(e, LogSeverity.Error)))
{
zip.addText("readme.txt", readme);
for (String name : BackupHooks.FILES)
{
Path file = Paths.get(ZomboidFileSystem.instance.getCacheDir() + File.separator + name);
if (Files.exists(file)) zip.addFile(name, file);
}
for (String folder : BackupHooks.TOP_LEVEL_FOLDERS) zip.addFolder(folder, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(folder)), subfolder -> false);
synchronized (IsoChunk.WriteLock)
{
zip.addFolder(saveDir, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(saveDir)), subfolder -> !subfolder.endsWith("blam"));
}
zip.finish();
}
}
// As vanilla's catch of Exception: errors pass; invokeExact declares Throwable.
catch (Error e) { throw e; }
catch (Throwable t) { DebugType.General.printException(t, LogSeverity.Error); }
DebugLog.log("Backup made in " + (System.currentTimeMillis() - startTime) + " ms");
}
}
@@ -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({"unused", "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;
}
}
}
@@ -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({"unused", "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;
}
}
}
@@ -0,0 +1,79 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.core.config.Feature;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Map;
import zombie.core.raknet.UdpEngine;
import zombie.network.GameServer;
/**
* Hooks for the shutdown sleep in {@code ServerMap.QueuedQuit} ({@link Feature#EXPERIMENTAL_PERFORMANCE}).
* After the world save, vanilla broadcasts {@code ServerQuit} and sleeps 5 s, so the clients
* receive it and disconnect, then closes the databases and the network.
*
* <p>The connections are those of {@code UdpEngine.connectionMap}: the network thread
* ({@code UdpEngine}) removes a connection from it as soon as RakNet reports the disconnect
* notification or the lost connection. {@code GameServer.udpEngine.connections} is updated only
* by the main thread, which is in {@code QueuedQuit} at this point.
*/
@SuppressWarnings("unused")
public final class QuitHooks
{
private static final long POLL_MILLIS = 10L;
/** {@code UdpEngine.connectionMap}, private; {@code null} when it cannot be reached. */
private static final @Nullable VarHandle CONNECTIONS;
static
{
VarHandle connections = null;
try
{
connections = MethodHandles.privateLookupIn(UdpEngine.class, MethodHandles.lookup())
.findVarHandle(UdpEngine.class, "connectionMap", Map.class);
}
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'QuitHooks.quitSleep': 'UdpEngine.connectionMap' not found: " + e); }
CONNECTIONS = connections;
}
private QuitHooks() {}
/**
* Replaces {@code Thread.sleep(5000L)} in {@code QueuedQuit}. Sleeps {@code millis} when the
* feature is off, {@code connectionMap} is unreachable, or there is no {@code udpEngine};
* otherwise returns once no client is connected, polling every 10 ms, after at most
* {@code millis}.
*/
@SuppressWarnings("BusyWait")
public static void quitSleep(long millis) throws InterruptedException
{
UdpEngine engine = GameServer.udpEngine;
if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE) || QuitHooks.CONNECTIONS == null || engine == null)
{
Thread.sleep(millis);
return;
}
long deadline = System.nanoTime() + millis * 1_000_000L;
while (true)
{
// The network thread writes the map without synchronisation.
VarHandle.acquireFence();
int connected = ((Map<?, ?>) QuitHooks.CONNECTIONS.get(engine)).size();
long now = System.nanoTime();
if (connected == 0 || now >= deadline) return;
Thread.sleep(Math.min(QuitHooks.POLL_MILLIS, (deadline - now) / 1_000_000L + 1L));
}
}
}
@@ -0,0 +1,82 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.sql.Connection;
import java.sql.SQLException;
import zombie.network.ServerWorldDatabase;
/**
* Hooks called by patched {@code zombie.characters.Roles} code: {@code Roles.save()} in one
* SQLite transaction.
*
* <p>{@code Roles.save()} writes every role and capability with its own statement, each in its
* own transaction on the autocommitting connection of {@code ServerWorldDatabase}: about 250
* transactions and 1,000 {@code fsync}s at every shutdown. In one transaction the same
* statements write the same rows. The hooks never fail the save: when the connection cannot be
* reached or switched, the save runs in autocommit mode as in vanilla.
*/
@SuppressWarnings("unused")
public final class RolesHooks
{
/** {@code ServerWorldDatabase.conn}, package-private; {@code null} when it cannot be reached. */
private static final @Nullable VarHandle CONNECTION;
static
{
VarHandle connection = null;
try
{
connection = MethodHandles.privateLookupIn(ServerWorldDatabase.class, MethodHandles.lookup())
.findVarHandle(ServerWorldDatabase.class, "conn", Connection.class);
}
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'RolesHooks.beginSave': 'ServerWorldDatabase.conn' not found: " + e); }
CONNECTION = connection;
}
/** The connection of the running save while it is in a transaction of these hooks. */
private static @Nullable Connection transaction;
private RolesHooks() {}
/** Called before {@code Roles.save()}: switches the database connection to one transaction. */
public static void beginSave()
{
if (RolesHooks.CONNECTION == null || ServerWorldDatabase.instance == null) return;
Connection connection = (Connection) RolesHooks.CONNECTION.get(ServerWorldDatabase.instance);
if (connection == null) return;
try
{
if (!connection.getAutoCommit()) return;
connection.setAutoCommit(false);
RolesHooks.transaction = connection;
}
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to begin the roles transaction: " + e); }
}
/**
* Called after {@code Roles.save()}, also when it threw: commits what it wrote, as autocommit
* would have, and switches autocommit back on.
*/
public static void endSave()
{
Connection connection = RolesHooks.transaction;
RolesHooks.transaction = null;
if (connection == null) return;
try { connection.commit(); }
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to commit the roles transaction: " + e); }
finally
{
try { connection.setAutoCommit(true); }
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to restore autocommit: " + e); }
}
}
}
@@ -17,7 +17,7 @@ import java.nio.file.Path;
* {@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")
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class ServerHooks
{
private ServerHooks() {}
@@ -75,7 +75,7 @@ public final class ServerHooks
ForgeInstance.FORGE.started();
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
}
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
/**
@@ -86,8 +86,8 @@ public final class ServerHooks
*/
public static void onTick()
{
try { ForgeInstance.FORGE.tick(); }
catch (RuntimeException e) { e.printStackTrace(); }
try { ForgeInstance.FORGE.tick(); }
catch (Throwable t) { t.printStackTrace(); }
}
/**
@@ -105,6 +105,6 @@ public final class ServerHooks
System.out.println("[ZomboidForge] Server stopping.");
ForgeInstance.FORGE.stopping();
}
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
@@ -0,0 +1,49 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.FrameBudget;
import zombie.network.ServerLOS;
import zombie.network.ServerMap;
/** Hooks called by patched {@code zombie.network.ServerMap} code. */
@SuppressWarnings("unused")
public final class ServerMapHooks
{
/**
* Main-thread time per frame for integrating finished cells (frames target 100 ms). One
* integration takes 70 to 300 ms on new terrain, so in practice a frame integrates one cell,
* or a few small ones.
*/
private static final long BUDGET_NANOS = 40_000_000L;
private static final FrameBudget CELL_INTEGRATION = new FrameBudget(ServerMapHooks.BUDGET_NANOS, System::nanoTime);
private ServerMapHooks() {}
/**
* Replaces {@code ServerLOS.instance.suspend()} in {@code ServerMap.preupdate}, which precedes
* the loop that integrates the finished cells of this frame: suspends, then starts the
* frame's integration budget.
*/
public static void beginIntegration(ServerLOS los)
{
los.suspend();
ServerMapHooks.CELL_INTEGRATION.begin();
}
/**
* Replaces {@code cell.Load2()} in that loop. Vanilla integrates every finished cell in the
* frame it finishes; here a cell beyond the frame's budget is skipped: {@code false} keeps it
* in {@code ServerCell.loaded2}, at the front, and the loop of the next frame integrates it.
* The work per cell is unchanged; a cell becomes active up to a few frames later.
*/
public static boolean integrate(ServerMap.ServerCell cell)
{
if (!ServerMapHooks.CELL_INTEGRATION.allowsAnother()) return false;
boolean integrated = cell.Load2();
if (integrated) ServerMapHooks.CELL_INTEGRATION.count();
return integrated;
}
}
@@ -3,7 +3,7 @@ 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")
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class StorageHooks
{
private StorageHooks() {}
@@ -20,6 +20,6 @@ public final class StorageHooks
if (running) ForgeInstance.FORGE.backupStarted();
else ForgeInstance.FORGE.backupFinished();
}
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
@@ -0,0 +1,51 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.WakeableSleep;
/**
* Hooks for the waiting loops of the shutdown and the world save, which poll with
* {@code Thread.sleep(100)} or {@code Thread.sleep(500)}: {@code ServerChunkLoader.quit},
* {@code ZipBackup.waitFinish}, {@code ServerPlayersVehicles.stop},
* {@code ServerPlayerDB.saveFinishWait}, and the round sleep of the
* {@code ServerPlayersVehicles} thread. The loops check the same conditions as in vanilla; the
* hooks only let them notice sooner that the condition holds.
*/
@SuppressWarnings("unused")
public final class WaitHooks
{
/** Longest sleep of a polling loop. */
private static final long POLL_MILLIS = 5L;
/** The round sleep of the {@code ServerPlayersVehicles} thread. */
private static final WakeableSleep VEHICLE_ROUND = new WakeableSleep();
private WaitHooks() {}
/** Replaces {@code Thread.sleep(millis)} in a polling loop: sleeps at most 5 ms. */
public static void pollSleep(long millis) throws InterruptedException
{
Thread.sleep(Math.min(millis, WaitHooks.POLL_MILLIS));
}
/**
* Replaces {@code Thread.sleep(500)} at the end of a round of the {@code ServerPlayersVehicles}
* thread ({@code SPVThread.runInner}): the same sleep, unless {@link #wakeVehiclesAndPoll}
* ends it early.
*/
public static void vehicleRoundSleep(long millis) throws InterruptedException
{
WaitHooks.VEHICLE_ROUND.sleep(millis);
}
/**
* Replaces {@code Thread.sleep(100)} in loops that wait for the {@code ServerPlayersVehicles}
* thread ({@code ServerPlayersVehicles.stop}: until it ended; {@code
* ServerPlayerDB.saveFinishWait}: until it saved the queued players): wakes the thread, so its
* next round starts now, then sleeps at most 5 ms.
*/
public static void wakeVehiclesAndPoll(long millis) throws InterruptedException
{
WaitHooks.VEHICLE_ROUND.wake();
Thread.sleep(Math.min(millis, WaitHooks.POLL_MILLIS));
}
}
@@ -0,0 +1,34 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.TileRules;
import java.util.List;
/**
* Hooks called by patched {@code zombie.iso.worldgen.WorldGenUtils} and
* {@code zombie.iso.worldgen.WorldGenChunk} code. Each returns what the vanilla code returns
* ({@link TileRules}).
*/
@SuppressWarnings("unused")
public final class WorldGenHooks
{
private WorldGenHooks() {}
/** Replaces the body of {@code WorldGenUtils.canPlace(List, String)}, which reads no field. */
public static boolean canPlace(List<?> placement, String floorName)
{
return TileRules.canPlace(placement, floorName);
}
/** Replaces the body of {@code WorldGenChunk.isProtected(List, String)}, which reads no field. */
public static boolean isProtected(List<?> protectedTiles, String tile)
{
return TileRules.isProtected(protectedTiles, tile);
}
/** Replaces {@code floorMaterial.matches(mat)} in {@code WorldGenChunk.cleanChunk}. */
public static boolean matches(String input, String regex)
{
return TileRules.matches(input, regex);
}
}
@@ -11,6 +11,7 @@ import zombie.scripting.objects.VehicleScript;
import zombie.vehicles.BaseVehicle;
/** Hooks called by patched {@code zombie.characters.IsoZombie} code. */
@SuppressWarnings("unused")
public final class ZombieVehicleHooks
{
/**
@@ -33,10 +34,8 @@ public final class ZombieVehicleHooks
* and is skipped here.
*/
public static @Nullable Vector3f getIntersectPoint(
@NotNull BaseVehicle vehicle,
@NotNull Vector3f start,
@NotNull Vector3f end,
@Nullable Vector3f result
BaseVehicle vehicle, Vector3f start,
Vector3f end, @Nullable Vector3f result
) {
VehicleScript script = vehicle.getScript();
Vector3f extents = script.getExtents();
@@ -0,0 +1,28 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.vanilla.VoronoiNoise;
import java.util.List;
import java.util.Random;
import zombie.iso.worldgen.zombie.ClosestSelection;
import zombie.iso.worldgen.zombie.Coord;
/** Hooks called by patched {@code zombie.iso.worldgen.zombie.ZombieVoronoi} code. */
@SuppressWarnings("unused")
public final class ZombieVoronoiHooks
{
private ZombieVoronoiHooks() {}
/**
* Replaces the body of {@code ZombieVoronoi.evaluateNoise(x, y, rng, points)}, which passes
* the voronoi's fields {@code closestPoint}, {@code seed} and {@code numberPoints}. Returns
* what the vanilla body returns ({@link VoronoiNoise}).
*/
public static double evaluateNoise(
ClosestSelection selection, long seed, int numberPoints,
double x, double y, Random rng, List<Coord> points
) {
return VoronoiNoise.evaluate(selection, seed, numberPoints, x, y, rng, points);
}
}
@@ -0,0 +1,60 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.MediaScan;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import zombie.ZomboidFileSystem;
import zombie.network.GameServer;
/** Hooks called by patched {@code zombie.ZomboidFileSystem} code. */
@SuppressWarnings("unused")
public final class ZomboidFileSystemHooks
{
private ZomboidFileSystemHooks() {}
/**
* Replaces the call {@code this.searchFolders(root)} in {@code ZomboidFileSystem.init}, which
* passes its fields {@code loadList} and {@code allAbsolutePaths}. Does what that call and the
* loop after it do, and empties {@code loadList}, so the loop finds nothing and the
* {@code loadList.clear()} after it has no effect.
*
* <p>The loop, per entry of {@code loadList}: the relative path
* ({@code getRelativeFile(entry)}), lowercased, maps to the absolute path, with a trailing
* separator for folders, in {@code activeFileMap}; the absolute path goes into
* {@code allAbsolutePaths}. Here the folder checks of {@code searchFolders}, of the loop, and
* of {@code getRelativeFile} come from one walk ({@link MediaScan}).
*
* <p>{@code searchFolders} also yields to the render loop on clients
* ({@code Core.DoFrameReady()} per entry); without {@code GameServer.server} the vanilla call
* runs unchanged.
*/
public static void searchAndIndex(ZomboidFileSystem fileSystem, File root, List<String> loadList, Set<String> allAbsolutePaths) throws IOException
{
if (!GameServer.server)
{
fileSystem.searchFolders(root);
return;
}
Map<String, Boolean> folders = MediaScan.walk(root, loadList);
for (String entry : loadList)
{
String relative = MediaScan.relativePath(fileSystem.base.lowercaseUri, entry, folders);
String absolute = new File(entry).getAbsoluteFile().getAbsolutePath();
if (MediaScan.isFolder(absolute, folders)) absolute = absolute + File.separator;
fileSystem.activeFileMap.put(relative.toLowerCase(Locale.ENGLISH), absolute);
allAbsolutePaths.add(absolute);
}
loadList.clear();
}
}
@@ -0,0 +1,40 @@
package dev.overlord.zomboidforge.compat.b42.util;
import java.util.function.LongSupplier;
/**
* A time budget for work spread over frames: after {@link #begin()}, work units are allowed
* until the budget is used up, but always the first one, so every frame makes progress.
* Not thread-safe; one instance per thread.
*/
public final class FrameBudget
{
private final long budgetNanos;
private final LongSupplier clock;
private long start;
private int units;
/** @param clock nanoseconds, e.g. {@code System::nanoTime} */
public FrameBudget(long budgetNanos, LongSupplier clock)
{
this.budgetNanos = budgetNanos;
this.clock = clock;
}
/** Starts the budget of a new frame. */
public void begin()
{
this.start = this.clock.getAsLong();
this.units = 0;
}
/** Whether another unit may run: the first of the frame always, later ones while time is left. */
public boolean allowsAnother()
{
return this.units == 0 || this.clock.getAsLong() - this.start < this.budgetNanos;
}
/** Records a unit that ran. */
public void count() { this.units++; }
}
@@ -0,0 +1,121 @@
package dev.overlord.zomboidforge.compat.b42.util;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The file list of {@code ZomboidFileSystem.searchFolders} and the paths of
* {@code ZomboidFileSystem.getRelativeFile(URI, String)}, with fewer file system calls.
*
* <p>Vanilla stats every entry under the media folder ({@code File.isDirectory}) and lists every
* folder; {@code init} then stats every entry again and builds two URIs per entry for its
* relative path. Here one walk stats each entry once and remembers which ones are folders.
*/
public final class MediaScan
{
private MediaScan() {}
/**
* Appends what {@code searchFolders(root)} appends to {@code loadList}: every file, and every
* folder whose path contains {@code media/maps/}, depth first, in directory order, links
* followed. Returns for each appended path whether it is a folder, for the paths whose
* appended form names the same file (vanilla appends {@code path.replace("\\", "/")
* .replace("./", "")}, which may name another file).
*/
public static Map<String, Boolean> walk(File root, List<String> loadList) throws IOException
{
Map<String, Boolean> folders = new HashMap<>();
Files.walkFileTree(root.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>()
{
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attributes)
{
String path = dir.toString();
String entry = MediaScan.entry(path);
if (entry.contains("media/maps/")) loadList.add(entry);
if (entry.equals(path)) folders.put(entry, Boolean.TRUE);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
{
MediaScan.addFile(file.toString(), loadList, folders);
return FileVisitResult.CONTINUE;
}
// Vanilla's isDirectory() is false for an entry it cannot read, so it appends it as a file.
@Override
public FileVisitResult visitFileFailed(Path file, IOException exception)
{
MediaScan.addFile(file.toString(), loadList, folders);
return FileVisitResult.CONTINUE;
}
});
return folders;
}
/**
* {@code getRelativeFile(root, path)}: the path relative to {@code root} (a folder URI from
* {@code File.toURI()}), lowercased, with a trailing slash for folders; {@code path} itself
* when it lies outside {@code root}. {@code File.toURI()} appends the slash when the
* <em>lowercased</em> path is a folder: known paths come from {@code folders}, other
* lowercased paths are checked on disk, as vanilla does.
*/
public static String relativePath(URI root, String path, Map<String, Boolean> folders)
{
String absolutePath = new File(path).getAbsolutePath();
String lowercase = absolutePath.toLowerCase(Locale.ENGLISH);
boolean folder = MediaScan.isFolder(lowercase, folders);
String uriPath = lowercase.replace(File.separatorChar, '/');
if (!uriPath.startsWith("/")) uriPath = "/" + uriPath;
if (folder && !uriPath.endsWith("/")) uriPath = uriPath + "/";
String rootPath = root.getPath();
if (!rootPath.endsWith("/")) rootPath = rootPath + "/";
if (!uriPath.startsWith(rootPath)) return path;
String relative = uriPath.substring(rootPath.length());
if (path.endsWith("/") && !relative.endsWith("/")) relative = relative + "/";
return relative;
}
/** {@code new File(path).isDirectory()}, from {@code folders} when the path is known. */
public static boolean isFolder(String path, Map<String, Boolean> folders)
{
Boolean known = folders.get(path);
return known != null ? known : new File(path).isDirectory();
}
private static void addFile(String path, List<String> loadList, Map<String, Boolean> folders)
{
String entry = MediaScan.entry(path);
loadList.add(entry);
if (entry.equals(path)) folders.put(entry, Boolean.FALSE);
}
/** The form {@code searchFolders} appends. */
private static String entry(String path)
{
return path.replace("\\", "/").replace("./", "");
}
}
@@ -0,0 +1,367 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.jspecify.annotations.Nullable;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.zip.CRC32;
/**
* A zip file of uncompressed (STORED) entries, Zip64 as needed, as {@code ZipBackup} writes,
* written in one pass from files that a thread pool reads in parallel.
*
* <p>{@code ZipBackup.makeBackupFile} hands every file to {@code ParallelScatterZipCreator}, whose
* threads copy the files into one temporary file per thread, which it then copies into the zip:
* every byte is written three times. Here reader threads list the folders and read each file
* with its CRC into memory, and the thread that adds a folder writes the files as entries with
* size and CRC known: each byte is written once, each header once. Files of more than
* {@value #LARGE} bytes are not held in memory: the writing thread copies them and patches size
* and CRC into the entry's header afterwards. Read files waiting to be written hold at most
* {@value #BUDGET} bytes.
*
* <p>Entries appear in the order their files were read, which varies between runs, as with
* {@code ParallelScatterZipCreator}. The file is a valid zip only after {@link #finish()}.
*/
public final class ParallelZip implements Closeable
{
/** Files larger than this are copied by the writing thread instead of read into memory. */
private static final int LARGE = 4 << 20;
/** Bytes of read files that wait for the writing thread, at most. */
private static final int BUDGET = 64 << 20;
/** Write buffer of the zip file. */
private static final int BUFFER = 1 << 20;
private static final AtomicInteger THREADS = new AtomicInteger();
/** A file read with its CRC; {@code permits} of the budget are released once it is written. */
private record Loaded(String name, byte[] data, long crc, int permits) implements Item {}
/** A file the writing thread copies itself; {@code size} as listed. */
private record Large(String name, Path file, long size) implements Item {}
/** An unexpected failure of a reader thread. */
private record Failed(Throwable cause) implements Item {}
/** Every folder of the current {@link #addFolder} is read. */
private record Done() implements Item {}
private sealed interface Item permits Loaded, Large, Failed, Done {}
private final BufferedChannel channel;
private final ZipArchiveOutputStream zip;
private final ExecutorService readers;
private final Consumer<IOException> failures;
private final Semaphore budget = new Semaphore(ParallelZip.BUDGET);
private boolean finished;
/**
* Creates or truncates {@code file}, with {@code threads} reader threads. Files and folders
* that cannot be read are passed to {@code failures}, from any of these threads, and left out.
*/
public ParallelZip(Path file, String comment, int threads, Consumer<IOException> failures) throws IOException
{
this.channel = new BufferedChannel(FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
this.zip = new ZipArchiveOutputStream(this.channel);
this.failures = failures;
this.readers = Executors.newFixedThreadPool(threads, task -> {
Thread thread = new Thread(task, "zf-backup-reader-" + ParallelZip.THREADS.incrementAndGet());
thread.setDaemon(true);
return thread;
});
this.zip.setUseZip64(Zip64Mode.AsNeeded);
this.zip.setMethod(ZipArchiveEntry.STORED);
this.zip.setComment(comment);
}
/** Adds the entry {@code name} with the UTF-8 bytes of {@code text}. */
public void addText(String name, String text) throws IOException
{
byte[] data = text.getBytes(StandardCharsets.UTF_8);
CRC32 crc = new CRC32();
crc.update(data);
this.write(new Loaded(name, data, crc.getValue(), 0));
}
/** Adds the entry {@code name} with the content of {@code file}, on the calling thread. */
public void addFile(String name, Path file) throws IOException
{
try
{
Item item = this.read(name, file, Files.readAttributes(file, BasicFileAttributes.class));
if (item != null) this.write(item);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw new InterruptedIOException("Interrupted while adding '" + file + "'.");
}
catch (IOException e) { this.failures.accept(e); }
}
/**
* Adds every file in {@code folder} as the entry {@code prefix/<path relative to folder>}, and
* the files of each subfolder for which {@code descend} holds, recursively; as
* {@code ZipBackup.zipDir}, links are not followed into folders, and a link to a file is
* added with the file's content. Returns once every entry is written; nothing when
* {@code folder} is no folder.
*/
@SuppressWarnings("DeconstructionCanBeUsed")
public void addFolder(String prefix, Path folder, Predicate<Path> descend) throws IOException
{
if (!Files.isDirectory(folder)) return;
BlockingQueue<Item> ready = new LinkedBlockingQueue<>();
AtomicInteger pending = new AtomicInteger(1);
this.readers.execute(() -> this.readFolder(prefix, folder, folder, descend, ready, pending));
try
{
while (true)
{
Item item = ready.take();
if (item instanceof Done) return;
if (item instanceof Failed failed) throw new IOException("Reading '" + folder + "' failed.", failed.cause());
this.write(item);
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw new InterruptedIOException("Interrupted while adding '" + folder + "'.");
}
}
/** Writes the central directory: the file is a complete zip. */
public void finish() throws IOException
{
this.zip.finish();
this.finished = true;
}
/**
* Stops the reader threads and closes the file; without {@link #finish()} the file has no
* central directory, so no tool takes it for a complete backup.
*/
@Override
public void close() throws IOException
{
this.readers.shutdownNow();
if (this.finished) this.zip.close();
else this.channel.close();
}
/** On a reader thread: lists {@code folder}, queues its files, and starts a task per subfolder to descend into. */
private void readFolder(String prefix, Path root, Path folder, Predicate<Path> descend, BlockingQueue<Item> ready, AtomicInteger pending)
{
try (DirectoryStream<Path> entries = Files.newDirectoryStream(folder))
{
for (Path entry : entries)
{
try
{
BasicFileAttributes attributes = Files.readAttributes(entry, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (attributes.isDirectory())
{
if (!descend.test(entry)) continue;
pending.incrementAndGet();
this.readers.execute(() -> this.readFolder(prefix, root, entry, descend, ready, pending));
continue;
}
String name = prefix + File.separator + root.relativize(entry).toString().replace("/", File.separator);
Item item = this.read(name, entry, attributes);
if (item != null) ready.add(item);
}
catch (IOException e) { this.failures.accept(e); }
}
}
catch (IOException e) { this.failures.accept(e); }
catch (DirectoryIteratorException e) { this.failures.accept(e.getCause()); }
// Interrupted by close(), or an unexpected failure: addFolder throws.
catch (Throwable t) { ready.add(new Failed(t)); }
finally { if (pending.decrementAndGet() == 0) ready.add(new Done()); }
}
/**
* {@code file} as an item to write: read with its CRC, or, when large, to be copied by the
* writing thread. {@code null} for files that cannot be read (sockets and the like).
*/
private @Nullable Item read(String name, Path file, BasicFileAttributes attributes) throws IOException, InterruptedException
{
if (attributes.isOther()) return null;
// A link: the size of the file it points to.
long size = attributes.isSymbolicLink() ? Files.size(file) : attributes.size();
if (size > ParallelZip.LARGE) return new Large(name, file, size);
int permits = (int) size;
this.budget.acquire(permits);
try
{
byte[] data = Files.readAllBytes(file);
CRC32 crc = new CRC32();
crc.update(data);
return new Loaded(name, data, crc.getValue(), permits);
}
catch (IOException | RuntimeException | Error e)
{
this.budget.release(permits);
throw e;
}
}
private void write(Item item) throws IOException
{
switch (item)
{
case Loaded loaded ->
{
ZipArchiveEntry entry = new ZipArchiveEntry(loaded.name());
entry.setMethod(ZipArchiveEntry.STORED);
entry.setSize(loaded.data().length);
entry.setCompressedSize(loaded.data().length);
entry.setCrc(loaded.crc());
// Size and CRC known: written once, no header rewrite.
this.zip.addRawArchiveEntry(entry, new ByteArrayInputStream(loaded.data()));
this.budget.release(loaded.permits());
}
case Large large ->
{
InputStream input;
try { input = Files.newInputStream(large.file()); }
catch (IOException e) { this.failures.accept(e); return; }
// The listed size keeps the header free of Zip64 fields below 4 GiB; the zip
// stream then writes the copied size and CRC into the header.
ZipArchiveEntry entry = new ZipArchiveEntry(large.name());
entry.setMethod(ZipArchiveEntry.STORED);
entry.setSize(large.size());
try (input)
{
this.zip.putArchiveEntry(entry);
input.transferTo(this.zip);
this.zip.closeArchiveEntry();
}
}
case Failed failed -> throw new IOException(failed.cause());
case Done done -> throw new IllegalStateException("'Done' is no entry.");
}
}
/**
* A {@link FileChannel} with a write buffer: the zip stream writes headers and data in small
* pieces. Moving the position writes the buffer first, so patched headers land where the
* zip stream puts them.
*/
private static final class BufferedChannel implements SeekableByteChannel
{
private final FileChannel channel;
private final ByteBuffer buffer = ByteBuffer.allocate(ParallelZip.BUFFER);
BufferedChannel(FileChannel channel) { this.channel = channel; }
@Override
public int write(ByteBuffer source) throws IOException
{
int length = source.remaining();
if (length > this.buffer.remaining()) this.flush();
if (length >= this.buffer.capacity())
{
while (source.hasRemaining()) this.channel.write(source);
}
else this.buffer.put(source);
return length;
}
@Override
public long position() throws IOException { return this.channel.position() + this.buffer.position(); }
@Override
public SeekableByteChannel position(long position) throws IOException
{
this.flush();
this.channel.position(position);
return this;
}
@Override
public long size() throws IOException
{
this.flush();
return this.channel.size();
}
@Override
public SeekableByteChannel truncate(long size) throws IOException
{
this.flush();
this.channel.truncate(size);
return this;
}
@Override
public int read(ByteBuffer target) { throw new NonReadableChannelException(); }
@Override
public boolean isOpen() { return this.channel.isOpen(); }
@Override
public void close() throws IOException
{
try { this.flush(); }
finally { this.channel.close(); }
}
private void flush() throws IOException
{
this.buffer.flip();
while (this.buffer.hasRemaining()) this.channel.write(this.buffer);
this.buffer.clear();
}
}
}
@@ -0,0 +1,49 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.jspecify.annotations.Nullable;
import java.io.Serial;
import java.util.ArrayDeque;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedDeque;
/**
* An object pool that keeps one {@link ArrayDeque} per thread behind the
* {@link ConcurrentLinkedDeque} methods {@link #poll()}, {@link #offer} and {@link #size()}:
* a thread polls what it offered, without synchronisation and without the node that
* {@code ConcurrentLinkedDeque} allocates per offer. Every other method works on the (empty)
* shared deque, so it suits only callers that use these three.
*
* <p>A pool keeps at most {@value #CAPACITY} objects per thread; further offers are dropped
* and the objects left to the garbage collector. Objects taken on one thread and returned on
* another end up in the second thread's pool, up to that limit.
*/
public final class PerThreadDeque<E> extends ConcurrentLinkedDeque<E>
{
@Serial
private static final long serialVersionUID = 1L;
private static final int CAPACITY = 1024;
private final transient ThreadLocal<ArrayDeque<E>> pools = ThreadLocal.withInitial(ArrayDeque::new);
/** The calling thread's most recently offered object, or {@code null} when its pool is empty. */
@Override
public @Nullable E poll() { return this.pools.get().pollLast(); }
/** Adds {@code element} to the calling thread's pool unless it is full. Always {@code true}, as the shared deque. */
@Override
public boolean offer(E element)
{
Objects.requireNonNull(element);
ArrayDeque<E> pool = this.pools.get();
if (pool.size() < PerThreadDeque.CAPACITY) pool.addLast(element);
return true;
}
/** The size of the calling thread's pool. */
@Override
public int size() { return this.pools.get().size(); }
}
@@ -0,0 +1,121 @@
package dev.overlord.zomboidforge.compat.b42.util;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* The tile rules of the world generation ({@code WorldGenUtils.canPlace},
* {@code WorldGenChunk.isProtected} and {@code cleanChunk}) with compiled patterns cached.
*
* <p>Vanilla turns each rule into a regular expression per call ({@code "^" + rule}, then
* {@code .} quoted, {@code *} to {@code .*}, {@code ?} to {@code .?}) and matches it with
* {@code String.matches}, which compiles a new {@link Pattern} each time; this happens for every
* rule of every square of a new chunk. {@code String.matches(regex)} is
* {@code Pattern.compile(regex).matcher(this).matches()}, so a pattern compiled once gives the
* same answers. The rules come from the biome definitions, so the caches stay small. A rule that
* does not compile is not cached and throws on every call, as in vanilla.
*/
public final class TileRules
{
private static final ConcurrentHashMap<String, Pattern> PATTERNS = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Placement> PLACEMENTS = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Pattern> PROTECTED = new ConcurrentHashMap<>();
private TileRules() {}
/** A placement rule: {@code allows} is {@code false} for rules starting with {@code !}. */
private record Placement(boolean allows, Pattern pattern) {}
/** {@code input.matches(regex)}. */
public static boolean matches(String input, String regex)
{
// Vanilla calls matches on the input: a null input fails before the regex is compiled.
Objects.requireNonNull(input);
Pattern pattern = TileRules.PATTERNS.get(regex);
if (pattern == null)
{
pattern = Pattern.compile(regex);
TileRules.PATTERNS.putIfAbsent(regex, pattern);
}
return pattern.matcher(input).matches();
}
/**
* {@code WorldGenUtils.canPlace(placement, floorName)}: the last rule that matches decides,
* {@code false} when none matches.
*/
public static boolean canPlace(List<?> placement, String floorName)
{
boolean toBePlaced = false;
for (Object entry : placement)
{
String rule = (String) entry;
Placement compiled = TileRules.PLACEMENTS.get(rule);
// Vanilla reads the rule first, then calls matches on floorName, then compiles.
Objects.requireNonNull(floorName);
if (compiled == null)
{
compiled = TileRules.placement(rule);
TileRules.PLACEMENTS.putIfAbsent(rule, compiled);
}
if (compiled.pattern().matcher(floorName).matches()) toBePlaced = compiled.allows();
}
return toBePlaced;
}
/**
* {@code WorldGenChunk.isProtected(protectedTiles, tile)}: whether any rule matches. Vanilla
* builds {@code "^" + rule}, so a {@code null} rule is the text {@code null}; it shares the
* cache key of that text.
*/
public static boolean isProtected(List<?> protectedTiles, String tile)
{
for (Object entry : protectedTiles)
{
String rule = String.valueOf((String) entry);
Pattern compiled = TileRules.PROTECTED.get(rule);
Objects.requireNonNull(tile);
if (compiled == null)
{
compiled = Pattern.compile(TileRules.regex(rule));
TileRules.PROTECTED.putIfAbsent(rule, compiled);
}
if (compiled.matcher(tile).matches()) return true;
}
return false;
}
private static Placement placement(String rule)
{
boolean allows = true;
String body = rule;
if (body.startsWith("!"))
{
allows = false;
body = body.substring(1);
}
return new Placement(allows, Pattern.compile(TileRules.regex(body)));
}
/** The regular expression vanilla builds from a rule. */
private static String regex(String rule)
{
String regex = "^" + rule;
regex = regex.replace(".", "\\.");
regex = regex.replace("*", ".*");
regex = regex.replace("?", ".?");
return regex;
}
}
@@ -0,0 +1,42 @@
package dev.overlord.zomboidforge.compat.b42.util;
/**
* A sleep that another thread can end early. {@link #wake()} ends the current
* {@link #sleep(long)}, or the next one if no thread sleeps at the moment, so a wake between two
* sleeps is not lost. Unlike {@code Thread.interrupt()}, waking does not close NIO channels the
* sleeping thread uses.
*/
public final class WakeableSleep
{
private final Object lock = new Object();
private boolean woken;
/** Sleeps {@code millis} milliseconds, or until {@link #wake()}; nothing for {@code millis <= 0}, as {@code Thread.sleep}. */
public void sleep(long millis) throws InterruptedException
{
if (millis <= 0) return;
long deadline = System.nanoTime() + millis * 1_000_000L;
synchronized (this.lock)
{
// wait() may return without a notify; the loop keeps the full time unless woken.
long remaining = millis;
while (!this.woken && remaining > 0)
{
this.lock.wait(remaining);
remaining = (deadline - System.nanoTime()) / 1_000_000L;
}
this.woken = false;
}
}
/** Ends the current or the next {@link #sleep(long)}. */
public void wake()
{
synchronized (this.lock)
{
this.woken = true;
this.lock.notifyAll();
}
}
}
@@ -0,0 +1,121 @@
package dev.overlord.zomboidforge.compat.b42.vanilla;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import zombie.iso.worldgen.zombie.ClosestSelection;
import zombie.iso.worldgen.zombie.ClosestSelectionType;
import zombie.iso.worldgen.zombie.Coord;
import zombie.iso.worldgen.zombie.HashUtil;
/**
* The value of {@code ZombieVoronoi.evaluateNoise} without its {@link Coord} list for the
* {@link ClosestSelectionType}s.
*
* <p>Vanilla clears {@code points}, adds {@code numberPoints} {@link Coord}s for each of the 9
* sectors around {@code (x, y)}, reseeding {@code rng} per sector, and returns
* {@code closestPoint.getClosest(x, y, points)}. The three {@link ClosestSelectionType}s map the
* points to boxed squared distances, sort them, and return the smallest, the second smallest,
* or the second minus the smallest.
*
* <p>Here the same random numbers in the same order feed the same distance expression, and one
* pass keeps the two smallest distances in the order of {@code Double.compare}, which
* {@code sorted()} uses. The results are identical without the {@code Coord}s, the boxing and
* the sort. {@code points} stays untouched: the only caller, {@code evaluateCellNoise}, passes a
* list it does not read. Any other selection gets the filled list as in vanilla.
*/
public final class VoronoiNoise
{
private VoronoiNoise() {}
public static double evaluate(
ClosestSelection selection, long seed, int numberPoints,
double x, double y, Random rng, List<Coord> points
) {
int rank = VoronoiNoise.rank(selection);
if (rank < 0) return VoronoiNoise.evaluateWithPoints(selection, seed, numberPoints, x, y, rng, points);
int sectorX = (int) Math.floor(x);
int sectorY = (int) Math.floor(y);
double smallest = 0.0;
double second = 0.0;
int count = 0;
for (int offsetX = -1; offsetX <= 1; ++offsetX)
{
int pointSectorX = sectorX + offsetX;
for (int offsetY = -1; offsetY <= 1; ++offsetY)
{
int pointSectorY = sectorY + offsetY;
rng.setSeed(HashUtil.hash2D(seed, pointSectorX, pointSectorY));
for (int i = 0; i < numberPoints; ++i)
{
double pointX = rng.nextDouble() + (double) pointSectorX;
double pointY = rng.nextDouble() + (double) pointSectorY;
double distance = (x - pointX) * (x - pointX) + (y - pointY) * (y - pointY);
if (count == 0) smallest = distance;
else if (Double.compare(distance, smallest) < 0)
{
second = smallest;
smallest = distance;
}
else if (count == 1 || Double.compare(distance, second) < 0) second = distance;
count++;
}
}
}
// Vanilla reads index 0, or index 1 first, of the sorted list: same exception when it is too short.
Objects.checkIndex(rank == 0 ? 0 : 1, count);
return switch (rank)
{
case 0 -> smallest;
case 1 -> second;
default -> second - smallest;
};
}
/** 0 for {@code FIRST}, 1 for {@code SECOND}, 2 for {@code SECOND_MINUS_FIRST}, -1 for any other selection. */
private static int rank(ClosestSelection selection)
{
return switch (selection) {
case ClosestSelectionType.FIRST -> 0;
case ClosestSelectionType.SECOND -> 1;
case ClosestSelectionType.SECOND_MINUS_FIRST -> 2;
default -> -1;
};
}
/** The vanilla body. */
private static double evaluateWithPoints(
ClosestSelection selection, long seed, int numberPoints,
double x, double y, Random rng, List<Coord> points
) {
points.clear();
int sectorX = (int) Math.floor(x);
int sectorY = (int) Math.floor(y);
for (int offsetX = -1; offsetX <= 1; ++offsetX)
{
int pointSectorX = sectorX + offsetX;
for (int offsetY = -1; offsetY <= 1; ++offsetY)
{
int pointSectorY = sectorY + offsetY;
rng.setSeed(HashUtil.hash2D(seed, pointSectorX, pointSectorY));
for (int i = 0; i < numberPoints; ++i) {
points.add(new Coord(rng.nextDouble() + (double) pointSectorX, rng.nextDouble() + (double) pointSectorY));
}
}
}
return selection.getClosest(x, y, points);
}
}
@@ -0,0 +1,11 @@
/**
* Equivalent implementations of vanilla game methods that hooks call instead of the original
* code. Unlike {@code util}, these classes use game classes; their tests compare them with the
* vanilla methods of the game jar.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.vanilla;
import org.jetbrains.annotations.NotNullByDefault;
@@ -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());
}
}
@@ -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");
}
}
@@ -0,0 +1,68 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.core.Forge;
import dev.overlord.zomboidforge.core.config.Feature;
import dev.overlord.zomboidforge.core.config.ForgeSettings;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import zombie.fileSystem.FileSystemImpl;
import java.lang.reflect.Field;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** The hook on a real {@code FileSystemImpl}; the feature is switched through the settings of {@code ForgeInstance.FORGE}. */
class AssetLoadingHooksTest
{
private static void settings(ForgeSettings settings) throws ReflectiveOperationException
{
Field field = Forge.class.getDeclaredField("settings");
field.setAccessible(true);
field.set(ForgeInstance.FORGE, settings);
}
private static ThreadPoolExecutor pool(FileSystemImpl fileSystem) throws ReflectiveOperationException
{
Field field = FileSystemImpl.class.getDeclaredField("executor");
field.setAccessible(true);
return (ThreadPoolExecutor) field.get(fileSystem);
}
@AfterEach
void resetSettings() throws ReflectiveOperationException
{
AssetLoadingHooksTest.settings(ForgeSettings.DEFAULTS);
}
/** One test: the first call with the feature on grows the pool once per JVM. */
@Test
void growsTheLoaderPoolOnlyWithTheFeature() throws ReflectiveOperationException
{
FileSystemImpl fileSystem = new FileSystemImpl();
ThreadPoolExecutor pool = AssetLoadingHooksTest.pool(fileSystem);
int vanilla = Runtime.getRuntime().availableProcessors() <= 4 ? 2 : 4;
int expected = Math.max(vanilla, Math.max(2, Runtime.getRuntime().availableProcessors() - 1));
try
{
assertEquals(vanilla, pool.getMaximumPoolSize());
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
assertEquals(vanilla, pool.getCorePoolSize());
assertEquals(vanilla, pool.getMaximumPoolSize());
AssetLoadingHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
assertEquals(expected, pool.getCorePoolSize());
assertEquals(expected, pool.getMaximumPoolSize());
}
finally { pool.shutdownNow(); }
}
}
@@ -0,0 +1,186 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import zombie.ZomboidFileSystem;
import zombie.core.backup.ZipBackup;
import zombie.core.random.RandStandard;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HexFormat;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The hook against vanilla's {@code ZipBackup.makeBackupFile} from the game jar, on the same cache folder. */
class BackupHooksTest
{
private static final String SERVER = "servertest";
private @TempDir Path cache;
/** Unset, {@code getCacheDir()} picks the default folder again. */
private static void unsetCacheDir() throws ReflectiveOperationException
{
Field field = ZomboidFileSystem.class.getDeclaredField("cacheDir");
field.setAccessible(true);
field.set(ZomboidFileSystem.instance, null);
}
private static Object type(String name) throws ClassNotFoundException
{
for (Object constant : Class.forName("zombie.core.backup.ZipBackup$BackupTypes").getEnumConstants()) {
if (((Enum<?>) constant).name().equals(name)) return constant;
}
throw new IllegalArgumentException(name);
}
private static void vanilla(String serverName, Object type) throws ReflectiveOperationException
{
Method make = ZipBackup.class.getDeclaredMethod("makeBackupFile", String.class, type.getClass());
make.setAccessible(true);
make.invoke(null, serverName, type);
}
private void write(String path, byte[] data) throws IOException
{
Path file = this.cache.resolve(path);
Files.createDirectories(file.getParent());
Files.write(file, data);
}
private static byte[] random(int size, long seed)
{
byte[] data = new byte[size];
new Random(seed).nextBytes(data);
return data;
}
/** Entry name to content and method; {@code readme.txt} holds the backup time and is compared apart. */
private static Map<String, String> entries(Path zip) throws IOException
{
Map<String, String> entries = new TreeMap<>();
try (ZipFile file = new ZipFile(zip.toFile()))
{
for (ZipEntry entry : Collections.list(file.entries()))
{
if (entry.getName().equals("readme.txt")) continue;
byte[] data = file.getInputStream(entry).readAllBytes();
entries.put(entry.getName(), entry.getMethod() + " " + HexFormat.of().formatHex(data));
}
}
return entries;
}
/** {@code ZipBackup.rotateBackupFile} reads {@code ServerOptions}, whose constructor draws a random number. */
@BeforeAll
static void initRandom()
{
RandStandard.INSTANCE.init();
}
@BeforeEach
void createCacheFolder() throws IOException
{
ZomboidFileSystem.instance.setCacheDir(this.cache.toString());
this.write("options.ini", "volume=1".getBytes(StandardCharsets.UTF_8));
this.write("sounds.ini", "sounds".getBytes(StandardCharsets.UTF_8));
this.write("mods/default.txt", "mods".getBytes(StandardCharsets.UTF_8));
this.write("mods/SomeMod/mod.info", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
this.write("Lua/settings.lua", "lua".getBytes(StandardCharsets.UTF_8));
this.write("db/" + BackupHooksTest.SERVER + ".db", BackupHooksTest.random(5000, 1));
this.write("Server/" + BackupHooksTest.SERVER + ".ini", "PVP=true".getBytes(StandardCharsets.UTF_8));
this.write("Server/backup/old.ini", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
String save = "Saves/Multiplayer/" + BackupHooksTest.SERVER + "/";
this.write(save + "map_t.bin", BackupHooksTest.random(100, 2));
this.write(save + "players.db", BackupHooksTest.random(5 << 20, 3));
this.write(save + "blam/skipped.bin", BackupHooksTest.random(10, 4));
this.write(save + "map/blam/skipped.bin", BackupHooksTest.random(10, 5));
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) this.write(save + "map/" + x + "/" + y + ".bin", BackupHooksTest.random(x * 300 + y, x * 100L + y));
}
Files.createDirectories(this.cache.resolve(save + "isoregiondata"));
}
@AfterEach
void resetCacheFolder() throws ReflectiveOperationException
{
BackupHooksTest.unsetCacheDir();
}
@Test
void writesTheEntriesOfVanilla() throws Exception
{
BackupHooksTest.vanilla(BackupHooksTest.SERVER, BackupHooksTest.type("version"));
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
Path vanilla = this.cache.resolve("backups/version/backup_1.zip");
Path hooked = this.cache.resolve("backups/period/backup_1.zip");
Map<String, String> expected = BackupHooksTest.entries(vanilla);
assertTrue(expected.containsKey("Saves/Multiplayer/" + BackupHooksTest.SERVER + "/map/9/9.bin"), expected.keySet().toString());
assertFalse(expected.containsKey("mods/SomeMod/mod.info"));
assertEquals(expected, BackupHooksTest.entries(hooked));
try (ZipFile vanillaZip = new ZipFile(vanilla.toFile()); ZipFile hookedZip = new ZipFile(hooked.toFile()))
{
byte[] vanillaReadme = vanillaZip.getInputStream(vanillaZip.getEntry("readme.txt")).readAllBytes();
byte[] hookedReadme = hookedZip.getInputStream(hookedZip.getEntry("readme.txt")).readAllBytes();
// Both start with the backup time, to the second.
String readme = new String(hookedReadme, StandardCharsets.UTF_8);
assertTrue(readme.startsWith("Backup time: "), readme);
assertEquals(readme, hookedZip.getComment());
assertArrayEquals(BackupHooksTest.tail(vanillaReadme), BackupHooksTest.tail(hookedReadme));
}
}
/** The readme after its first line, the backup time. */
private static byte[] tail(byte[] readme)
{
String text = new String(readme, StandardCharsets.UTF_8);
return text.substring(text.indexOf('\n')).getBytes(StandardCharsets.UTF_8);
}
@Test
void rotatesTheBackupsAsVanilla() throws Exception
{
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
assertTrue(Files.exists(this.cache.resolve("backups/period/backup_1.zip")));
assertTrue(Files.exists(this.cache.resolve("backups/period/backup_2.zip")));
}
@Test
void doesNotThrowWhenTheBackupFails() throws Exception
{
// A folder where the zip file goes: opening it fails.
Files.createDirectories(this.cache.resolve("backups/period/backup_1.zip/blocked"));
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
}
}
@@ -0,0 +1,69 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.core.Forge;
import dev.overlord.zomboidforge.core.config.Feature;
import dev.overlord.zomboidforge.core.config.ForgeSettings;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import zombie.core.raknet.UdpEngine;
import zombie.network.GameServer;
import java.lang.reflect.Field;
import java.time.Duration;
import java.util.Map;
import java.util.Set;
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 paths without a network engine; the wait for disconnects is checked on a running server. */
class QuitHooksTest
{
private static final long MILLIS = 50L;
private static void settings(ForgeSettings settings) throws ReflectiveOperationException
{
Field field = Forge.class.getDeclaredField("settings");
field.setAccessible(true);
field.set(ForgeInstance.FORGE, settings);
}
private static long sleptMillis() throws InterruptedException
{
long start = System.nanoTime();
QuitHooks.quitSleep(QuitHooksTest.MILLIS);
return (System.nanoTime() - start) / 1_000_000L;
}
@AfterEach
void resetSettings() throws ReflectiveOperationException
{
QuitHooksTest.settings(ForgeSettings.DEFAULTS);
}
@Test
void sleepsTheFullTimeWithoutTheFeature() throws InterruptedException
{
assertTrue(QuitHooksTest.sleptMillis() >= QuitHooksTest.MILLIS);
}
@Test
void sleepsTheFullTimeWithoutANetworkEngine() throws Exception
{
assertNull(GameServer.udpEngine);
QuitHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
assertTrue(QuitHooksTest.sleptMillis() >= QuitHooksTest.MILLIS);
}
/** The hook reads this field; without it the shutdown keeps the vanilla sleep. */
@Test
void connectionMapExistsInTheGame() throws NoSuchFieldException
{
assertEquals(Map.class, UdpEngine.class.getDeclaredField("connectionMap").getType());
}
}
@@ -0,0 +1,99 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import zombie.network.ServerWorldDatabase;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The hooks on a real SQLite database, installed as the connection of {@code ServerWorldDatabase}. */
class RolesHooksTest
{
private Connection connection;
private void install(Connection connection) throws ReflectiveOperationException
{
Field field = ServerWorldDatabase.class.getDeclaredField("conn");
field.setAccessible(true);
field.set(ServerWorldDatabase.instance, connection);
this.connection = connection;
}
@AfterEach
void uninstall() throws ReflectiveOperationException, SQLException
{
this.install(null);
}
private static int count(Connection connection) throws SQLException
{
try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM roles"))
{
rows.next();
return rows.getInt(1);
}
}
@Test
void writesBetweenTheHooksBecomeVisibleTogetherAtTheEnd(@TempDir Path temp) throws Exception
{
String url = "jdbc:sqlite:" + temp.resolve("test.db");
try (Connection server = DriverManager.getConnection(url); Connection reader = DriverManager.getConnection(url))
{
try (Statement statement = server.createStatement()) { statement.executeUpdate("CREATE TABLE roles (name TEXT)"); }
this.install(server);
RolesHooks.beginSave();
assertFalse(server.getAutoCommit());
try (Statement statement = server.createStatement())
{
statement.executeUpdate("INSERT INTO roles VALUES ('admin')");
statement.executeUpdate("INSERT INTO roles VALUES ('user')");
}
assertEquals(0, RolesHooksTest.count(reader), "Rows are visible before the end of the save.");
RolesHooks.endSave();
assertTrue(server.getAutoCommit());
assertEquals(2, RolesHooksTest.count(reader));
}
}
@Test
void leavesAConnectionAloneThatIsAlreadyInATransaction(@TempDir Path temp) throws Exception
{
try (Connection server = DriverManager.getConnection("jdbc:sqlite:" + temp.resolve("test.db")))
{
server.setAutoCommit(false);
this.install(server);
RolesHooks.beginSave();
RolesHooks.endSave();
assertFalse(server.getAutoCommit());
}
}
@Test
void doesNothingWithoutAConnection() throws ReflectiveOperationException
{
this.install(null);
RolesHooks.beginSave();
RolesHooks.endSave();
}
}
@@ -0,0 +1,179 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import zombie.ZomboidFileSystem;
import zombie.network.GameServer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Compares {@link ZomboidFileSystemHooks#searchAndIndex} with vanilla: {@code searchFolders} of
* the game jar, followed by the loop of {@code ZomboidFileSystem.init} (copied below, it cannot
* run alone), on fresh {@code ZomboidFileSystem} instances.
*/
class ZomboidFileSystemHooksTest
{
private boolean server;
@BeforeEach
void serverMode()
{
this.server = GameServer.server;
GameServer.server = true;
}
@AfterEach
void restoreServerMode() { GameServer.server = this.server; }
/** The maps, lists and sets of one {@code ZomboidFileSystem} after the indexing. */
private record Index(List<String> loadList, Map<String, String> activeFileMap, Set<String> allAbsolutePaths) {}
private static ZomboidFileSystem newFileSystem(Path base) throws ReflectiveOperationException, IOException
{
Constructor<ZomboidFileSystem> constructor = ZomboidFileSystem.class.getDeclaredConstructor();
constructor.setAccessible(true);
ZomboidFileSystem fileSystem = constructor.newInstance();
fileSystem.base.set(base.toFile());
return fileSystem;
}
@SuppressWarnings("unchecked")
private static <T> T field(ZomboidFileSystem fileSystem, String name) throws ReflectiveOperationException
{
Field field = ZomboidFileSystem.class.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(fileSystem);
}
private static Index vanilla(Path base, File media) throws ReflectiveOperationException, IOException
{
ZomboidFileSystem fileSystem = ZomboidFileSystemHooksTest.newFileSystem(base);
List<String> loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList");
Set<String> allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths");
Map<String, String> activeFileMap = fileSystem.activeFileMap;
fileSystem.searchFolders(media);
List<String> searched = new ArrayList<>(loadList);
// The loop of ZomboidFileSystem.init after searchFolders.
for (int n = 0; n < loadList.size(); ++n)
{
String rel = fileSystem.getRelativeFile(loadList.get(n));
File file = new File(loadList.get(n)).getAbsoluteFile();
String abs = file.getAbsolutePath();
if (file.isDirectory()) abs = abs + File.separator;
activeFileMap.put(rel.toLowerCase(Locale.ENGLISH), abs);
allAbsolutePaths.add(abs);
}
loadList.clear();
return new Index(searched, new HashMap<>(activeFileMap), new HashSet<>(allAbsolutePaths));
}
private static Index hook(Path base, File media) throws ReflectiveOperationException, IOException
{
ZomboidFileSystem fileSystem = ZomboidFileSystemHooksTest.newFileSystem(base);
List<String> loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList");
Set<String> allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths");
List<String> searched = new ArrayList<>();
// Records what the walk appends: the hook empties the list before returning.
List<String> recording = new ArrayList<>(loadList)
{
@Override
public boolean add(String entry)
{
searched.add(entry);
return super.add(entry);
}
};
ZomboidFileSystemHooks.searchAndIndex(fileSystem, media, recording, allAbsolutePaths);
assertTrue(recording.isEmpty(), "The hook leaves entries in loadList.");
return new Index(searched, new HashMap<>(fileSystem.activeFileMap), new HashSet<>(allAbsolutePaths));
}
private static void file(Path path) throws IOException
{
Files.createDirectories(path.getParent());
Files.writeString(path, path.getFileName().toString());
}
@Test
void indexesEdgeCasesLikeVanilla(@TempDir Path temp) throws Exception
{
// A lowercase base: "Clash" lowercased then names the existing folder "clash".
Path base = temp.resolve("base");
Path media = base.resolve("media");
ZomboidFileSystemHooksTest.file(media.resolve("maps/Muldraugh, KY/world_1_2.lotpack"));
ZomboidFileSystemHooksTest.file(media.resolve("maps/Test%Map/objects.lua"));
ZomboidFileSystemHooksTest.file(media.resolve("scripts/Items/Weapon.txt"));
ZomboidFileSystemHooksTest.file(media.resolve("textures/Äpfel ö.png"));
ZomboidFileSystemHooksTest.file(media.resolve("clash/inside.txt"));
ZomboidFileSystemHooksTest.file(media.resolve("Clash")); // lowercased, a folder
ZomboidFileSystemHooksTest.file(media.resolve("back\\slash.txt")); // vanilla appends another path
ZomboidFileSystemHooksTest.file(media.resolve("dot./inside.txt")); // vanilla removes "./"
Files.createDirectories(media.resolve("empty"));
Files.createSymbolicLink(media.resolve("LinkedScripts"), media.resolve("scripts"));
Files.createSymbolicLink(media.resolve("broken"), media.resolve("missing"));
Index expected = ZomboidFileSystemHooksTest.vanilla(base, media.toFile());
Index actual = ZomboidFileSystemHooksTest.hook(base, media.toFile());
assertEquals(expected.loadList(), actual.loadList());
assertEquals(expected.activeFileMap(), actual.activeFileMap());
assertEquals(expected.allAbsolutePaths(), actual.allAbsolutePaths());
assertTrue(expected.activeFileMap().containsKey("media/clash/"), "The test tree misses the lowercase folder case.");
}
/**
* The media folder of an installed server, when the game jar is part of one
* ({@code <install>/java/projectzomboid.jar}, as {@code lib/server}); the image build uses a
* copied jar without it.
*/
@Test
void indexesTheGameMediaFolderLikeVanilla() throws Exception
{
Path jar = Path.of(ZomboidFileSystem.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path folder = jar.getParent();
assumeTrue(folder.getFileName() != null && folder.getFileName().toString().equals("java"), "The game jar " + jar + " is not in an installed server.");
Path base = folder.getParent();
Path media = base.resolve("media");
assumeTrue(Files.isDirectory(media.resolve("scripts")), "No media folder at " + media);
Index expected = ZomboidFileSystemHooksTest.vanilla(base, media.toRealPath().toFile());
Index actual = ZomboidFileSystemHooksTest.hook(base, media.toRealPath().toFile());
assertEquals(expected.loadList(), actual.loadList());
assertEquals(expected.activeFileMap(), actual.activeFileMap());
assertEquals(expected.allAbsolutePaths(), actual.allAbsolutePaths());
assertTrue(expected.activeFileMap().size() > 30_000, () -> "Only " + expected.activeFileMap().size() + " entries.");
}
}
@@ -0,0 +1,68 @@
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 FrameBudgetTest
{
/** A clock the test sets; nanoseconds. */
private long now;
private FrameBudget budget(long budgetNanos)
{
return new FrameBudget(budgetNanos, () -> this.now);
}
@Test
void firstUnitOfAFrameRunsEvenWhenTheBudgetIsUsedUp()
{
FrameBudget budget = this.budget(40);
budget.begin();
this.now += 1_000;
assertTrue(budget.allowsAnother());
}
@Test
void laterUnitsRunWhileTimeIsLeft()
{
FrameBudget budget = this.budget(40);
budget.begin();
budget.count();
this.now += 39;
assertTrue(budget.allowsAnother());
this.now += 1;
assertFalse(budget.allowsAnother());
}
@Test
void aNewFrameStartsAFreshBudget()
{
FrameBudget budget = this.budget(40);
budget.begin();
budget.count();
this.now += 100;
assertFalse(budget.allowsAnother());
budget.begin();
assertTrue(budget.allowsAnother());
budget.count();
assertTrue(budget.allowsAnother());
}
@Test
void anUnusedSkipDoesNotCountAsAUnit()
{
// A frame where nothing ran yet still allows its first unit, however late.
FrameBudget budget = this.budget(40);
budget.begin();
this.now += 100;
assertTrue(budget.allowsAnother());
assertTrue(budget.allowsAnother());
}
}
@@ -0,0 +1,219 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ParallelZipTest
{
private static byte[] random(int size, long seed)
{
byte[] data = new byte[size];
new Random(seed).nextBytes(data);
return data;
}
private static void write(Path file, byte[] data) throws IOException
{
Files.createDirectories(file.getParent());
Files.write(file, data);
}
/** Entry name to content, read with {@code ZipInputStream}, which checks each entry's CRC and size. */
private static Map<String, byte[]> entries(Path zip) throws IOException
{
Map<String, byte[]> entries = new TreeMap<>();
try (ZipInputStream input = new ZipInputStream(Files.newInputStream(zip)))
{
for (ZipEntry entry = input.getNextEntry(); entry != null; entry = input.getNextEntry()) {
entries.put(entry.getName(), input.readAllBytes());
}
}
return entries;
}
private static Path zip(Path temp, Path folder, String prefix) throws IOException
{
Path zip = temp.resolve("out.zip");
try (ParallelZip writer = new ParallelZip(zip, "comment", 4, e -> { throw new AssertionError(e); }))
{
writer.addFolder(prefix, folder, subfolder -> !subfolder.endsWith("blam"));
writer.finish();
}
return zip;
}
@Test
void addsEveryFileOfTheTreeExceptSkippedFolders(@TempDir Path temp) throws IOException
{
Path root = temp.resolve("save");
List<String> expected = new ArrayList<>();
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 30; y++)
{
ParallelZipTest.write(root.resolve("map/" + x + "/" + y + ".bin"), ParallelZipTest.random(x * 100 + y, x * 1000L + y));
expected.add("world/map/" + x + "/" + y + ".bin");
}
}
ParallelZipTest.write(root.resolve("map_t.bin"), ParallelZipTest.random(10, 1));
ParallelZipTest.write(root.resolve("blam/skipped.bin"), ParallelZipTest.random(10, 2));
ParallelZipTest.write(root.resolve("map/blam/skipped.bin"), ParallelZipTest.random(10, 3));
ParallelZipTest.write(root.resolve("notblam/kept.bin"), ParallelZipTest.random(10, 4));
Files.createDirectories(root.resolve("empty"));
expected.add("world/map_t.bin");
expected.add("world/notblam/kept.bin");
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
Collections.sort(expected);
assertEquals(expected, new ArrayList<>(entries.keySet()));
for (String name : expected) assertArrayEquals(Files.readAllBytes(root.resolve(name.substring("world/".length()))), entries.get(name), name);
}
@Test
void addsOnlyTopLevelFilesWhenNotDescending(@TempDir Path temp) throws IOException
{
Path root = temp.resolve("mods");
ParallelZipTest.write(root.resolve("a.txt"), "a".getBytes(StandardCharsets.UTF_8));
ParallelZipTest.write(root.resolve("sub/b.txt"), "b".getBytes(StandardCharsets.UTF_8));
Path zip = temp.resolve("out.zip");
try (ParallelZip writer = new ParallelZip(zip, "", 2, e -> { throw new AssertionError(e); }))
{
writer.addFolder("mods", root, subfolder -> false);
writer.finish();
}
assertEquals(List.of("mods/a.txt"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
}
/** Large files are copied by the writing thread; more read data than the budget waits for it. */
@Test
void writesLargeFilesAndMoreThanTheBudget(@TempDir Path temp) throws IOException
{
Path root = temp.resolve("save");
for (int i = 0; i < 80; i++) ParallelZipTest.write(root.resolve("chunks/" + i + ".bin"), ParallelZipTest.random(1 << 20, i));
ParallelZipTest.write(root.resolve("players.db"), ParallelZipTest.random(9 << 20, 100));
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
assertEquals(81, entries.size());
assertArrayEquals(Files.readAllBytes(root.resolve("players.db")), entries.get("world/players.db"));
assertArrayEquals(Files.readAllBytes(root.resolve("chunks/42.bin")), entries.get("world/chunks/42.bin"));
}
/** As {@code ParallelScatterZipCreator}'s entries: STORED, without Zip64 fields; the comment is set. */
@Test
void writesStoredEntriesWithoutZip64Fields(@TempDir Path temp) throws IOException
{
Path root = temp.resolve("save");
ParallelZipTest.write(root.resolve("small.bin"), ParallelZipTest.random(100, 1));
ParallelZipTest.write(root.resolve("large.bin"), ParallelZipTest.random(5 << 20, 2));
Path zip = ParallelZipTest.zip(temp, root, "world");
try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip.toFile())) { assertEquals("comment", file.getComment()); }
try (ZipFile file = ZipFile.builder().setPath(zip).get())
{
for (ZipArchiveEntry entry : Collections.list(file.getEntries()))
{
assertEquals(ZipEntry.STORED, entry.getMethod(), entry.getName());
assertEquals(0, entry.getLocalFileDataExtra().length, entry.getName());
assertEquals(0, entry.getCentralDirectoryExtra().length, entry.getName());
assertTrue(file.canReadEntryData(entry));
try (InputStream input = file.getInputStream(entry)) { assertEquals(entry.getSize(), input.readAllBytes().length); }
}
}
}
@Test
void reportsAndSkipsFilesThatCannotBeRead(@TempDir Path temp) throws IOException
{
Path root = temp.resolve("save");
ParallelZipTest.write(root.resolve("kept.bin"), ParallelZipTest.random(10, 1));
Files.createSymbolicLink(root.resolve("dangling.bin"), root.resolve("missing.bin"));
Path zip = temp.resolve("out.zip");
List<IOException> failures = Collections.synchronizedList(new ArrayList<>());
try (ParallelZip writer = new ParallelZip(zip, "", 2, failures::add))
{
writer.addFolder("world", root, subfolder -> true);
writer.finish();
}
assertEquals(List.of("world/kept.bin"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
assertEquals(1, failures.size());
assertTrue(failures.getFirst().getMessage().contains("dangling.bin"), failures.getFirst().getMessage());
}
@Test
void addsLinkedFilesWithTheirContent(@TempDir Path temp) throws IOException
{
Path root = temp.resolve("save");
ParallelZipTest.write(temp.resolve("target.bin"), ParallelZipTest.random(10, 1));
Files.createDirectories(root);
Files.createSymbolicLink(root.resolve("link.bin"), temp.resolve("target.bin"));
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
assertArrayEquals(Files.readAllBytes(temp.resolve("target.bin")), entries.get("world/link.bin"));
}
@Test
void addsTextAndSingleFiles(@TempDir Path temp) throws IOException
{
Path file = temp.resolve("options.ini");
ParallelZipTest.write(file, "volume=1".getBytes(StandardCharsets.UTF_8));
Path zip = temp.resolve("out.zip");
try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); }))
{
writer.addText("readme.txt", "Backup time: now");
writer.addFile("options.ini", file);
writer.finish();
}
Map<String, byte[]> entries = ParallelZipTest.entries(zip);
assertEquals("Backup time: now", new String(entries.get("readme.txt"), StandardCharsets.UTF_8));
assertEquals("volume=1", new String(entries.get("options.ini"), StandardCharsets.UTF_8));
}
/** Without finish(), as after a failure, the file has no central directory. */
@Test
void unfinishedFileIsNoZip(@TempDir Path temp) throws IOException
{
Path zip = temp.resolve("out.zip");
try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); })) { writer.addText("readme.txt", "text"); }
assertTrue(Files.size(zip) > 0);
assertThrows(IOException.class, () -> ZipFile.builder().setPath(zip).get().close());
}
}
@@ -0,0 +1,70 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
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;
class PerThreadDequeTest
{
@Test
void pollReturnsWhatThisThreadOfferedNewestFirst()
{
PerThreadDeque<String> pool = new PerThreadDeque<>();
String first = "first";
String second = "second";
assertTrue(pool.offer(first));
assertTrue(pool.offer(second));
assertSame(second, pool.poll());
assertSame(first, pool.poll());
assertNull(pool.poll());
}
@Test
void threadsDoNotSeeEachOthersObjects() throws InterruptedException
{
PerThreadDeque<String> pool = new PerThreadDeque<>();
pool.offer("main");
AtomicReference<String> polled = new AtomicReference<>("not polled");
AtomicReference<Integer> size = new AtomicReference<>(-1);
Thread other = new Thread(() -> {
polled.set(pool.poll());
pool.offer("other");
size.set(pool.size());
});
other.start();
other.join();
assertNull(polled.get());
assertEquals(1, size.get());
assertEquals("main", pool.poll());
assertNull(pool.poll());
}
@Test
void keepsAtMostTheCapacityPerThread()
{
PerThreadDeque<Integer> pool = new PerThreadDeque<>();
for (int i = 0; i < 2_000; i++) assertTrue(pool.offer(i));
assertEquals(1_024, pool.size());
assertEquals(1_023, pool.poll());
}
@Test
void rejectsNullLikeConcurrentLinkedDeque()
{
PerThreadDeque<String> pool = new PerThreadDeque<>();
assertThrows(NullPointerException.class, () -> pool.offer(null));
}
}
@@ -0,0 +1,198 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.junit.jupiter.api.Test;
import zombie.iso.worldgen.WorldGenChunk;
import zombie.iso.worldgen.WorldGenUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/** Compares {@link TileRules} with the vanilla methods of the game jar. */
class TileRulesTest
{
/** Rules with every special character of the conversion, negation, and edge cases. */
private static final List<String> RULES = List.of(
"blends_natural_01_*", "!blends_natural_02_*", "vegetation_drying*", "floors_exterior_natural_01_?",
"a.b", "*", "!*", "?", "blends_natural_01_1", "", "!", "null", "x*y?z"
);
private static final List<String> NAMES = List.of(
"blends_natural_01_16", "blends_natural_02_3", "vegetation_drying_01_0", "floors_exterior_natural_01_1",
"floors_exterior_natural_01_12", "a.b", "axb", "", "null", "xyz", "x__y_z", "X", "blends_natural_01_1"
);
private static final Pattern QUOTED_RULE = Pattern.compile("\"(!?[A-Za-z0-9_.*?]+)\"");
/** Outcome of a call: its result or the class of what it threw. */
private static String outcome(Callable<Object> call)
{
try { return String.valueOf(call.call()); }
catch (Throwable t) { return t.getClass().getName(); }
}
private static WorldGenChunk chunkWithoutConstructor() throws ReflectiveOperationException
{
// isProtected reads no field; WorldGenChunk's constructor needs a running world.
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
Field field = unsafeClass.getDeclaredField("theUnsafe");
field.setAccessible(true);
return (WorldGenChunk) unsafeClass.getMethod("allocateInstance", Class.class).invoke(field.get(null), WorldGenChunk.class);
}
/** All lists of up to three rules from {@code rules}, in every order. */
private static List<List<String>> ruleLists(List<String> rules)
{
List<List<String>> lists = new ArrayList<>();
lists.add(List.of());
for (String first : rules)
{
lists.add(List.of(first));
for (String second : rules)
{
lists.add(List.of(first, second));
for (String third : rules) lists.add(List.of(first, second, third));
}
}
return lists;
}
private static void compare(List<List<String>> lists, List<String> names) throws ReflectiveOperationException
{
WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor();
for (List<String> rules : lists)
{
for (String name : names)
{
assertEquals(
TileRulesTest.outcome(() -> WorldGenUtils.INSTANCE.canPlace(rules, name)),
TileRulesTest.outcome(() -> TileRules.canPlace(rules, name)),
() -> "canPlace(" + rules + ", " + name + ")"
);
assertEquals(
TileRulesTest.outcome(() -> chunk.isProtected(rules, name)),
TileRulesTest.outcome(() -> TileRules.isProtected(rules, name)),
() -> "isProtected(" + rules + ", " + name + ")"
);
}
}
}
@Test
void answersLikeVanillaForEdgeCases() throws ReflectiveOperationException
{
TileRulesTest.compare(TileRulesTest.ruleLists(TileRulesTest.RULES), TileRulesTest.NAMES);
}
@Test
void throwsLikeVanillaForBrokenRules() throws ReflectiveOperationException
{
List<List<String>> lists = new ArrayList<>();
lists.add(List.of("a(b")); // not a valid regular expression
lists.add(List.of("vegetation_drying*", "a[b"));
lists.add(Arrays.asList("vegetation_drying*", null)); // canPlace fails, isProtected matches "^null"
lists.add(Arrays.asList((String) null));
List<String> names = new ArrayList<>(TileRulesTest.NAMES);
names.add(null);
TileRulesTest.compare(lists, names);
}
/**
* The quoted rules of the game's world generation Lua files ({@code media/lua/server/WorldGen}
* next to the game jar, when the jar is part of an installed server), against names derived
* from them.
*/
@Test
void answersLikeVanillaForTheGameRules() throws Exception
{
Path jar = Path.of(WorldGenUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path parent = jar.getParent();
assumeTrue(parent.getFileName() != null && parent.getFileName().toString().equals("java"), "The game jar " + jar + " is not in an installed server.");
Path folder = parent.getParent().resolve("media/lua/server/WorldGen");
assumeTrue(Files.isDirectory(folder), "No world generation scripts at " + folder);
TreeSet<String> rules = new TreeSet<>();
try (Stream<Path> files = Files.walk(folder))
{
for (Path file : files.filter(path -> path.toString().endsWith(".lua")).toList())
{
Matcher matcher = TileRulesTest.QUOTED_RULE.matcher(TileRulesTest.read(file));
while (matcher.find()) rules.add(matcher.group(1));
}
}
assertTrue(rules.size() > 100, () -> "Only " + rules.size() + " rules in " + folder);
// Names: each rule with its wildcards filled in, some of them changed.
Random random = new Random(7L);
List<String> names = new ArrayList<>();
for (String rule : rules)
{
String name = rule.replace("!", "").replace("*", String.valueOf(random.nextInt(64))).replace("?", "");
names.add(name);
names.add(name + "x");
}
// Random rule lists of up to four rules, each against a sample of the names.
List<String> pool = new ArrayList<>(rules);
List<List<String>> lists = new ArrayList<>();
for (int i = 0; i < 2_000; i++)
{
List<String> list = new ArrayList<>();
for (int n = random.nextInt(5); n > 0; n--) list.add(pool.get(random.nextInt(pool.size())));
lists.add(list);
}
WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor();
for (List<String> list : lists)
{
for (int i = 0; i < 20; i++)
{
String name = names.get(random.nextInt(names.size()));
assertEquals(WorldGenUtils.INSTANCE.canPlace(list, name), TileRules.canPlace(list, name), () -> "canPlace(" + list + ", " + name + ")");
assertEquals(chunk.isProtected(list, name), TileRules.isProtected(list, name), () -> "isProtected(" + list + ", " + name + ")");
}
}
}
@Test
void matchesLikeString()
{
for (String regex : List.of("^Sand", "^Road_.*", "^Road_.*", "^a\\.b", "^x.?"))
{
for (String input : List.of("Sand", "Sandy", "Road_1", "road_1", "a.b", "axb", "x", "xy", "xyz"))
{
assertEquals(input.matches(regex), TileRules.matches(input, regex), () -> input + " ~ " + regex);
}
}
}
private static String read(Path file)
{
try { return Files.readString(file, StandardCharsets.ISO_8859_1); }
catch (IOException e) { throw new IllegalStateException("Cannot read '" + file + "'.", e); }
}
}
@@ -0,0 +1,74 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import static org.junit.jupiter.api.Assertions.assertTrue;
class WakeableSleepTest
{
private static long millisOf(Runnable sleep)
{
long start = System.nanoTime();
sleep.run();
return (System.nanoTime() - start) / 1_000_000L;
}
private static Runnable sleeping(WakeableSleep sleep, long millis)
{
return () -> {
try { sleep.sleep(millis); }
catch (InterruptedException e) { throw new IllegalStateException(e); }
};
}
@Test
void sleepsTheFullTimeWithoutAWake()
{
long slept = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(new WakeableSleep(), 200));
assertTrue(slept >= 195, () -> "Slept only " + slept + " ms.");
}
@Test
void aWakeEndsTheSleepEarly() throws InterruptedException
{
WakeableSleep sleep = new WakeableSleep();
CountDownLatch started = new CountDownLatch(1);
long[] slept = new long[1];
Thread sleeper = new Thread(() -> {
started.countDown();
slept[0] = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(sleep, 10_000));
});
sleeper.start();
started.await();
Thread.sleep(50);
sleep.wake();
sleeper.join(5_000);
assertTrue(slept[0] < 5_000, () -> "Slept " + slept[0] + " ms despite the wake.");
}
@Test
void aWakeBeforeTheSleepEndsTheNextSleep()
{
WakeableSleep sleep = new WakeableSleep();
sleep.wake();
long first = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(sleep, 5_000));
long second = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(sleep, 100));
assertTrue(first < 1_000, () -> "Slept " + first + " ms despite the earlier wake.");
assertTrue(second >= 95, () -> "The wake ended a second sleep too: " + second + " ms.");
}
@Test
void doesNotSleepForZeroOrLess()
{
assertTrue(WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(new WakeableSleep(), 0)) < 50);
assertTrue(WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(new WakeableSleep(), -1)) < 50);
}
}
@@ -0,0 +1,118 @@
package dev.overlord.zomboidforge.compat.b42.vanilla;
import org.junit.jupiter.api.Test;
import zombie.iso.worldgen.zombie.ClosestSelection;
import zombie.iso.worldgen.zombie.ClosestSelectionType;
import zombie.iso.worldgen.zombie.Coord;
import zombie.iso.worldgen.zombie.ZombieVoronoi;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** Compares {@link VoronoiNoise} with the vanilla {@code ZombieVoronoi.evaluateNoise} of the game jar. */
class VoronoiNoiseTest
{
private static final long[] SEEDS = { 0L, 12345L, -987654321L, Long.MAX_VALUE };
private static double vanilla(ZombieVoronoi voronoi, double x, double y, List<Coord> points) throws ReflectiveOperationException
{
Method method = ZombieVoronoi.class.getDeclaredMethod("evaluateNoise", double.class, double.class, Random.class, List.class);
method.setAccessible(true);
return (double) method.invoke(voronoi, x, y, new Random(), points);
}
/** Random coordinates, and coordinates on and next to sector borders, including negative ones. */
private static List<double[]> coordinates()
{
List<double[]> coordinates = new ArrayList<>();
Random random = new Random(42L);
for (int i = 0; i < 500; i++) coordinates.add(new double[] { random.nextDouble() * 2000.0 - 1000.0, random.nextDouble() * 2000.0 - 1000.0 });
for (double border : new double[] { -2.0, -1.0, 0.0, 1.0, 37.0 })
{
coordinates.add(new double[] { border, border });
coordinates.add(new double[] { Math.nextDown(border), Math.nextUp(border) });
coordinates.add(new double[] { -0.0, border });
}
return coordinates;
}
@Test
void returnsTheVanillaValueForEveryClosestSelectionType() throws ReflectiveOperationException
{
int compared = 0;
for (ClosestSelectionType type : ClosestSelectionType.values())
{
for (int numberPoints = 1; numberPoints <= 3; numberPoints++)
{
for (long seed : VoronoiNoiseTest.SEEDS)
{
ZombieVoronoi voronoi = new ZombieVoronoi(seed, numberPoints, type, 1.0, 0.0);
for (double[] point : VoronoiNoiseTest.coordinates())
{
double expected = VoronoiNoiseTest.vanilla(voronoi, point[0], point[1], new ArrayList<>());
double actual = VoronoiNoise.evaluate(type, seed, numberPoints, point[0], point[1], new Random(), new ArrayList<>());
assertEquals(
Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual),
() -> type + ", " + seed + ", " + point[0] + ", " + point[1]
);
compared++;
}
}
}
}
assertEquals(3 * 3 * VoronoiNoiseTest.SEEDS.length * VoronoiNoiseTest.coordinates().size(), compared);
}
@Test
void otherSelectionsGetTheVanillaPoints() throws ReflectiveOperationException
{
// Sums every coordinate, so any difference in the points shows in the result.
ClosestSelection sum = (x, y, points) -> {
double total = 0.0;
for (Object point : points) total += ((Coord) point).x() * 3.0 + ((Coord) point).y();
return total;
};
ZombieVoronoi voronoi = new ZombieVoronoi(777L, 2, sum, 1.0, 0.0);
List<Coord> vanillaPoints = new ArrayList<>();
List<Coord> noisePoints = new ArrayList<>(List.of(new Coord(9.0, 9.0)));
double expected = VoronoiNoiseTest.vanilla(voronoi, 12.5, -3.25, vanillaPoints);
double actual = VoronoiNoise.evaluate(sum, 777L, 2, 12.5, -3.25, new Random(), noisePoints);
assertEquals(expected, actual);
assertEquals(vanillaPoints, noisePoints);
assertEquals(18, noisePoints.size());
}
@Test
void withoutPointsThrowsLikeVanilla()
{
for (ClosestSelectionType type : ClosestSelectionType.values())
{
ZombieVoronoi voronoi = new ZombieVoronoi(1L, 0, type, 1.0, 0.0);
InvocationTargetException vanilla = assertThrows(InvocationTargetException.class, () -> VoronoiNoiseTest.vanilla(voronoi, 1.0, 1.0, new ArrayList<>()));
assertThrows(IndexOutOfBoundsException.class, () -> VoronoiNoise.evaluate(type, 1L, 0, 1.0, 1.0, new Random(), new ArrayList<>()));
// Only the type: once compiled, the JVM may throw a preallocated exception without a
// message (OmitStackTraceInFastThrow, on by default in tests).
assertInstanceOf(IndexOutOfBoundsException.class, vanilla.getCause());
}
}
}
+18 -14
View File
@@ -6,20 +6,24 @@ services:
image: localhost/zomboidforge:dev
platform: linux/amd64
environment:
SERVER_NAME: ${SERVER_NAME:-zomboidforgetest}
SERVER_PASSWORD: ${SERVER_PASSWORD:-}
PUBLIC: ${PUBLIC:-}
PUBLIC_NAME: ${PUBLIC_NAME:-}
PORT: ${PORT:-16261}
UDP_PORT: ${UDP_PORT:-16262}
ADMIN_USERNAME: ${ADMIN_USERNAME:-}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
SERVER_PRESET: ${SERVER_PRESET:-}
MODS: ${MODS:-}
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
RCON_PASSWORD: ${RCON_PASSWORD:-}
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g}
SERVER_NAME: ${SERVER_NAME:-zomboidforgetest}
SERVER_PASSWORD: ${SERVER_PASSWORD:-}
PUBLIC: ${PUBLIC:-}
PUBLIC_NAME: ${PUBLIC_NAME:-}
PORT: ${PORT:-16261}
UDP_PORT: ${UDP_PORT:-16262}
ADMIN_USERNAME: ${ADMIN_USERNAME:-}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
SERVER_PRESET: ${SERVER_PRESET:-}
MODS: ${MODS:-}
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
RCON_PASSWORD: ${RCON_PASSWORD:-}
UPNP: ${UPNP:-}
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-}
JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-}
JVM_EXPERIMENTAL_PERFORMANCE: ${JVM_EXPERIMENTAL_PERFORMANCE:-}
ZF_EXPERIMENTAL_PERFORMANCE: ${ZF_EXPERIMENTAL_PERFORMANCE:-}
ports:
# Host and container ports must be equal: the server reports its own port
# to Steam and to clients, so a remapped port is unreachable.
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more