Skip to content

Architecture and Optimizations

prop11 edited this page Sep 8, 2026 · 1 revision

Architecture and Technical Deep-Dive

This document provides a technical breakdown of the architecture, native hooks, bytecode instrumentation, and memory management mechanisms behind Project Zomboid Optimiser (PZO).


High-Level Architecture Overview

PZO operates at three interconnected layers:

+-------------------------------------------------------------+
|                      Project Zomboid                         |
|   (zombie.gameStates.MainScreenState / zombie.network.GameServer)
+-------------------------------------------------------------+
                              |
      +-----------------------+-----------------------+
      |                                               |
      v                                               v
+-------------------------------+   +-----------------------------------+
|  JVM Bytecode Instrumentation  |   | Native C/C++ Hardware Engine      |
|  (java.lang.instrument)       |   | (pzo_native64.dll / libpzo_native64)|
|  - In-memory bytecode patches |   | - 1.0ms high-precision OS timers  |
|  - Vanilla bug neutralization |   | - Off-heap page-aligned buffers   |
|  - Lock-free cell queues      |   | - Fast bitwise chunk coordinate   |
+-------------------------------+   +-----------------------------------+
                              |
                              v
+-------------------------------------------------------------+
|                  Dedicated Server Engine                    |
|  - Netty direct byte buffer pooling                         |
|  - 4096 UDP datagram sockets & RakNet queue expansion       |
|  - ForkJoinPool multi-threaded horde pathfinding            |
|  - 256KB async SQLite & chunk disk write streamer           |
+-------------------------------------------------------------+

1. JVM Runtime Bytecode Instrumentation

PZO attaches to the HotSpot JVM via the Java Instrumentation API (-javaagent:PZOptimEngine.jar or -javaagent:PZOServerEngine.jar). Using custom bytecode transformers, PZO modifies compiled classes as they load into memory without altering game files on disk:

IsoGridSquare.isWallTo (StackOverflowError Fix)

  • The Vanilla Issue: In vanilla Build 42, IsoGridSquare.isWallTo(IsoGridSquare, int) contains a bytecode compiler bug where the depth recursion limit test executes istore_3 (storing the limit value into a local variable) instead of ireturn (returning false). When complex map geometry triggers deep recursion, the method fails to exit and crashes the JVM with a java.lang.StackOverflowError.
  • PZO Patch: Replaces istore_3 (0x3E) with ireturn (0xAC) at the recursion boundary, cleanly terminating the call and eliminating the crash.

IsoChunk$SanityCheck (Multi-Core Chunk Log Neutralizer)

  • The Vanilla Issue: When chunks stream in parallel across multiple CPU cores, vanilla sanity check routines flood console.txt and disk files with locking log statements, causing severe thread contention and I/O hitching.
  • PZO Patch: Rewrites the log() method's Code attribute to an immediate RETURN (0xB1) no-op, removing disk I/O bottlenecks during chunk loading.

IsoChunkMap.calculateZExtentsForChunkMap (99.4% Loop Reduction)

  • The Vanilla Issue: Vanilla calculates vertical chunk extents by iterating over an unconstrained swap buffer array (chunksSwapA), performing 28,561 loop iterations every single frame.
  • PZO Patch: Rewires the loop boundary to evaluate the active chunkGridWidth field (169 iterations), eliminating over 99.4% of loop overhead and saving significant CPU cycles per tick.

ZombiePopulationManager.requestSaveCell (Lock-Free Cell Queue)

  • The Vanilla Issue: Multiple game threads requesting cell saves compete for a single re-entrant lock (saveLock), causing thread stalling whenever zombies cross cell boundaries.
  • PZO Patch: Bytecode-neutralizes saveLock.lock() and saveLock.unlock() calls inside requestSaveCell, allowing cell save requests to process lock-free across worker threads.

HumanVisual & SpriteConfig Fixes

  • Corrects default uninitialized field states in HumanVisual that cause visual glitching.
  • Neutralizes repetitive warning logging in SpriteConfig.initObjectInfo.

2. Native C/C++ Acceleration Engine

Built with low-overhead C/C++ compiled via MSVC/GCC (pzo_native64.dll on Windows, libpzo_native64.so on Linux, libpzo_native64.dylib on macOS):

OS High-Precision Multimedia Timer

  • Windows Default: Standard Windows thread scheduling runs at 64Hz (15.625ms ticks). This causes frame time micro-stutters and uneven game loop pacing.
  • PZO Native Hook: Calls Windows timeBeginPeriod(1) to force OS timer resolution to 1.0ms. On Linux/macOS, PZO interfaces directly with POSIX clock_nanosleep monotonic timers.

Off-Heap Direct Memory Pooling

  • Bypasses the JVM garbage-collected heap for large temporary buffers (map chunk decompression, netty socket packets).
  • Eliminates memory fragmentation and prevents "Stop-the-World" GC pause spikes.

Fast Bitwise Coordinate Indexing (FastBitwiseChunkIndexer)

  • Provides bitwise bit-shift operations for chunk coordinate calculation (x >> 4, y >> 4), replacing division and modulo operations in hot game loops.

3. Dedicated Server Optimization Engine

The server suite (PZOServerEngine.jar) addresses multiplayer synchronization and server hosting bottlenecks:

Off-Heap Netty Socket Buffer Pooling (ServerNetworkTuner & PZOServerNetGovernor)

  • Sets io.netty.allocator.type=pooled with 8KB page alignment and 4MB chunk limits.
  • Direct byte buffers are recycled per network thread, preventing heap churn during vehicle driving and gunfights.
  • Expands sun.net.maxDatagramSockets to 4096 and configures RakNet socket buffers to prevent UDP packet drops.

Multi-Threaded Zombie Simulation (ServerHordeSimEngine)

  • Scales java.util.concurrent.ForkJoinPool.common.parallelism to match available host CPU cores (up to 32 worker threads).
  • Zombie pathfinding, perception checks, and collision detection are divided dynamically across CPU cores instead of running single-threaded.

Zero-Lag World Save Booster (ServerChunkStreamBooster)

  • Configures 256KB page-aligned disk write buffering (pzo.server.stream_buffer_size=262144, jdk.nio.maxCachedBufferSize=524288).
  • Asynchronously streams chunk writes and SQLite .db transaction commits (players.db, vehicles.db), eliminating the notorious server-wide lag spike during auto-saves.

Linux Steam Native Sanitizer (LinuxSteamServerSanitizer)

  • Scans local and container paths (/home/container/, /home/steam/, linux64/) for steamclient.so.
  • Pre-loads the library and symlinks it to ~/.steam/sdk64/steamclient.so, resolving Steamworks SDK load failures on headless Linux and Docker hosts.

4. JIT Compiler & Runtime Memory Tuning

Configures HotSpot JVM runtime properties early in the boot sequence:

  • Tiered Compilation Hints: Accelerates JIT C2 optimization for mathematical and spatial indexing routines.
  • Generational Heap Cleaner: Periodically trims unreferenced objects and schedules minor garbage collections during idle moments to avoid deep GC pauses during active combat.

Clone this wiki locally