41 Commits
Author SHA1 Message Date
Overlord 4ab7473e5c Merge tag 'v0.6.0' into develop
ci / image (42, public) (push) Successful in 5m4s
Tagging version v0.6.0 v0.6.0
2026-10-10 19:22:29 +02:00
Overlord b71d163909 Merge branch 'release/v0.6.0'
ci / image (42, public) (push) Successful in 20s
publish / maven (push) Successful in 3m10s
2026-10-10 19:22:29 +02:00
Overlord 9f5871905a Refactor mod plugin structure. 2026-10-10 19:20:14 +02:00
Overlord 32fab0c1d4 Add mod setup tools and project initialization support. 2026-10-10 19:16:56 +02:00
Overlord a5766f3a1b Merge branch 'feature/annotations' into develop 2026-10-10 13:04:05 +02:00
Overlord 22c74a0030 Bump ZomboidForge plugin version to 0.6.0. 2026-10-10 12:48:50 +02:00
Overlord c79a90b88f Add mod validation for annotations: schemas, migrations, configuration bounds, listener methods, and commands. 2026-10-08 12:44:23 +02:00
Overlord 9af951b4be Add support for @RegisterCommand, @Key, @Min, and @Max annotations for command registration, custom keys, and configuration bounds. 2026-10-07 23:02:14 +02:00
Overlord 9fcde10fed Add support for @Every and @EveryNTicks annotations to schedule periodic and tick-based method execution. 2026-10-07 20:02:29 +02:00
Overlord b10504e9af Add support for @Schema and @Migrate annotations to declare storage record schema versions and migrations. 2026-10-07 14:47:57 +02:00
Overlord 1664bb6f28 Add support for @OnClientCommand annotation to register and filter client command event handlers. 2026-10-07 13:09:27 +02:00
Overlord b4d70c3d3a Add register listener methods annotated with @OnMain and @OnModThread; validate methods before mod loading. 2026-10-07 11:58:02 +02:00
Overlord 7ac442c4f6 Annotate public APIs with JetBrains annotations and enforce immutability constraints on collections. 2026-10-07 11:02:55 +02:00
Overlord 36ac320c9c Add compileOnlyApi dependency for JetBrains annotations 2026-10-07 10:42:57 +02:00
Overlord 7b721490cb Merge tag 'v0.5.1' into develop
ci / image (42, public) (push) Successful in 4m26s
Tagging version v0.5.1 v0.5.1
2026-10-07 08:15:35 +02:00
Overlord 8a8db34b69 Merge branch 'hotfix/v0.5.1'
ci / image (42, public) (push) Successful in 17s
publish / maven (push) Successful in 2m51s
2026-10-07 08:14:14 +02:00
Overlord 28b3510c10 Fix race in ForgeTest.modsUseTheirThreadTheMainThreadAndEvents 2026-10-07 08:13:45 +02:00
Overlord 1576d8a38b Merge tag 'v0.5.0' into develop
ci / image (42, public) (push) Successful in 3m20s
Tagging version v0.5.0 v0.5.0
2026-10-07 07:57:27 +02:00
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 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
155 changed files with 9915 additions and 247 deletions

No files matched your search

