Optimize IsoZombie.isVehicleBetween performance: implement IsoZombieVehiclePerformancePatch. Add SegmentReach class for efficient distance checks and ZombieVehicleHooks for targeted vehicle intersection. Include tests for new functionality and integrate patch into B42PatchSet.

This commit is contained in:
Overlord committed 2026-10-01 10:09:54 +02:00
1 parent d7151f60e8
commit da7ae49618
8 files changed
+446 -6

No files matched your search

@@ -9,7 +9,8 @@ import java.util.List;
public final class B42PatchSet implements PatchSet public final class B42PatchSet implements PatchSet
{ {
private static final List<ClassPatch> PATCHES = List.of( private static final List<ClassPatch> PATCHES = List.of(
new ServerStartedPatch() new ServerStartedPatch(),
new IsoZombieVehiclePerformancePatch()
); );
@Override @Override
@@ -0,0 +1,94 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Makes {@code IsoZombie.isVehicleBetween} cheaper without changing its result, in two steps:
*
* <ul>
* <li>Returns {@code false} at the start of the method when the cell has no vehicles. The
* loop would not run, but the three pooled vectors are allocated and released first.</li>
* <li>Replaces the call to {@code BaseVehicle.getIntersectPoint} with
* {@code ZombieVehicleHooks.getIntersectPoint}, which skips vehicles that the segment
* cannot reach.</li>
* </ul>
*/
public final class IsoZombieVehiclePerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("isVehicleBetween", "(FFF)Z"),
"zombie/vehicles/BaseVehicle", "getIntersectPoint",
"(Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", "getIntersectPoint",
"(Lzombie/vehicles/BaseVehicle;Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
);
public IsoZombieVehiclePerformancePatch() {
super("zombie/characters/IsoZombie", IsoZombieVehiclePerformancePatch.ANCHOR, IsoZombieVehiclePerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoZombieVehiclePerformancePatch.ANCHOR.in().resolve(node);
MethodInsnNode call = IsoZombieVehiclePerformancePatch.ANCHOR.resolve(node);
// The hook takes the receiver as its first argument, so the operand stack is the same
// as for the virtual call it replaces: vehicle, start, end, result -> Vector3f.
method.instructions.set(call, new MethodInsnNode(
Opcodes.INVOKESTATIC,
IsoZombieVehiclePerformancePatch.HOOK.owner(),
IsoZombieVehiclePerformancePatch.HOOK.name(),
IsoZombieVehiclePerformancePatch.HOOK.desc(),
false
));
method.instructions.insert(IsoZombieVehiclePerformancePatch.returnFalseWithoutVehicles());
}
/**
* {@code if (IsoWorld.instance.currentCell.getVehicles().isEmpty()) return false;}, the same
* expression the method iterates over. The method starts with an empty operand stack, so the
* stack map frame at the jump target is the one of the method entry; the class writer
* computes it.
*/
private static @NotNull InsnList returnFalseWithoutVehicles()
{
LabelNode hasVehicles = new LabelNode();
InsnList code = new InsnList();
code.add(new FieldInsnNode(Opcodes.GETSTATIC, "zombie/iso/IsoWorld", "instance", "Lzombie/iso/IsoWorld;"));
code.add(new FieldInsnNode(Opcodes.GETFIELD, "zombie/iso/IsoWorld", "currentCell", "Lzombie/iso/IsoCell;"));
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "zombie/iso/IsoCell", "getVehicles", "()Ljava/util/Set;", false));
code.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "java/util/Set", "isEmpty", "()Z", true));
code.add(new JumpInsnNode(Opcodes.IFEQ, hasVehicles));
code.add(new InsnNode(Opcodes.ICONST_0));
code.add(new InsnNode(Opcodes.IRETURN));
code.add(hasVehicles);
return code;
}
}
@@ -0,0 +1,161 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.ISTORE;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieVehiclePerformancePatchTest
{
private static final String VECTOR = "org/joml/Vector3f";
private static final String CALL = "(L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";";
/**
* {@code IsoZombie} with a reduced {@code isVehicleBetween}: one call to
* {@code BaseVehicle.getIntersectPoint}, result ignored, then {@code return intersect}.
*/
private static ClassNode target()
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, "zombie/characters/IsoZombie", null, "java/lang/Object", null);
MethodVisitor m = cw.visitMethod(ACC_PRIVATE, "isVehicleBetween", "(FFF)Z", null, null);
m.visitInsn(ICONST_0);
m.visitVarInsn(ISTORE, 4);
m.visitInsn(ACONST_NULL);
m.visitTypeInsn(CHECKCAST, "zombie/vehicles/BaseVehicle");
m.visitInsn(ACONST_NULL);
m.visitInsn(ACONST_NULL);
m.visitInsn(ACONST_NULL);
m.visitMethodInsn(INVOKEVIRTUAL, "zombie/vehicles/BaseVehicle", "getIntersectPoint", IsoZombieVehiclePerformancePatchTest.CALL, false);
m.visitInsn(POP);
m.visitVarInsn(ILOAD, 4);
m.visitInsn(IRETURN);
m.visitMaxs(0, 0);
cw.visitEnd();
ClassNode node = new ClassNode();
new ClassReader(cw.toByteArray()).accept(node, 0);
return node;
}
private static MethodNode isVehicleBetween(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("isVehicleBetween")).findFirst().orElseThrow();
}
/** Opcodes of the real instructions: no labels, line numbers, or frames. */
private static List<Integer> opcodes(MethodNode method)
{
List<Integer> opcodes = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) opcodes.add(instruction.getOpcode());
}
return opcodes;
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieVehiclePerformancePatch().anchor().verify(IsoZombieVehiclePerformancePatchTest.target());
}
@Test
void returnsFalseFirstWhenTheCellHasNoVehicles()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
List<Integer> opcodes = IsoZombieVehiclePerformancePatchTest.opcodes(IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node));
assertEquals(
List.of(GETSTATIC, GETFIELD, INVOKEVIRTUAL, INVOKEINTERFACE, IFEQ, ICONST_0, IRETURN),
opcodes.subList(0, 7)
);
}
@Test
void jumpsOverTheEarlyReturnToTheOriginalCode()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
MethodNode method = IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node);
JumpInsnNode jump = null;
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof JumpInsnNode candidate) jump = candidate;
}
// The label sits directly before the original first instruction, iconst_0 of "intersectVision = false".
AbstractInsnNode firstOriginal = jump.label.getNext();
while (firstOriginal.getOpcode() == -1) firstOriginal = firstOriginal.getNext();
assertEquals(ICONST_0, firstOriginal.getOpcode());
assertEquals(ISTORE, firstOriginal.getNext().getOpcode());
}
@Test
void replacesTheVirtualCallWithTheHook()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node).instructions) {
if (instruction instanceof MethodInsnNode call && call.name.equals("getIntersectPoint")) calls.add(call);
}
assertEquals(1, calls.size());
MethodInsnNode call = calls.getFirst();
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", call.owner);
assertEquals("(Lzombie/vehicles/BaseVehicle;L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";", call.desc);
assertFalse(call.itf);
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieVehiclePerformancePatch patch = new IsoZombieVehiclePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -4,7 +4,6 @@ import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MethodNode;
@@ -44,7 +43,7 @@ class NamingRulesTest
} }
@Test @Test
void hookClassesEndInHooksAndExposeOnlyPublicStaticVoidMethods() throws Exception void hookClassesEndInHooksAndExposeOnlyPublicStaticMethods() throws Exception
{ {
List<String> problems = new ArrayList<>(); List<String> problems = new ArrayList<>();
List<String> names = PackageScan.topLevelClassNames(NamingRulesTest.HOOKS_PACKAGE); List<String> names = PackageScan.topLevelClassNames(NamingRulesTest.HOOKS_PACKAGE);
@@ -69,9 +68,7 @@ class NamingRulesTest
} }
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0; boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
if (!publicStatic || Type.getReturnType(method.desc) != Type.VOID_TYPE) { if (!publicStatic) problems.add("'" + name + "." + method.name + method.desc + "' must be public static");
problems.add("'" + name + "." + method.name + method.desc + "' must be public static and return void");
}
} }
} }
+4
View File
@@ -9,4 +9,8 @@ dependencies {
implementation(project(":core")) implementation(project(":core"))
implementation(project(":api")) implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar)) compileOnly(files(projectZomboid.serverJar))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
} }
@@ -0,0 +1,57 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.perf.SegmentReach;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import zombie.core.physics.WorldSimulation;
import zombie.scripting.objects.VehicleScript;
import zombie.vehicles.BaseVehicle;
/** Hooks called by patched {@code zombie.characters.IsoZombie} code. */
public final class ZombieVehicleHooks
{
/**
* World units added to the bounding radius. Float resolution near the world coordinates
* (about 10000) is 0.001, so this covers rounding differences to the vanilla test.
*/
private static final float MARGIN = 0.1F;
private ZombieVehicleHooks() {}
/**
* Replaces the call {@code vehicle.getIntersectPoint(start, end, result)} in
* {@code IsoZombie.isVehicleBetween}. Returns what that call returns.
*
* <p>The vanilla test is 2-dimensional: {@code getLocalPos} drops the height of both
* points, and the vehicle's box is centered on its physics origin with the half extents
* {@code extents * 0.5 + centerOfMassOffset}. Whatever its rotation, the box lies inside
* the circle around that origin with the radius of its half diagonal. A segment that stays
* outside the circle cannot hit the box, so the vanilla call returns {@code null} for it
* and is skipped here.
*/
public static @Nullable Vector3f getIntersectPoint(
@NotNull BaseVehicle vehicle,
@NotNull Vector3f start,
@NotNull Vector3f end,
@Nullable Vector3f result
) {
VehicleScript script = vehicle.getScript();
Vector3f extents = script.getExtents();
Vector3f centerOfMass = script.getCenterOfMassOffset();
float halfX = extents.x * 0.5F + centerOfMass.x;
float halfZ = extents.z * 0.5F + centerOfMass.z;
float radius = (float) Math.sqrt(halfX * halfX + halfZ * halfZ) + ZombieVehicleHooks.MARGIN;
// Same position that BaseVehicle.getWorldPos and getLocalPos use for the physics origin.
float centerX = vehicle.jniTransform.origin.x + WorldSimulation.instance.offsetX;
float centerY = vehicle.jniTransform.origin.z + WorldSimulation.instance.offsetY;
if (SegmentReach.missesCircle(start.x, start.y, end.x, end.y, centerX, centerY, radius)) return null;
return vehicle.getIntersectPoint(start, end, result);
}
}
@@ -0,0 +1,38 @@
package dev.overlord.zomboidforge.compat.b42.perf;
/** Distance checks in the XY plane. Uses no game classes, so it can be tested on its own. */
public final class SegmentReach
{
private SegmentReach() {}
/**
* Whether every point of the segment from ({@code startX}, {@code startY}) to
* ({@code endX}, {@code endY}) is farther than {@code radius} from
* ({@code centerX}, {@code centerY}).
*
* <p>False when any input is NaN. A caller that skips work only on {@code true} therefore
* still runs the full computation for such input.
*/
public static boolean missesCircle(
float startX, float startY, float endX, float endY,
float centerX, float centerY, float radius
) {
float directionX = endX - startX;
float directionY = endY - startY;
float lengthSquared = directionX * directionX + directionY * directionY;
// Position of the point on the segment closest to the center, from 0 (start) to 1 (end).
// A segment of length 0 is its start. NaN passes through every comparison unchanged.
float along = lengthSquared == 0.0F
? 0.0F
: ((centerX - startX) * directionX + (centerY - startY) * directionY) / lengthSquared;
if (along < 0.0F) along = 0.0F;
else if (along > 1.0F) along = 1.0F;
float offsetX = startX + along * directionX - centerX;
float offsetY = startY + along * directionY - centerY;
return offsetX * offsetX + offsetY * offsetY > radius * radius;
}
}
@@ -0,0 +1,88 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SegmentReachTest
{
@Test
void segmentFarFromTheCircleMisses()
{
assertTrue(SegmentReach.missesCircle(0, 10, 20, 10, 10, 0, 5));
}
@Test
void segmentThroughTheCenterDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 0, 1));
}
@Test
void segmentThatEndsBeforeTheCircleMissesEvenWhenItsLineWouldHit()
{
// The line y = 0 passes through the circle at (10, 0); the segment stops at x = 5.
assertTrue(SegmentReach.missesCircle(0, 0, 5, 0, 10, 0, 2));
}
@Test
void segmentThatStartsAfterTheCircleMissesEvenWhenItsLineWouldHit()
{
assertTrue(SegmentReach.missesCircle(15, 0, 30, 0, 10, 0, 2));
}
@Test
void segmentThatTouchesTheCircleEdgeDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(0, 5, 20, 5, 10, 0, 5));
}
@Test
void segmentJustOutsideTheCircleMisses()
{
assertTrue(SegmentReach.missesCircle(0, 5.001F, 20, 5.001F, 10, 0, 5));
}
@Test
void segmentStartingInsideTheCircleDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(10, 1, 100, 100, 10, 0, 2));
}
@Test
void segmentOfLengthZeroIsItsStart()
{
assertFalse(SegmentReach.missesCircle(10, 1, 10, 1, 10, 0, 2));
assertTrue(SegmentReach.missesCircle(50, 50, 50, 50, 10, 0, 2));
}
@Test
void diagonalSegmentIsMeasuredToItsClosestPoint()
{
// Closest point of (0,0)-(10,10) to (10,0) is (5,5), distance sqrt(50) = 7.07.
assertTrue(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.0F));
assertFalse(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.2F));
}
@Test
void worksAtWorldCoordinates()
{
assertFalse(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10196, 2));
assertTrue(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10210, 2));
}
@Test
void neverMissesOnNaN()
{
float nan = Float.NaN;
assertFalse(SegmentReach.missesCircle(nan, 0, 20, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, nan, 20, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, nan, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, nan, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, nan, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, nan, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 100, nan));
}
}