Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ab7473e5c | ||
|
|
b71d163909 | ||
|
|
9f5871905a | ||
|
|
32fab0c1d4 | ||
|
|
a5766f3a1b | ||
|
|
22c74a0030 | ||
|
|
c79a90b88f | ||
|
|
9af951b4be | ||
|
|
9fcde10fed | ||
|
|
b10504e9af | ||
|
|
1664bb6f28 | ||
|
|
b4d70c3d3a | ||
|
|
7ac442c4f6 | ||
|
|
36ac320c9c | ||
|
|
7b721490cb | ||
|
|
8a8db34b69 | ||
|
|
28b3510c10 | ||
|
|
1576d8a38b | ||
|
|
68f090061f | ||
|
|
be08756c36 | ||
|
|
49af536786 | ||
|
|
9178d36168 | ||
|
|
e61026a3d4 | ||
|
|
99f4f49a7c | ||
|
|
43df96391c | ||
|
|
607d5b2b32 | ||
|
|
07dc3f0fad | ||
|
|
7ffcbdbb06 | ||
|
|
9b721bfd45 | ||
|
|
88cd68b5cb | ||
|
|
529e48ed5a | ||
|
|
dd113961e6 | ||
|
|
eb09a77941 | ||
|
|
2081235433 | ||
|
|
e932c7401a | ||
|
|
56e01c5cbe | ||
|
|
38a15db299 | ||
|
|
05a4b9dbd9 | ||
|
|
900f65b591 | ||
|
|
05eed7e205 | ||
|
|
a0cd30a0d7 | ||
|
|
151e1d459f | ||
|
|
a351fc237c | ||
|
|
af7174e128 | ||
|
|
22077514fe | ||
|
|
6761f2d9ea | ||
|
|
18ff32b5ce | ||
|
|
67530d35e9 |
No files matched your search
@@ -18,9 +18,9 @@ jobs:
|
||||
- pz_version: "42"
|
||||
steam_branch: public
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# release.sh derives the version from the newest v* tag
|
||||
# release.sh derives the version from the v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Build and verify
|
||||
|
||||
@@ -9,25 +9,27 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
maven:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# publish.sh derives the version from the newest v* tag
|
||||
# publish.sh derives the version from the v* tag on HEAD
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "25"
|
||||
|
||||
- name: Test and publish
|
||||
# The tests run without the registry credentials; only the publish step gets them.
|
||||
- name: Test
|
||||
run: ci/publish.sh test
|
||||
|
||||
- name: Publish
|
||||
env:
|
||||
ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }}
|
||||
ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }}
|
||||
PUBLISH: "true"
|
||||
run: ci/publish.sh
|
||||
run: ci/publish.sh publish
|
||||
@@ -24,9 +24,9 @@ jobs:
|
||||
steam_branch: public
|
||||
latest: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# release.sh derives the version from the newest v* tag
|
||||
# release.sh derives the version from the v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Log in to the registry
|
||||
@@ -43,3 +43,8 @@ jobs:
|
||||
PUBLISH: "true"
|
||||
LATEST: ${{ matrix.latest }}
|
||||
run: ci/release.sh
|
||||
|
||||
# Removes the stored registry token, also when a step failed, in case the runner is reused.
|
||||
- name: Log out of the registry
|
||||
if: always()
|
||||
run: docker logout git.security-command.org
|
||||
+6
-3
@@ -29,8 +29,11 @@ ARG STEAMCLIENT=bundled
|
||||
ARG FORGE_VERSION="0.0.0-prerelease"
|
||||
ARG STEAM_BUILDID=""
|
||||
|
||||
# Base images are pinned by digest; the tag in front of the digest is for readers only.
|
||||
# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame.
|
||||
|
||||
# --- Stage 1: vanilla dedicated server -----------------------------------------
|
||||
FROM docker.io/steamcmd/steamcmd:debian-13 AS server
|
||||
FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server
|
||||
|
||||
# steamcmd updates itself on its first run. This runs in its own layer so the
|
||||
# update is cached and separate from the app installation.
|
||||
@@ -42,7 +45,7 @@ COPY docker/install-server.sh /usr/local/bin/install-server
|
||||
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
|
||||
|
||||
# --- Stage 2: ZomboidForge sources and Gradle -----------------------------------
|
||||
FROM docker.io/library/eclipse-temurin:25-jdk AS sources
|
||||
FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources
|
||||
WORKDIR /src
|
||||
|
||||
# Gradle distribution download, cached independently of the sources.
|
||||
@@ -102,7 +105,7 @@ RUN ./gradlew --no-daemon \
|
||||
build -x :gradle-plugin:test :patcher:patchServerJar
|
||||
|
||||
# --- Stage 4: runtime ------------------------------------------------------------
|
||||
FROM docker.io/library/debian:trixie-slim
|
||||
FROM docker.io/library/debian:trixie-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a
|
||||
|
||||
# ca-certificates: required by steamclient.so to connect to Steam.
|
||||
# sqlite3: the entrypoint checks the admin account in the server database.
|
||||
|
||||
+283
-44
@@ -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()
|
||||
}
|
||||
repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "shop"
|
||||
```
|
||||
|
||||
`build.gradle.kts`:
|
||||
|
||||
```kotlin
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge.mod") version "0.3.0" // the plugin's version is the API version
|
||||
id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the API version
|
||||
}
|
||||
|
||||
version = "1.2.0"
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
version = "1.0.0"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
game("42") // only when the mod uses game classes
|
||||
dependsOn("economy", "2.1") // other mods: id and minimum version
|
||||
}
|
||||
```
|
||||
|
||||
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 -
|
||||
```
|
||||
|
||||
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
|
||||
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 |
|
||||
@@ -69,7 +83,8 @@ game jar for mods that declare `game` versions. Default settings go into
|
||||
| `gameJar` | see below | the `projectzomboid.jar` to compile and check against |
|
||||
| `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` |
|
||||
| `serverImage` | the ZomboidForge image, `latest` | image for `runServer` |
|
||||
| `adminPassword` | `admin` | admin password of the `runServer` server |
|
||||
| `adminPassword` | random, generated once per volume | admin password of the `runServer` server (see below) |
|
||||
| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network |
|
||||
| `dataVolume` | `zomboidforge-<id>` | volume for the `runServer` world and server config |
|
||||
| `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download |
|
||||
| `deployDirectory` | none | a server's mods directory for `deployMod` |
|
||||
@@ -98,14 +113,21 @@ 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` |
|
||||
| `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
|
||||
keeps it in `<Gradle user home>/zomboidforge/admin-passwords/<volume>`. The server uses the
|
||||
password only when it creates the admin account, on the volume's first start; a later change
|
||||
needs a new volume (`dataVolume`, or remove the old one).
|
||||
|
||||
### Working on ZomboidForge itself
|
||||
|
||||
@@ -135,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
|
||||
@@ -143,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));
|
||||
}
|
||||
|
||||
@@ -155,10 +183,10 @@ public final class ShopMod extends Mod
|
||||
|
||||
## Services
|
||||
|
||||
Methods of `Mod`, usable from the constructor on (also in field initializers):
|
||||
Methods of `Mod`, usable from the constructor on, and in field initializers:
|
||||
|
||||
| Method | Returns | Use |
|
||||
|-----------------|-----------------|---------------------------------------------------------------|
|
||||
|--------------------|------------------|---------------------------------------------------------------|
|
||||
| `id()` | `String` | the mod's id from `mod.toml` |
|
||||
| `version()` | `String` | the mod's version from `mod.toml` |
|
||||
| `gameVersion()` | `GameVersion` | the running Project Zomboid version |
|
||||
@@ -170,6 +198,27 @@ Methods of `Mod`, usable from the constructor on (also in field initializers):
|
||||
| `modThread()` | `ModThread` | the mod's own work, one task at a time |
|
||||
| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O |
|
||||
| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` |
|
||||
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
|
||||
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
|
||||
|
||||
## 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
|
||||
|
||||
@@ -203,11 +252,166 @@ 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
|
||||
(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the
|
||||
mod declares `game` versions. In Build 42 a command is a subclass of
|
||||
`zombie.commands.CommandBase`:
|
||||
|
||||
```java
|
||||
@CommandName(name = "zfhello")
|
||||
@CommandArgs(optional = "(.+)")
|
||||
@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false)
|
||||
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||
public class HelloCommand extends CommandBase
|
||||
{
|
||||
public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||
|
||||
@Override
|
||||
protected String Command()
|
||||
{
|
||||
String name = this.getCommandArg(0);
|
||||
return "Hello " + (name == null ? this.getExecutorUsername() : name);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
@Override
|
||||
public void onLoad() { this.commands().register(HelloCommand.class); }
|
||||
```
|
||||
|
||||
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()`; 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
|
||||
differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands.
|
||||
A name matches when it is the first word of the input, ignoring case.
|
||||
- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one.
|
||||
RCON and the server console run commands with the default admin role.
|
||||
- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become
|
||||
`getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with
|
||||
`shouldTranslated = false` the text is used as written) are optional.
|
||||
- **`Command()`** runs on the main thread, for every use on a new instance; its return value
|
||||
is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms
|
||||
that the work started.
|
||||
- Project Zomboid's commands are looked up first; mods' commands follow in load order.
|
||||
|
||||
## Client commands
|
||||
|
||||
A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk
|
||||
through Project Zomboid's command channel, so players keep the official client.
|
||||
|
||||
Client to server: the Lua mod calls `sendClientCommand`, and the server posts
|
||||
`ClientCommandEvent` on the main thread.
|
||||
|
||||
```lua
|
||||
sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 })
|
||||
```
|
||||
|
||||
```java
|
||||
this.events().onMain(ClientCommandEvent.class, event ->
|
||||
{
|
||||
if (!event.module().equals("Shop")) return;
|
||||
event.cancel(); // Lua's OnClientCommand does not see it
|
||||
|
||||
String item = (String) event.args().get("item");
|
||||
int count = ((Double) event.args().get("count")).intValue();
|
||||
// ...
|
||||
this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count));
|
||||
});
|
||||
```
|
||||
|
||||
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`.
|
||||
|
||||
```lua
|
||||
Events.OnServerCommand.Add(function(module, command, args)
|
||||
if module == "Shop" and command == "bought" then print(args.item, args.count) end
|
||||
end)
|
||||
```
|
||||
|
||||
- **Every** client command is posted, including those of Project Zomboid (`vehicle`,
|
||||
`player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`.
|
||||
- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`.
|
||||
Every listener still runs; `isCancelled()` tells whether another one cancelled.
|
||||
- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua
|
||||
arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number),
|
||||
`Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is
|
||||
empty when the client sent no table.
|
||||
- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other
|
||||
threads and after the player left. Sending to a player who left sends nothing.
|
||||
- **Sending** works from any thread. The arguments are copied and checked at once
|
||||
(`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua
|
||||
numbers, lists become Lua arrays. The command is sent on the main thread: at once when
|
||||
called there, otherwise as one of the mod's queued main-thread tasks.
|
||||
- Client commands come from players and can be forged by a modified client. Check every
|
||||
argument and the player's rights before acting on it.
|
||||
|
||||
## Storage
|
||||
|
||||
Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's
|
||||
save folder. Vanilla backups include it, and deleting the world deletes it. Each mod only
|
||||
reaches its own tables.
|
||||
save folder. Vanilla backups include it, and deleting the world deletes it. Through the API,
|
||||
each mod only reaches its own tables.
|
||||
|
||||
A record declares a table's columns; each row has a `String` key:
|
||||
|
||||
@@ -220,7 +424,7 @@ balances.set("player1", new Balance(250, Instant.now()));
|
||||
Optional<Balance> balance = balances.get("player1");
|
||||
balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null));
|
||||
|
||||
this.storage().transaction(() -> { // all or nothing
|
||||
this.storage().transaction(() -> { // all or nothing, also when nested
|
||||
balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null));
|
||||
balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null));
|
||||
});
|
||||
@@ -235,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:
|
||||
|
||||
@@ -253,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
|
||||
@@ -261,6 +484,10 @@ Things to know:
|
||||
world goes back to its last save, but the mod data keeps later writes.
|
||||
3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables
|
||||
move to the new id once.
|
||||
4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits.
|
||||
These callbacks must not wait for other threads, for example with
|
||||
`main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs
|
||||
without pausing storage, so its copy of `zomboidforge.db` may be incomplete.
|
||||
|
||||
## Checks at startup
|
||||
|
||||
@@ -273,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
|
||||
@@ -286,8 +520,13 @@ Every problem of every mod is listed in the log.
|
||||
| game jar (game code and its bundled libraries) | only with `game` declared |
|
||||
| ZomboidForge internals | no |
|
||||
|
||||
These rules keep mods from linking against the wrong classes by accident. They are not a
|
||||
sandbox: a mod runs with the full privileges of the server process. Through reflection or the
|
||||
file system it can reach anything the server can, including other mods' data in
|
||||
`zomboidforge.db`.
|
||||
|
||||
## Profiling
|
||||
|
||||
Main-thread tasks and event listener calls appear in JFR recordings as the event
|
||||
`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).
|
||||
@@ -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,19 +108,24 @@ forge/
|
||||
podman run ... -v ./forge:/forge zomboidforge
|
||||
```
|
||||
|
||||
A mod's settings live in its `config.toml`. When the file is missing, it is created from the
|
||||
mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a
|
||||
file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]`
|
||||
table switches the mod off; mods that depend on it then fail to load.
|
||||
> [!WARNING]
|
||||
> Mods are trusted code. <br>
|
||||
> They run inside the server process with its full privileges, which means they can
|
||||
> read and write any file the server can, open network connections, and stop the server. <br>
|
||||
> The class loader isolation and the startup checks catch mistakes; they do not contain
|
||||
> or restrict a malicious mod.
|
||||
>
|
||||
> Install only mods whose authors you trust, or whose code you can verify yourself!
|
||||
|
||||
Mods keep their data in `zomboidforge.db` in the world's save folder
|
||||
(`/data/Saves/Multiplayer/<server>/`). Vanilla backups include it, and deleting the world
|
||||
deletes it.
|
||||
|
||||
A mod that cannot be loaded stops the server with exit code 1, and the log lists every
|
||||
problem: a missing or too old dependency, an unsupported game version, game classes or methods
|
||||
that do not exist in the running version, invalid settings, or an exception in the mod's
|
||||
startup code. Changes to mods and their settings take effect when the server restarts.
|
||||
problem. For example, a missing or too old dependency, an unsupported game version,
|
||||
game classes or methods that do not exist in the running version, invalid settings,
|
||||
or an exception in the mod's startup code. Changes to mods and their settings take
|
||||
effect when the server restarts.
|
||||
|
||||
`forge.toml`, every key optional:
|
||||
|
||||
@@ -117,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
|
||||
@@ -134,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.
|
||||
+14
-6
@@ -2,6 +2,7 @@
|
||||
|
||||
plugins {
|
||||
id("zomboidforge.java-conventions")
|
||||
alias(libs.plugins.shadow)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -11,12 +12,19 @@ dependencies {
|
||||
compileOnly(files(projectZomboid.serverJar))
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
// The agent jar is appended to the system class path behind the game jar and includes api,
|
||||
// core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same
|
||||
// library in the game jar cannot replace them.
|
||||
tasks.shadowJar {
|
||||
archiveBaseName = "zomboidforge-agent"
|
||||
archiveClassifier = ""
|
||||
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
|
||||
// The agent jar is appended to the system class path and includes api, core and compat runtime.
|
||||
// Mapping the classpath to zip trees loses its task dependencies; the input restores them.
|
||||
inputs.files(configurations.runtimeClasspath)
|
||||
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
|
||||
relocate("org.objectweb.asm", "dev.overlord.zomboidforge.shaded.asm")
|
||||
relocate("com.electronwill.nightconfig", "dev.overlord.zomboidforge.shaded.nightconfig")
|
||||
}
|
||||
|
||||
// Only the shadow jar is used; the plain jar would match the same file name pattern.
|
||||
tasks.jar {
|
||||
enabled = false
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
/**
|
||||
* An event whose default action, what Project Zomboid does after the event, can be prevented.
|
||||
* Only listeners on the main thread can cancel: the default action runs once every main-thread
|
||||
* listener returned. Every listener is called, also after one cancelled.
|
||||
*/
|
||||
public interface Cancellable
|
||||
{
|
||||
/** Prevents the default action. */
|
||||
void cancel();
|
||||
|
||||
boolean isCancelled();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A client command arrived: a client called Lua's {@code sendClientCommand(module, command, args)}.
|
||||
* Posted on the main thread for every client command, including those of Project Zomboid and of
|
||||
* Lua mods, so listeners filter by {@link #module()}.
|
||||
*
|
||||
* <p>Default action: Project Zomboid passes the command to Lua's {@code Events.OnClientCommand}.
|
||||
* {@link #cancel()} prevents that, for example when a Java mod handles the module itself.
|
||||
*
|
||||
* <p>{@link #args()} is the Lua table converted to Java: keys are {@code String} or
|
||||
* {@code Double} (Lua arrays have the keys {@code 1.0}, {@code 2.0}, ...), values are
|
||||
* {@code String}, {@code Double}, {@code Boolean}, a nested {@code Map} of the same kind, or a
|
||||
* game object that Project Zomboid sends with commands (in Build 42 an inventory item, an
|
||||
* {@code IsoDirections}, or a dead body). The maps cannot be modified.
|
||||
*/
|
||||
public final class ClientCommandEvent implements MainThreadEvent, Cancellable
|
||||
{
|
||||
private final PlayerRef player;
|
||||
private final String module;
|
||||
private final String command;
|
||||
private final Map<Object, Object> args;
|
||||
|
||||
private boolean cancelled;
|
||||
|
||||
/** @param args the converted arguments; empty when the client sent none */
|
||||
public ClientCommandEvent(PlayerRef player, String module, String command, Map<Object, Object> args)
|
||||
{
|
||||
this.player = Objects.requireNonNull(player, "player");
|
||||
this.module = Objects.requireNonNull(module, "module");
|
||||
this.command = Objects.requireNonNull(command, "command");
|
||||
this.args = Objects.requireNonNull(args, "args");
|
||||
}
|
||||
|
||||
/** The player who sent the command. */
|
||||
public PlayerRef player() { return this.player; }
|
||||
|
||||
public String module() { return this.module; }
|
||||
|
||||
public String command() { return this.command; }
|
||||
|
||||
public @Unmodifiable Map<Object, Object> args() { return this.args; }
|
||||
|
||||
@Override
|
||||
public void cancel() { this.cancelled = true; }
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() { return this.cancelled; }
|
||||
|
||||
@Override
|
||||
public String toString() { return "ClientCommandEvent[" + this.player + ", " + this.module + "." + this.command + ", " + this.args + (this.cancelled ? ", cancelled" : "") + "]"; }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Server commands to clients, the reply channel to {@link ClientCommandEvent}: a client receives
|
||||
* them in Lua's {@code Events.OnServerCommand(module, command, args)}. Together, a Java mod on the
|
||||
* server and a Lua mod on the client exchange commands while players keep the official client.
|
||||
*
|
||||
* <p>{@code args} becomes a Lua table: keys are {@code String} or a {@code Number} (sent as a
|
||||
* Lua number), values are {@code String}, {@code Number}, {@code Boolean}, a nested {@code Map}, a
|
||||
* {@code List} (a Lua array, indexed from 1), or a game object that Project Zomboid sends with
|
||||
* commands (see {@link ClientCommandEvent}). {@code null} keys or values, and cycles, are not
|
||||
* allowed. An empty map sends no arguments; the client then receives {@code nil}.
|
||||
*
|
||||
* <p>The methods can be called on any thread. The arguments are checked at once; the command is
|
||||
* sent on the main thread, at once when called there, otherwise with the mod's queued
|
||||
* main-thread tasks.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface ClientCommands
|
||||
{
|
||||
/**
|
||||
* Sends a command to {@code player}. Nothing is sent when the player is no longer connected.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
|
||||
*/
|
||||
void send(PlayerRef player, String module, String command, Map<?, ?> args);
|
||||
|
||||
/**
|
||||
* Sends a command to every connected client.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
|
||||
*/
|
||||
void sendToAll(String module, String command, Map<?, ?> args);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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
|
||||
* is looked up after the commands of Project Zomboid and runs on the main thread.
|
||||
*
|
||||
* <p>A command is a class of the running Project Zomboid version's command framework, so a mod
|
||||
* that registers commands declares {@code game} versions in {@code mod.toml}. In Build 42 it is
|
||||
* a public, non-abstract subclass of {@code zombie.commands.CommandBase} with:
|
||||
* <ul>
|
||||
* <li>one public constructor {@code (String username, Role role, String command, UdpConnection connection)},
|
||||
* which passes its arguments to {@code super};</li>
|
||||
* <li>at least one {@code @CommandName}; names consist of letters, digits, and {@code _}, and
|
||||
* differ (ignoring case) from every name of Project Zomboid and of other mods;</li>
|
||||
* <li>at least one {@code @RequiredCapability}; Project Zomboid refuses to run a command
|
||||
* without one;</li>
|
||||
* <li>optionally {@code @CommandArgs} (argument patterns) and {@code @CommandHelp}
|
||||
* ({@code help <name>} and the {@code help} list).</li>
|
||||
* </ul>
|
||||
* Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose
|
||||
* result is the reply.
|
||||
*/
|
||||
@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()}. 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
|
||||
* @throws IllegalStateException when called later or on another thread
|
||||
*/
|
||||
void register(Class<?> command);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -9,8 +9,9 @@ import java.util.regex.Pattern;
|
||||
/** Project Zomboid version, e.g. 42.21.0 ({@code Core.getGameAndBuildVersion()}). */
|
||||
public record GameVersion(int major, int minor, int build) implements Comparable<GameVersion>
|
||||
{
|
||||
private static final Pattern VERSION = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?");
|
||||
private static final Pattern PREFIX = Pattern.compile("(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?");
|
||||
// At most 9 digits per number, so every number fits an int.
|
||||
private static final Pattern VERSION = Pattern.compile("(\\d{1,9})\\.(\\d{1,9})(?:\\.(\\d{1,9}))?");
|
||||
private static final Pattern PREFIX = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9})(?:\\.(\\d{1,9}))?)?");
|
||||
|
||||
private static final Comparator<GameVersion> ORDER = Comparator
|
||||
.comparingInt(GameVersion::major)
|
||||
|
||||
@@ -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. */
|
||||
@@ -84,4 +100,10 @@ public abstract class Mod
|
||||
|
||||
/** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */
|
||||
protected final ModStorage storage() { return this.context.storage(); }
|
||||
|
||||
/** Admin command registration. */
|
||||
protected final Commands commands() { return this.context.commands(); }
|
||||
|
||||
/** Server commands to clients, received by their Lua mods. */
|
||||
protected final ClientCommands clientCommands() { return this.context.clientCommands(); }
|
||||
}
|
||||
@@ -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}. */
|
||||
@@ -42,4 +45,10 @@ public interface ModContext
|
||||
|
||||
/** The mod's tables in the world's {@code zomboidforge.db}. */
|
||||
ModStorage storage();
|
||||
|
||||
/** Admin command registration. */
|
||||
Commands commands();
|
||||
|
||||
/** Server commands to clients, received by their Lua mods. */
|
||||
ClientCommands clientCommands();
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A connected player, by value: usable on any thread and after the player left. Project
|
||||
* Zomboid reuses online ids of players who left, so ZomboidForge matches both the id and the
|
||||
* username before it acts on a player.
|
||||
*
|
||||
* @param onlineId the player's online id while connected
|
||||
* @param username the player's account name
|
||||
*/
|
||||
public record PlayerRef(int onlineId, String username)
|
||||
{
|
||||
public PlayerRef
|
||||
{
|
||||
Objects.requireNonNull(username, "username");
|
||||
}
|
||||
}
|
||||
@@ -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,10 +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 java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to
|
||||
* the mod; other mods cannot reach it.
|
||||
* the mod; this interface gives no access to the tables of other mods. It is not a security
|
||||
* boundary: mod code runs with the server's privileges and can open the file directly.
|
||||
*
|
||||
* <p>A record declares a table's columns: {@code String}, {@code long}/{@code int},
|
||||
* {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant},
|
||||
@@ -15,20 +22,40 @@ 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);
|
||||
|
||||
/**
|
||||
* Runs {@code work} in one transaction: writes of this thread inside it are committed
|
||||
* together, or not at all when {@code work} throws.
|
||||
*
|
||||
* <p>Storage of every mod waits while {@code work} runs, so {@code work} must not wait for
|
||||
* other threads, for example with {@code main().submit(...).join()}. A backup waits at most
|
||||
* 10 seconds for it and then runs without pausing storage.
|
||||
*/
|
||||
@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,9 +41,13 @@ 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. */
|
||||
/**
|
||||
* Calls {@code action} for every row, sorted by key, without loading all rows at once.
|
||||
* Storage of every mod waits until it returns, so {@code action} must not wait for other
|
||||
* threads.
|
||||
*/
|
||||
void forEach(BiConsumer<String, R> action);
|
||||
|
||||
long count();
|
||||
@@ -45,6 +55,8 @@ public interface Table<R extends Record>
|
||||
/**
|
||||
* Replaces the row under {@code key} with {@code change} applied to it, or to
|
||||
* {@code initial} when there is none, in one transaction: no other write comes in between.
|
||||
* As in {@link ModStorage#transaction}, {@code change} and {@code initial} must not wait for
|
||||
* other threads.
|
||||
*
|
||||
* @return the stored value
|
||||
*/
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -42,6 +42,16 @@ class GameVersionTest
|
||||
assertThrows(IllegalArgumentException.class, () -> version.matches("42.21.3.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNumbersOutsideTheIntRange()
|
||||
{
|
||||
GameVersion version = new GameVersion(42, 21, 3);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42.99999999999"));
|
||||
assertThrows(IllegalArgumentException.class, () -> version.matches("99999999999"));
|
||||
assertFalse(GameVersion.isPrefix("42.99999999999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void comparesNumerically()
|
||||
{
|
||||
|
||||
+45
-26
@@ -1,16 +1,19 @@
|
||||
#!/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 newest v* git tag reachable from 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 any v* tag nothing is published.
|
||||
# published. Without a v* tag on HEAD nothing is published.
|
||||
#
|
||||
# Environment:
|
||||
# Usage:
|
||||
# ci/publish.sh test runs the checks of the published modules; needs no credentials
|
||||
# ci/publish.sh publish publishes them without running the checks again
|
||||
#
|
||||
# Environment (publish only):
|
||||
# ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access
|
||||
# ORG_GRADLE_PROJECT_giteaPassword Token of that user
|
||||
# PUBLISH true: publish after the tests. Default: false (test only)
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
@@ -19,8 +22,6 @@ set -o pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
readonly REPO_ROOT
|
||||
|
||||
readonly REQUESTED_PUBLISH="${PUBLISH:-false}"
|
||||
|
||||
readonly MODULES=(
|
||||
api
|
||||
mod-tools
|
||||
@@ -31,11 +32,11 @@ log() {
|
||||
echo "[publish] $*" >&2
|
||||
}
|
||||
|
||||
# Prints the newest v* tag reachable from HEAD without its "v", or nothing.
|
||||
# Prints the v* tag on HEAD without its "v", or nothing.
|
||||
release_tag_version() {
|
||||
local tag
|
||||
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
fi
|
||||
}
|
||||
@@ -61,36 +62,54 @@ run_gradle() {
|
||||
"$@"
|
||||
}
|
||||
|
||||
main() {
|
||||
local version
|
||||
local publish="${REQUESTED_PUBLISH}"
|
||||
run_tests() {
|
||||
local version="$1"
|
||||
local check_tasks
|
||||
local publish_tasks
|
||||
|
||||
version="$(release_tag_version)"
|
||||
if [[ -z "${version}" ]]; then
|
||||
log "No v* git tag found (shallow clone without tags?); nothing to publish."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${version}" == *-* ]]; then
|
||||
publish=false
|
||||
log "${version} is a pre-release version; nothing will be published."
|
||||
fi
|
||||
|
||||
mapfile -t check_tasks < <(module_tasks check)
|
||||
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
|
||||
|
||||
log "Testing ZomboidForge ${version}: ${MODULES[*]}"
|
||||
run_gradle "${version}" :core:check "${check_tasks[@]}"
|
||||
}
|
||||
|
||||
if [[ "${publish}" != "true" ]]; then
|
||||
log "Not publishing (PUBLISH=${REQUESTED_PUBLISH})."
|
||||
publish() {
|
||||
local version="$1"
|
||||
local publish_tasks
|
||||
|
||||
if [[ "${version}" == *-* ]]; then
|
||||
log "${version} is a pre-release version; nothing is published."
|
||||
return
|
||||
fi
|
||||
|
||||
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
|
||||
|
||||
log "Publishing ZomboidForge ${version}"
|
||||
run_gradle "${version}" "${publish_tasks[@]}"
|
||||
log "Published ${MODULES[*]} ${version}"
|
||||
}
|
||||
|
||||
main() {
|
||||
local step="${1:-}"
|
||||
local version
|
||||
|
||||
version="$(release_tag_version)"
|
||||
if [[ -z "${version}" ]]; then
|
||||
log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "${step}" in
|
||||
test)
|
||||
run_tests "${version}"
|
||||
;;
|
||||
publish)
|
||||
publish "${version}"
|
||||
;;
|
||||
*)
|
||||
log "Usage: ci/publish.sh test|publish"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
+10
-6
@@ -10,9 +10,10 @@
|
||||
# <major.minor.build> is the version the branch's server jar reports, read before the full
|
||||
# build (Dockerfile stage game-version, which downloads only the jar).
|
||||
#
|
||||
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0).
|
||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never
|
||||
# published. Without any v* tag the version is "0.0.0-prerelease".
|
||||
# <forge> is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such
|
||||
# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0).
|
||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and
|
||||
# verified but never published. Without any v* tag the version is "0.0.0-prerelease".
|
||||
#
|
||||
# Nothing is built when <forge>-pz<major.minor.build> already exists in the registry. The
|
||||
# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 ->
|
||||
@@ -69,12 +70,15 @@ gradle_property() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Prints the forge version: the newest v* tag reachable from HEAD without its "v",
|
||||
# or nothing when the repository has no such tag.
|
||||
# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
|
||||
# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the
|
||||
# repository has no such tag.
|
||||
release_tag_version() {
|
||||
local tag
|
||||
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
fi
|
||||
}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ set -o nounset
|
||||
set -o pipefail
|
||||
|
||||
readonly APP_ID="380870"
|
||||
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13"
|
||||
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d"
|
||||
|
||||
readonly BRANCH="$1"
|
||||
|
||||
|
||||
+20
-1
@@ -17,11 +17,30 @@ public final class B42PatchSet implements PatchSet
|
||||
new ServerStartedPatch(),
|
||||
new ServerTickPatch(),
|
||||
new ServerStoppingPatch(),
|
||||
new ZipBackupSinglePassPerformancePatch(),
|
||||
new BackupStoragePatch(),
|
||||
new CommandLookupPatch(),
|
||||
new CommandListPatch(),
|
||||
new ClientCommandPatch(),
|
||||
new IsoZombieVehiclePerformancePatch(),
|
||||
new IsoZombieNetworkComponentPerformancePatch(),
|
||||
new IsoZombieSpotChancePerformancePatch(),
|
||||
new IsoGameCharacterStateMachinePerformancePatch()
|
||||
new IsoGameCharacterStateMachinePerformancePatch(),
|
||||
new ZombieVoronoiPerformancePatch(),
|
||||
new ZomboidFileSystemInitPerformancePatch(),
|
||||
new ServerMapCellBudgetPerformancePatch(),
|
||||
new WorldGenUtilsPlacementPerformancePatch(),
|
||||
new WorldGenChunkRulesPerformancePatch(),
|
||||
new BitHeaderPoolPerformancePatch(),
|
||||
new IsoChunkSaveDirectoryPerformancePatch(),
|
||||
new RolesSavePerformancePatch(),
|
||||
new ServerChunkLoaderQuitPerformancePatch(),
|
||||
new ZipBackupWaitPerformancePatch(),
|
||||
new ServerPlayersVehiclesRoundPerformancePatch(),
|
||||
new ServerPlayersVehiclesStopPerformancePatch(),
|
||||
new ServerPlayerDBSaveWaitPerformancePatch(),
|
||||
new GameServerAssetLoadingPerformancePatch(),
|
||||
new ServerMapQuitSleepPerformancePatch()
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
import dev.overlord.zomboidforge.patcher.patches.CancellableHookPatch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Makes the Lua event {@code OnClientCommand} in {@code GameServer.receiveClientCommand} depend on
|
||||
* {@code ClientCommandHooks.onClientCommand(module, command, player, tbl)}:
|
||||
*
|
||||
* <pre>{@code
|
||||
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
|
||||
* {
|
||||
* LuaEventManager.triggerEvent(
|
||||
* "OnClientCommand", module,
|
||||
* command, player, tbl
|
||||
* );
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The arguments are the method's local variables of these names.
|
||||
*/
|
||||
public final class ClientCommandPatch extends CancellableHookPatch
|
||||
{
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("receiveClientCommand", "(Lzombie/core/network/ByteBufferReader;Lzombie/core/raknet/UdpConnection;S)V"),
|
||||
"zombie/Lua/LuaEventManager", "triggerEvent", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks", "onClientCommand",
|
||||
"(Ljava/lang/String;Ljava/lang/String;Lzombie/characters/IsoPlayer;Lse/krka/kahlua/vm/KahluaTable;)Z"
|
||||
);
|
||||
|
||||
private static final List<HookArgument> ARGUMENTS = List.of(
|
||||
new HookArgument.Local("module"),
|
||||
new HookArgument.Local("command"),
|
||||
new HookArgument.Local("player"),
|
||||
new HookArgument.Local("tbl")
|
||||
);
|
||||
|
||||
public ClientCommandPatch() {
|
||||
super("zombie/network/GameServer", ClientCommandPatch.ANCHOR, ClientCommandPatch.HOOK, ClientCommandPatch.ARGUMENTS);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Makes {@code CommandBase.getSubClasses()} return
|
||||
* {@code CommandHooks.listCommands(childrenClasses)}: Project Zomboid's command classes followed
|
||||
* by the mods'. The {@code help} command lists commands through this method.
|
||||
*/
|
||||
public final class CommandListPatch extends ReturnHookPatch
|
||||
{
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "listCommands", "([Ljava/lang/Class;)[Ljava/lang/Class;"
|
||||
);
|
||||
|
||||
public CommandListPatch() {
|
||||
super("zombie/commands/CommandBase", CommandListPatch.ANCHOR, CommandListPatch.HOOK, List.of());
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Makes {@code CommandBase.findCommandCls(command)} return
|
||||
* {@code CommandHooks.findCommand(null, command)} where it returns {@code null}: when no command
|
||||
* of Project Zomboid matches, the mods' commands are searched. The server console, RCON, chat
|
||||
* commands, and {@code help <name>} look commands up through this method.
|
||||
*/
|
||||
public final class CommandLookupPatch extends ReturnHookPatch
|
||||
{
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("findCommandCls", "(Ljava/lang/String;)Ljava/lang/Class;"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ACONST_NULL),
|
||||
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "findCommand", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;"
|
||||
);
|
||||
|
||||
public CommandLookupPatch() {
|
||||
super("zombie/commands/CommandBase", CommandLookupPatch.ANCHOR, CommandLookupPatch.HOOK, List.of(new HookArgument.Parameter(0)));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+93
@@ -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;
|
||||
}
|
||||
}
|
||||
+62
@@ -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));
|
||||
}
|
||||
}
|
||||
+85
@@ -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;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+58
@@ -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);
|
||||
}
|
||||
}
|
||||
+26
@@ -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"); }
|
||||
}
|
||||
+90
@@ -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);
|
||||
}
|
||||
}
|
||||
+26
@@ -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"); }
|
||||
}
|
||||
+27
@@ -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"); }
|
||||
}
|
||||
+26
@@ -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"); }
|
||||
}
|
||||
+26
@@ -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"); }
|
||||
}
|
||||
+76
@@ -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
|
||||
));
|
||||
}
|
||||
}
|
||||
+56
@@ -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);
|
||||
}
|
||||
}
|
||||
+60
@@ -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);
|
||||
}
|
||||
}
|
||||
+26
@@ -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"); }
|
||||
}
|
||||
+121
@@ -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 + "'.");
|
||||
}
|
||||
}
|
||||
+119
@@ -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 + "'.");
|
||||
}
|
||||
}
|
||||
+138
@@ -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")));
|
||||
}
|
||||
}
|
||||
+120
@@ -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")));
|
||||
}
|
||||
}
|
||||
+193
@@ -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")));
|
||||
}
|
||||
}
|
||||
+119
@@ -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")));
|
||||
}
|
||||
}
|
||||
+181
@@ -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")));
|
||||
}
|
||||
}
|
||||
+132
@@ -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")));
|
||||
}
|
||||
}
|
||||
+160
@@ -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")));
|
||||
}
|
||||
}
|
||||
+134
@@ -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")));
|
||||
}
|
||||
}
|
||||
+157
@@ -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")));
|
||||
}
|
||||
}
|
||||
+188
@@ -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")));
|
||||
}
|
||||
}
|
||||
+197
@@ -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")));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ dependencies {
|
||||
implementation(project(":api"))
|
||||
compileOnly(files(projectZomboid.serverJar))
|
||||
|
||||
// ModCommandsTest checks command classes against the game's command framework.
|
||||
testImplementation(files(projectZomboid.serverJar))
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
|
||||
+5
-1
@@ -1,11 +1,15 @@
|
||||
package dev.overlord.zomboidforge.compat.b42;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
|
||||
import dev.overlord.zomboidforge.core.Forge;
|
||||
|
||||
/** The one {@link Forge} of the server, shared by the hook classes. */
|
||||
public final class ForgeInstance
|
||||
{
|
||||
public static final Forge FORGE = Forge.fromSystemProperties();
|
||||
public static final Forge FORGE = Forge.fromSystemProperties(
|
||||
ModCommands::check, ClientCommandChannel::prepare
|
||||
);
|
||||
|
||||
private ForgeInstance() {}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import dev.overlord.zomboidforge.api.PlayerRef;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
|
||||
import zombie.Lua.LuaManager;
|
||||
import zombie.characters.IsoPlayer;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Client commands in Build 42: players as {@link PlayerRef}s, and server commands to clients. */
|
||||
public final class ClientCommandChannel
|
||||
{
|
||||
private ClientCommandChannel() {}
|
||||
|
||||
public static PlayerRef ref(IsoPlayer player) { return new PlayerRef(player.getOnlineID(), player.getUsername()); }
|
||||
|
||||
/**
|
||||
* Copies {@code args} at once and returns the action that sends the command with
|
||||
* {@code GameServer.sendServerCommand}, to every connection when {@code player} is
|
||||
* {@code null}. The action runs on the main thread and sends nothing when the player is no
|
||||
* longer connected.
|
||||
*
|
||||
* @throws IllegalArgumentException naming a key or value that cannot be sent
|
||||
*/
|
||||
public static Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args)
|
||||
{
|
||||
Map<Object, Object> copy = LuaTables.copy(args);
|
||||
|
||||
return () ->
|
||||
{
|
||||
KahluaTable table = copy.isEmpty() ? null : LuaTables.toLua(copy, LuaManager.platform::newTable);
|
||||
|
||||
if (player == null) {
|
||||
GameServer.sendServerCommand(module, command, table);
|
||||
return;
|
||||
}
|
||||
|
||||
IsoPlayer target = ClientCommandChannel.find(player);
|
||||
if (target != null) GameServer.sendServerCommand(target, module, command, table);
|
||||
};
|
||||
}
|
||||
|
||||
/** The connected player with the online id and the username of {@code player}, or {@code null}. Main thread. */
|
||||
private static @Nullable IsoPlayer find(PlayerRef player)
|
||||
{
|
||||
Object connected = GameServer.IDToPlayerMap.get((short) player.onlineId());
|
||||
|
||||
return connected instanceof IsoPlayer target && player.username().equals(target.getUsername()) ? target : null;
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
import se.krka.kahlua.vm.KahluaTableIterator;
|
||||
|
||||
import zombie.inventory.InventoryItem;
|
||||
import zombie.iso.IsoDirections;
|
||||
import zombie.iso.objects.IsoDeadBody;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Conversion between the Kahlua tables of command arguments and the Java maps of the API. The
|
||||
* types are those {@code TableNetworkUtils} sends: {@code String} and {@code Double} keys;
|
||||
* {@code String}, {@code Double}, {@code Boolean}, table, {@code InventoryItem},
|
||||
* {@code IsoDirections}, and {@code IsoDeadBody} values.
|
||||
*/
|
||||
public final class LuaTables
|
||||
{
|
||||
private LuaTables() {}
|
||||
|
||||
/** {@code table} as an unmodifiable map, nested tables as nested maps; empty for {@code null}. */
|
||||
public static Map<Object, Object> toJava(@Nullable KahluaTable table)
|
||||
{
|
||||
if (table == null) return Map.of();
|
||||
|
||||
Map<Object, Object> map = new LinkedHashMap<>();
|
||||
KahluaTableIterator iterator = table.iterator();
|
||||
|
||||
while (iterator.advance())
|
||||
{
|
||||
Object value = iterator.getValue();
|
||||
map.put(iterator.getKey(), value instanceof KahluaTable nested ? LuaTables.toJava(nested) : value);
|
||||
}
|
||||
|
||||
return Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* A deep, unmodifiable copy of {@code args} in Lua's types: number keys and values become
|
||||
* {@code Double}, lists become maps with the keys {@code 1.0}, {@code 2.0}, ....
|
||||
*
|
||||
* @throws IllegalArgumentException naming the first key or value that cannot be sent, or a
|
||||
* map or list that contains itself
|
||||
*/
|
||||
public static Map<Object, Object> copy(Map<?, ?> args) { return LuaTables.copy(args, "args", Collections.newSetFromMap(new IdentityHashMap<>())); }
|
||||
|
||||
/** A new table with the entries of {@code args}, a result of {@link #copy}; nested maps become nested tables. */
|
||||
public static KahluaTable toLua(Map<Object, Object> args, Supplier<KahluaTable> newTable)
|
||||
{
|
||||
KahluaTable table = newTable.get();
|
||||
|
||||
for (Map.Entry<Object, Object> entry : args.entrySet())
|
||||
{
|
||||
Object value = entry.getValue();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Object luaValue = value instanceof Map<?, ?> nested ? LuaTables.toLua((Map<Object, Object>) nested, newTable) : value;
|
||||
|
||||
table.rawset(entry.getKey(), luaValue);
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static Map<Object, Object> copy(Map<?, ?> map, String path, Set<Object> open)
|
||||
{
|
||||
if (!open.add(map)) throw new IllegalArgumentException("'" + path + "' contains itself.");
|
||||
|
||||
Map<Object, Object> copy = new LinkedHashMap<>();
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet())
|
||||
{
|
||||
Object key = LuaTables.key(entry.getKey(), path);
|
||||
String here = path + "[" + key + "]";
|
||||
|
||||
copy.put(key, LuaTables.value(entry.getValue(), here, open));
|
||||
}
|
||||
|
||||
open.remove(map);
|
||||
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
private static Map<Object, Object> copy(List<?> list, String path, Set<Object> open)
|
||||
{
|
||||
if (!open.add(list)) throw new IllegalArgumentException("'" + path + "' contains itself.");
|
||||
|
||||
Map<Object, Object> copy = new LinkedHashMap<>();
|
||||
|
||||
for (int i = 0; i < list.size(); i++) copy.put((double) (i + 1), LuaTables.value(list.get(i), path + "[" + (i + 1) + "]", open));
|
||||
|
||||
open.remove(list);
|
||||
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
private static Object key(@Nullable Object key, String path)
|
||||
{
|
||||
if (key instanceof String) return key;
|
||||
if (key instanceof Number number) return number.doubleValue();
|
||||
|
||||
throw new IllegalArgumentException("'" + path + "' has the key '" + key + "'" + LuaTables.typeOf(key) + "; keys are strings or numbers.");
|
||||
}
|
||||
|
||||
private static Object value(@Nullable Object value, String path, Set<Object> open)
|
||||
{
|
||||
return switch (value)
|
||||
{
|
||||
case String string -> string;
|
||||
case Boolean bool -> bool;
|
||||
case Number number -> number.doubleValue();
|
||||
case Map<?, ?> map -> LuaTables.copy(map, path, open);
|
||||
case List<?> list -> LuaTables.copy(list, path, open);
|
||||
case InventoryItem item -> item;
|
||||
case IsoDirections direction -> direction;
|
||||
case IsoDeadBody body -> body;
|
||||
case null -> throw new IllegalArgumentException("'" + path + "' is null.");
|
||||
default -> throw new IllegalArgumentException(
|
||||
"'" + path + "' is a '" + value.getClass().getName() + "'; values are strings, numbers, booleans, maps, lists, inventory items, directions, or dead bodies."
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
private static String typeOf(@Nullable Object value) { return value == null ? "" : " ('" + value.getClass().getName() + "')"; }
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import zombie.characters.Role;
|
||||
import zombie.commands.CommandBase;
|
||||
import zombie.commands.CommandName;
|
||||
import zombie.commands.RequiredCapability;
|
||||
import zombie.core.raknet.UdpConnection;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Command classes of mods in Build 42: subclasses of {@code CommandBase}, which
|
||||
* {@code GameServer.handleServerCommand} creates through {@code getConstructors()[0]} with
|
||||
* {@code (username, role, command, connection)}.
|
||||
*/
|
||||
public final class ModCommands
|
||||
{
|
||||
private static final Class<?>[] CONSTRUCTOR = {String.class, Role.class, String.class, UdpConnection.class};
|
||||
|
||||
/**
|
||||
* Names are inserted into a regular expression by {@code findCommandCls}, so they are limited
|
||||
* to word characters. With such names, {@code ^name\b} matches the input exactly when its first
|
||||
* word equals the name, ignoring case.
|
||||
*/
|
||||
private static final Pattern NAME = Pattern.compile("\\w+");
|
||||
|
||||
private ModCommands() {}
|
||||
|
||||
/**
|
||||
* Fails unless {@code command} is a usable Build 42 command whose names are not taken by
|
||||
* Project Zomboid's commands or by {@code registered}.
|
||||
*
|
||||
* @throws IllegalArgumentException listing every problem
|
||||
*/
|
||||
public static void check(Class<?> command, List<Class<?>> registered)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
int modifiers = command.getModifiers();
|
||||
|
||||
if (!CommandBase.class.isAssignableFrom(command)) problems.add("it does not extend '" + CommandBase.class.getName() + "'");
|
||||
if (!Modifier.isPublic(modifiers)) problems.add("it is not public");
|
||||
if (Modifier.isAbstract(modifiers)) problems.add("it is abstract");
|
||||
|
||||
Constructor<?>[] constructors = command.getConstructors();
|
||||
if (constructors.length != 1 || !Arrays.equals(constructors[0].getParameterTypes(), ModCommands.CONSTRUCTOR))
|
||||
problems.add("it needs exactly one public constructor '(String, Role, String, UdpConnection)'");
|
||||
|
||||
if (command.getAnnotationsByType(RequiredCapability.class).length == 0)
|
||||
problems.add("it has no @RequiredCapability, and Project Zomboid runs no command without one");
|
||||
|
||||
CommandName[] names = command.getAnnotationsByType(CommandName.class);
|
||||
if (names.length == 0) problems.add("it has no @CommandName");
|
||||
|
||||
for (CommandName name : names)
|
||||
{
|
||||
if (!ModCommands.NAME.matcher(name.name()).matches()) {
|
||||
problems.add("the name '" + name.name() + "' contains characters other than letters, digits, and '_'");
|
||||
continue;
|
||||
}
|
||||
|
||||
Class<?> owner = ModCommands.owner(name.name(), registered);
|
||||
if (owner != null) problems.add("the name '" + name.name() + "' is taken by '" + owner.getName() + "'");
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException("'" + command.getName() + "' cannot be a command: " + String.join("; ", problems) + ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* The first class of {@code commands} that is not disabled and has a name that {@code input}
|
||||
* starts with, matched like {@code CommandBase.findCommandCls} matches Project Zomboid's
|
||||
* commands; {@code null} when there is none.
|
||||
*/
|
||||
public static @Nullable Class<?> find(List<Class<?>> commands, String input)
|
||||
{
|
||||
for (Class<?> command : commands)
|
||||
{
|
||||
if (CommandBase.isDisabled(command)) continue;
|
||||
|
||||
for (CommandName name : command.getAnnotationsByType(CommandName.class)) {
|
||||
if (Pattern.compile("^" + name.name() + "\\b", Pattern.CASE_INSENSITIVE).matcher(input).find()) return command;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The class among Project Zomboid's commands and {@code registered} that has {@code name}, ignoring case. */
|
||||
private static @Nullable Class<?> owner(String name, List<Class<?>> registered)
|
||||
{
|
||||
Set<Class<?>> taken = new LinkedHashSet<>(Arrays.<Class<?>>asList(CommandBase.getSubClasses()));
|
||||
taken.addAll(registered);
|
||||
|
||||
for (Class<?> command : taken)
|
||||
{
|
||||
for (CommandName existing : command.getAnnotationsByType(CommandName.class)) {
|
||||
if (existing.name().equalsIgnoreCase(name)) return command;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Commands of mods in Build 42: checks for registered admin command classes and the lookup that
|
||||
* mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion
|
||||
* of their Lua tables.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+91
@@ -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);
|
||||
}
|
||||
}
|
||||
+114
@@ -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");
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ClientCommandEvent;
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.LuaTables;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import se.krka.kahlua.vm.KahluaTable;
|
||||
|
||||
import zombie.characters.IsoPlayer;
|
||||
|
||||
/**
|
||||
* Hooks called by patched {@code zombie.network.GameServer.receiveClientCommand} code, on the main
|
||||
* thread (client commands are queued for the main loop). Exceptions are caught here; the command
|
||||
* then reaches Lua as in vanilla.
|
||||
*/
|
||||
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
|
||||
public final class ClientCommandHooks
|
||||
{
|
||||
private ClientCommandHooks() {}
|
||||
|
||||
/**
|
||||
* Called directly before {@code LuaEventManager.triggerEvent("OnClientCommand", module, command, player, args)},
|
||||
* after the vanilla checks (the player exists; {@code vehicle.remove} only with permission).
|
||||
* Posts {@link ClientCommandEvent} when a mod listens for it.
|
||||
*
|
||||
* @param args {@code null} when the client sent no arguments
|
||||
* @return {@code true} when a listener cancelled the event, which skips the Lua event
|
||||
*/
|
||||
public static boolean onClientCommand(String module, String command, IsoPlayer player, @Nullable KahluaTable args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ForgeInstance.FORGE.hasListeners(ClientCommandEvent.class)) return false;
|
||||
|
||||
ClientCommandEvent event = new ClientCommandEvent(
|
||||
ClientCommandChannel.ref(player),
|
||||
module, command,
|
||||
LuaTables.toJava(args)
|
||||
);
|
||||
|
||||
ForgeInstance.FORGE.post(event);
|
||||
|
||||
return event.isCancelled();
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
t.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Hooks called by patched {@code zombie.commands.CommandBase} code, on the main thread: the
|
||||
* server console, RCON, and chat commands all run there. Exceptions are caught here, and the
|
||||
* vanilla value is returned.
|
||||
*/
|
||||
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
|
||||
public final class CommandHooks
|
||||
{
|
||||
private CommandHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces the {@code null} that {@code CommandBase.findCommandCls} returns when no command of
|
||||
* Project Zomboid matches {@code command}: the mods' command class for it, or {@code null}.
|
||||
*/
|
||||
public static @Nullable Class<?> findCommand(@Nullable Class<?> vanilla, String command)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ModCommands.find(ForgeInstance.FORGE.commands(), command);
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
t.printStackTrace();
|
||||
return vanilla;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the array that {@code CommandBase.getSubClasses} returns: Project Zomboid's
|
||||
* command classes followed by the mods', in registration order. Without mod commands, the
|
||||
* vanilla array itself.
|
||||
*/
|
||||
public static Class<?>[] listCommands(Class<?>[] vanilla)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<Class<?>> mods = ForgeInstance.FORGE.commands();
|
||||
if (mods.isEmpty()) return vanilla;
|
||||
|
||||
Class<?>[] all = Arrays.copyOf(vanilla, vanilla.length + mods.size());
|
||||
for (int i = 0; i < mods.size(); i++) all[vanilla.length + i] = mods.get(i);
|
||||
|
||||
return all;
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
t.printStackTrace();
|
||||
return vanilla;
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -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); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -17,7 +17,7 @@ import java.nio.file.Path;
|
||||
* {@code GameServer$1}. Exceptions are caught here: the main loop logs repeated exceptions only
|
||||
* a limited number of times, and an exception in the shutdown hook would skip the world save.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
|
||||
public final class ServerHooks
|
||||
{
|
||||
private ServerHooks() {}
|
||||
@@ -75,7 +75,7 @@ public final class ServerHooks
|
||||
ForgeInstance.FORGE.started();
|
||||
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
|
||||
}
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,7 +87,7 @@ public final class ServerHooks
|
||||
public static void onTick()
|
||||
{
|
||||
try { ForgeInstance.FORGE.tick(); }
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,6 +105,6 @@ public final class ServerHooks
|
||||
System.out.println("[ZomboidForge] Server stopping.");
|
||||
ForgeInstance.FORGE.stopping();
|
||||
}
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
+49
@@ -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;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -3,7 +3,7 @@ package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
|
||||
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
|
||||
public final class StorageHooks
|
||||
{
|
||||
private StorageHooks() {}
|
||||
@@ -20,6 +20,6 @@ public final class StorageHooks
|
||||
if (running) ForgeInstance.FORGE.backupStarted();
|
||||
else ForgeInstance.FORGE.backupFinished();
|
||||
}
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
+51
@@ -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));
|
||||
}
|
||||
}
|
||||
+34
@@ -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);
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -11,6 +11,7 @@ import zombie.scripting.objects.VehicleScript;
|
||||
import zombie.vehicles.BaseVehicle;
|
||||
|
||||
/** Hooks called by patched {@code zombie.characters.IsoZombie} code. */
|
||||
@SuppressWarnings("unused")
|
||||
public final class ZombieVehicleHooks
|
||||
{
|
||||
/**
|
||||
@@ -33,10 +34,8 @@ public final class ZombieVehicleHooks
|
||||
* and is skipped here.
|
||||
*/
|
||||
public static @Nullable Vector3f getIntersectPoint(
|
||||
@NotNull BaseVehicle vehicle,
|
||||
@NotNull Vector3f start,
|
||||
@NotNull Vector3f end,
|
||||
@Nullable Vector3f result
|
||||
BaseVehicle vehicle, Vector3f start,
|
||||
Vector3f end, @Nullable Vector3f result
|
||||
) {
|
||||
VehicleScript script = vehicle.getScript();
|
||||
Vector3f extents = script.getExtents();
|
||||
|
||||
+28
@@ -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);
|
||||
}
|
||||
}
|
||||
+60
@@ -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();
|
||||
}
|
||||
}
|
||||
+40
@@ -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++; }
|
||||
}
|
||||
Loaded 100 of 200 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user