+165 -43
View File
@@ -5,54 +5,68 @@ described in the [README](README.md#mods).
## Project setup
A mod is a normal Gradle project with the ZomboidForge plugin. It needs JDK 25 (Project
Zomboid's runtime); the plugin sets the Java toolchain to 25.
A mod project starts as one file. It needs JDK 25 (Project Zomboid's runtime); the plugin sets
the Java toolchain to 25.
`settings.gradle.kts`:
1. Create a directory with this `settings.gradle.kts`, with your mod's id, version, and entry
point:
```kotlin
pluginManagement {
repositories {
maven("https://git.security-command.org/api/packages/overlord/maven")
gradlePluginPortal()
```kotlin
pluginManagement {
repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
}
}
dependencyResolutionManagement {
repositories {
maven("https://git.security-command.org/api/packages/overlord/maven")
mavenCentral()
plugins {
id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the API version
}
}
rootProject.name = "shop"
zomboidForge {
id = "shop"
version = "1.0.0"
entrypoint = "com.example.shop.ShopMod"
}
```
2. Run in that directory (Linux, macOS, Windows; on Windows PowerShell 5.1 write `curl.exe`):
```
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -
```
The command sets the newest ZomboidForge version in `settings.gradle.kts`, writes the Gradle
wrapper (`gradlew`, `gradlew.bat`, `gradle/wrapper/`), creates `.gitignore` and the entry point
class when they are missing, and builds the mod. It needs no installed Gradle.
The same command updates a project to the newest version; a given version goes in
`-R-Dzomboidforge.version`:
```
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -R-Dzomboidforge.version=0.7.0 -
```
`build.gradle.kts`:
It prints links to this document in the new version and to the changes since the old one, and
ends with a build, so code that the new version breaks shows at once. Files other than the
version line in `settings.gradle.kts` and the wrapper stay as they are.
The root project is named after the mod id. The plugin adds the API
(`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the game jar for mods that
declare `game` versions. Default settings go into
`src/main/resources/META-INF/zomboidforge/config.toml`.
Libraries and other mods go into an optional `build.gradle.kts`, which can also set any
`zomboidForge { }` setting:
```kotlin
plugins {
id("dev.overlord.zomboidforge.mod") version "0.3.0" // the plugin's version is the API version
}
version = "1.2.0"
zomboidForge {
id = "shop"
entrypoint = "com.example.shop.ShopMod"
game("42") // only when the mod uses game classes
dependsOn("economy", "2.1") // other mods: id and minimum version
}
dependencies {
implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/
forgeMods("com.example:economy:2.1") // other mods to compile against
}
```
The plugin adds the API (`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the
game jar for mods that declare `game` versions. Default settings go into
`src/main/resources/META-INF/zomboidforge/config.toml`.
zomboidForge {
game("42") // only when the mod uses game classes
dependsOn("economy", "2.1") // other mods: id and minimum version
}
```
### `zomboidForge { }`
@@ -61,7 +75,7 @@ game jar for mods that declare `game` versions. Default settings go into
| `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters |
| `entrypoint` | (required) | the class that extends `Mod` |
| `name` | the id | display name |
| `version` | the project version | the mod's version |
| `version` | (required) | the mod's version, such as `1.2.0` |
| `api` | the plugin's version | ZomboidForge API version the mod is built against |
| `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` |
| `dependsOn(id, version)` | none | another mod this one needs, with its minimum version |
@@ -99,14 +113,15 @@ The game jar has to be one of the declared `game` versions; the check below fail
### Tasks
| Task | Does |
|----------------|---------------------------------------------------------------------------------------------|
|---------------------|---------------------------------------------------------------------------------------------|
| `build` | compiles, runs `checkMod`, and assembles the mod |
| `checkMod` | the server's load checks, at build time (see [Checks at startup](#checks-at-startup)) |
| `checkMod` | the server's load checks, at build time (see [checks at startup](#checks-at-startup)) |
| `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
| `modZip` | the same as `build/distributions/<id>-<version>.zip` |
| `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world |
| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod |
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
| `zomboidForgeSetup` | creates `.gitignore` and the entry point class when they are missing |
`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
@@ -142,7 +157,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
@@ -150,8 +167,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));
}
@@ -162,7 +183,7 @@ 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 |
|--------------------|------------------|---------------------------------------------------------------|
@@ -180,6 +201,25 @@ Methods of `Mod`, usable from the constructor on (also in field initializers):
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
## Settings
`config().bind(Settings.class)` reads `config.toml` into a record. Keys are the component names
in `snake_case` (`maxBalance` reads `max_balance`); defaults come from the jar's
`META-INF/zomboidforge/config.toml`.
```java
record Settings(
@Key("max_hp_regen") int healthRegenPerHour, // keeps its key after a rename
@Min(1) @Max(100) int maxPlayers, // bounds for numbers, also inside List, Map, Optional
String greeting
) {}
```
A missing, mistyped, or out-of-bounds value stops the server, and the log lists every problem
with its key (`'max_players' must be at most 100, found 250.`). `@Key` names are `snake_case`
and differ within a record; `@Min`/`@Max` only fit numeric components and may be fractions
(`@Max(0.5) double ratio`).
## Threads
Game objects belong to the server's main thread. Everything else should stay off it, because
@@ -212,6 +252,47 @@ 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.
The same listeners as annotated methods (`dev.overlord.zomboidforge.api.annotations`):
```java
@OnMain
void onTick(TickEvent event) { ... }
@OnModThread
void onGreeting(SomeEvent event) { ... }
```
- **The entry point's methods** are registered after its constructor and before `onLoad()`, so
they run before the listeners that `onLoad()` registers for the same event. Other objects
opt in with `this.events().register(object)`, which returns one `Subscription` for all of
their methods. Registering an object twice throws; the entry point is registered already.
- **A listener method** returns `void` and has one parameter: the event class, not an
interface or an abstract class. It may be static or private, and may be declared in a
superclass. An override listens only when it carries the annotation itself.
- **Order:** superclass methods first, the methods of one class by name. When two listeners of
one event need a specific order, register them with `onMain` instead.
- A method that breaks these rules stops the server with every problem in the log;
`register` throws an `IllegalArgumentException` instead.
### Scheduled methods
```java
@Every(value = 1, unit = ChronoUnit.MINUTES) // on zf-mod-<id>; optional: initialDelay, fixedDelay = true
void report() { ... }
@EveryNTicks(10) // on the main thread, every 10th frame
void sweep() { ... }
```
- They follow the rules of listener methods, with no parameters. `unit` is `MILLIS`,
`SECONDS` (default), `MINUTES`, `HOURS`, or `DAYS`, and also applies to `initialDelay`.
- `@Every` starts after the mod's `onServerStarted()` (also when it threw), or at once for an
object registered later. Without `fixedDelay`, the period counts from the start of each
run; with it, from the end. A run that throws is logged and ends the schedule.
- `@EveryNTicks(n)` is a `TickEvent` listener for the ticks n, 2n, ...: it may touch game
objects and must return quickly.
- Cancelling the object's `Subscription` ends both; stopping the server ends `@Every`.
## Commands
Admin commands work wherever Project Zomboid's own commands work: in the in-game chat
@@ -242,9 +323,14 @@ public class HelloCommand extends CommandBase
public void onLoad() { this.commands().register(HelloCommand.class); }
```
Or `@RegisterCommand` on the class (`dev.overlord.zomboidforge.api.annotations`), without the
call: ZomboidForge registers the annotated classes of the mod's own jar (not of `lib/`) by name,
before `onLoad()`.
- **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()`.
which stops the server like any other exception in `onLoad()`; an annotated class that breaks
the rules stops it the same way.
- **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
@@ -285,6 +371,16 @@ this.events().onMain(ClientCommandEvent.class, event ->
});
```
The same as an annotated listener method (see [Events](#events)), which filters and cancels:
```java
@OnClientCommand(module = "Shop", command = "buy", cancel = true) // command optional: every command of the module
void buy(ClientCommandEvent event) { ... }
```
`cancel = true` cancels the event before the method runs, so Lua does not receive the command
even when the method throws.
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
receives them in `Events.OnServerCommand`.
@@ -343,7 +439,9 @@ this.storage().transaction(() -> { // all or nothin
| `Instant` | ISO-8601 text |
| `byte[]` | blob |
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`.
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. `@Key("paid_at")`
on a component sets the column name instead, so a renamed component keeps its column and data.
`@Min`/`@Max` are for settings; storage ignores them.
When the record changes between versions of the mod:
@@ -361,6 +459,23 @@ Table<Balance> balances = this.storage().define("balances", Balance.class)
.open();
```
The same on the record (`dev.overlord.zomboidforge.api.annotations`), so `table(...)` is enough:
```java
@Schema(version = 2)
record Balance(long coins, @Nullable Instant lastPaid)
{
@Migrate(from = 1)
static Balance fromV1(Row row) { return new Balance(row.getLong("coins"), null); }
}
Table<Balance> balances = this.storage().table("balances", Balance.class);
```
A `@Migrate` method is static, takes a `Row`, returns the record, and may be private. `define`
starts from the annotations: `version(...)` replaces the `@Schema` version, and `migrate(...)`
adds migrations. Each version has one migration at most; a second one throws.
Things to know:
1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the
@@ -385,6 +500,13 @@ mod and its libraries. The server does not start when a mod
3. uses ZomboidForge classes outside the API, or
4. contains classes in a ZomboidForge package, or a class with the name of a game class.
While it loads a mod, the server also checks the annotations: the entry point's listener and
scheduled methods, `@Schema`/`@Migrate`/`@Key`/`@Min`/`@Max` on records, and the
`@RegisterCommand` classes. `checkMod` runs the same rules on the built jar (records only when
they carry one of these annotations), loading the classes without running any of their code.
Objects passed to `events().register(...)` are only checked on the server, when they are
registered.
Every problem of every mod is listed in the log.
## What a mod can see
@@ -407,4 +529,4 @@ file system it can reach anything the server can, including other mods' data in
Main-thread tasks and event listener calls appear in JFR recordings as the event
`zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the
event class).
event class, followed by `#<method>` for a listener method).
+43 -25
View File
@@ -22,10 +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<major.minor.build>` (never overwritten),
`<forge>-pz<major.minor>` (the newest hotfix of that minor version), and `latest`. A new image
is built for every ZomboidForge release and every Project Zomboid version, hotfixes included:
the server only admits clients with the same version.
> [!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
@@ -39,23 +39,27 @@ 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`) |
| `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_MAX_HEAP` | `-Xms` |
| `JVM_MAX_HEAP` | `8g` | `-Xmx` |
| `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:
@@ -66,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
@@ -95,24 +108,24 @@ forge/
podman run ... -v ./forge:/forge zomboidforge
```
Mods are trusted code. They run inside the server process with its full privileges: they can
read and write any file the server can, open network connections, and stop the server. The
class loader isolation and the startup checks catch mistakes; they do not contain a malicious
mod. Install only mods whose authors you trust.
A mod's settings live in its `config.toml`. When the file is missing, it is created from the
mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a
file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]`
table switches the mod off; mods that depend on it then fail to load.
> [!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:
@@ -122,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
@@ -139,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.
+3
View File
@@ -32,6 +32,9 @@ publishing {
}
dependencies {
// Published as a compile-time dependency, so mods see the API's annotations; never in their lib/.
compileOnlyApi(libs.jetbrains.annotations)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.ApiStatus;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@@ -9,6 +11,7 @@ import java.util.concurrent.Executor;
* task, named {@code zf-async-<id>-<n>}. ZomboidForge shuts it down when the server stops; tasks
* submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}.
*/
@ApiStatus.NonExtendable
public interface AsyncExecutor extends Executor
{
/** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Map;
import java.util.Objects;
@@ -42,7 +44,7 @@ public final class ClientCommandEvent implements MainThreadEvent, Cancellable
public String command() { return this.command; }
public Map<Object, Object> args() { return this.args; }
public @Unmodifiable Map<Object, Object> args() { return this.args; }
@Override
public void cancel() { this.cancelled = true; }
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.ApiStatus;
import java.util.Map;
/**
@@ -17,6 +19,7 @@ import java.util.Map;
* sent on the main thread, at once when called there, otherwise with the mod's queued
* main-thread tasks.
*/
@ApiStatus.NonExtendable
public interface ClientCommands
{
/**
@@ -1,5 +1,9 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
import org.jetbrains.annotations.ApiStatus;
/**
* 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
@@ -21,11 +25,13 @@ package dev.overlord.zomboidforge.api;
* Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose
* result is the reply.
*/
@ApiStatus.NonExtendable
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()}.
* constructor or {@link Mod#onLoad()}. Classes annotated with {@link RegisterCommand} are
* registered without this call.
*
* @throws IllegalArgumentException when {@code command} does not meet the rules above, or is
* registered already
@@ -1,11 +1,20 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.annotations.Every;
import dev.overlord.zomboidforge.api.annotations.EveryNTicks;
import dev.overlord.zomboidforge.api.annotations.OnClientCommand;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
import org.jetbrains.annotations.ApiStatus;
import java.util.function.Consumer;
/**
* Registration of event listeners. Listeners of one event run in registration order. A listener
* that throws is logged with the mod's id; one that throws repeatedly is removed.
*/
@ApiStatus.NonExtendable
public interface Events
{
/**
@@ -21,4 +30,35 @@ public interface Events
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
*/
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
/**
* Registers the methods of {@code listener} annotated with {@link OnMain},
* {@link OnModThread}, or {@link OnClientCommand}, as {@link #onMain} and {@link #onModThread}
* do, and schedules those annotated with {@link Every} or {@link EveryNTicks}. ZomboidForge
* registers the mod's entry point this way after its constructor and before
* {@link Mod#onLoad()}; other objects opt in through this method.
*
* <p>Each annotated method:
* <ul>
* <li>returns {@code void}. A listener has one parameter, a class that implements
* {@link Event} and is neither abstract nor an interface, because listeners are matched
* by the event's exact class; a scheduled method has none;</li>
* <li>carries one of the annotations; {@link OnModThread} not for a
* {@link MainThreadEvent}, {@link OnClientCommand} only for a
* {@link ClientCommandEvent};</li>
* <li>may be static, private, and declared in a superclass of {@code listener}'s class.
* An instance method that a subclass overrides listens only when the override carries
* the annotation itself.</li>
* </ul>
*
* Superclass methods are registered before subclass methods, and the methods of one class
* sorted by name, then by parameter type.
*
* @return one subscription for every listener and scheduled method of {@code listener};
* cancelling it allows registering {@code listener} again
* @throws IllegalArgumentException listing every method that breaks a rule, when a class
* the methods name cannot be loaded, or when
* {@code listener} is registered already
*/
Subscription register(Object listener);
}
@@ -1,5 +1,8 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Range;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@@ -14,6 +17,7 @@ import java.util.concurrent.Executor;
* main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the
* follow-up work back. The main thread must never wait for another thread's result.
*/
@ApiStatus.NonExtendable
public interface MainThread extends Executor
{
/**
@@ -37,7 +41,7 @@ public interface MainThread extends Executor
*
* @throws IllegalArgumentException when {@code ticks} is less than 1
*/
void runLater(int ticks, Runnable task);
void runLater(@Range(from = 1, to = Integer.MAX_VALUE) int ticks, Runnable task);
/** Whether the calling thread is the main thread. */
boolean isMainThread();
@@ -3,6 +3,9 @@ package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.internal.ModBinding;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonBlocking;
import java.nio.file.Path;
/**
@@ -15,12 +18,21 @@ import java.nio.file.Path;
*
* <p>Lifecycle, in this order:
* <ol>
* <li>Listener methods: the methods annotated with
* {@link dev.overlord.zomboidforge.api.annotations.OnMain OnMain},
* {@link dev.overlord.zomboidforge.api.annotations.OnModThread OnModThread},
* {@link dev.overlord.zomboidforge.api.annotations.OnClientCommand OnClientCommand}, or
* {@link dev.overlord.zomboidforge.api.annotations.EveryNTicks EveryNTicks} are registered (see
* {@link Events#register(Object)}).</li>
* <li>{@link #onLoad()}: registration and setup. The server database, Lua, and the world do
* not exist yet.</li>
* <li>{@link #onServerStarted()}: the world is loaded and the network port is open.</li>
* <li>{@link #onServerStarted()}: the world is loaded and the network port is open. Once it
* returned, the methods annotated with
* {@link dev.overlord.zomboidforge.api.annotations.Every Every} start.</li>
* <li>{@link #onStopping()}: the server stops; the world has not been saved yet.</li>
* </ol>
* An exception thrown by the constructor or {@link #onLoad()} stops the server.
* An exception thrown by the constructor or {@link #onLoad()}, or a listener method that breaks
* the rules, stops the server.
*/
public abstract class Mod
{
@@ -42,6 +54,7 @@ public abstract class Mod
public final String version() { return this.context.version(); }
/** Called once on the main thread, after the instance is created. */
@ApiStatus.OverrideOnly
@SuppressWarnings("RedundantThrows")
public void onLoad() throws Exception {}
@@ -49,12 +62,15 @@ public abstract class Mod
* Called once on the main thread, after the world is loaded, the network port is open, and
* RCON is initialized; directly before the main loop starts.
*/
@ApiStatus.OverrideOnly
@NonBlocking
public void onServerStarted() {}
/**
* Called once on the shutdown thread when the server stops, before the world is saved.
* The main thread may still be finishing a tick. Mods are stopped in reverse load order.
*/
@ApiStatus.OverrideOnly
public void onStopping() {}
/** The running Project Zomboid version. */
@@ -1,5 +1,11 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.annotations.Key;
import dev.overlord.zomboidforge.api.annotations.Max;
import dev.overlord.zomboidforge.api.annotations.Min;
import org.jetbrains.annotations.ApiStatus;
import java.util.Optional;
/**
@@ -8,8 +14,10 @@ import java.util.Optional;
* default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings.
*
* <p>Keys are {@code snake_case}; record components and paths use the same names converted
* from {@code camelCase} ({@code maxBalance} reads {@code max_balance}).
* from {@code camelCase} ({@code maxBalance} reads {@code max_balance}), or the name of the
* component's {@link Key}.
*/
@ApiStatus.NonExtendable
public interface ModConfig
{
/**
@@ -18,9 +26,13 @@ public interface ModConfig
* wrappers), enums (by constant name), records (TOML tables), {@code List<T>},
* {@code Map<String, T>} (tables with free keys), and {@code Optional<T>} for values that
* may be missing. Every other component must have a value. Keys without a component are
* logged as warnings.
* logged as warnings. {@link Min} and {@link Max} bound numeric components.
*
* @throws IllegalStateException listing every missing or mistyped value
* @throws IllegalStateException listing every missing, mistyped, or out-of-bounds value
* @throws IllegalArgumentException when {@code type} has a component that configuration
* values cannot have, an invalid or repeated {@link Key},
* or {@link Min}/{@link Max} on a component that is not
* numeric or with the minimum above the maximum
*/
<T extends Record> T bind(Class<T> type);
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.ApiStatus;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import java.nio.file.Path;
@@ -8,6 +10,7 @@ import java.nio.file.Path;
* What ZomboidForge provides to one mod. Mods reach it through the methods of {@link Mod};
* ZomboidForge implements it.
*/
@ApiStatus.NonExtendable
public interface ModContext
{
/** The mod's id from {@code mod.toml}. */
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.ApiStatus;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
@@ -12,6 +14,7 @@ import java.util.concurrent.ScheduledFuture;
* that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not
* touch game objects; that goes through {@code main()}.
*/
@ApiStatus.NonExtendable
public interface ModThread extends Executor
{
/** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */
@@ -1,6 +1,9 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.ApiStatus;
/** A registered event listener. */
@ApiStatus.NonExtendable
public interface Subscription
{
/** Removes the listener; it receives no further events. Calling it again has no effect. */
@@ -0,0 +1,48 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.ModThread;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.temporal.ChronoUnit;
/**
* Runs the method periodically on the mod's own thread, as {@link ModThread#scheduleAtFixedRate}
* or {@link ModThread#scheduleWithFixedDelay} do. The schedule starts once the mod's
* {@code onServerStarted()} returned (also when it threw); for an object registered later with
* {@link Events#register(Object)}, at once. A run that throws is logged and ends the schedule;
* the schedule ends as well when the server stops or the object's subscription is cancelled.
*
* <p>The method has no parameters and returns {@code void}; otherwise the rules of
* {@link Events#register(Object)} apply. Like any mod-thread work, it must not touch game
* objects.
*
* <pre>{@code
* @Every(value = 1, unit = ChronoUnit.MINUTES)
* void report() { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Every
{
/** The period, at least 1. */
long value();
/** The unit of {@link #value} and {@link #initialDelay}: {@code MILLIS}, {@code SECONDS}, {@code MINUTES}, {@code HOURS}, or {@code DAYS}. */
ChronoUnit unit() default ChronoUnit.SECONDS;
/** The time before the first run, at least 0. */
long initialDelay() default 0;
/**
* {@code false}: the period counts from the start of each run (fixed rate); {@code true}: from
* the end of each run (fixed delay).
*/
boolean fixedDelay() default false;
}
@@ -0,0 +1,32 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.TickEvent;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Runs the method on the main thread every n-th frame of the main loop: a {@link TickEvent}
* listener for the ticks that {@link #value} divides (n, 2n, ...). It may touch game objects and,
* like every main-thread listener, must return quickly.
*
* <p>The method has no parameters and returns {@code void}; otherwise the rules of
* {@link Events#register(Object)} apply.
*
* <pre>{@code
* @EveryNTicks(10)
* void sweep() { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EveryNTicks
{
/** n, at least 1. */
int value();
}
@@ -0,0 +1,32 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.ModConfig;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The key of a record component, instead of the one converted from its name ({@code maxBalance}
* to {@code max_balance}): the {@code config.toml} key for {@link ModConfig#bind}, the column
* name for {@link ModStorage} tables. A component keeps its key when it is renamed:
*
* <pre>{@code
* record Settings(@Key("max_hp_regen") int healthRegenPerHour) {}
* }</pre>
*
* The key is {@code snake_case}: lowercase letters, digits, and single underscores, starting with
* a letter. Two components of a record cannot have the same key. For a storage record, giving an
* existing component another key renames its column, which the table treats as a removed and a
* new column, as when the component is renamed without {@code @Key}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.RECORD_COMPONENT)
public @interface Key
{
String value();
}
@@ -0,0 +1,21 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.ModConfig;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The largest value a numeric component of a configuration record accepts; see {@link Min}.
* {@link ModConfig#bind} reports a larger value in {@code config.toml} with its key.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.RECORD_COMPONENT)
public @interface Max
{
double value();
}
@@ -0,0 +1,26 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.storage.Row;
import dev.overlord.zomboidforge.api.storage.TableDefinition;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A migration of a storage record, as {@link TableDefinition#migrate} adds one: turns a row stored
* with schema version {@link #from} into the record. Declared in the record itself, as a static
* method with one {@link Row} parameter that returns the record; it may be private. A record has
* at most one migration per version, whether from this annotation or from
* {@link TableDefinition#migrate}. See {@link Schema}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Migrate
{
/** The stored schema version this method migrates from; at least 1. */
int from();
}
@@ -0,0 +1,28 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.ModConfig;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The smallest value a numeric component of a configuration record accepts. {@link ModConfig#bind}
* reports a smaller value in {@code config.toml} with its key, together with every other
* problem. On a {@code List}, {@code Map}, or {@code Optional} component, it applies to each
* value. The bound may be a fraction ({@code @Min(0.1)}); it is not {@code NaN}. Values are
* compared as {@code double}. Storage records ignore it.
*
* <pre>{@code
* record Settings(@Min(1) @Max(100) int maxPlayers) {}
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.RECORD_COMPONENT)
public @interface Min
{
double value();
}
@@ -0,0 +1,39 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.ClientCommandEvent;
import dev.overlord.zomboidforge.api.Events;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the method with {@link Events#onMain} for the {@link ClientCommandEvent}s of one
* module, and optionally one command. The method has one parameter, a {@code ClientCommandEvent};
* otherwise the rules of {@link Events#register(Object)} apply, and the method carries none of
* the other listener annotations.
*
* <pre>{@code
* @OnClientCommand(module = "Shop", command = "buy", cancel = true)
* void buy(ClientCommandEvent event) { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnClientCommand
{
/** The Lua module, matched exactly; not blank. */
String module();
/** The command, matched exactly; empty matches every command of the module. */
String command() default "";
/**
* Cancels the event before the method runs, so Lua's {@code OnClientCommand} does not
* receive the command, also when the method throws.
*/
boolean cancel() default false;
}
@@ -0,0 +1,19 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Events;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the method with {@link Events#onMain} for the event type of its only parameter. Read
* on the entry point before {@code onLoad()}, and on objects passed to
* {@link Events#register(Object)}, which lists the rules for the method.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnMain {}
@@ -0,0 +1,19 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Events;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the method with {@link Events#onModThread} for the event type of its only parameter.
* Read on the entry point before {@code onLoad()}, and on objects passed to
* {@link Events#register(Object)}, which lists the rules for the method.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnModThread {}
@@ -0,0 +1,28 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Mod;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the class as an admin command, as {@link Commands#register} does, while the mod
* loads: after the entry point's listener methods and before {@link Mod#onLoad()}. Only classes
* in the mod's own jar are found, not those of its libraries; several are registered in the
* order of their names. The class follows the rules of {@link Commands}.
*
* <pre>{@code
* @RegisterCommand
* @CommandName(name = "zfhello")
* @RequiredCapability(requiredCapability = Capability.LoginOnServer)
* public class HelloCommand extends CommandBase { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RegisterCommand {}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import dev.overlord.zomboidforge.api.storage.TableDefinition;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The schema version of a storage record, read by {@link ModStorage#table} and
* {@link ModStorage#define}; {@link TableDefinition#version} overrides it. Records without it
* have version 1. The migrations from older versions are the record's {@link Migrate} methods.
*
* <pre>{@code
* @Schema(version = 2)
* record Balance(long coins, @Nullable Instant lastPaid)
* {
* @Migrate(from = 1)
* static Balance fromV1(Row row) {
* return new Balance(row.getLong("coins"), null);
* }
* }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Schema
{
/** At least 1. */
int version();
}
@@ -0,0 +1,10 @@
/**
* Annotations that stand for calls a mod can also make through the services of
* {@link dev.overlord.zomboidforge.api.Mod}.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.api.annotations;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,5 +1,11 @@
package dev.overlord.zomboidforge.api.storage;
import dev.overlord.zomboidforge.api.annotations.Migrate;
import dev.overlord.zomboidforge.api.annotations.Schema;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Blocking;
import java.util.function.Supplier;
/**
@@ -16,12 +22,26 @@ import java.util.function.Supplier;
* once the server runs they throw an {@link IllegalStateException}, so database I/O never costs
* tick time. Use {@code modThread()} or {@code async()}.
*/
@ApiStatus.NonExtendable
public interface ModStorage
{
/** Opens the table {@code name} with schema version 1 and no migrations. */
/**
* Opens the table {@code name} with the schema version and migrations that {@code type}
* declares with {@link Schema} and {@link Migrate}; without them, version 1 and no migrations.
*
* @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of
* {@code type}, is invalid
*/
@Blocking
<R extends Record> Table<R> table(String name, Class<R> type);
/** A table with a schema version and migrations; see {@link TableDefinition}. */
/**
* A table to open with a schema version and migrations, starting from those of
* {@link Schema} and {@link Migrate} on {@code type}; see {@link TableDefinition}.
*
* @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of
* {@code type}, is invalid
*/
<R extends Record> TableDefinition<R> define(String name, Class<R> type);
/**
@@ -32,8 +52,10 @@ public interface ModStorage
* other threads, for example with {@code main().submit(...).join()}. A backup waits at most
* 10 seconds for it and then runs without pausing storage.
*/
@Blocking
void transaction(Runnable work);
/** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */
@Blocking
<T> T transaction(Supplier<T> work);
}
@@ -1,6 +1,8 @@
package dev.overlord.zomboidforge.api.storage;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Set;
@@ -10,12 +12,13 @@ import java.util.Set;
* numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as
* {@code String}, bytes as {@code byte[]}.
*/
@ApiStatus.NonExtendable
public interface Row
{
String key();
/** The names of the stored columns. */
Set<String> columns();
@Unmodifiable Set<String> columns();
/** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */
@Nullable Object get(String column);
@@ -1,5 +1,9 @@
package dev.overlord.zomboidforge.api.storage;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -13,6 +17,8 @@ import java.util.function.UnaryOperator;
* unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they
* are only allowed during startup.
*/
@ApiStatus.NonExtendable
@Blocking
public interface Table<R extends Record>
{
/** Stores {@code value} under {@code key}, replacing an existing row. */
@@ -24,7 +30,7 @@ public interface Table<R extends Record>
Optional<R> get(String key);
/** The rows of the given keys that exist. */
Map<String, R> getAll(Collection<String> keys);
@Unmodifiable Map<String, R> getAll(Collection<String> keys);
boolean contains(String key);
@@ -35,7 +41,7 @@ public interface Table<R extends Record>
int deleteAll(Collection<String> keys);
/** Every key, sorted. */
List<String> keys();
@Unmodifiable List<String> keys();
/**
* Calls {@code action} for every row, sorted by key, without loading all rows at once.
@@ -1,9 +1,17 @@
package dev.overlord.zomboidforge.api.storage;
import dev.overlord.zomboidforge.api.annotations.Migrate;
import dev.overlord.zomboidforge.api.annotations.Schema;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.Range;
import java.util.function.Function;
/**
* A table to open with a schema version and migrations:
* A table to open with a schema version and migrations. It starts from the record's
* {@link Schema} and {@link Migrate} methods, if any; the calls below add to them:
*
* <pre>{@code
* Table<Balance> balances = this.storage().define("balances", Balance.class)
@@ -12,15 +20,19 @@ import java.util.function.Function;
* .open();
* }</pre>
*/
@ApiStatus.NonExtendable
public interface TableDefinition<R extends Record>
{
/** Schema version of the record, at least 1. Default: 1. */
TableDefinition<R> version(int version);
/** Schema version of the record, at least 1. Default: the record's {@link Schema}, or 1. */
TableDefinition<R> version(@Range(from = 1, to = Integer.MAX_VALUE) int version);
/**
* How to turn a row stored with schema version {@code from} into the current record. Needed
* when the stored version is older than {@link #version} or the record changed in a way that
* cannot be applied without data.
*
* @throws IllegalArgumentException when a migration from {@code from} exists already, also one
* from a {@link Migrate} method of the record
*/
TableDefinition<R> migrate(int from, Function<Row, R> migration);
@@ -29,5 +41,6 @@ public interface TableDefinition<R extends Record>
*
* @throws StorageException when the stored table does not match and no migration applies
*/
@Blocking
Table<R> open();
}
+2 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash
#
# Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the
# Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea,
# in the version of the v* git tag on HEAD, without the "v".
# Gradle plugin (dev.overlord.zomboidforge) to the Maven registry of the ZomboidForge Gitea, in
# the version of the v* git tag on HEAD, without the "v".
#
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
# published. Without a v* tag on HEAD nothing is published.
@@ -17,6 +17,7 @@ public final class B42PatchSet implements PatchSet
new ServerStartedPatch(),
new ServerTickPatch(),
new ServerStoppingPatch(),
new ZipBackupSinglePassPerformancePatch(),
new BackupStoragePatch(),
new CommandLookupPatch(),
new CommandListPatch(),
@@ -24,7 +25,22 @@ public final class B42PatchSet implements PatchSet
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
@@ -3,7 +3,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.HookArgument;
import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch;
import dev.overlord.zomboidforge.patcher.patches.CancellableHookPatch;
import java.util.List;
@@ -13,7 +13,12 @@ import java.util.List;
*
* <pre>{@code
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
* LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
* {
* LuaEventManager.triggerEvent(
* "OnClientCommand", module,
* command, player, tbl
* );
* }
* }</pre>
*
* The arguments are the method's local variables of these names.
@@ -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.ReturnHookPatch;
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
import org.objectweb.asm.Opcodes;
@@ -15,7 +15,6 @@ import java.util.List;
*/
public final class CommandListPatch extends ReturnHookPatch
{
/** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
@@ -3,7 +3,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.HookArgument;
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
import org.objectweb.asm.Opcodes;
@@ -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")));
}
}
@@ -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");
}
}
@@ -16,7 +16,7 @@ import zombie.characters.IsoPlayer;
* thread (client commands are queued for the main loop). Exceptions are caught here; the command
* then reaches Lua as in vanilla.
*/
@SuppressWarnings("CallToPrintStackTrace")
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class ClientCommandHooks
{
private ClientCommandHooks() {}
@@ -13,7 +13,7 @@ import java.util.List;
* server console, RCON, and chat commands all run there. Exceptions are caught here, and the
* vanilla value is returned.
*/
@SuppressWarnings("CallToPrintStackTrace")
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class CommandHooks
{
private CommandHooks() {}
@@ -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() {}
@@ -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() {}
@@ -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
{
/**
@@ -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,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);
}
}
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more