diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index c056012..dfc0c6c 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -25,7 +25,8 @@ public final class B42PatchSet implements PatchSet new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), new IsoGameCharacterStateMachinePerformancePatch(), - new ZombieVoronoiPerformancePatch() + new ZombieVoronoiPerformancePatch(), + new ZomboidFileSystemInitPerformancePatch() ); @Override diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZomboidFileSystemInitPerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZomboidFileSystemInitPerformancePatch.java new file mode 100644 index 0000000..1fc2bc1 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZomboidFileSystemInitPerformancePatch.java @@ -0,0 +1,113 @@ +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: + * + *
{@code
+ * ZomboidFileSystemHooks.searchAndIndex(this, this.workdir.canonicalFile, this.loadList, this.allAbsolutePaths);
+ * for (int n = 0; n < this.loadList.size(); ++n) { ... }    // loadList is empty now
+ * this.loadList.clear();
+ * }
+ * + * 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 + "'."); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZomboidFileSystemInitPerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZomboidFileSystemInitPerformancePatchTest.java new file mode 100644 index 0000000..3c21ab1 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZomboidFileSystemInitPerformancePatchTest.java @@ -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}: + * + *
{@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();
+     * }
+     * }
+ */ + 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, "", "()V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()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 instructions(MethodNode method) + { + List 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 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"))); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks.java new file mode 100644 index 0000000..4cf34fd --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks.java @@ -0,0 +1,59 @@ +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. */ +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. + * + *

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}). + * + *

{@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 loadList, Set allAbsolutePaths) throws IOException + { + if (!GameServer.server) + { + fileSystem.searchFolders(root); + return; + } + + Map 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(); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/MediaScan.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/MediaScan.java new file mode 100644 index 0000000..13d0b82 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/MediaScan.java @@ -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. + * + *

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 walk(File root, List loadList) throws IOException + { + Map 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 + * lowercased 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 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 folders) + { + Boolean known = folders.get(path); + return known != null ? known : new File(path).isDirectory(); + } + + private static void addFile(String path, List loadList, Map 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("./", ""); + } +} diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooksTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooksTest.java new file mode 100644 index 0000000..708fa00 --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooksTest.java @@ -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 loadList, Map activeFileMap, Set allAbsolutePaths) {} + + private static ZomboidFileSystem newFileSystem(Path base) throws ReflectiveOperationException, IOException + { + Constructor constructor = ZomboidFileSystem.class.getDeclaredConstructor(); + constructor.setAccessible(true); + + ZomboidFileSystem fileSystem = constructor.newInstance(); + fileSystem.base.set(base.toFile()); + + return fileSystem; + } + + @SuppressWarnings("unchecked") + private static 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 loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList"); + Set allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths"); + Map activeFileMap = fileSystem.activeFileMap; + + fileSystem.searchFolders(media); + List 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 loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList"); + Set allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths"); + List searched = new ArrayList<>(); + + // Records what the walk appends: the hook empties the list before returning. + List 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 /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."); + } +}