Compare commits
17
Commits
v0.4.0
..
43df96391c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43df96391c | ||
|
|
607d5b2b32 | ||
|
|
07dc3f0fad | ||
|
|
7ffcbdbb06 | ||
|
|
9b721bfd45 | ||
|
|
88cd68b5cb | ||
|
|
529e48ed5a | ||
|
|
dd113961e6 | ||
|
|
eb09a77941 | ||
|
|
2081235433 | ||
|
|
e932c7401a | ||
|
|
56e01c5cbe | ||
|
|
38a15db299 | ||
|
|
05a4b9dbd9 | ||
|
|
900f65b591 | ||
|
|
05eed7e205 | ||
|
|
151e1d459f |
No files matched your search
+10
-4
@@ -142,7 +142,9 @@ public final class ShopMod extends Mod
|
||||
@Override
|
||||
public void onLoad() // main thread, registration only
|
||||
{
|
||||
this.events().onMain(TickEvent.class, event -> { /* every frame, on the main thread */ });
|
||||
this.events().onMain(TickEvent.class, event -> {
|
||||
/* every frame, on the main thread */
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -150,8 +152,12 @@ public final class ShopMod extends Mod
|
||||
{
|
||||
this.modThread().scheduleAtFixedRate(() -> {
|
||||
// on zf-mod-shop: slow work, no game objects
|
||||
this.main().submit(GameServer::getPlayerCount) // game objects only on the main thread
|
||||
.thenAcceptAsync(players -> this.logger().log(INFO, players + " online"), this.modThread());
|
||||
this.main()
|
||||
.submit(GameServer::getPlayerCount) // game objects only on the main thread
|
||||
.thenAcceptAsync(
|
||||
players -> this.logger().log(INFO, players + " online"),
|
||||
this.modThread()
|
||||
);
|
||||
}, Duration.ZERO, Duration.ofMinutes(1));
|
||||
}
|
||||
|
||||
@@ -162,7 +168,7 @@ public final class ShopMod extends Mod
|
||||
|
||||
## Services
|
||||
|
||||
Methods of `Mod`, usable from the constructor on (also in field initializers):
|
||||
Methods of `Mod`, usable from the constructor on, and in field initializers:
|
||||
|
||||
| Method | Returns | Use |
|
||||
|--------------------|------------------|---------------------------------------------------------------|
|
||||
|
||||
@@ -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,26 @@ 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`) |
|
||||
| `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 +69,16 @@ 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.
|
||||
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large worlds.
|
||||
|
||||
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
||||
For local testing use `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
||||
|
||||
## Mods
|
||||
|
||||
@@ -95,24 +104,24 @@ forge/
|
||||
podman run ... -v ./forge:/forge zomboidforge
|
||||
```
|
||||
|
||||
Mods are trusted code. They run inside the server process with its full privileges: they can
|
||||
read and write any file the server can, open network connections, and stop the server. The
|
||||
class loader isolation and the startup checks catch mistakes; they do not contain a malicious
|
||||
mod. Install only mods whose authors you trust.
|
||||
|
||||
A mod's settings live in its `config.toml`. When the file is missing, it is created from the
|
||||
mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a
|
||||
file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]`
|
||||
table switches the mod off; mods that depend on it then fail to load.
|
||||
> [!WARNING]
|
||||
> Mods are trusted code. <br>
|
||||
> They run inside the server process with its full privileges, which means they can
|
||||
> read and write any file the server can, open network connections, and stop the server. <br>
|
||||
> The class loader isolation and the startup checks catch mistakes; they do not contain
|
||||
> or restrict a malicious mod.
|
||||
>
|
||||
> Install only mods whose authors you trust, or whose code you can verify yourself!
|
||||
|
||||
Mods keep their data in `zomboidforge.db` in the world's save folder
|
||||
(`/data/Saves/Multiplayer/<server>/`). Vanilla backups include it, and deleting the world
|
||||
deletes it.
|
||||
|
||||
A mod that cannot be loaded stops the server with exit code 1, and the log lists every
|
||||
problem: a missing or too old dependency, an unsupported game version, game classes or methods
|
||||
that do not exist in the running version, invalid settings, or an exception in the mod's
|
||||
startup code. Changes to mods and their settings take effect when the server restarts.
|
||||
problem. For example, a missing or too old dependency, an unsupported game version,
|
||||
game classes or methods that do not exist in the running version, invalid settings,
|
||||
or an exception in the mod's startup code. Changes to mods and their settings take
|
||||
effect when the server restarts.
|
||||
|
||||
`forge.toml`, every key optional:
|
||||
|
||||
@@ -122,6 +131,9 @@ budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
|
||||
[shutdown]
|
||||
timeout_s = 10 # time the mods' threads get to finish when the server stops
|
||||
|
||||
[features]
|
||||
experimental_performance = false # default false; ZF_EXPERIMENTAL_PERFORMANCE takes precedence when set
|
||||
```
|
||||
|
||||
### Mod development
|
||||
@@ -139,9 +151,11 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
|
||||
./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar
|
||||
```
|
||||
|
||||
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
|
||||
`pz.version` in `gradle.properties` selects the targeted version. `mod-tools` (the build-time
|
||||
mod checks) and `gradle-plugin` (the plugin for mod authors) are for mod builds, not the server.
|
||||
> [!IMPORTANT]
|
||||
> Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent. <br>
|
||||
> `pz.version` in `gradle.properties` selects the targeted version. <br>
|
||||
> `mod-tools` (the build-time mod checks) and `gradle-plugin` (the plugin for mod authors)
|
||||
> are for mod builds, not the server.
|
||||
|
||||
Release tags publish `api`, `mod-tools`, and the Gradle plugin to the Gitea Maven registry
|
||||
(`.gitea/workflows/publish.yml`, `ci/publish.sh`); tags with a `-` are only tested.
|
||||
+15
-1
@@ -17,6 +17,7 @@ public final class B42PatchSet implements PatchSet
|
||||
new ServerStartedPatch(),
|
||||
new ServerTickPatch(),
|
||||
new ServerStoppingPatch(),
|
||||
new ZipBackupSinglePassPerformancePatch(),
|
||||
new BackupStoragePatch(),
|
||||
new CommandLookupPatch(),
|
||||
new CommandListPatch(),
|
||||
@@ -24,7 +25,20 @@ public final class B42PatchSet implements PatchSet
|
||||
new IsoZombieVehiclePerformancePatch(),
|
||||
new IsoZombieNetworkComponentPerformancePatch(),
|
||||
new IsoZombieSpotChancePerformancePatch(),
|
||||
new IsoGameCharacterStateMachinePerformancePatch()
|
||||
new IsoGameCharacterStateMachinePerformancePatch(),
|
||||
new ZombieVoronoiPerformancePatch(),
|
||||
new ZomboidFileSystemInitPerformancePatch(),
|
||||
new ServerMapCellBudgetPerformancePatch(),
|
||||
new WorldGenUtilsPlacementPerformancePatch(),
|
||||
new WorldGenChunkRulesPerformancePatch(),
|
||||
new BitHeaderPoolPerformancePatch(),
|
||||
new IsoChunkSaveDirectoryPerformancePatch(),
|
||||
new RolesSavePerformancePatch(),
|
||||
new ServerChunkLoaderQuitPerformancePatch(),
|
||||
new ZipBackupWaitPerformancePatch(),
|
||||
new ServerPlayersVehiclesRoundPerformancePatch(),
|
||||
new ServerPlayersVehiclesStopPerformancePatch(),
|
||||
new ServerPlayerDBSaveWaitPerformancePatch()
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch;
|
||||
import dev.overlord.zomboidforge.patcher.patches.CancellableHookPatch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
+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.ReturnHookPatch;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package dev.overlord.zomboidforge.compat.b42.patches;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+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")));
|
||||
}
|
||||
}
|
||||
+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")));
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
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 five Build 42 waiting-loop patches: each with its target, number of sleeps and hook. */
|
||||
class ThreadSleepPatchesTest
|
||||
{
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks";
|
||||
|
||||
/** Each patch with its target method, number of sleeps and hook. */
|
||||
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, 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, "pollSleep"),
|
||||
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "pollSleep"),
|
||||
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "vehicleRoundSleep"),
|
||||
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "wakeVehiclesAndPoll")
|
||||
);
|
||||
}
|
||||
|
||||
/** 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, 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")));
|
||||
}
|
||||
}
|
||||
+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");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -16,7 +16,7 @@ import zombie.characters.IsoPlayer;
|
||||
* thread (client commands are queued for the main loop). Exceptions are caught here; the command
|
||||
* then reaches Lua as in vanilla.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
|
||||
public final class ClientCommandHooks
|
||||
{
|
||||
private ClientCommandHooks() {}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import java.util.List;
|
||||
* server console, RCON, and chat commands all run there. Exceptions are caught here, and the
|
||||
* vanilla value is returned.
|
||||
*/
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
|
||||
public final class CommandHooks
|
||||
{
|
||||
private CommandHooks() {}
|
||||
|
||||
+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] Roles are saved without a transaction: '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] Roles are saved without a 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] Committing the saved roles failed: " + e); }
|
||||
finally
|
||||
{
|
||||
try { connection.setAutoCommit(true); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Switching the database back to autocommit failed: " + e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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() {}
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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() {}
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+1
@@ -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
|
||||
{
|
||||
/**
|
||||
|
||||
+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++; }
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The file list of {@code ZomboidFileSystem.searchFolders} and the paths of
|
||||
* {@code ZomboidFileSystem.getRelativeFile(URI, String)}, with fewer file system calls.
|
||||
*
|
||||
* <p>Vanilla stats every entry under the media folder ({@code File.isDirectory}) and lists every
|
||||
* folder; {@code init} then stats every entry again and builds two URIs per entry for its
|
||||
* relative path. Here one walk stats each entry once and remembers which ones are folders.
|
||||
*/
|
||||
public final class MediaScan
|
||||
{
|
||||
private MediaScan() {}
|
||||
|
||||
/**
|
||||
* Appends what {@code searchFolders(root)} appends to {@code loadList}: every file, and every
|
||||
* folder whose path contains {@code media/maps/}, depth first, in directory order, links
|
||||
* followed. Returns for each appended path whether it is a folder, for the paths whose
|
||||
* appended form names the same file (vanilla appends {@code path.replace("\\", "/")
|
||||
* .replace("./", "")}, which may name another file).
|
||||
*/
|
||||
public static Map<String, Boolean> walk(File root, List<String> loadList) throws IOException
|
||||
{
|
||||
Map<String, Boolean> folders = new HashMap<>();
|
||||
|
||||
Files.walkFileTree(root.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>()
|
||||
{
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attributes)
|
||||
{
|
||||
String path = dir.toString();
|
||||
String entry = MediaScan.entry(path);
|
||||
|
||||
if (entry.contains("media/maps/")) loadList.add(entry);
|
||||
if (entry.equals(path)) folders.put(entry, Boolean.TRUE);
|
||||
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
|
||||
{
|
||||
MediaScan.addFile(file.toString(), loadList, folders);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
// Vanilla's isDirectory() is false for an entry it cannot read, so it appends it as a file.
|
||||
@Override
|
||||
public FileVisitResult visitFileFailed(Path file, IOException exception)
|
||||
{
|
||||
MediaScan.addFile(file.toString(), loadList, folders);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
|
||||
return folders;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code getRelativeFile(root, path)}: the path relative to {@code root} (a folder URI from
|
||||
* {@code File.toURI()}), lowercased, with a trailing slash for folders; {@code path} itself
|
||||
* when it lies outside {@code root}. {@code File.toURI()} appends the slash when the
|
||||
* <em>lowercased</em> path is a folder: known paths come from {@code folders}, other
|
||||
* lowercased paths are checked on disk, as vanilla does.
|
||||
*/
|
||||
public static String relativePath(URI root, String path, Map<String, Boolean> folders)
|
||||
{
|
||||
String absolutePath = new File(path).getAbsolutePath();
|
||||
String lowercase = absolutePath.toLowerCase(Locale.ENGLISH);
|
||||
boolean folder = MediaScan.isFolder(lowercase, folders);
|
||||
|
||||
String uriPath = lowercase.replace(File.separatorChar, '/');
|
||||
if (!uriPath.startsWith("/")) uriPath = "/" + uriPath;
|
||||
if (folder && !uriPath.endsWith("/")) uriPath = uriPath + "/";
|
||||
|
||||
String rootPath = root.getPath();
|
||||
if (!rootPath.endsWith("/")) rootPath = rootPath + "/";
|
||||
if (!uriPath.startsWith(rootPath)) return path;
|
||||
|
||||
String relative = uriPath.substring(rootPath.length());
|
||||
if (path.endsWith("/") && !relative.endsWith("/")) relative = relative + "/";
|
||||
|
||||
return relative;
|
||||
}
|
||||
|
||||
/** {@code new File(path).isDirectory()}, from {@code folders} when the path is known. */
|
||||
public static boolean isFolder(String path, Map<String, Boolean> folders)
|
||||
{
|
||||
Boolean known = folders.get(path);
|
||||
return known != null ? known : new File(path).isDirectory();
|
||||
}
|
||||
|
||||
private static void addFile(String path, List<String> loadList, Map<String, Boolean> folders)
|
||||
{
|
||||
String entry = MediaScan.entry(path);
|
||||
|
||||
loadList.add(entry);
|
||||
if (entry.equals(path)) folders.put(entry, Boolean.FALSE);
|
||||
}
|
||||
|
||||
/** The form {@code searchFolders} appends. */
|
||||
private static String entry(String path)
|
||||
{
|
||||
return path.replace("\\", "/").replace("./", "");
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.Zip64Mode;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.NonReadableChannelException;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryIteratorException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
/**
|
||||
* A zip file of uncompressed (STORED) entries, Zip64 as needed, as {@code ZipBackup} writes,
|
||||
* written in one pass from files that a thread pool reads in parallel.
|
||||
*
|
||||
* <p>{@code ZipBackup.makeBackupFile} hands every file to {@code ParallelScatterZipCreator}, whose
|
||||
* threads copy the files into one temporary file per thread, which it then copies into the zip:
|
||||
* every byte is written three times. Here reader threads list the folders and read each file
|
||||
* with its CRC into memory, and the thread that adds a folder writes the files as entries with
|
||||
* size and CRC known: each byte is written once, each header once. Files of more than
|
||||
* {@value #LARGE} bytes are not held in memory: the writing thread copies them and patches size
|
||||
* and CRC into the entry's header afterwards. Read files waiting to be written hold at most
|
||||
* {@value #BUDGET} bytes.
|
||||
*
|
||||
* <p>Entries appear in the order their files were read, which varies between runs, as with
|
||||
* {@code ParallelScatterZipCreator}. The file is a valid zip only after {@link #finish()}.
|
||||
*/
|
||||
public final class ParallelZip implements Closeable
|
||||
{
|
||||
/** Files larger than this are copied by the writing thread instead of read into memory. */
|
||||
private static final int LARGE = 4 << 20;
|
||||
/** Bytes of read files that wait for the writing thread, at most. */
|
||||
private static final int BUDGET = 64 << 20;
|
||||
/** Write buffer of the zip file. */
|
||||
private static final int BUFFER = 1 << 20;
|
||||
|
||||
private static final AtomicInteger THREADS = new AtomicInteger();
|
||||
|
||||
/** A file read with its CRC; {@code permits} of the budget are released once it is written. */
|
||||
private record Loaded(String name, byte[] data, long crc, int permits) implements Item {}
|
||||
|
||||
/** A file the writing thread copies itself; {@code size} as listed. */
|
||||
private record Large(String name, Path file, long size) implements Item {}
|
||||
|
||||
/** An unexpected failure of a reader thread. */
|
||||
private record Failed(Throwable cause) implements Item {}
|
||||
|
||||
/** Every folder of the current {@link #addFolder} is read. */
|
||||
private record Done() implements Item {}
|
||||
|
||||
private sealed interface Item permits Loaded, Large, Failed, Done {}
|
||||
|
||||
private final BufferedChannel channel;
|
||||
private final ZipArchiveOutputStream zip;
|
||||
private final ExecutorService readers;
|
||||
private final Consumer<IOException> failures;
|
||||
private final Semaphore budget = new Semaphore(ParallelZip.BUDGET);
|
||||
private boolean finished;
|
||||
|
||||
/**
|
||||
* Creates or truncates {@code file}, with {@code threads} reader threads. Files and folders
|
||||
* that cannot be read are passed to {@code failures}, from any of these threads, and left out.
|
||||
*/
|
||||
public ParallelZip(Path file, String comment, int threads, Consumer<IOException> failures) throws IOException
|
||||
{
|
||||
this.channel = new BufferedChannel(FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
|
||||
this.zip = new ZipArchiveOutputStream(this.channel);
|
||||
this.failures = failures;
|
||||
this.readers = Executors.newFixedThreadPool(threads, task -> {
|
||||
Thread thread = new Thread(task, "zf-backup-reader-" + ParallelZip.THREADS.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
this.zip.setUseZip64(Zip64Mode.AsNeeded);
|
||||
this.zip.setMethod(ZipArchiveEntry.STORED);
|
||||
this.zip.setComment(comment);
|
||||
}
|
||||
|
||||
/** Adds the entry {@code name} with the UTF-8 bytes of {@code text}. */
|
||||
public void addText(String name, String text) throws IOException
|
||||
{
|
||||
byte[] data = text.getBytes(StandardCharsets.UTF_8);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(data);
|
||||
|
||||
this.write(new Loaded(name, data, crc.getValue(), 0));
|
||||
}
|
||||
|
||||
/** Adds the entry {@code name} with the content of {@code file}, on the calling thread. */
|
||||
public void addFile(String name, Path file) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
Item item = this.read(name, file, Files.readAttributes(file, BasicFileAttributes.class));
|
||||
if (item != null) this.write(item);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
throw new InterruptedIOException("Interrupted while adding '" + file + "'.");
|
||||
}
|
||||
catch (IOException e) { this.failures.accept(e); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds every file in {@code folder} as the entry {@code prefix/<path relative to folder>}, and
|
||||
* the files of each subfolder for which {@code descend} holds, recursively; as
|
||||
* {@code ZipBackup.zipDir}, links are not followed into folders, and a link to a file is
|
||||
* added with the file's content. Returns once every entry is written; nothing when
|
||||
* {@code folder} is no folder.
|
||||
*/
|
||||
@SuppressWarnings("DeconstructionCanBeUsed")
|
||||
public void addFolder(String prefix, Path folder, Predicate<Path> descend) throws IOException
|
||||
{
|
||||
if (!Files.isDirectory(folder)) return;
|
||||
|
||||
BlockingQueue<Item> ready = new LinkedBlockingQueue<>();
|
||||
AtomicInteger pending = new AtomicInteger(1);
|
||||
|
||||
this.readers.execute(() -> this.readFolder(prefix, folder, folder, descend, ready, pending));
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Item item = ready.take();
|
||||
|
||||
if (item instanceof Done) return;
|
||||
if (item instanceof Failed failed) throw new IOException("Reading '" + folder + "' failed.", failed.cause());
|
||||
|
||||
this.write(item);
|
||||
}
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
throw new InterruptedIOException("Interrupted while adding '" + folder + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the central directory: the file is a complete zip. */
|
||||
public void finish() throws IOException
|
||||
{
|
||||
this.zip.finish();
|
||||
this.finished = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the reader threads and closes the file; without {@link #finish()} the file has no
|
||||
* central directory, so no tool takes it for a complete backup.
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
this.readers.shutdownNow();
|
||||
|
||||
if (this.finished) this.zip.close();
|
||||
else this.channel.close();
|
||||
}
|
||||
|
||||
/** On a reader thread: lists {@code folder}, queues its files, and starts a task per subfolder to descend into. */
|
||||
private void readFolder(String prefix, Path root, Path folder, Predicate<Path> descend, BlockingQueue<Item> ready, AtomicInteger pending)
|
||||
{
|
||||
try (DirectoryStream<Path> entries = Files.newDirectoryStream(folder))
|
||||
{
|
||||
for (Path entry : entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
BasicFileAttributes attributes = Files.readAttributes(entry, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
|
||||
if (attributes.isDirectory())
|
||||
{
|
||||
if (!descend.test(entry)) continue;
|
||||
|
||||
pending.incrementAndGet();
|
||||
this.readers.execute(() -> this.readFolder(prefix, root, entry, descend, ready, pending));
|
||||
continue;
|
||||
}
|
||||
|
||||
String name = prefix + File.separator + root.relativize(entry).toString().replace("/", File.separator);
|
||||
Item item = this.read(name, entry, attributes);
|
||||
if (item != null) ready.add(item);
|
||||
}
|
||||
catch (IOException e) { this.failures.accept(e); }
|
||||
}
|
||||
}
|
||||
catch (IOException e) { this.failures.accept(e); }
|
||||
catch (DirectoryIteratorException e) { this.failures.accept(e.getCause()); }
|
||||
// Interrupted by close(), or an unexpected failure: addFolder throws.
|
||||
catch (Throwable t) { ready.add(new Failed(t)); }
|
||||
finally { if (pending.decrementAndGet() == 0) ready.add(new Done()); }
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code file} as an item to write: read with its CRC, or, when large, to be copied by the
|
||||
* writing thread. {@code null} for files that cannot be read (sockets and the like).
|
||||
*/
|
||||
private @Nullable Item read(String name, Path file, BasicFileAttributes attributes) throws IOException, InterruptedException
|
||||
{
|
||||
if (attributes.isOther()) return null;
|
||||
|
||||
// A link: the size of the file it points to.
|
||||
long size = attributes.isSymbolicLink() ? Files.size(file) : attributes.size();
|
||||
if (size > ParallelZip.LARGE) return new Large(name, file, size);
|
||||
|
||||
int permits = (int) size;
|
||||
this.budget.acquire(permits);
|
||||
|
||||
try
|
||||
{
|
||||
byte[] data = Files.readAllBytes(file);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(data);
|
||||
|
||||
return new Loaded(name, data, crc.getValue(), permits);
|
||||
}
|
||||
catch (IOException | RuntimeException | Error e)
|
||||
{
|
||||
this.budget.release(permits);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void write(Item item) throws IOException
|
||||
{
|
||||
switch (item)
|
||||
{
|
||||
case Loaded loaded ->
|
||||
{
|
||||
ZipArchiveEntry entry = new ZipArchiveEntry(loaded.name());
|
||||
entry.setMethod(ZipArchiveEntry.STORED);
|
||||
entry.setSize(loaded.data().length);
|
||||
entry.setCompressedSize(loaded.data().length);
|
||||
entry.setCrc(loaded.crc());
|
||||
|
||||
// Size and CRC known: written once, no header rewrite.
|
||||
this.zip.addRawArchiveEntry(entry, new ByteArrayInputStream(loaded.data()));
|
||||
this.budget.release(loaded.permits());
|
||||
}
|
||||
case Large large ->
|
||||
{
|
||||
InputStream input;
|
||||
try { input = Files.newInputStream(large.file()); }
|
||||
catch (IOException e) { this.failures.accept(e); return; }
|
||||
|
||||
// The listed size keeps the header free of Zip64 fields below 4 GiB; the zip
|
||||
// stream then writes the copied size and CRC into the header.
|
||||
ZipArchiveEntry entry = new ZipArchiveEntry(large.name());
|
||||
entry.setMethod(ZipArchiveEntry.STORED);
|
||||
entry.setSize(large.size());
|
||||
|
||||
try (input)
|
||||
{
|
||||
this.zip.putArchiveEntry(entry);
|
||||
input.transferTo(this.zip);
|
||||
this.zip.closeArchiveEntry();
|
||||
}
|
||||
}
|
||||
case Failed failed -> throw new IOException(failed.cause());
|
||||
case Done done -> throw new IllegalStateException("'Done' is no entry.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link FileChannel} with a write buffer: the zip stream writes headers and data in small
|
||||
* pieces. Moving the position writes the buffer first, so patched headers land where the
|
||||
* zip stream puts them.
|
||||
*/
|
||||
private static final class BufferedChannel implements SeekableByteChannel
|
||||
{
|
||||
private final FileChannel channel;
|
||||
private final ByteBuffer buffer = ByteBuffer.allocate(ParallelZip.BUFFER);
|
||||
|
||||
BufferedChannel(FileChannel channel) { this.channel = channel; }
|
||||
|
||||
@Override
|
||||
public int write(ByteBuffer source) throws IOException
|
||||
{
|
||||
int length = source.remaining();
|
||||
|
||||
if (length > this.buffer.remaining()) this.flush();
|
||||
|
||||
if (length >= this.buffer.capacity())
|
||||
{
|
||||
while (source.hasRemaining()) this.channel.write(source);
|
||||
}
|
||||
else this.buffer.put(source);
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long position() throws IOException { return this.channel.position() + this.buffer.position(); }
|
||||
|
||||
@Override
|
||||
public SeekableByteChannel position(long position) throws IOException
|
||||
{
|
||||
this.flush();
|
||||
this.channel.position(position);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long size() throws IOException
|
||||
{
|
||||
this.flush();
|
||||
|
||||
return this.channel.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SeekableByteChannel truncate(long size) throws IOException
|
||||
{
|
||||
this.flush();
|
||||
this.channel.truncate(size);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(ByteBuffer target) { throw new NonReadableChannelException(); }
|
||||
|
||||
@Override
|
||||
public boolean isOpen() { return this.channel.isOpen(); }
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
try { this.flush(); }
|
||||
finally { this.channel.close(); }
|
||||
}
|
||||
|
||||
private void flush() throws IOException
|
||||
{
|
||||
this.buffer.flip();
|
||||
while (this.buffer.hasRemaining()) this.channel.write(this.buffer);
|
||||
this.buffer.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
|
||||
/**
|
||||
* An object pool that keeps one {@link ArrayDeque} per thread behind the
|
||||
* {@link ConcurrentLinkedDeque} methods {@link #poll()}, {@link #offer} and {@link #size()}:
|
||||
* a thread polls what it offered, without synchronisation and without the node that
|
||||
* {@code ConcurrentLinkedDeque} allocates per offer. Every other method works on the (empty)
|
||||
* shared deque, so it suits only callers that use these three.
|
||||
*
|
||||
* <p>A pool keeps at most {@value #CAPACITY} objects per thread; further offers are dropped
|
||||
* and the objects left to the garbage collector. Objects taken on one thread and returned on
|
||||
* another end up in the second thread's pool, up to that limit.
|
||||
*/
|
||||
public final class PerThreadDeque<E> extends ConcurrentLinkedDeque<E>
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final int CAPACITY = 1024;
|
||||
|
||||
private final transient ThreadLocal<ArrayDeque<E>> pools = ThreadLocal.withInitial(ArrayDeque::new);
|
||||
|
||||
/** The calling thread's most recently offered object, or {@code null} when its pool is empty. */
|
||||
@Override
|
||||
public @Nullable E poll() { return this.pools.get().pollLast(); }
|
||||
|
||||
/** Adds {@code element} to the calling thread's pool unless it is full. Always {@code true}, as the shared deque. */
|
||||
@Override
|
||||
public boolean offer(E element)
|
||||
{
|
||||
Objects.requireNonNull(element);
|
||||
|
||||
ArrayDeque<E> pool = this.pools.get();
|
||||
if (pool.size() < PerThreadDeque.CAPACITY) pool.addLast(element);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The size of the calling thread's pool. */
|
||||
@Override
|
||||
public int size() { return this.pools.get().size(); }
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The tile rules of the world generation ({@code WorldGenUtils.canPlace},
|
||||
* {@code WorldGenChunk.isProtected} and {@code cleanChunk}) with compiled patterns cached.
|
||||
*
|
||||
* <p>Vanilla turns each rule into a regular expression per call ({@code "^" + rule}, then
|
||||
* {@code .} quoted, {@code *} to {@code .*}, {@code ?} to {@code .?}) and matches it with
|
||||
* {@code String.matches}, which compiles a new {@link Pattern} each time; this happens for every
|
||||
* rule of every square of a new chunk. {@code String.matches(regex)} is
|
||||
* {@code Pattern.compile(regex).matcher(this).matches()}, so a pattern compiled once gives the
|
||||
* same answers. The rules come from the biome definitions, so the caches stay small. A rule that
|
||||
* does not compile is not cached and throws on every call, as in vanilla.
|
||||
*/
|
||||
public final class TileRules
|
||||
{
|
||||
private static final ConcurrentHashMap<String, Pattern> PATTERNS = new ConcurrentHashMap<>();
|
||||
private static final ConcurrentHashMap<String, Placement> PLACEMENTS = new ConcurrentHashMap<>();
|
||||
private static final ConcurrentHashMap<String, Pattern> PROTECTED = new ConcurrentHashMap<>();
|
||||
|
||||
private TileRules() {}
|
||||
|
||||
/** A placement rule: {@code allows} is {@code false} for rules starting with {@code !}. */
|
||||
private record Placement(boolean allows, Pattern pattern) {}
|
||||
|
||||
/** {@code input.matches(regex)}. */
|
||||
public static boolean matches(String input, String regex)
|
||||
{
|
||||
// Vanilla calls matches on the input: a null input fails before the regex is compiled.
|
||||
Objects.requireNonNull(input);
|
||||
|
||||
Pattern pattern = TileRules.PATTERNS.get(regex);
|
||||
if (pattern == null)
|
||||
{
|
||||
pattern = Pattern.compile(regex);
|
||||
TileRules.PATTERNS.putIfAbsent(regex, pattern);
|
||||
}
|
||||
|
||||
return pattern.matcher(input).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code WorldGenUtils.canPlace(placement, floorName)}: the last rule that matches decides,
|
||||
* {@code false} when none matches.
|
||||
*/
|
||||
public static boolean canPlace(List<?> placement, String floorName)
|
||||
{
|
||||
boolean toBePlaced = false;
|
||||
|
||||
for (Object entry : placement)
|
||||
{
|
||||
String rule = (String) entry;
|
||||
Placement compiled = TileRules.PLACEMENTS.get(rule);
|
||||
|
||||
// Vanilla reads the rule first, then calls matches on floorName, then compiles.
|
||||
Objects.requireNonNull(floorName);
|
||||
if (compiled == null)
|
||||
{
|
||||
compiled = TileRules.placement(rule);
|
||||
TileRules.PLACEMENTS.putIfAbsent(rule, compiled);
|
||||
}
|
||||
if (compiled.pattern().matcher(floorName).matches()) toBePlaced = compiled.allows();
|
||||
}
|
||||
|
||||
return toBePlaced;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code WorldGenChunk.isProtected(protectedTiles, tile)}: whether any rule matches. Vanilla
|
||||
* builds {@code "^" + rule}, so a {@code null} rule is the text {@code null}; it shares the
|
||||
* cache key of that text.
|
||||
*/
|
||||
public static boolean isProtected(List<?> protectedTiles, String tile)
|
||||
{
|
||||
for (Object entry : protectedTiles)
|
||||
{
|
||||
String rule = String.valueOf((String) entry);
|
||||
Pattern compiled = TileRules.PROTECTED.get(rule);
|
||||
|
||||
Objects.requireNonNull(tile);
|
||||
if (compiled == null)
|
||||
{
|
||||
compiled = Pattern.compile(TileRules.regex(rule));
|
||||
TileRules.PROTECTED.putIfAbsent(rule, compiled);
|
||||
}
|
||||
if (compiled.matcher(tile).matches()) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Placement placement(String rule)
|
||||
{
|
||||
boolean allows = true;
|
||||
String body = rule;
|
||||
|
||||
if (body.startsWith("!"))
|
||||
{
|
||||
allows = false;
|
||||
body = body.substring(1);
|
||||
}
|
||||
|
||||
return new Placement(allows, Pattern.compile(TileRules.regex(body)));
|
||||
}
|
||||
|
||||
/** The regular expression vanilla builds from a rule. */
|
||||
private static String regex(String rule)
|
||||
{
|
||||
String regex = "^" + rule;
|
||||
regex = regex.replace(".", "\\.");
|
||||
regex = regex.replace("*", ".*");
|
||||
regex = regex.replace("?", ".?");
|
||||
|
||||
return regex;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
/**
|
||||
* A sleep that another thread can end early. {@link #wake()} ends the current
|
||||
* {@link #sleep(long)}, or the next one if no thread sleeps at the moment, so a wake between two
|
||||
* sleeps is not lost. Unlike {@code Thread.interrupt()}, waking does not close NIO channels the
|
||||
* sleeping thread uses.
|
||||
*/
|
||||
public final class WakeableSleep
|
||||
{
|
||||
private final Object lock = new Object();
|
||||
private boolean woken;
|
||||
|
||||
/** Sleeps {@code millis} milliseconds, or until {@link #wake()}; nothing for {@code millis <= 0}, as {@code Thread.sleep}. */
|
||||
public void sleep(long millis) throws InterruptedException
|
||||
{
|
||||
if (millis <= 0) return;
|
||||
|
||||
long deadline = System.nanoTime() + millis * 1_000_000L;
|
||||
synchronized (this.lock)
|
||||
{
|
||||
// wait() may return without a notify; the loop keeps the full time unless woken.
|
||||
long remaining = millis;
|
||||
while (!this.woken && remaining > 0)
|
||||
{
|
||||
this.lock.wait(remaining);
|
||||
remaining = (deadline - System.nanoTime()) / 1_000_000L;
|
||||
}
|
||||
this.woken = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends the current or the next {@link #sleep(long)}. */
|
||||
public void wake()
|
||||
{
|
||||
synchronized (this.lock)
|
||||
{
|
||||
this.woken = true;
|
||||
this.lock.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.vanilla;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Random;
|
||||
|
||||
import zombie.iso.worldgen.zombie.ClosestSelection;
|
||||
import zombie.iso.worldgen.zombie.ClosestSelectionType;
|
||||
import zombie.iso.worldgen.zombie.Coord;
|
||||
import zombie.iso.worldgen.zombie.HashUtil;
|
||||
|
||||
/**
|
||||
* The value of {@code ZombieVoronoi.evaluateNoise} without its {@link Coord} list for the
|
||||
* {@link ClosestSelectionType}s.
|
||||
*
|
||||
* <p>Vanilla clears {@code points}, adds {@code numberPoints} {@link Coord}s for each of the 9
|
||||
* sectors around {@code (x, y)}, reseeding {@code rng} per sector, and returns
|
||||
* {@code closestPoint.getClosest(x, y, points)}. The three {@link ClosestSelectionType}s map the
|
||||
* points to boxed squared distances, sort them, and return the smallest, the second smallest,
|
||||
* or the second minus the smallest.
|
||||
*
|
||||
* <p>Here the same random numbers in the same order feed the same distance expression, and one
|
||||
* pass keeps the two smallest distances in the order of {@code Double.compare}, which
|
||||
* {@code sorted()} uses. The results are identical without the {@code Coord}s, the boxing and
|
||||
* the sort. {@code points} stays untouched: the only caller, {@code evaluateCellNoise}, passes a
|
||||
* list it does not read. Any other selection gets the filled list as in vanilla.
|
||||
*/
|
||||
public final class VoronoiNoise
|
||||
{
|
||||
private VoronoiNoise() {}
|
||||
|
||||
public static double evaluate(
|
||||
ClosestSelection selection, long seed, int numberPoints,
|
||||
double x, double y, Random rng, List<Coord> points
|
||||
) {
|
||||
int rank = VoronoiNoise.rank(selection);
|
||||
if (rank < 0) return VoronoiNoise.evaluateWithPoints(selection, seed, numberPoints, x, y, rng, points);
|
||||
|
||||
int sectorX = (int) Math.floor(x);
|
||||
int sectorY = (int) Math.floor(y);
|
||||
double smallest = 0.0;
|
||||
double second = 0.0;
|
||||
int count = 0;
|
||||
|
||||
for (int offsetX = -1; offsetX <= 1; ++offsetX)
|
||||
{
|
||||
int pointSectorX = sectorX + offsetX;
|
||||
|
||||
for (int offsetY = -1; offsetY <= 1; ++offsetY)
|
||||
{
|
||||
int pointSectorY = sectorY + offsetY;
|
||||
rng.setSeed(HashUtil.hash2D(seed, pointSectorX, pointSectorY));
|
||||
|
||||
for (int i = 0; i < numberPoints; ++i)
|
||||
{
|
||||
double pointX = rng.nextDouble() + (double) pointSectorX;
|
||||
double pointY = rng.nextDouble() + (double) pointSectorY;
|
||||
double distance = (x - pointX) * (x - pointX) + (y - pointY) * (y - pointY);
|
||||
|
||||
if (count == 0) smallest = distance;
|
||||
else if (Double.compare(distance, smallest) < 0)
|
||||
{
|
||||
second = smallest;
|
||||
smallest = distance;
|
||||
}
|
||||
else if (count == 1 || Double.compare(distance, second) < 0) second = distance;
|
||||
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vanilla reads index 0, or index 1 first, of the sorted list: same exception when it is too short.
|
||||
Objects.checkIndex(rank == 0 ? 0 : 1, count);
|
||||
|
||||
return switch (rank)
|
||||
{
|
||||
case 0 -> smallest;
|
||||
case 1 -> second;
|
||||
default -> second - smallest;
|
||||
};
|
||||
}
|
||||
|
||||
/** 0 for {@code FIRST}, 1 for {@code SECOND}, 2 for {@code SECOND_MINUS_FIRST}, -1 for any other selection. */
|
||||
private static int rank(ClosestSelection selection)
|
||||
{
|
||||
return switch (selection) {
|
||||
case ClosestSelectionType.FIRST -> 0;
|
||||
case ClosestSelectionType.SECOND -> 1;
|
||||
case ClosestSelectionType.SECOND_MINUS_FIRST -> 2;
|
||||
default -> -1;
|
||||
};
|
||||
}
|
||||
|
||||
/** The vanilla body. */
|
||||
private static double evaluateWithPoints(
|
||||
ClosestSelection selection, long seed, int numberPoints,
|
||||
double x, double y, Random rng, List<Coord> points
|
||||
) {
|
||||
points.clear();
|
||||
int sectorX = (int) Math.floor(x);
|
||||
int sectorY = (int) Math.floor(y);
|
||||
|
||||
for (int offsetX = -1; offsetX <= 1; ++offsetX)
|
||||
{
|
||||
int pointSectorX = sectorX + offsetX;
|
||||
|
||||
for (int offsetY = -1; offsetY <= 1; ++offsetY)
|
||||
{
|
||||
int pointSectorY = sectorY + offsetY;
|
||||
rng.setSeed(HashUtil.hash2D(seed, pointSectorX, pointSectorY));
|
||||
|
||||
for (int i = 0; i < numberPoints; ++i) {
|
||||
points.add(new Coord(rng.nextDouble() + (double) pointSectorX, rng.nextDouble() + (double) pointSectorY));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return selection.getClosest(x, y, points);
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Equivalent implementations of vanilla game methods that hooks call instead of the original
|
||||
* code. Unlike {@code util}, these classes use game classes; their tests compare them with the
|
||||
* vanilla methods of the game jar.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.compat.b42.vanilla;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import zombie.ZomboidFileSystem;
|
||||
import zombie.core.backup.ZipBackup;
|
||||
import zombie.core.random.RandStandard;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The hook against vanilla's {@code ZipBackup.makeBackupFile} from the game jar, on the same cache folder. */
|
||||
class BackupHooksTest
|
||||
{
|
||||
private static final String SERVER = "servertest";
|
||||
|
||||
private @TempDir Path cache;
|
||||
|
||||
/** Unset, {@code getCacheDir()} picks the default folder again. */
|
||||
private static void unsetCacheDir() throws ReflectiveOperationException
|
||||
{
|
||||
Field field = ZomboidFileSystem.class.getDeclaredField("cacheDir");
|
||||
field.setAccessible(true);
|
||||
field.set(ZomboidFileSystem.instance, null);
|
||||
}
|
||||
|
||||
private static Object type(String name) throws ClassNotFoundException
|
||||
{
|
||||
for (Object constant : Class.forName("zombie.core.backup.ZipBackup$BackupTypes").getEnumConstants()) {
|
||||
if (((Enum<?>) constant).name().equals(name)) return constant;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(name);
|
||||
}
|
||||
|
||||
private static void vanilla(String serverName, Object type) throws ReflectiveOperationException
|
||||
{
|
||||
Method make = ZipBackup.class.getDeclaredMethod("makeBackupFile", String.class, type.getClass());
|
||||
make.setAccessible(true);
|
||||
make.invoke(null, serverName, type);
|
||||
}
|
||||
|
||||
private void write(String path, byte[] data) throws IOException
|
||||
{
|
||||
Path file = this.cache.resolve(path);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, data);
|
||||
}
|
||||
|
||||
private static byte[] random(int size, long seed)
|
||||
{
|
||||
byte[] data = new byte[size];
|
||||
new Random(seed).nextBytes(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** Entry name to content and method; {@code readme.txt} holds the backup time and is compared apart. */
|
||||
private static Map<String, String> entries(Path zip) throws IOException
|
||||
{
|
||||
Map<String, String> entries = new TreeMap<>();
|
||||
|
||||
try (ZipFile file = new ZipFile(zip.toFile()))
|
||||
{
|
||||
for (ZipEntry entry : Collections.list(file.entries()))
|
||||
{
|
||||
if (entry.getName().equals("readme.txt")) continue;
|
||||
|
||||
byte[] data = file.getInputStream(entry).readAllBytes();
|
||||
entries.put(entry.getName(), entry.getMethod() + " " + HexFormat.of().formatHex(data));
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** {@code ZipBackup.rotateBackupFile} reads {@code ServerOptions}, whose constructor draws a random number. */
|
||||
@BeforeAll
|
||||
static void initRandom()
|
||||
{
|
||||
RandStandard.INSTANCE.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createCacheFolder() throws IOException
|
||||
{
|
||||
ZomboidFileSystem.instance.setCacheDir(this.cache.toString());
|
||||
|
||||
this.write("options.ini", "volume=1".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("sounds.ini", "sounds".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("mods/default.txt", "mods".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("mods/SomeMod/mod.info", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("Lua/settings.lua", "lua".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("db/" + BackupHooksTest.SERVER + ".db", BackupHooksTest.random(5000, 1));
|
||||
this.write("Server/" + BackupHooksTest.SERVER + ".ini", "PVP=true".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("Server/backup/old.ini", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String save = "Saves/Multiplayer/" + BackupHooksTest.SERVER + "/";
|
||||
this.write(save + "map_t.bin", BackupHooksTest.random(100, 2));
|
||||
this.write(save + "players.db", BackupHooksTest.random(5 << 20, 3));
|
||||
this.write(save + "blam/skipped.bin", BackupHooksTest.random(10, 4));
|
||||
this.write(save + "map/blam/skipped.bin", BackupHooksTest.random(10, 5));
|
||||
for (int x = 0; x < 10; x++) {
|
||||
for (int y = 0; y < 10; y++) this.write(save + "map/" + x + "/" + y + ".bin", BackupHooksTest.random(x * 300 + y, x * 100L + y));
|
||||
}
|
||||
Files.createDirectories(this.cache.resolve(save + "isoregiondata"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetCacheFolder() throws ReflectiveOperationException
|
||||
{
|
||||
BackupHooksTest.unsetCacheDir();
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheEntriesOfVanilla() throws Exception
|
||||
{
|
||||
BackupHooksTest.vanilla(BackupHooksTest.SERVER, BackupHooksTest.type("version"));
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
|
||||
Path vanilla = this.cache.resolve("backups/version/backup_1.zip");
|
||||
Path hooked = this.cache.resolve("backups/period/backup_1.zip");
|
||||
|
||||
Map<String, String> expected = BackupHooksTest.entries(vanilla);
|
||||
assertTrue(expected.containsKey("Saves/Multiplayer/" + BackupHooksTest.SERVER + "/map/9/9.bin"), expected.keySet().toString());
|
||||
assertFalse(expected.containsKey("mods/SomeMod/mod.info"));
|
||||
assertEquals(expected, BackupHooksTest.entries(hooked));
|
||||
|
||||
try (ZipFile vanillaZip = new ZipFile(vanilla.toFile()); ZipFile hookedZip = new ZipFile(hooked.toFile()))
|
||||
{
|
||||
byte[] vanillaReadme = vanillaZip.getInputStream(vanillaZip.getEntry("readme.txt")).readAllBytes();
|
||||
byte[] hookedReadme = hookedZip.getInputStream(hookedZip.getEntry("readme.txt")).readAllBytes();
|
||||
|
||||
// Both start with the backup time, to the second.
|
||||
String readme = new String(hookedReadme, StandardCharsets.UTF_8);
|
||||
assertTrue(readme.startsWith("Backup time: "), readme);
|
||||
assertEquals(readme, hookedZip.getComment());
|
||||
assertArrayEquals(BackupHooksTest.tail(vanillaReadme), BackupHooksTest.tail(hookedReadme));
|
||||
}
|
||||
}
|
||||
|
||||
/** The readme after its first line, the backup time. */
|
||||
private static byte[] tail(byte[] readme)
|
||||
{
|
||||
String text = new String(readme, StandardCharsets.UTF_8);
|
||||
return text.substring(text.indexOf('\n')).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotatesTheBackupsAsVanilla() throws Exception
|
||||
{
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
|
||||
assertTrue(Files.exists(this.cache.resolve("backups/period/backup_1.zip")));
|
||||
assertTrue(Files.exists(this.cache.resolve("backups/period/backup_2.zip")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotThrowWhenTheBackupFails() throws Exception
|
||||
{
|
||||
// A folder where the zip file goes: opening it fails.
|
||||
Files.createDirectories(this.cache.resolve("backups/period/backup_1.zip/blocked"));
|
||||
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import zombie.network.ServerWorldDatabase;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The hooks on a real SQLite database, installed as the connection of {@code ServerWorldDatabase}. */
|
||||
class RolesHooksTest
|
||||
{
|
||||
private Connection connection;
|
||||
|
||||
private void install(Connection connection) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = ServerWorldDatabase.class.getDeclaredField("conn");
|
||||
field.setAccessible(true);
|
||||
field.set(ServerWorldDatabase.instance, connection);
|
||||
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void uninstall() throws ReflectiveOperationException, SQLException
|
||||
{
|
||||
this.install(null);
|
||||
}
|
||||
|
||||
private static int count(Connection connection) throws SQLException
|
||||
{
|
||||
try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM roles"))
|
||||
{
|
||||
rows.next();
|
||||
return rows.getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesBetweenTheHooksBecomeVisibleTogetherAtTheEnd(@TempDir Path temp) throws Exception
|
||||
{
|
||||
String url = "jdbc:sqlite:" + temp.resolve("test.db");
|
||||
|
||||
try (Connection server = DriverManager.getConnection(url); Connection reader = DriverManager.getConnection(url))
|
||||
{
|
||||
try (Statement statement = server.createStatement()) { statement.executeUpdate("CREATE TABLE roles (name TEXT)"); }
|
||||
this.install(server);
|
||||
|
||||
RolesHooks.beginSave();
|
||||
assertFalse(server.getAutoCommit());
|
||||
|
||||
try (Statement statement = server.createStatement())
|
||||
{
|
||||
statement.executeUpdate("INSERT INTO roles VALUES ('admin')");
|
||||
statement.executeUpdate("INSERT INTO roles VALUES ('user')");
|
||||
}
|
||||
assertEquals(0, RolesHooksTest.count(reader), "Rows are visible before the end of the save.");
|
||||
|
||||
RolesHooks.endSave();
|
||||
assertTrue(server.getAutoCommit());
|
||||
assertEquals(2, RolesHooksTest.count(reader));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesAConnectionAloneThatIsAlreadyInATransaction(@TempDir Path temp) throws Exception
|
||||
{
|
||||
try (Connection server = DriverManager.getConnection("jdbc:sqlite:" + temp.resolve("test.db")))
|
||||
{
|
||||
server.setAutoCommit(false);
|
||||
this.install(server);
|
||||
|
||||
RolesHooks.beginSave();
|
||||
RolesHooks.endSave();
|
||||
|
||||
assertFalse(server.getAutoCommit());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNothingWithoutAConnection() throws ReflectiveOperationException
|
||||
{
|
||||
this.install(null);
|
||||
|
||||
RolesHooks.beginSave();
|
||||
RolesHooks.endSave();
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import zombie.ZomboidFileSystem;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* Compares {@link ZomboidFileSystemHooks#searchAndIndex} with vanilla: {@code searchFolders} of
|
||||
* the game jar, followed by the loop of {@code ZomboidFileSystem.init} (copied below, it cannot
|
||||
* run alone), on fresh {@code ZomboidFileSystem} instances.
|
||||
*/
|
||||
class ZomboidFileSystemHooksTest
|
||||
{
|
||||
private boolean server;
|
||||
|
||||
@BeforeEach
|
||||
void serverMode()
|
||||
{
|
||||
this.server = GameServer.server;
|
||||
GameServer.server = true;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreServerMode() { GameServer.server = this.server; }
|
||||
|
||||
/** The maps, lists and sets of one {@code ZomboidFileSystem} after the indexing. */
|
||||
private record Index(List<String> loadList, Map<String, String> activeFileMap, Set<String> allAbsolutePaths) {}
|
||||
|
||||
private static ZomboidFileSystem newFileSystem(Path base) throws ReflectiveOperationException, IOException
|
||||
{
|
||||
Constructor<ZomboidFileSystem> constructor = ZomboidFileSystem.class.getDeclaredConstructor();
|
||||
constructor.setAccessible(true);
|
||||
|
||||
ZomboidFileSystem fileSystem = constructor.newInstance();
|
||||
fileSystem.base.set(base.toFile());
|
||||
|
||||
return fileSystem;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> T field(ZomboidFileSystem fileSystem, String name) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = ZomboidFileSystem.class.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
|
||||
return (T) field.get(fileSystem);
|
||||
}
|
||||
|
||||
private static Index vanilla(Path base, File media) throws ReflectiveOperationException, IOException
|
||||
{
|
||||
ZomboidFileSystem fileSystem = ZomboidFileSystemHooksTest.newFileSystem(base);
|
||||
List<String> loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList");
|
||||
Set<String> allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths");
|
||||
Map<String, String> activeFileMap = fileSystem.activeFileMap;
|
||||
|
||||
fileSystem.searchFolders(media);
|
||||
List<String> searched = new ArrayList<>(loadList);
|
||||
|
||||
// The loop of ZomboidFileSystem.init after searchFolders.
|
||||
for (int n = 0; n < loadList.size(); ++n)
|
||||
{
|
||||
String rel = fileSystem.getRelativeFile(loadList.get(n));
|
||||
File file = new File(loadList.get(n)).getAbsoluteFile();
|
||||
String abs = file.getAbsolutePath();
|
||||
if (file.isDirectory()) abs = abs + File.separator;
|
||||
|
||||
activeFileMap.put(rel.toLowerCase(Locale.ENGLISH), abs);
|
||||
allAbsolutePaths.add(abs);
|
||||
}
|
||||
loadList.clear();
|
||||
|
||||
return new Index(searched, new HashMap<>(activeFileMap), new HashSet<>(allAbsolutePaths));
|
||||
}
|
||||
|
||||
private static Index hook(Path base, File media) throws ReflectiveOperationException, IOException
|
||||
{
|
||||
ZomboidFileSystem fileSystem = ZomboidFileSystemHooksTest.newFileSystem(base);
|
||||
List<String> loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList");
|
||||
Set<String> allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths");
|
||||
List<String> searched = new ArrayList<>();
|
||||
|
||||
// Records what the walk appends: the hook empties the list before returning.
|
||||
List<String> recording = new ArrayList<>(loadList)
|
||||
{
|
||||
@Override
|
||||
public boolean add(String entry)
|
||||
{
|
||||
searched.add(entry);
|
||||
return super.add(entry);
|
||||
}
|
||||
};
|
||||
|
||||
ZomboidFileSystemHooks.searchAndIndex(fileSystem, media, recording, allAbsolutePaths);
|
||||
|
||||
assertTrue(recording.isEmpty(), "The hook leaves entries in loadList.");
|
||||
return new Index(searched, new HashMap<>(fileSystem.activeFileMap), new HashSet<>(allAbsolutePaths));
|
||||
}
|
||||
|
||||
private static void file(Path path) throws IOException
|
||||
{
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, path.getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void indexesEdgeCasesLikeVanilla(@TempDir Path temp) throws Exception
|
||||
{
|
||||
// A lowercase base: "Clash" lowercased then names the existing folder "clash".
|
||||
Path base = temp.resolve("base");
|
||||
Path media = base.resolve("media");
|
||||
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("maps/Muldraugh, KY/world_1_2.lotpack"));
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("maps/Test%Map/objects.lua"));
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("scripts/Items/Weapon.txt"));
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("textures/Äpfel ö.png"));
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("clash/inside.txt"));
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("Clash")); // lowercased, a folder
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("back\\slash.txt")); // vanilla appends another path
|
||||
ZomboidFileSystemHooksTest.file(media.resolve("dot./inside.txt")); // vanilla removes "./"
|
||||
Files.createDirectories(media.resolve("empty"));
|
||||
Files.createSymbolicLink(media.resolve("LinkedScripts"), media.resolve("scripts"));
|
||||
Files.createSymbolicLink(media.resolve("broken"), media.resolve("missing"));
|
||||
|
||||
Index expected = ZomboidFileSystemHooksTest.vanilla(base, media.toFile());
|
||||
Index actual = ZomboidFileSystemHooksTest.hook(base, media.toFile());
|
||||
|
||||
assertEquals(expected.loadList(), actual.loadList());
|
||||
assertEquals(expected.activeFileMap(), actual.activeFileMap());
|
||||
assertEquals(expected.allAbsolutePaths(), actual.allAbsolutePaths());
|
||||
assertTrue(expected.activeFileMap().containsKey("media/clash/"), "The test tree misses the lowercase folder case.");
|
||||
}
|
||||
|
||||
/**
|
||||
* The media folder of an installed server, when the game jar is part of one
|
||||
* ({@code <install>/java/projectzomboid.jar}, as {@code lib/server}); the image build uses a
|
||||
* copied jar without it.
|
||||
*/
|
||||
@Test
|
||||
void indexesTheGameMediaFolderLikeVanilla() throws Exception
|
||||
{
|
||||
Path jar = Path.of(ZomboidFileSystem.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
Path folder = jar.getParent();
|
||||
assumeTrue(folder.getFileName() != null && folder.getFileName().toString().equals("java"), "The game jar " + jar + " is not in an installed server.");
|
||||
|
||||
Path base = folder.getParent();
|
||||
Path media = base.resolve("media");
|
||||
assumeTrue(Files.isDirectory(media.resolve("scripts")), "No media folder at " + media);
|
||||
|
||||
Index expected = ZomboidFileSystemHooksTest.vanilla(base, media.toRealPath().toFile());
|
||||
Index actual = ZomboidFileSystemHooksTest.hook(base, media.toRealPath().toFile());
|
||||
|
||||
assertEquals(expected.loadList(), actual.loadList());
|
||||
assertEquals(expected.activeFileMap(), actual.activeFileMap());
|
||||
assertEquals(expected.allAbsolutePaths(), actual.allAbsolutePaths());
|
||||
assertTrue(expected.activeFileMap().size() > 30_000, () -> "Only " + expected.activeFileMap().size() + " entries.");
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class FrameBudgetTest
|
||||
{
|
||||
/** A clock the test sets; nanoseconds. */
|
||||
private long now;
|
||||
|
||||
private FrameBudget budget(long budgetNanos)
|
||||
{
|
||||
return new FrameBudget(budgetNanos, () -> this.now);
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstUnitOfAFrameRunsEvenWhenTheBudgetIsUsedUp()
|
||||
{
|
||||
FrameBudget budget = this.budget(40);
|
||||
budget.begin();
|
||||
|
||||
this.now += 1_000;
|
||||
assertTrue(budget.allowsAnother());
|
||||
}
|
||||
|
||||
@Test
|
||||
void laterUnitsRunWhileTimeIsLeft()
|
||||
{
|
||||
FrameBudget budget = this.budget(40);
|
||||
budget.begin();
|
||||
budget.count();
|
||||
|
||||
this.now += 39;
|
||||
assertTrue(budget.allowsAnother());
|
||||
|
||||
this.now += 1;
|
||||
assertFalse(budget.allowsAnother());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewFrameStartsAFreshBudget()
|
||||
{
|
||||
FrameBudget budget = this.budget(40);
|
||||
budget.begin();
|
||||
budget.count();
|
||||
this.now += 100;
|
||||
assertFalse(budget.allowsAnother());
|
||||
|
||||
budget.begin();
|
||||
assertTrue(budget.allowsAnother());
|
||||
budget.count();
|
||||
assertTrue(budget.allowsAnother());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnusedSkipDoesNotCountAsAUnit()
|
||||
{
|
||||
// A frame where nothing ran yet still allows its first unit, however late.
|
||||
FrameBudget budget = this.budget(40);
|
||||
budget.begin();
|
||||
this.now += 100;
|
||||
|
||||
assertTrue(budget.allowsAnother());
|
||||
assertTrue(budget.allowsAnother());
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ParallelZipTest
|
||||
{
|
||||
private static byte[] random(int size, long seed)
|
||||
{
|
||||
byte[] data = new byte[size];
|
||||
new Random(seed).nextBytes(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void write(Path file, byte[] data) throws IOException
|
||||
{
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, data);
|
||||
}
|
||||
|
||||
/** Entry name to content, read with {@code ZipInputStream}, which checks each entry's CRC and size. */
|
||||
private static Map<String, byte[]> entries(Path zip) throws IOException
|
||||
{
|
||||
Map<String, byte[]> entries = new TreeMap<>();
|
||||
|
||||
try (ZipInputStream input = new ZipInputStream(Files.newInputStream(zip)))
|
||||
{
|
||||
for (ZipEntry entry = input.getNextEntry(); entry != null; entry = input.getNextEntry()) {
|
||||
entries.put(entry.getName(), input.readAllBytes());
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static Path zip(Path temp, Path folder, String prefix) throws IOException
|
||||
{
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "comment", 4, e -> { throw new AssertionError(e); }))
|
||||
{
|
||||
writer.addFolder(prefix, folder, subfolder -> !subfolder.endsWith("blam"));
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
return zip;
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsEveryFileOfTheTreeExceptSkippedFolders(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
List<String> expected = new ArrayList<>();
|
||||
|
||||
for (int x = 0; x < 20; x++)
|
||||
{
|
||||
for (int y = 0; y < 30; y++)
|
||||
{
|
||||
ParallelZipTest.write(root.resolve("map/" + x + "/" + y + ".bin"), ParallelZipTest.random(x * 100 + y, x * 1000L + y));
|
||||
expected.add("world/map/" + x + "/" + y + ".bin");
|
||||
}
|
||||
}
|
||||
ParallelZipTest.write(root.resolve("map_t.bin"), ParallelZipTest.random(10, 1));
|
||||
ParallelZipTest.write(root.resolve("blam/skipped.bin"), ParallelZipTest.random(10, 2));
|
||||
ParallelZipTest.write(root.resolve("map/blam/skipped.bin"), ParallelZipTest.random(10, 3));
|
||||
ParallelZipTest.write(root.resolve("notblam/kept.bin"), ParallelZipTest.random(10, 4));
|
||||
Files.createDirectories(root.resolve("empty"));
|
||||
expected.add("world/map_t.bin");
|
||||
expected.add("world/notblam/kept.bin");
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
|
||||
|
||||
Collections.sort(expected);
|
||||
assertEquals(expected, new ArrayList<>(entries.keySet()));
|
||||
for (String name : expected) assertArrayEquals(Files.readAllBytes(root.resolve(name.substring("world/".length()))), entries.get(name), name);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsOnlyTopLevelFilesWhenNotDescending(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("mods");
|
||||
ParallelZipTest.write(root.resolve("a.txt"), "a".getBytes(StandardCharsets.UTF_8));
|
||||
ParallelZipTest.write(root.resolve("sub/b.txt"), "b".getBytes(StandardCharsets.UTF_8));
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 2, e -> { throw new AssertionError(e); }))
|
||||
{
|
||||
writer.addFolder("mods", root, subfolder -> false);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
assertEquals(List.of("mods/a.txt"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
|
||||
}
|
||||
|
||||
/** Large files are copied by the writing thread; more read data than the budget waits for it. */
|
||||
@Test
|
||||
void writesLargeFilesAndMoreThanTheBudget(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
for (int i = 0; i < 80; i++) ParallelZipTest.write(root.resolve("chunks/" + i + ".bin"), ParallelZipTest.random(1 << 20, i));
|
||||
ParallelZipTest.write(root.resolve("players.db"), ParallelZipTest.random(9 << 20, 100));
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
|
||||
|
||||
assertEquals(81, entries.size());
|
||||
assertArrayEquals(Files.readAllBytes(root.resolve("players.db")), entries.get("world/players.db"));
|
||||
assertArrayEquals(Files.readAllBytes(root.resolve("chunks/42.bin")), entries.get("world/chunks/42.bin"));
|
||||
}
|
||||
|
||||
/** As {@code ParallelScatterZipCreator}'s entries: STORED, without Zip64 fields; the comment is set. */
|
||||
@Test
|
||||
void writesStoredEntriesWithoutZip64Fields(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
ParallelZipTest.write(root.resolve("small.bin"), ParallelZipTest.random(100, 1));
|
||||
ParallelZipTest.write(root.resolve("large.bin"), ParallelZipTest.random(5 << 20, 2));
|
||||
Path zip = ParallelZipTest.zip(temp, root, "world");
|
||||
|
||||
try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip.toFile())) { assertEquals("comment", file.getComment()); }
|
||||
|
||||
try (ZipFile file = ZipFile.builder().setPath(zip).get())
|
||||
{
|
||||
for (ZipArchiveEntry entry : Collections.list(file.getEntries()))
|
||||
{
|
||||
assertEquals(ZipEntry.STORED, entry.getMethod(), entry.getName());
|
||||
assertEquals(0, entry.getLocalFileDataExtra().length, entry.getName());
|
||||
assertEquals(0, entry.getCentralDirectoryExtra().length, entry.getName());
|
||||
assertTrue(file.canReadEntryData(entry));
|
||||
|
||||
try (InputStream input = file.getInputStream(entry)) { assertEquals(entry.getSize(), input.readAllBytes().length); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsAndSkipsFilesThatCannotBeRead(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
ParallelZipTest.write(root.resolve("kept.bin"), ParallelZipTest.random(10, 1));
|
||||
Files.createSymbolicLink(root.resolve("dangling.bin"), root.resolve("missing.bin"));
|
||||
Path zip = temp.resolve("out.zip");
|
||||
List<IOException> failures = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 2, failures::add))
|
||||
{
|
||||
writer.addFolder("world", root, subfolder -> true);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
assertEquals(List.of("world/kept.bin"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
|
||||
assertEquals(1, failures.size());
|
||||
assertTrue(failures.getFirst().getMessage().contains("dangling.bin"), failures.getFirst().getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsLinkedFilesWithTheirContent(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
ParallelZipTest.write(temp.resolve("target.bin"), ParallelZipTest.random(10, 1));
|
||||
Files.createDirectories(root);
|
||||
Files.createSymbolicLink(root.resolve("link.bin"), temp.resolve("target.bin"));
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
|
||||
|
||||
assertArrayEquals(Files.readAllBytes(temp.resolve("target.bin")), entries.get("world/link.bin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsTextAndSingleFiles(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path file = temp.resolve("options.ini");
|
||||
ParallelZipTest.write(file, "volume=1".getBytes(StandardCharsets.UTF_8));
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); }))
|
||||
{
|
||||
writer.addText("readme.txt", "Backup time: now");
|
||||
writer.addFile("options.ini", file);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(zip);
|
||||
assertEquals("Backup time: now", new String(entries.get("readme.txt"), StandardCharsets.UTF_8));
|
||||
assertEquals("volume=1", new String(entries.get("options.ini"), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** Without finish(), as after a failure, the file has no central directory. */
|
||||
@Test
|
||||
void unfinishedFileIsNoZip(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); })) { writer.addText("readme.txt", "text"); }
|
||||
|
||||
assertTrue(Files.size(zip) > 0);
|
||||
assertThrows(IOException.class, () -> ZipFile.builder().setPath(zip).get().close());
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PerThreadDequeTest
|
||||
{
|
||||
@Test
|
||||
void pollReturnsWhatThisThreadOfferedNewestFirst()
|
||||
{
|
||||
PerThreadDeque<String> pool = new PerThreadDeque<>();
|
||||
String first = "first";
|
||||
String second = "second";
|
||||
|
||||
assertTrue(pool.offer(first));
|
||||
assertTrue(pool.offer(second));
|
||||
|
||||
assertSame(second, pool.poll());
|
||||
assertSame(first, pool.poll());
|
||||
assertNull(pool.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void threadsDoNotSeeEachOthersObjects() throws InterruptedException
|
||||
{
|
||||
PerThreadDeque<String> pool = new PerThreadDeque<>();
|
||||
pool.offer("main");
|
||||
|
||||
AtomicReference<String> polled = new AtomicReference<>("not polled");
|
||||
AtomicReference<Integer> size = new AtomicReference<>(-1);
|
||||
Thread other = new Thread(() -> {
|
||||
polled.set(pool.poll());
|
||||
pool.offer("other");
|
||||
size.set(pool.size());
|
||||
});
|
||||
other.start();
|
||||
other.join();
|
||||
|
||||
assertNull(polled.get());
|
||||
assertEquals(1, size.get());
|
||||
assertEquals("main", pool.poll());
|
||||
assertNull(pool.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsAtMostTheCapacityPerThread()
|
||||
{
|
||||
PerThreadDeque<Integer> pool = new PerThreadDeque<>();
|
||||
|
||||
for (int i = 0; i < 2_000; i++) assertTrue(pool.offer(i));
|
||||
|
||||
assertEquals(1_024, pool.size());
|
||||
assertEquals(1_023, pool.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNullLikeConcurrentLinkedDeque()
|
||||
{
|
||||
PerThreadDeque<String> pool = new PerThreadDeque<>();
|
||||
|
||||
assertThrows(NullPointerException.class, () -> pool.offer(null));
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.iso.worldgen.WorldGenChunk;
|
||||
import zombie.iso.worldgen.WorldGenUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/** Compares {@link TileRules} with the vanilla methods of the game jar. */
|
||||
class TileRulesTest
|
||||
{
|
||||
/** Rules with every special character of the conversion, negation, and edge cases. */
|
||||
private static final List<String> RULES = List.of(
|
||||
"blends_natural_01_*", "!blends_natural_02_*", "vegetation_drying*", "floors_exterior_natural_01_?",
|
||||
"a.b", "*", "!*", "?", "blends_natural_01_1", "", "!", "null", "x*y?z"
|
||||
);
|
||||
|
||||
private static final List<String> NAMES = List.of(
|
||||
"blends_natural_01_16", "blends_natural_02_3", "vegetation_drying_01_0", "floors_exterior_natural_01_1",
|
||||
"floors_exterior_natural_01_12", "a.b", "axb", "", "null", "xyz", "x__y_z", "X", "blends_natural_01_1"
|
||||
);
|
||||
|
||||
private static final Pattern QUOTED_RULE = Pattern.compile("\"(!?[A-Za-z0-9_.*?]+)\"");
|
||||
|
||||
/** Outcome of a call: its result or the class of what it threw. */
|
||||
private static String outcome(Callable<Object> call)
|
||||
{
|
||||
try { return String.valueOf(call.call()); }
|
||||
catch (Throwable t) { return t.getClass().getName(); }
|
||||
}
|
||||
|
||||
private static WorldGenChunk chunkWithoutConstructor() throws ReflectiveOperationException
|
||||
{
|
||||
// isProtected reads no field; WorldGenChunk's constructor needs a running world.
|
||||
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
|
||||
Field field = unsafeClass.getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
|
||||
return (WorldGenChunk) unsafeClass.getMethod("allocateInstance", Class.class).invoke(field.get(null), WorldGenChunk.class);
|
||||
}
|
||||
|
||||
/** All lists of up to three rules from {@code rules}, in every order. */
|
||||
private static List<List<String>> ruleLists(List<String> rules)
|
||||
{
|
||||
List<List<String>> lists = new ArrayList<>();
|
||||
lists.add(List.of());
|
||||
|
||||
for (String first : rules)
|
||||
{
|
||||
lists.add(List.of(first));
|
||||
for (String second : rules)
|
||||
{
|
||||
lists.add(List.of(first, second));
|
||||
for (String third : rules) lists.add(List.of(first, second, third));
|
||||
}
|
||||
}
|
||||
|
||||
return lists;
|
||||
}
|
||||
|
||||
private static void compare(List<List<String>> lists, List<String> names) throws ReflectiveOperationException
|
||||
{
|
||||
WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor();
|
||||
|
||||
for (List<String> rules : lists)
|
||||
{
|
||||
for (String name : names)
|
||||
{
|
||||
assertEquals(
|
||||
TileRulesTest.outcome(() -> WorldGenUtils.INSTANCE.canPlace(rules, name)),
|
||||
TileRulesTest.outcome(() -> TileRules.canPlace(rules, name)),
|
||||
() -> "canPlace(" + rules + ", " + name + ")"
|
||||
);
|
||||
assertEquals(
|
||||
TileRulesTest.outcome(() -> chunk.isProtected(rules, name)),
|
||||
TileRulesTest.outcome(() -> TileRules.isProtected(rules, name)),
|
||||
() -> "isProtected(" + rules + ", " + name + ")"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void answersLikeVanillaForEdgeCases() throws ReflectiveOperationException
|
||||
{
|
||||
TileRulesTest.compare(TileRulesTest.ruleLists(TileRulesTest.RULES), TileRulesTest.NAMES);
|
||||
}
|
||||
|
||||
@Test
|
||||
void throwsLikeVanillaForBrokenRules() throws ReflectiveOperationException
|
||||
{
|
||||
List<List<String>> lists = new ArrayList<>();
|
||||
lists.add(List.of("a(b")); // not a valid regular expression
|
||||
lists.add(List.of("vegetation_drying*", "a[b"));
|
||||
lists.add(Arrays.asList("vegetation_drying*", null)); // canPlace fails, isProtected matches "^null"
|
||||
lists.add(Arrays.asList((String) null));
|
||||
|
||||
List<String> names = new ArrayList<>(TileRulesTest.NAMES);
|
||||
names.add(null);
|
||||
|
||||
TileRulesTest.compare(lists, names);
|
||||
}
|
||||
|
||||
/**
|
||||
* The quoted rules of the game's world generation Lua files ({@code media/lua/server/WorldGen}
|
||||
* next to the game jar, when the jar is part of an installed server), against names derived
|
||||
* from them.
|
||||
*/
|
||||
@Test
|
||||
void answersLikeVanillaForTheGameRules() throws Exception
|
||||
{
|
||||
Path jar = Path.of(WorldGenUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
Path parent = jar.getParent();
|
||||
assumeTrue(parent.getFileName() != null && parent.getFileName().toString().equals("java"), "The game jar " + jar + " is not in an installed server.");
|
||||
|
||||
Path folder = parent.getParent().resolve("media/lua/server/WorldGen");
|
||||
assumeTrue(Files.isDirectory(folder), "No world generation scripts at " + folder);
|
||||
|
||||
TreeSet<String> rules = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.walk(folder))
|
||||
{
|
||||
for (Path file : files.filter(path -> path.toString().endsWith(".lua")).toList())
|
||||
{
|
||||
Matcher matcher = TileRulesTest.QUOTED_RULE.matcher(TileRulesTest.read(file));
|
||||
while (matcher.find()) rules.add(matcher.group(1));
|
||||
}
|
||||
}
|
||||
assertTrue(rules.size() > 100, () -> "Only " + rules.size() + " rules in " + folder);
|
||||
|
||||
// Names: each rule with its wildcards filled in, some of them changed.
|
||||
Random random = new Random(7L);
|
||||
List<String> names = new ArrayList<>();
|
||||
for (String rule : rules)
|
||||
{
|
||||
String name = rule.replace("!", "").replace("*", String.valueOf(random.nextInt(64))).replace("?", "");
|
||||
names.add(name);
|
||||
names.add(name + "x");
|
||||
}
|
||||
|
||||
// Random rule lists of up to four rules, each against a sample of the names.
|
||||
List<String> pool = new ArrayList<>(rules);
|
||||
List<List<String>> lists = new ArrayList<>();
|
||||
for (int i = 0; i < 2_000; i++)
|
||||
{
|
||||
List<String> list = new ArrayList<>();
|
||||
for (int n = random.nextInt(5); n > 0; n--) list.add(pool.get(random.nextInt(pool.size())));
|
||||
lists.add(list);
|
||||
}
|
||||
|
||||
WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor();
|
||||
for (List<String> list : lists)
|
||||
{
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
String name = names.get(random.nextInt(names.size()));
|
||||
|
||||
assertEquals(WorldGenUtils.INSTANCE.canPlace(list, name), TileRules.canPlace(list, name), () -> "canPlace(" + list + ", " + name + ")");
|
||||
assertEquals(chunk.isProtected(list, name), TileRules.isProtected(list, name), () -> "isProtected(" + list + ", " + name + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesLikeString()
|
||||
{
|
||||
for (String regex : List.of("^Sand", "^Road_.*", "^Road_.*", "^a\\.b", "^x.?"))
|
||||
{
|
||||
for (String input : List.of("Sand", "Sandy", "Road_1", "road_1", "a.b", "axb", "x", "xy", "xyz"))
|
||||
{
|
||||
assertEquals(input.matches(regex), TileRules.matches(input, regex), () -> input + " ~ " + regex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String read(Path file)
|
||||
{
|
||||
try { return Files.readString(file, StandardCharsets.ISO_8859_1); }
|
||||
catch (IOException e) { throw new IllegalStateException("Cannot read '" + file + "'.", e); }
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class WakeableSleepTest
|
||||
{
|
||||
private static long millisOf(Runnable sleep)
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
sleep.run();
|
||||
return (System.nanoTime() - start) / 1_000_000L;
|
||||
}
|
||||
|
||||
private static Runnable sleeping(WakeableSleep sleep, long millis)
|
||||
{
|
||||
return () -> {
|
||||
try { sleep.sleep(millis); }
|
||||
catch (InterruptedException e) { throw new IllegalStateException(e); }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void sleepsTheFullTimeWithoutAWake()
|
||||
{
|
||||
long slept = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(new WakeableSleep(), 200));
|
||||
|
||||
assertTrue(slept >= 195, () -> "Slept only " + slept + " ms.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWakeEndsTheSleepEarly() throws InterruptedException
|
||||
{
|
||||
WakeableSleep sleep = new WakeableSleep();
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
long[] slept = new long[1];
|
||||
|
||||
Thread sleeper = new Thread(() -> {
|
||||
started.countDown();
|
||||
slept[0] = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(sleep, 10_000));
|
||||
});
|
||||
sleeper.start();
|
||||
started.await();
|
||||
Thread.sleep(50);
|
||||
|
||||
sleep.wake();
|
||||
sleeper.join(5_000);
|
||||
|
||||
assertTrue(slept[0] < 5_000, () -> "Slept " + slept[0] + " ms despite the wake.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWakeBeforeTheSleepEndsTheNextSleep()
|
||||
{
|
||||
WakeableSleep sleep = new WakeableSleep();
|
||||
sleep.wake();
|
||||
|
||||
long first = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(sleep, 5_000));
|
||||
long second = WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(sleep, 100));
|
||||
|
||||
assertTrue(first < 1_000, () -> "Slept " + first + " ms despite the earlier wake.");
|
||||
assertTrue(second >= 95, () -> "The wake ended a second sleep too: " + second + " ms.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotSleepForZeroOrLess()
|
||||
{
|
||||
assertTrue(WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(new WakeableSleep(), 0)) < 50);
|
||||
assertTrue(WakeableSleepTest.millisOf(WakeableSleepTest.sleeping(new WakeableSleep(), -1)) < 50);
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.vanilla;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.iso.worldgen.zombie.ClosestSelection;
|
||||
import zombie.iso.worldgen.zombie.ClosestSelectionType;
|
||||
import zombie.iso.worldgen.zombie.Coord;
|
||||
import zombie.iso.worldgen.zombie.ZombieVoronoi;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** Compares {@link VoronoiNoise} with the vanilla {@code ZombieVoronoi.evaluateNoise} of the game jar. */
|
||||
class VoronoiNoiseTest
|
||||
{
|
||||
private static final long[] SEEDS = { 0L, 12345L, -987654321L, Long.MAX_VALUE };
|
||||
|
||||
private static double vanilla(ZombieVoronoi voronoi, double x, double y, List<Coord> points) throws ReflectiveOperationException
|
||||
{
|
||||
Method method = ZombieVoronoi.class.getDeclaredMethod("evaluateNoise", double.class, double.class, Random.class, List.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
return (double) method.invoke(voronoi, x, y, new Random(), points);
|
||||
}
|
||||
|
||||
/** Random coordinates, and coordinates on and next to sector borders, including negative ones. */
|
||||
private static List<double[]> coordinates()
|
||||
{
|
||||
List<double[]> coordinates = new ArrayList<>();
|
||||
Random random = new Random(42L);
|
||||
|
||||
for (int i = 0; i < 500; i++) coordinates.add(new double[] { random.nextDouble() * 2000.0 - 1000.0, random.nextDouble() * 2000.0 - 1000.0 });
|
||||
|
||||
for (double border : new double[] { -2.0, -1.0, 0.0, 1.0, 37.0 })
|
||||
{
|
||||
coordinates.add(new double[] { border, border });
|
||||
coordinates.add(new double[] { Math.nextDown(border), Math.nextUp(border) });
|
||||
coordinates.add(new double[] { -0.0, border });
|
||||
}
|
||||
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTheVanillaValueForEveryClosestSelectionType() throws ReflectiveOperationException
|
||||
{
|
||||
int compared = 0;
|
||||
|
||||
for (ClosestSelectionType type : ClosestSelectionType.values())
|
||||
{
|
||||
for (int numberPoints = 1; numberPoints <= 3; numberPoints++)
|
||||
{
|
||||
for (long seed : VoronoiNoiseTest.SEEDS)
|
||||
{
|
||||
ZombieVoronoi voronoi = new ZombieVoronoi(seed, numberPoints, type, 1.0, 0.0);
|
||||
|
||||
for (double[] point : VoronoiNoiseTest.coordinates())
|
||||
{
|
||||
double expected = VoronoiNoiseTest.vanilla(voronoi, point[0], point[1], new ArrayList<>());
|
||||
double actual = VoronoiNoise.evaluate(type, seed, numberPoints, point[0], point[1], new Random(), new ArrayList<>());
|
||||
|
||||
assertEquals(
|
||||
Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual),
|
||||
() -> type + ", " + seed + ", " + point[0] + ", " + point[1]
|
||||
);
|
||||
compared++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(3 * 3 * VoronoiNoiseTest.SEEDS.length * VoronoiNoiseTest.coordinates().size(), compared);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherSelectionsGetTheVanillaPoints() throws ReflectiveOperationException
|
||||
{
|
||||
// Sums every coordinate, so any difference in the points shows in the result.
|
||||
ClosestSelection sum = (x, y, points) -> {
|
||||
double total = 0.0;
|
||||
for (Object point : points) total += ((Coord) point).x() * 3.0 + ((Coord) point).y();
|
||||
return total;
|
||||
};
|
||||
|
||||
ZombieVoronoi voronoi = new ZombieVoronoi(777L, 2, sum, 1.0, 0.0);
|
||||
List<Coord> vanillaPoints = new ArrayList<>();
|
||||
List<Coord> noisePoints = new ArrayList<>(List.of(new Coord(9.0, 9.0)));
|
||||
double expected = VoronoiNoiseTest.vanilla(voronoi, 12.5, -3.25, vanillaPoints);
|
||||
double actual = VoronoiNoise.evaluate(sum, 777L, 2, 12.5, -3.25, new Random(), noisePoints);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
assertEquals(vanillaPoints, noisePoints);
|
||||
assertEquals(18, noisePoints.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutPointsThrowsLikeVanilla()
|
||||
{
|
||||
for (ClosestSelectionType type : ClosestSelectionType.values())
|
||||
{
|
||||
ZombieVoronoi voronoi = new ZombieVoronoi(1L, 0, type, 1.0, 0.0);
|
||||
|
||||
InvocationTargetException vanilla = assertThrows(InvocationTargetException.class, () -> VoronoiNoiseTest.vanilla(voronoi, 1.0, 1.0, new ArrayList<>()));
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> VoronoiNoise.evaluate(type, 1L, 0, 1.0, 1.0, new Random(), new ArrayList<>()));
|
||||
|
||||
// Only the type: once compiled, the JVM may throw a preallocated exception without a
|
||||
// message (OmitStackTraceInFastThrow, on by default in tests).
|
||||
assertInstanceOf(IndexOutOfBoundsException.class, vanilla.getCause());
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -18,8 +18,11 @@ services:
|
||||
MODS: ${MODS:-}
|
||||
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
|
||||
RCON_PASSWORD: ${RCON_PASSWORD:-}
|
||||
UPNP: ${UPNP:-}
|
||||
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
|
||||
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g}
|
||||
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-}
|
||||
JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-}
|
||||
ZF_EXPERIMENTAL_PERFORMANCE: ${ZF_EXPERIMENTAL_PERFORMANCE:-}
|
||||
ports:
|
||||
# Host and container ports must be equal: the server reports its own port
|
||||
# to Steam and to clients, so a remapped port is unreachable.
|
||||
|
||||
@@ -10,6 +10,7 @@ import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||
import dev.overlord.zomboidforge.core.commands.ClientCommandSender;
|
||||
import dev.overlord.zomboidforge.core.commands.CommandRegistry;
|
||||
import dev.overlord.zomboidforge.core.commands.ModClientCommands;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||
@@ -100,6 +101,9 @@ public final class Forge
|
||||
|
||||
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
||||
|
||||
/** The settings from {@code forge.toml} and the system properties; {@link ForgeSettings#DEFAULTS} until {@link #load} reads them. */
|
||||
public ForgeSettings settings() { return this.settings; }
|
||||
|
||||
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
||||
|
||||
/** The admin command classes that mods registered, in registration order. */
|
||||
@@ -119,8 +123,14 @@ public final class Forge
|
||||
{
|
||||
Path modsDirectory = this.directory.resolve(Forge.MODS);
|
||||
|
||||
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); }
|
||||
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), System.getProperties()); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "' or system properties: " + e.getMessage(), e); }
|
||||
|
||||
if (!this.settings.features().isEmpty())
|
||||
{
|
||||
String features = this.settings.features().stream().sorted().map(Feature::key).collect(Collectors.joining(", "));
|
||||
this.logger.log(System.Logger.Level.INFO, "Features on: " + features + ".");
|
||||
}
|
||||
|
||||
this.queue.budget(this.settings.mainThreadBudget());
|
||||
this.queue.bindToCurrentThread();
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Optional behavior of ZomboidForge, off by default. Each feature has one key, from which its
|
||||
* switches follow:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code features.<key> = true|false} in {@code forge.toml};</li>
|
||||
* <li>the system property {@code zomboidforge.features.<key>=true|false}, which takes
|
||||
* precedence; the container entrypoint sets it from the environment variable
|
||||
* {@code ZF_<KEY>}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Code that a feature switches reads it through {@link ForgeSettings#enabled(Feature)} of the
|
||||
* running {@code Forge}, which has the defaults (every feature off) until the settings are read
|
||||
* at load.
|
||||
*/
|
||||
public enum Feature
|
||||
{
|
||||
/**
|
||||
* Performance changes that alter timing or resource use: more threads, shorter waits. Off,
|
||||
* the patched code does what vanilla does.
|
||||
*/
|
||||
EXPERIMENTAL_PERFORMANCE;
|
||||
|
||||
/** Prefix of the system properties: {@code zomboidforge.features.<key>}. */
|
||||
public static final String PROPERTY_PREFIX = "zomboidforge.features.";
|
||||
|
||||
/** The key in {@code forge.toml} and in the property name: the lowercase constant name. */
|
||||
public String key() { return this.name().toLowerCase(Locale.ROOT); }
|
||||
|
||||
/** The system property that switches this feature. */
|
||||
public String property() { return Feature.PROPERTY_PREFIX + this.key(); }
|
||||
|
||||
/** The feature with {@code key}. */
|
||||
public static Optional<Feature> byKey(String key)
|
||||
{
|
||||
return Arrays.stream(Feature.values()).filter(feature -> feature.key().equals(key)).findFirst();
|
||||
}
|
||||
}
|
||||
@@ -7,47 +7,58 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Global settings from {@code <forge>/forge.toml}. Every key is optional:
|
||||
*
|
||||
* <pre>
|
||||
* [main_thread]
|
||||
* budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
*
|
||||
* [shutdown]
|
||||
* timeout_s = 10 # how long mod threads get to finish when the server stops
|
||||
* </pre>
|
||||
* Global settings from {@code <forge>/forge.toml}.
|
||||
* The system property {@code zomboidforge.features.<key>}
|
||||
* of a feature takes precedence over its key in the file.
|
||||
*
|
||||
* @param mainThreadBudget at least 1 ms
|
||||
* @param shutdownTimeout 0 or more
|
||||
* @param features the features that are enabled
|
||||
*/
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout, Set<Feature> features)
|
||||
{
|
||||
public static final String FILE = "forge.toml";
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of());
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
|
||||
public ForgeSettings
|
||||
{
|
||||
features = Set.copyOf(features);
|
||||
}
|
||||
|
||||
/** Whether {@code feature} is on. */
|
||||
public boolean enabled(Feature feature) { return this.features.contains(feature); }
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown, Optional<Map<String, Boolean>> features) {}
|
||||
private record MainThread(Optional<Long> budgetMs) {}
|
||||
private record Shutdown(Optional<Long> timeoutS) {}
|
||||
|
||||
/**
|
||||
* The settings in {@code file}, or {@link #DEFAULTS} when it does not exist.
|
||||
* The settings in {@code file}, the defaults for what it leaves out or when it does not
|
||||
* exist; then the features switched in {@code properties} (the system properties).
|
||||
*
|
||||
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
|
||||
* of the wrong type or out of range
|
||||
* of the wrong type or out of range, feature properties that
|
||||
* name no feature or are not {@code true} or {@code false}
|
||||
*/
|
||||
public static ForgeSettings read(Path file)
|
||||
public static ForgeSettings read(Path file, Properties properties)
|
||||
{
|
||||
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
|
||||
|
||||
Map<String, Object> values;
|
||||
Map<String, Object> values = Map.of();
|
||||
|
||||
if (Files.isRegularFile(file))
|
||||
{
|
||||
try { values = TomlTree.parse(Files.readString(file)); }
|
||||
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
|
||||
}
|
||||
|
||||
RecordBinder binder = new RecordBinder();
|
||||
@Nullable Document document = binder.record(values, Document.class, "");
|
||||
@@ -63,8 +74,31 @@ public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + ".");
|
||||
if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + ".");
|
||||
|
||||
Set<Feature> features = EnumSet.noneOf(Feature.class);
|
||||
|
||||
for (Map.Entry<String, Boolean> entry : new TreeMap<>(document.features().orElse(Map.of())).entrySet())
|
||||
{
|
||||
Optional<Feature> feature = Feature.byKey(entry.getKey());
|
||||
|
||||
if (feature.isEmpty()) problems.add("Unknown key 'features." + entry.getKey() + "'.");
|
||||
else if (entry.getValue()) features.add(feature.get());
|
||||
}
|
||||
|
||||
for (String name : new TreeSet<>(properties.stringPropertyNames()))
|
||||
{
|
||||
if (!name.startsWith(Feature.PROPERTY_PREFIX)) continue;
|
||||
|
||||
Optional<Feature> feature = Feature.byKey(name.substring(Feature.PROPERTY_PREFIX.length()));
|
||||
String value = properties.getProperty(name);
|
||||
|
||||
if (feature.isEmpty()) problems.add("Unknown system property '" + name + "'.");
|
||||
else if (value.equalsIgnoreCase("true")) features.add(feature.get());
|
||||
else if (value.equalsIgnoreCase("false")) features.remove(feature.get());
|
||||
else problems.add("System property '" + name + "' must be true or false, found \"" + value + "\".");
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout), features);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class FeatureTest
|
||||
{
|
||||
@Test
|
||||
void keyAndPropertyFollowFromTheName()
|
||||
{
|
||||
assertEquals("experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.key());
|
||||
assertEquals("zomboidforge.features.experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.property());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsFeaturesByKey()
|
||||
{
|
||||
assertEquals(Optional.of(Feature.EXPERIMENTAL_PERFORMANCE), Feature.byKey("experimental_performance"));
|
||||
assertEquals(Optional.empty(), Feature.byKey("EXPERIMENTAL_PERFORMANCE"));
|
||||
assertEquals(Optional.empty(), Feature.byKey("faster"));
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
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;
|
||||
|
||||
class ForgeSettingsTest
|
||||
{
|
||||
@@ -16,27 +20,41 @@ class ForgeSettingsTest
|
||||
Path directory;
|
||||
|
||||
private ForgeSettings read(String toml) throws Exception
|
||||
{
|
||||
return this.read(toml, new Properties());
|
||||
}
|
||||
|
||||
private ForgeSettings read(String toml, Properties properties) throws Exception
|
||||
{
|
||||
Path file = this.directory.resolve(ForgeSettings.FILE);
|
||||
Files.writeString(file, toml);
|
||||
|
||||
return ForgeSettings.read(file);
|
||||
return ForgeSettings.read(file, properties);
|
||||
}
|
||||
|
||||
private static Properties properties(String... namesAndValues)
|
||||
{
|
||||
Properties properties = new Properties();
|
||||
for (int i = 0; i < namesAndValues.length; i += 2) properties.setProperty(namesAndValues[i], namesAndValues[i + 1]);
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsWithoutFileOrKeys() throws Exception
|
||||
{
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)));
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), new Properties()));
|
||||
assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n"));
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS);
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of()), ForgeSettings.DEFAULTS);
|
||||
assertFalse(ForgeSettings.DEFAULTS.enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsEveryKey() throws Exception
|
||||
{
|
||||
assertEquals(
|
||||
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0)),
|
||||
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n")
|
||||
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)),
|
||||
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n\n[features]\nexperimental_performance = true\n")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -52,4 +70,50 @@ class ForgeSettingsTest
|
||||
IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n"));
|
||||
assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void featuresAreOffUnlessSwitchedOn() throws Exception
|
||||
{
|
||||
assertFalse(this.read("[features]\nexperimental_performance = false\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertTrue(this.read("[features]\nexperimental_performance = true\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemPropertyTakesPrecedenceOverTheFile() throws Exception
|
||||
{
|
||||
String property = Feature.EXPERIMENTAL_PERFORMANCE.property();
|
||||
|
||||
assertTrue(this.read("", ForgeSettingsTest.properties(property, "true")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertTrue(this.read("[features]\nexperimental_performance = false\n", ForgeSettingsTest.properties(property, "TRUE")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertFalse(this.read("[features]\nexperimental_performance = true\n", ForgeSettingsTest.properties(property, "false")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemPropertyAppliesWithoutFile()
|
||||
{
|
||||
Properties properties = ForgeSettingsTest.properties(Feature.EXPERIMENTAL_PERFORMANCE.property(), "true");
|
||||
|
||||
assertTrue(ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), properties).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsUnknownFeaturesAndInvalidPropertyValues()
|
||||
{
|
||||
IllegalArgumentException key = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nexperimental_performance = \"yes\"\nfaster = true\n"));
|
||||
assertEquals("'features.experimental_performance' must be true or false, found \"yes\".", key.getMessage());
|
||||
|
||||
IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nfaster = true\n"));
|
||||
assertEquals("Unknown key 'features.faster'.", unknown.getMessage());
|
||||
|
||||
Properties properties = ForgeSettingsTest.properties(
|
||||
"zomboidforge.features.faster", "true",
|
||||
Feature.EXPERIMENTAL_PERFORMANCE.property(), "yes",
|
||||
"zomboidforge.dir", "/forge"
|
||||
);
|
||||
IllegalArgumentException property = assertThrows(IllegalArgumentException.class, () -> this.read("", properties));
|
||||
assertEquals(
|
||||
"System property 'zomboidforge.features.experimental_performance' must be true or false, found \"yes\". Unknown system property 'zomboidforge.features.faster'.",
|
||||
property.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
+89
-4
@@ -14,6 +14,10 @@
|
||||
# PORT Game port (-port). Default: 16261
|
||||
# UDP_PORT Direct connection port (-udpport). Default: 16262
|
||||
# STEAM 1 = Steam mode (required for official Steam clients), 0 = no Steam. Default: 1
|
||||
# UPNP true/false: UPnP port mapping on the router (.ini UPnP). false is
|
||||
# recommended: in a container the server sees only its container address,
|
||||
# publishing the ports is the container runtime's job, and the router
|
||||
# discovery delays every start by about 12 s.
|
||||
#
|
||||
# Admin account
|
||||
# ADMIN_USERNAME Admin account name (-adminusername), passed on every start.
|
||||
@@ -33,12 +37,23 @@
|
||||
# RCON_PASSWORD Written into the .ini before every start. RCON is disabled when empty.
|
||||
#
|
||||
# JVM
|
||||
# JVM_MIN_HEAP Value for -Xms. Default: JVM default
|
||||
# JVM_MAX_HEAP Value for -Xmx. Default: 8g (the vanilla ProjectZomboid64.json value)
|
||||
# JVM_MIN_HEAP Value for -Xms. Default: JVM default. ZGC returns unused heap memory
|
||||
# only down to this size.
|
||||
# JVM_MAX_HEAP Value for -Xmx. Default: 75 % of the container memory limit
|
||||
# (cgroup v2 memory.max); 8g, the vanilla ProjectZomboid64.json value,
|
||||
# when the container has no limit
|
||||
# JVM_UNCOMMIT_DELAY
|
||||
# Seconds of disuse after which ZGC returns heap memory to the system
|
||||
# (-XX:ZUncommitDelay). Default: 60 (JVM default: 300)
|
||||
#
|
||||
# Maintenance
|
||||
# SOFT_RESET true: start in Project Zomboid's soft reset mode (-Dsoftreset).
|
||||
# Intended for a single start; unset it afterwards.
|
||||
#
|
||||
# ZomboidForge features (also /forge/forge.toml [features]; a set variable takes precedence)
|
||||
# ZF_EXPERIMENTAL_PERFORMANCE
|
||||
# true/false: performance changes that alter timing or resource use
|
||||
# (more threads, shorter waits). Default: false
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
@@ -58,6 +73,7 @@ readonly PUBLIC_NAME="${PUBLIC_NAME:-}"
|
||||
readonly PORT="${PORT:-}"
|
||||
readonly UDP_PORT="${UDP_PORT:-}"
|
||||
readonly STEAM="${STEAM:-1}"
|
||||
readonly UPNP="${UPNP:-}"
|
||||
readonly ADMIN_USERNAME="${ADMIN_USERNAME:-}"
|
||||
readonly ADMIN_PASSWORD="${ADMIN_PASSWORD:-}"
|
||||
readonly SERVER_PRESET="${SERVER_PRESET:-}"
|
||||
@@ -65,7 +81,8 @@ readonly MODS="${MODS:-}"
|
||||
readonly WORKSHOP_ITEMS="${WORKSHOP_ITEMS:-}"
|
||||
readonly RCON_PASSWORD="${RCON_PASSWORD:-}"
|
||||
readonly JVM_MIN_HEAP="${JVM_MIN_HEAP:-}"
|
||||
readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-8g}"
|
||||
readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-}"
|
||||
readonly JVM_UNCOMMIT_DELAY="${JVM_UNCOMMIT_DELAY:-60}"
|
||||
readonly SOFT_RESET="${SOFT_RESET:-}"
|
||||
|
||||
readonly SERVER_INI="${DATA_DIR}/Server/${SERVER_NAME}.ini"
|
||||
@@ -73,6 +90,11 @@ readonly SERVER_SANDBOX_VARS="${DATA_DIR}/Server/${SERVER_NAME}_SandboxVars.lua"
|
||||
readonly SERVER_DB="${DATA_DIR}/db/${SERVER_NAME}.db"
|
||||
# Target of the /opt/pz/steamapps symlink; Steam stores Workshop downloads there.
|
||||
readonly STEAMAPPS_DIR="${DATA_DIR}/steamapps"
|
||||
readonly CGROUP_MEMORY_MAX="/sys/fs/cgroup/memory.max"
|
||||
# Keys of the ZomboidForge features (core/config/Feature): ZF_<KEY> becomes
|
||||
# -Dzomboidforge.features.<key>.
|
||||
readonly FEATURES=(experimental_performance)
|
||||
readonly UNLIMITED_MAX_HEAP="8g"
|
||||
|
||||
log() {
|
||||
echo "[entrypoint] $*" >&2
|
||||
@@ -166,6 +188,16 @@ apply_ini_settings() {
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "${UPNP}" ]]; then
|
||||
if is_true "${UPNP}"; then
|
||||
set_ini_value "UPnP" "true"
|
||||
elif is_false "${UPNP}"; then
|
||||
set_ini_value "UPnP" "false"
|
||||
else
|
||||
fail "UPNP must be true or false, got '${UPNP}'."
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "${RCON_PASSWORD}" ]]; then
|
||||
set_ini_value "RCONPassword" "${RCON_PASSWORD}"
|
||||
else
|
||||
@@ -231,16 +263,68 @@ check_admin_account() {
|
||||
fi
|
||||
}
|
||||
|
||||
# 75 % of the cgroup v2 memory limit in MiB; UNLIMITED_MAX_HEAP without a limit.
|
||||
# The rest of the limit is left for native memory (JVM, native libraries, thread stacks).
|
||||
default_max_heap() {
|
||||
local limit
|
||||
|
||||
if [[ ! -r "${CGROUP_MEMORY_MAX}" ]]; then
|
||||
echo "${UNLIMITED_MAX_HEAP}"
|
||||
return
|
||||
fi
|
||||
limit="$(< "${CGROUP_MEMORY_MAX}")"
|
||||
if [[ "${limit}" == "max" ]]; then
|
||||
echo "${UNLIMITED_MAX_HEAP}"
|
||||
return
|
||||
fi
|
||||
echo "$(( limit * 3 / 4 / 1024 / 1024 ))m"
|
||||
}
|
||||
|
||||
# Appends -Dzomboidforge.features.<key>=true|false for every feature whose ZF_<KEY> is set.
|
||||
# Unset or empty: no property, so forge.toml or the default (off) decides.
|
||||
add_feature_properties() {
|
||||
local key
|
||||
local variable
|
||||
local value
|
||||
|
||||
for key in "${FEATURES[@]}"; do
|
||||
variable="ZF_${key^^}"
|
||||
value="${!variable:-}"
|
||||
|
||||
if [[ -z "${value}" ]]; then
|
||||
continue
|
||||
fi
|
||||
if is_true "${value}"; then
|
||||
jvm_args+=("-Dzomboidforge.features.${key}=true")
|
||||
elif is_false "${value}"; then
|
||||
jvm_args+=("-Dzomboidforge.features.${key}=false")
|
||||
else
|
||||
fail "${variable} must be true or false, got '${value}'."
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh.
|
||||
# Java runs directly instead of through the native ProjectZomboid64 launcher.
|
||||
build_jvm_args() {
|
||||
local max_heap="${JVM_MAX_HEAP}"
|
||||
|
||||
if [[ -z "${max_heap}" ]]; then
|
||||
max_heap="$(default_max_heap)"
|
||||
log "JVM_MAX_HEAP is not set: using -Xmx${max_heap}."
|
||||
fi
|
||||
if [[ ! "${JVM_UNCOMMIT_DELAY}" =~ ^[0-9]+$ ]]; then
|
||||
fail "JVM_UNCOMMIT_DELAY must be a number of seconds, got '${JVM_UNCOMMIT_DELAY}'."
|
||||
fi
|
||||
|
||||
jvm_args=(
|
||||
"-javaagent:${AGENT_JAR}"
|
||||
"-Dzomboidforge.dir=${FORGE_DIR}"
|
||||
"-Djava.awt.headless=true"
|
||||
"--enable-native-access=ALL-UNNAMED"
|
||||
"-Xmx${JVM_MAX_HEAP}"
|
||||
"-Xmx${max_heap}"
|
||||
"-XX:+UseZGC"
|
||||
"-XX:ZUncommitDelay=${JVM_UNCOMMIT_DELAY}"
|
||||
"-XX:-OmitStackTraceInFastThrow"
|
||||
"-Dzomboid.steam=${STEAM}"
|
||||
"-Dzomboid.znetlog=1"
|
||||
@@ -256,6 +340,7 @@ build_jvm_args() {
|
||||
log "SOFT_RESET is set: starting in soft reset mode. Unset it for the next start."
|
||||
jvm_args+=("-Dsoftreset")
|
||||
fi
|
||||
add_feature_properties
|
||||
}
|
||||
|
||||
build_server_args() {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.LabelNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.TryCatchBlockNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
/** Replaces the body of a method of the target class with a call to a {@link Hook}, or wraps it in hook calls. */
|
||||
public final class MethodBody
|
||||
{
|
||||
private static final Type OBJECT = Type.getObjectType("java/lang/Object");
|
||||
|
||||
private MethodBody() {}
|
||||
|
||||
/**
|
||||
* Replaces the body of {@code method} with {@code return hook(arguments);}: the hook receives
|
||||
* the method's arguments, without {@code this}, and has the method's parameter and return
|
||||
* types; a parameter of a reference type may be {@code Object} in the hook, for types the hook
|
||||
* cannot name (private classes of the game). Fails when the method has no body, when the types
|
||||
* differ otherwise, or when an instance method's old body uses {@code this}, which the hook
|
||||
* would not receive.
|
||||
*/
|
||||
public static void delegate(ClassNode node, MethodNode method, Hook hook)
|
||||
{
|
||||
String name = "'" + node.name + "." + method.name + method.desc + "'";
|
||||
Type type = Type.getMethodType(method.desc);
|
||||
Type hookType = Type.getMethodType(hook.desc());
|
||||
boolean isStatic = (method.access & Opcodes.ACC_STATIC) != 0;
|
||||
|
||||
if ((method.access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0)
|
||||
throw new IllegalStateException(name + " has no body.");
|
||||
|
||||
if (!MethodBody.accepts(hookType.getArgumentTypes(), type.getArgumentTypes()) || !type.getReturnType().equals(hookType.getReturnType()))
|
||||
throw new IllegalStateException(name + " and its hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' have different types.");
|
||||
|
||||
if (!isStatic && MethodBody.usesThis(method))
|
||||
throw new IllegalStateException(name + " uses 'this', which the hook does not receive.");
|
||||
|
||||
// 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;
|
||||
|
||||
int slot = isStatic ? 0 : 1;
|
||||
for (Type argument : type.getArgumentTypes())
|
||||
{
|
||||
method.instructions.add(new VarInsnNode(argument.getOpcode(Opcodes.ILOAD), slot));
|
||||
slot += argument.getSize();
|
||||
}
|
||||
|
||||
method.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false));
|
||||
method.instructions.add(new InsnNode(type.getReturnType().getOpcode(Opcodes.IRETURN)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the static void method {@code method}: renames it to {@code renamed} and adds a method
|
||||
* with its name, descriptor and access that runs
|
||||
*
|
||||
* <pre>{@code
|
||||
* before();
|
||||
* try { renamed(arguments); }
|
||||
* finally { after(); }
|
||||
* }</pre>
|
||||
*
|
||||
* {@code before} and {@code after} take no arguments. Fails for instance methods, methods
|
||||
* that return a value, and when {@code node} already has a method named {@code renamed}.
|
||||
*/
|
||||
public static void wrap(ClassNode node, MethodNode method, String renamed, Hook before, Hook after)
|
||||
{
|
||||
String name = "'" + node.name + "." + method.name + method.desc + "'";
|
||||
|
||||
if ((method.access & Opcodes.ACC_STATIC) == 0)
|
||||
throw new IllegalStateException(name + " is not static.");
|
||||
if (Type.getReturnType(method.desc) != Type.VOID_TYPE)
|
||||
throw new IllegalStateException(name + " returns a value.");
|
||||
if (node.methods.stream().anyMatch(other -> other.name.equals(renamed)))
|
||||
throw new IllegalStateException("'" + node.name + "' already has a method '" + renamed + "'.");
|
||||
|
||||
MethodNode wrapper = new MethodNode(method.access, method.name, method.desc, method.signature, method.exceptions.toArray(String[]::new));
|
||||
method.name = renamed;
|
||||
|
||||
LabelNode start = new LabelNode();
|
||||
LabelNode end = new LabelNode();
|
||||
LabelNode handler = new LabelNode();
|
||||
InsnList code = wrapper.instructions;
|
||||
int slot = 0;
|
||||
|
||||
code.add(MethodBody.call(before));
|
||||
code.add(start);
|
||||
for (Type argument : Type.getArgumentTypes(method.desc))
|
||||
{
|
||||
code.add(new VarInsnNode(argument.getOpcode(Opcodes.ILOAD), slot));
|
||||
slot += argument.getSize();
|
||||
}
|
||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, node.name, renamed, method.desc, (node.access & Opcodes.ACC_INTERFACE) != 0));
|
||||
code.add(end);
|
||||
code.add(MethodBody.call(after));
|
||||
code.add(new InsnNode(Opcodes.RETURN));
|
||||
|
||||
// finally on the exception path: run after(), rethrow; the exception goes to the first free slot.
|
||||
code.add(handler);
|
||||
code.add(new VarInsnNode(Opcodes.ASTORE, slot));
|
||||
code.add(MethodBody.call(after));
|
||||
code.add(new VarInsnNode(Opcodes.ALOAD, slot));
|
||||
code.add(new InsnNode(Opcodes.ATHROW));
|
||||
|
||||
wrapper.tryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, null));
|
||||
node.methods.add(wrapper);
|
||||
}
|
||||
|
||||
private static MethodInsnNode call(Hook hook)
|
||||
{
|
||||
if (!hook.desc().equals("()V"))
|
||||
throw new IllegalStateException("The hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' must take no arguments and return nothing.");
|
||||
|
||||
return new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false);
|
||||
}
|
||||
|
||||
/** Whether a hook with {@code parameters} takes {@code arguments}: equal types, or {@code Object} for a reference type. */
|
||||
private static boolean accepts(Type[] parameters, Type[] arguments)
|
||||
{
|
||||
if (parameters.length != arguments.length) return false;
|
||||
|
||||
for (int i = 0; i < arguments.length; i++)
|
||||
{
|
||||
boolean reference = arguments[i].getSort() == Type.OBJECT || arguments[i].getSort() == Type.ARRAY;
|
||||
boolean asObject = reference && parameters[i].equals(MethodBody.OBJECT);
|
||||
|
||||
if (!parameters[i].equals(arguments[i]) && !asObject) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether the method reads or writes local variable 0, which holds {@code this}. */
|
||||
private static boolean usesThis(MethodNode method)
|
||||
{
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction instanceof VarInsnNode variable && variable.var == 0) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package dev.overlord.zomboidforge.patcher.Patches;
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package dev.overlord.zomboidforge.patcher.Patches;
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package dev.overlord.zomboidforge.patcher.Patches;
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package dev.overlord.zomboidforge.patcher.Patches;
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package dev.overlord.zomboidforge.patcher.Patches;
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Redirects the {@code Thread.sleep(long)} calls of one method to a {@link Hook} with the same
|
||||
* signature, {@code (J)V}. For waiting loops that check a condition, sleep, and check again: the
|
||||
* hook sleeps shorter or can be woken, while the loop's condition stays the vanilla one. Fails
|
||||
* unless the method has exactly the expected number of sleeps. {@link #appliesTo} is left to the
|
||||
* subclass, as for every {@link PerformancePatch}.
|
||||
*/
|
||||
public abstract class ThreadSleepPerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final String SLEEP = "(J)V";
|
||||
|
||||
private final Anchor.Method method;
|
||||
private final int sleeps;
|
||||
private final Hook hook;
|
||||
|
||||
/**
|
||||
* @param target internal name of the class
|
||||
* @param method the method with the waiting loop
|
||||
* @param sleeps the number of {@code Thread.sleep(long)} calls in it
|
||||
* @param hook the replacement for {@code Thread.sleep(long)}, {@code (J)V}
|
||||
*/
|
||||
protected ThreadSleepPerformancePatch(String target, Anchor.Method method, int sleeps, Hook hook)
|
||||
{
|
||||
super(target, method, hook);
|
||||
|
||||
if (!hook.desc().equals(ThreadSleepPerformancePatch.SLEEP))
|
||||
throw new IllegalArgumentException("The hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' must have the signature of 'Thread.sleep(long)', (J)V.");
|
||||
if (sleeps < 1)
|
||||
throw new IllegalArgumentException("A method with " + sleeps + " sleeps has nothing to redirect.");
|
||||
|
||||
this.method = method;
|
||||
this.sleeps = sleeps;
|
||||
this.hook = hook;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode method = this.method.resolve(node);
|
||||
List<MethodInsnNode> found = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions)
|
||||
{
|
||||
if (instruction instanceof MethodInsnNode call && call.getOpcode() == Opcodes.INVOKESTATIC
|
||||
&& call.owner.equals("java/lang/Thread") && call.name.equals("sleep") && call.desc.equals(ThreadSleepPerformancePatch.SLEEP))
|
||||
found.add(call);
|
||||
}
|
||||
|
||||
if (found.size() != this.sleeps)
|
||||
throw new IllegalStateException("Expected " + this.sleeps + " call(s) to 'Thread.sleep(long)' in '" + node.name + "." + method.name + method.desc + "', found " + found.size() + ".");
|
||||
|
||||
for (MethodInsnNode call : found)
|
||||
{
|
||||
call.owner = this.hook.owner();
|
||||
call.name = this.hook.name();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/** @noinspection UnstableApiUsage, RedundantSuppression */
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.patcher.Patches;
|
||||
package dev.overlord.zomboidforge.patcher.patches;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch;
|
||||
import dev.overlord.zomboidforge.patcher.patches.CancellableHookPatch;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
|
||||
import dev.overlord.zomboidforge.patcher.patches.HookInjectionPatch;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.ICONST_0;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.IRETURN;
|
||||
import static org.objectweb.asm.Opcodes.LCONST_0;
|
||||
import static org.objectweb.asm.Opcodes.LLOAD;
|
||||
import static org.objectweb.asm.Opcodes.LRETURN;
|
||||
import static org.objectweb.asm.Opcodes.POP;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
/** Runs methods whose bodies {@link MethodBody#delegate} replaced with calls to the hooks below. */
|
||||
public class MethodBodyTest
|
||||
{
|
||||
private static final String TARGET = "t/Target";
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/patcher/MethodBodyTest";
|
||||
|
||||
public static String recorded;
|
||||
|
||||
public static int sum(int a, int b) { return a + b; }
|
||||
|
||||
/** Two-slot arguments around a one-slot one, so wrong slot numbers show. */
|
||||
public static long combine(long a, String b, double c) { return a * 1000 + b.length() * 100 + (long) c; }
|
||||
|
||||
public static void record(String value) { MethodBodyTest.recorded = value; }
|
||||
|
||||
public static void recordAny(String value, Object other) { MethodBodyTest.recorded = value + " " + other; }
|
||||
|
||||
public static void recordObject(Object value) { MethodBodyTest.recorded = String.valueOf(value); }
|
||||
|
||||
/** Calls of the hooks below, in order. */
|
||||
public static final List<String> EVENTS = new ArrayList<>();
|
||||
|
||||
public static void before() { MethodBodyTest.EVENTS.add("before"); }
|
||||
|
||||
public static void after() { MethodBodyTest.EVENTS.add("after"); }
|
||||
|
||||
public static void work(long value, String text) { MethodBodyTest.EVENTS.add("work " + value + " " + text); }
|
||||
|
||||
public static void fail() { throw new IllegalStateException("failed"); }
|
||||
|
||||
/** Defines classes from nodes, with the test classes as parent so the hooks resolve. */
|
||||
private static final class Definer extends ClassLoader
|
||||
{
|
||||
Definer() { super(MethodBodyTest.class.getClassLoader()); }
|
||||
|
||||
Class<?> define(ClassNode node)
|
||||
{
|
||||
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
|
||||
node.accept(writer);
|
||||
byte[] bytes = writer.toByteArray();
|
||||
return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code t/Target} with a constructor and one method whose body returns a constant (or uses
|
||||
* {@code this} when {@code usesThis}).
|
||||
*/
|
||||
private static ClassNode target(int access, String name, String desc, boolean usesThis)
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC | ((access & ACC_ABSTRACT) != 0 ? ACC_ABSTRACT : 0), MethodBodyTest.TARGET, 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 method = node.visitMethod(access, name, desc, null, null);
|
||||
if ((access & ACC_ABSTRACT) == 0)
|
||||
{
|
||||
if (usesThis)
|
||||
{
|
||||
method.visitVarInsn(ALOAD, 0);
|
||||
method.visitInsn(POP);
|
||||
}
|
||||
switch (desc.charAt(desc.length() - 1))
|
||||
{
|
||||
case 'I' -> { method.visitInsn(ICONST_0); method.visitInsn(IRETURN); }
|
||||
case 'J' -> { method.visitInsn(LCONST_0); method.visitInsn(LRETURN); }
|
||||
default -> method.visitInsn(RETURN);
|
||||
}
|
||||
method.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 Object run(ClassNode node, String name, Class<?>[] types, Object... arguments) throws ReflectiveOperationException
|
||||
{
|
||||
Class<?> loaded = new Definer().define(node);
|
||||
Method method = loaded.getMethod(name, types);
|
||||
Object self = (method.getModifiers() & ACC_STATIC) != 0 ? null : loaded.getConstructor().newInstance();
|
||||
|
||||
return method.invoke(self, arguments);
|
||||
}
|
||||
|
||||
@Test
|
||||
void staticMethodReturnsWhatTheHookReturns() throws ReflectiveOperationException
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false);
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"));
|
||||
|
||||
assertEquals(7, MethodBodyTest.run(node, "add", new Class<?>[] { int.class, int.class }, 3, 4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceMethodPassesItsArgumentsWithoutThis() throws ReflectiveOperationException
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC, "mix", "(JLjava/lang/String;D)J", false);
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "mix"), new Hook(MethodBodyTest.HOOKS, "combine", "(JLjava/lang/String;D)J"));
|
||||
|
||||
assertEquals(5_327L, MethodBodyTest.run(node, "mix", new Class<?>[] { long.class, String.class, double.class }, 5L, "abc", 27.9));
|
||||
}
|
||||
|
||||
@Test
|
||||
void voidMethodCallsTheHook() throws ReflectiveOperationException
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(Ljava/lang/String;)V", false);
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "record", "(Ljava/lang/String;)V"));
|
||||
|
||||
MethodBodyTest.recorded = null;
|
||||
assertNull(MethodBodyTest.run(node, "save", new Class<?>[] { String.class }, "saved"));
|
||||
assertEquals("saved", MethodBodyTest.recorded);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hookTakesAReferenceArgumentAsObject() throws ReflectiveOperationException
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(Ljava/lang/String;Ljava/lang/StringBuilder;)V", false);
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "recordAny", "(Ljava/lang/String;Ljava/lang/Object;)V"));
|
||||
|
||||
MethodBodyTest.recorded = null;
|
||||
MethodBodyTest.run(node, "save", new Class<?>[] { String.class, StringBuilder.class }, "saved", new StringBuilder("text"));
|
||||
assertEquals("saved text", MethodBodyTest.recorded);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheHookTakesAPrimitiveArgumentAsObject()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(I)V", false);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "recordObject", "(Ljava/lang/Object;)V"))
|
||||
);
|
||||
assertTrue(e.getMessage().contains("different types"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropsTheLocalVariablesOfTheOldBody()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false);
|
||||
MethodNode method = MethodBodyTest.method(node, "add");
|
||||
method.localVariables = new ArrayList<>();
|
||||
|
||||
MethodBody.delegate(node, method, new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"));
|
||||
|
||||
assertNull(method.localVariables);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheTypesDiffer()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "combine", "(JLjava/lang/String;D)J"))
|
||||
);
|
||||
assertTrue(e.getMessage().contains("different types"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheOldBodyUsesThis()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC, "add", "(II)I", true);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"))
|
||||
);
|
||||
assertTrue(e.getMessage().contains("uses 'this'"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsForAMethodWithoutBody()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_ABSTRACT, "add", "(II)I", false);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
|
||||
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"))
|
||||
);
|
||||
assertTrue(e.getMessage().contains("has no body"), e.getMessage());
|
||||
}
|
||||
|
||||
/** {@code t/Target} with {@code public static void run(long, String)} calling {@code body} with its arguments or none. */
|
||||
private static ClassNode wrappable(String body, String bodyDesc)
|
||||
{
|
||||
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "placeholder", "()V", false);
|
||||
MethodVisitor run = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "(JLjava/lang/String;)V", null, null);
|
||||
|
||||
if (bodyDesc.equals("(JLjava/lang/String;)V"))
|
||||
{
|
||||
run.visitVarInsn(LLOAD, 0);
|
||||
run.visitVarInsn(ALOAD, 2);
|
||||
}
|
||||
run.visitMethodInsn(INVOKESTATIC, MethodBodyTest.HOOKS, body, bodyDesc, false);
|
||||
run.visitInsn(RETURN);
|
||||
run.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static final Hook BEFORE = new Hook(MethodBodyTest.HOOKS, "before", "()V");
|
||||
private static final Hook AFTER = new Hook(MethodBodyTest.HOOKS, "after", "()V");
|
||||
|
||||
@Test
|
||||
void wrapRunsBeforeTheOriginalWithItsArgumentsThenAfter() throws ReflectiveOperationException
|
||||
{
|
||||
ClassNode node = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V");
|
||||
MethodBody.wrap(node, MethodBodyTest.method(node, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER);
|
||||
|
||||
MethodBodyTest.EVENTS.clear();
|
||||
MethodBodyTest.run(node, "run", new Class<?>[] { long.class, String.class }, 42L, "abc");
|
||||
|
||||
assertEquals(List.of("before", "work 42 abc", "after"), MethodBodyTest.EVENTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapRunsAfterAndRethrowsWhenTheOriginalThrows()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.wrappable("fail", "()V");
|
||||
MethodBody.wrap(node, MethodBodyTest.method(node, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER);
|
||||
|
||||
MethodBodyTest.EVENTS.clear();
|
||||
InvocationTargetException e = assertThrows(InvocationTargetException.class, () ->
|
||||
MethodBodyTest.run(node, "run", new Class<?>[] { long.class, String.class }, 1L, "x")
|
||||
);
|
||||
|
||||
assertTrue(e.getCause() instanceof IllegalStateException);
|
||||
assertEquals("failed", e.getCause().getMessage());
|
||||
assertEquals(List.of("before", "after"), MethodBodyTest.EVENTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapKeepsTheOriginalUnderTheNewName()
|
||||
{
|
||||
ClassNode node = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V");
|
||||
MethodBody.wrap(node, MethodBodyTest.method(node, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER);
|
||||
|
||||
assertEquals(1, node.methods.stream().filter(method -> method.name.equals("run")).count());
|
||||
assertEquals(1, node.methods.stream().filter(method -> method.name.equals("original$run") && method.desc.equals("(JLjava/lang/String;)V")).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapFailsForInstanceMethodsValuesTakenNamesAndHooksWithArguments()
|
||||
{
|
||||
ClassNode instance = MethodBodyTest.target(ACC_PUBLIC, "run", "()V", false);
|
||||
assertThrows(IllegalStateException.class, () -> MethodBody.wrap(instance, MethodBodyTest.method(instance, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER));
|
||||
|
||||
ClassNode value = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "run", "()I", false);
|
||||
assertThrows(IllegalStateException.class, () -> MethodBody.wrap(value, MethodBodyTest.method(value, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER));
|
||||
|
||||
ClassNode taken = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V");
|
||||
assertThrows(IllegalStateException.class, () -> MethodBody.wrap(taken, MethodBodyTest.method(taken, "run"), "placeholder", MethodBodyTest.BEFORE, MethodBodyTest.AFTER));
|
||||
|
||||
ClassNode arguments = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V");
|
||||
Hook withArgs = new Hook(MethodBodyTest.HOOKS, "record", "(Ljava/lang/String;)V");
|
||||
assertThrows(IllegalStateException.class, () -> MethodBody.wrap(arguments, MethodBodyTest.method(arguments, "run"), "original$run", withArgs, MethodBodyTest.AFTER));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
|
||||
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package dev.overlord.zomboidforge.patcher;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ThreadSleepPerformancePatch;
|
||||
|
||||
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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.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;
|
||||
|
||||
class ThreadSleepPerformancePatchTest
|
||||
{
|
||||
private static final Hook HOOK = new Hook("t/WaitHooks", "shortSleep", "(J)V");
|
||||
|
||||
private static final class Patch extends ThreadSleepPerformancePatch
|
||||
{
|
||||
Patch(int sleeps, Hook hook) { super("t/Target", new Anchor.Method("waitLoop", "()V"), sleeps, hook); }
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return true; }
|
||||
}
|
||||
|
||||
/** {@code t/Target.waitLoop()} with {@code sleeps} calls of {@code Thread.sleep(1L)} and one of {@code Thread.yield()}. */
|
||||
private static ClassNode target(int sleeps)
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor method = node.visitMethod(ACC_PUBLIC, "waitLoop", "()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.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "yield", "()V", false);
|
||||
method.visitInsn(RETURN);
|
||||
method.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static List<String> calls(ClassNode node)
|
||||
{
|
||||
List<String> calls = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : node.methods.getFirst().instructions) {
|
||||
if (instruction instanceof MethodInsnNode call) calls.add(call.owner + "." + call.name + call.desc);
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectsEverySleepAndNothingElse()
|
||||
{
|
||||
ClassNode node = ThreadSleepPerformancePatchTest.target(2);
|
||||
new Patch(2, ThreadSleepPerformancePatchTest.HOOK).apply(node);
|
||||
|
||||
assertEquals(List.of("t/WaitHooks.shortSleep(J)V", "t/WaitHooks.shortSleep(J)V", "java/lang/Thread.yield()V"), ThreadSleepPerformancePatchTest.calls(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsForAnotherNumberOfSleeps()
|
||||
{
|
||||
ClassNode node = ThreadSleepPerformancePatchTest.target(1);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new Patch(2, ThreadSleepPerformancePatchTest.HOOK).apply(node));
|
||||
assertTrue(e.getMessage().contains("Expected 2 call(s)") && e.getMessage().contains("found 1"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAHookWithAnotherSignature()
|
||||
{
|
||||
assertThrows(IllegalArgumentException.class, () -> new Patch(1, new Hook("t/WaitHooks", "shortSleep", "(I)V")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsZeroSleeps()
|
||||
{
|
||||
assertThrows(IllegalArgumentException.class, () -> new Patch(0, ThreadSleepPerformancePatchTest.HOOK));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user