Files
ZomboidForge/MOD_DEVELOPMENT.md

533 lines
27 KiB
Markdown

# Mod development
How to write a server-side Java mod for ZomboidForge. Installing mods on a server is
described in the [README](README.md#mods).
## Project setup
A mod project starts as one file. It needs JDK 25 (Project Zomboid's runtime); the plugin sets
the Java toolchain to 25.
1. Create a directory with this `settings.gradle.kts`, with your mod's id, version, and entry
point:
```kotlin
pluginManagement {
repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
}
plugins {
id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the API version
}
zomboidForge {
id = "shop"
version = "1.0.0"
entrypoint = "com.example.shop.ShopMod"
}
```
2. Run in that directory (Linux, macOS, Windows; on Windows PowerShell 5.1 write `curl.exe`):
```
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -
```
The command sets the newest ZomboidForge version in `settings.gradle.kts`, writes the Gradle
wrapper (`gradlew`, `gradlew.bat`, `gradle/wrapper/`), creates `.gitignore` and the entry point
class when they are missing, and builds the mod. It needs no installed Gradle.
The same command updates a project to the newest version; a given version goes in
`-R-Dzomboidforge.version`:
```
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -R-Dzomboidforge.version=0.7.0 -
```
It prints links to this document in the new version and to the changes since the old one, and
ends with a build, so code that the new version breaks shows at once. Files other than the
version line in `settings.gradle.kts` and the wrapper stay as they are.
The root project is named after the mod id. The plugin adds the API
(`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the game jar for mods that
declare `game` versions. Default settings go into
`src/main/resources/META-INF/zomboidforge/config.toml`.
Libraries and other mods go into an optional `build.gradle.kts`, which can also set any
`zomboidForge { }` setting:
```kotlin
dependencies {
implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/
forgeMods("com.example:economy:2.1") // other mods to compile against
}
zomboidForge {
game("42") // only when the mod uses game classes
dependsOn("economy", "2.1") // other mods: id and minimum version
}
```
### `zomboidForge { }`
| Setting | Default | Meaning |
|--------------------------|------------------------------------------|-----------------------------------------------------------------------------------|
| `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters |
| `entrypoint` | (required) | the class that extends `Mod` |
| `name` | the id | display name |
| `version` | (required) | the mod's version, such as `1.2.0` |
| `api` | the plugin's version | ZomboidForge API version the mod is built against |
| `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` |
| `dependsOn(id, version)` | none | another mod this one needs, with its minimum version |
| `previousIds(...)` | none | earlier ids of the mod; their storage moves to the current id |
| `gameJar` | see below | the `projectzomboid.jar` to compile and check against |
| `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` |
| `serverImage` | the ZomboidForge image, `latest` | image for `runServer` |
| `adminPassword` | random, generated once per volume | admin password of the `runServer` server (see below) |
| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network |
| `dataVolume` | `zomboidforge-<id>` | volume for the `runServer` world and server config |
| `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download |
| `deployDirectory` | none | a server's mods directory for `deployMod` |
The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one
fails the build.
Declare a minor version in `game(...)` only when the mod needs it. A mod declaring `"42.21"`
stops the server after an update to 42.22, while the server checks every game member a mod uses
against the running jar anyway.
### The game jar
Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be
published. The plugin uses the first of:
1. `zomboidForge.gameJar`, or the Gradle property `zomboidforge.gameJar` (for example in
`~/.gradle/gradle.properties`);
2. a local Steam installation of the dedicated server or the game, in any Steam library;
3. a download of the dedicated server with steamcmd (`steamcmd` if installed, otherwise its
container image with podman or docker), once per Steam branch, into the Gradle user home.
It is a few gigabytes.
The game jar has to be one of the declared `game` versions; the check below fails otherwise.
### Tasks
| Task | Does |
|---------------------|---------------------------------------------------------------------------------------------|
| `build` | compiles, runs `checkMod`, and assembles the mod |
| `checkMod` | the server's load checks, at build time (see [checks at startup](#checks-at-startup)) |
| `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
| `modZip` | the same as `build/distributions/<id>-<version>.zip` |
| `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world |
| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod |
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
| `zomboidForgeSetup` | creates `.gitignore` and the entry point class when they are missing |
`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without
`adminPassword`, the first run generates a random admin password for the volume, prints it, and
keeps it in `<Gradle user home>/zomboidforge/admin-passwords/<volume>`. The server uses the
password only when it creates the admin account, on the volume's first start; a later change
needs a new volume (`dataVolume`, or remove the old one).
### Working on ZomboidForge itself
To build a mod against a local ZomboidForge checkout instead of a published version, include it
in `settings.gradle.kts`; Gradle then builds the plugin, the API, and the mod tools from the
checkout:
```kotlin
pluginManagement {
includeBuild("../ZomboidForge")
}
includeBuild("../ZomboidForge")
```
## Entry point
The entry point extends `dev.overlord.zomboidforge.api.Mod`:
```java
public final class ShopMod extends Mod
{
record Settings(String greeting, long maxBalance) {}
private final Settings settings = this.config().bind(Settings.class); // max_balance in config.toml
@Override
public void onLoad() // main thread, registration only
{
this.events().onMain(TickEvent.class, event -> {
/* every frame, on the main thread */
});
}
@Override
public void onServerStarted() // world loaded, port open
{
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()
);
}, Duration.ZERO, Duration.ofMinutes(1));
}
@Override
public void onStopping() {} // before the world is saved
}
```
## Services
Methods of `Mod`, usable from the constructor on, and in field initializers:
| Method | Returns | Use |
|--------------------|------------------|---------------------------------------------------------------|
| `id()` | `String` | the mod's id from `mod.toml` |
| `version()` | `String` | the mod's version from `mod.toml` |
| `gameVersion()` | `GameVersion` | the running Project Zomboid version |
| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path |
| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id |
| `directory()` | `Path` | the mod's folder, `<forge>/mods/<id>` |
| `events()` | `Events` | event listeners |
| `main()` | `MainThread` | code that touches game objects |
| `modThread()` | `ModThread` | the mod's own work, one task at a time |
| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O |
| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` |
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
## Settings
`config().bind(Settings.class)` reads `config.toml` into a record. Keys are the component names
in `snake_case` (`maxBalance` reads `max_balance`); defaults come from the jar's
`META-INF/zomboidforge/config.toml`.
```java
record Settings(
@Key("max_hp_regen") int healthRegenPerHour, // keeps its key after a rename
@Min(1) @Max(100) int maxPlayers, // bounds for numbers, also inside List, Map, Optional
String greeting
) {}
```
A missing, mistyped, or out-of-bounds value stops the server, and the log lists every problem
with its key (`'max_players' must be at most 100, found 250.`). `@Key` names are `snake_case`
and differ within a record; `@Min`/`@Max` only fit numeric components and may be fractions
(`@Max(0.5) double ratio`).
## Threads
Game objects belong to the server's main thread. Everything else should stay off it, because
it also runs the game: the main loop runs about 10 frames per second.
| Executor | Thread | A task runs |
|---------------|-------------------------------------|-------------------------------------------------------------------------|
| `main()` | `main` | immediately when called on the main thread, otherwise in the next ticks |
| `modThread()` | `zf-mod-<id>` | one at a time, in the order submitted |
| `async()` | virtual threads `zf-async-<id>-<n>` | at once, each on its own thread |
Three rules follow from that:
1. Touch game objects only on the main thread; hand results over with `main().execute(...)`
or `main().submit(...)`.
2. Never wait on the main thread for another thread (`get()`, `join()`). Continue with
`thenAcceptAsync(..., modThread())` instead.
3. Keep main-thread work short. Queued tasks share a time budget per tick
(`forge.toml`, `main_thread.budget_ms`); the rest waits for the next tick.
## Events
```java
this.events().onMain(TickEvent.class, event -> ...); // main thread, while the event is posted
this.events().onModThread(SomeEvent.class, event -> ...); // later, on zf-mod-<id>
```
Listeners are matched by the event's exact class. Events that carry live game objects, such as
`TickEvent`, can only be received on the main thread. A listener that keeps throwing is
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
it earlier.
The same listeners as annotated methods (`dev.overlord.zomboidforge.api.annotations`):
```java
@OnMain
void onTick(TickEvent event) { ... }
@OnModThread
void onGreeting(SomeEvent event) { ... }
```
- **The entry point's methods** are registered after its constructor and before `onLoad()`, so
they run before the listeners that `onLoad()` registers for the same event. Other objects
opt in with `this.events().register(object)`, which returns one `Subscription` for all of
their methods. Registering an object twice throws; the entry point is registered already.
- **A listener method** returns `void` and has one parameter: the event class, not an
interface or an abstract class. It may be static or private, and may be declared in a
superclass. An override listens only when it carries the annotation itself.
- **Order:** superclass methods first, the methods of one class by name. When two listeners of
one event need a specific order, register them with `onMain` instead.
- A method that breaks these rules stops the server with every problem in the log;
`register` throws an `IllegalArgumentException` instead.
### Scheduled methods
```java
@Every(value = 1, unit = ChronoUnit.MINUTES) // on zf-mod-<id>; optional: initialDelay, fixedDelay = true
void report() { ... }
@EveryNTicks(10) // on the main thread, every 10th frame
void sweep() { ... }
```
- They follow the rules of listener methods, with no parameters. `unit` is `MILLIS`,
`SECONDS` (default), `MINUTES`, `HOURS`, or `DAYS`, and also applies to `initialDelay`.
- `@Every` starts after the mod's `onServerStarted()` (also when it threw), or at once for an
object registered later. Without `fixedDelay`, the period counts from the start of each
run; with it, from the end. A run that throws is logged and ends the schedule.
- `@EveryNTicks(n)` is a `TickEvent` listener for the ticks n, 2n, ...: it may touch game
objects and must return quickly.
- Cancelling the object's `Subscription` ends both; stopping the server ends `@Every`.
## Commands
Admin commands work wherever Project Zomboid's own commands work: in the in-game chat
(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the
mod declares `game` versions. In Build 42 a command is a subclass of
`zombie.commands.CommandBase`:
```java
@CommandName(name = "zfhello")
@CommandArgs(optional = "(.+)")
@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false)
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
public class HelloCommand extends CommandBase
{
public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
@Override
protected String Command()
{
String name = this.getCommandArg(0);
return "Hello " + (name == null ? this.getExecutorUsername() : name);
}
}
```
```java
@Override
public void onLoad() { this.commands().register(HelloCommand.class); }
```
Or `@RegisterCommand` on the class (`dev.overlord.zomboidforge.api.annotations`), without the
call: ZomboidForge registers the annotated classes of the mod's own jar (not of `lib/`) by name,
before `onLoad()`.
- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw.
`register` checks the class and throws `IllegalArgumentException` listing every problem,
which stops the server like any other exception in `onLoad()`; an annotated class that breaks
the rules stops it the same way.
- **The class** is public and not abstract, with one public constructor
`(String, Role, String, UdpConnection)`.
- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and
differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands.
A name matches when it is the first word of the input, ignoring case.
- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one.
RCON and the server console run commands with the default admin role.
- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become
`getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with
`shouldTranslated = false` the text is used as written) are optional.
- **`Command()`** runs on the main thread, for every use on a new instance; its return value
is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms
that the work started.
- Project Zomboid's commands are looked up first; mods' commands follow in load order.
## Client commands
A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk
through Project Zomboid's command channel, so players keep the official client.
Client to server: the Lua mod calls `sendClientCommand`, and the server posts
`ClientCommandEvent` on the main thread.
```lua
sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 })
```
```java
this.events().onMain(ClientCommandEvent.class, event ->
{
if (!event.module().equals("Shop")) return;
event.cancel(); // Lua's OnClientCommand does not see it
String item = (String) event.args().get("item");
int count = ((Double) event.args().get("count")).intValue();
// ...
this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count));
});
```
The same as an annotated listener method (see [Events](#events)), which filters and cancels:
```java
@OnClientCommand(module = "Shop", command = "buy", cancel = true) // command optional: every command of the module
void buy(ClientCommandEvent event) { ... }
```
`cancel = true` cancels the event before the method runs, so Lua does not receive the command
even when the method throws.
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
receives them in `Events.OnServerCommand`.
```lua
Events.OnServerCommand.Add(function(module, command, args)
if module == "Shop" and command == "bought" then print(args.item, args.count) end
end)
```
- **Every** client command is posted, including those of Project Zomboid (`vehicle`,
`player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`.
- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`.
Every listener still runs; `isCancelled()` tells whether another one cancelled.
- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua
arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number),
`Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is
empty when the client sent no table.
- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other
threads and after the player left. Sending to a player who left sends nothing.
- **Sending** works from any thread. The arguments are copied and checked at once
(`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua
numbers, lists become Lua arrays. The command is sent on the main thread: at once when
called there, otherwise as one of the mod's queued main-thread tasks.
- Client commands come from players and can be forged by a modified client. Check every
argument and the player's rights before acting on it.
## Storage
Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's
save folder. Vanilla backups include it, and deleting the world deletes it. Through the API,
each mod only reaches its own tables.
A record declares a table's columns; each row has a `String` key:
```java
record Balance(long coins, @Nullable Instant lastPaid) {}
Table<Balance> balances = this.storage().table("balances", Balance.class);
balances.set("player1", new Balance(250, Instant.now()));
Optional<Balance> balance = balances.get("player1");
balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null));
this.storage().transaction(() -> { // all or nothing, also when nested
balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null));
balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null));
});
```
| Component type | Stored as |
|-----------------------------------|-------------------------|
| `long`, `int`, `boolean` | integer, never null |
| `double`, `float` | real number, never null |
| `Long`, `Integer`, `Boolean`, ... | the same, may be null |
| `String`, `UUID`, enums | text (enums by name) |
| `Instant` | ISO-8601 text |
| `byte[]` | blob |
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. `@Key("paid_at")`
on a component sets the column name instead, so a renamed component keeps its column and data.
`@Min`/`@Max` are for settings; storage ignores them.
When the record changes between versions of the mod:
| Change | What happens |
|--------------------------------|-------------------------------------------|
| new component that may be null | added; existing rows read `null` |
| new primitive component | needs a migration |
| removed component | the column and its data stay; logged once |
| component with another type | needs a migration |
```java
Table<Balance> balances = this.storage().define("balances", Balance.class)
.version(2)
.migrate(1, row -> new Balance(row.getLong("coins"), null)) // from stored version 1
.open();
```
The same on the record (`dev.overlord.zomboidforge.api.annotations`), so `table(...)` is enough:
```java
@Schema(version = 2)
record Balance(long coins, @Nullable Instant lastPaid)
{
@Migrate(from = 1)
static Balance fromV1(Row row) { return new Balance(row.getLong("coins"), null); }
}
Table<Balance> balances = this.storage().table("balances", Balance.class);
```
A `@Migrate` method is static, takes a `Row`, returns the record, and may be private. `define`
starts from the annotations: `version(...)` replaces the `@Schema` version, and `migrate(...)`
adds migrations. Each version has one migration at most; a second one throws.
Things to know:
1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the
server runs they throw, so use `modThread()` or `async()`.
2. Writes commit immediately, while the world is saved periodically. After a crash, the
world goes back to its last save, but the mod data keeps later writes.
3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables
move to the new id once.
4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits.
These callbacks must not wait for other threads, for example with
`main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs
without pausing storage, so its copy of `zomboidforge.db` may be incomplete.
## Checks at startup
`checkMod` runs these checks when the mod is built, so a mod that would not load fails its
build instead. On the server, before any mod code runs, ZomboidForge reads every class of the
mod and its libraries. The server does not start when a mod
1. uses game classes without declaring `game` versions in `mod.toml`,
2. uses a game class, field, or method that does not exist in the running version,
3. uses ZomboidForge classes outside the API, or
4. contains classes in a ZomboidForge package, or a class with the name of a game class.
While it loads a mod, the server also checks the annotations: the entry point's listener and
scheduled methods, `@Schema`/`@Migrate`/`@Key`/`@Min`/`@Max` on records, and the
`@RegisterCommand` classes. `checkMod` runs the same rules on the built jar (records only when
they carry one of these annotations), loading the classes without running any of their code.
Objects passed to `events().register(...)` are only checked on the server, when they are
registered.
Every problem of every mod is listed in the log.
## What a mod can see
| Source | Visible |
|----------------------------------------------------|-----------------------------------------------|
| JDK | yes |
| ZomboidForge API (`dev.overlord.zomboidforge.api`) | yes |
| the mod's own jar and `lib/*.jar` | yes; own libraries win over the game's copies |
| own jars of declared dependencies | yes (not their libraries) |
| game jar (game code and its bundled libraries) | only with `game` declared |
| ZomboidForge internals | no |
These rules keep mods from linking against the wrong classes by accident. They are not a
sandbox: a mod runs with the full privileges of the server process. Through reflection or the
file system it can reach anything the server can, including other mods' data in
`zomboidforge.db`.
## Profiling
Main-thread tasks and event listener calls appear in JFR recordings as the event
`zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the
event class, followed by `#<method>` for a listener method).