Add client command integration for Build 42: define APIs, event system, hooks, patches, and Lua table converters. Include tests, documentation, and mod support.

This commit is contained in:
Overlord committed 2026-10-03 13:22:47 +02:00
1 parent af7174e128
commit a351fc237c
24 files changed
+870 -48

No files matched your search

@@ -2,11 +2,14 @@ package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.ZomboidForge;
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.ForgeSettings;
import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
@@ -54,6 +57,7 @@ public final class Forge
private final Path directory;
private final @Nullable ModVersion api;
private final CommandRegistry commands;
private final ClientCommandSender clientCommands;
private volatile List<ModLoader.LoadedMod> mods = List.of();
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
@@ -63,14 +67,16 @@ public final class Forge
* @param directory the ZomboidForge directory
* @param api the API version mods are checked against, or {@code null} to skip the
* check
* @param commands checks the command classes that mods register against the running game
* version
* @param commands checks the command classes that mods register against the running
* game version
* @param clientCommands sends the mods' server commands to clients in the running game version
*/
public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands)
public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands, ClientCommandSender clientCommands)
{
this.directory = directory;
this.api = api;
this.commands = new CommandRegistry(commands, this::commandsOpen);
this.directory = directory;
this.api = api;
this.commands = new CommandRegistry(commands, this::commandsOpen);
this.clientCommands = clientCommands;
}
/**
@@ -78,17 +84,18 @@ public final class Forge
* version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev},
* {@code 0.0.0-...}) skip the API check.
*
* @param commands checks the command classes that mods register against the running game
* version
* @param commands checks the command classes that mods register against the running
* game version
* @param clientCommands sends the mods' server commands to clients in the running game version
*/
public static Forge fromSystemProperties(CommandRegistry.Validator commands)
public static Forge fromSystemProperties(CommandRegistry.Validator commands, ClientCommandSender clientCommands)
{
Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY));
ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION)
.filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0)
.orElse(null);
return new Forge(directory, api, commands);
return new Forge(directory, api, commands, clientCommands);
}
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
@@ -197,6 +204,9 @@ public final class Forge
*/
public void post(Event event) { this.events.post(event); }
/** Whether any mod listens for {@code type}, so a hook can skip creating the event. */
public boolean hasListeners(Class<? extends Event> type) { return this.events.hasListeners(type); }
/**
* Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}).
* Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup.
@@ -268,14 +278,16 @@ public final class Forge
ModThreads.ModExecutors executors = this.threads.create(id, logger);
StorageDatabase storage = Objects.requireNonNull(this.storage, "storage");
MainThread main = this.queue.forMod(id, logger);
return new ModServices(
this.events.forMod(id, executors.modThread(), logger),
this.queue.forMod(id, logger),
main,
executors.modThread(),
executors.async(),
new ModTables(id, storage, logger),
this.commands.forMod(logger)
this.commands.forMod(logger),
new ModClientCommands(this.clientCommands, main)
);
}
}
@@ -0,0 +1,21 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.PlayerRef;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
/** Sends server commands to clients; implemented by the compat module of the running game version. */
@FunctionalInterface
public interface ClientCommandSender
{
/**
* Checks {@code args} on the calling thread and returns the action that converts and sends
* the command, which runs on the main thread.
*
* @param player the receiving player, or {@code null} for every connected client
* @throws IllegalArgumentException naming a key or value that cannot be sent
*/
Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args);
}
@@ -0,0 +1,45 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.PlayerRef;
import java.util.Map;
import java.util.Objects;
/**
* The {@link ClientCommands} of one mod: checks on the calling thread, sends through the mod's
* {@link MainThread}, so a command sent off the main thread is one of the mod's queued tasks.
*/
public final class ModClientCommands implements ClientCommands
{
private final ClientCommandSender sender;
private final MainThread main;
public ModClientCommands(ClientCommandSender sender, MainThread main)
{
this.sender = Objects.requireNonNull(sender);
this.main = Objects.requireNonNull(main);
}
@Override
public void send(PlayerRef player, String module, String command, Map<?, ?> args)
{
Objects.requireNonNull(player, "player");
this.main.execute(this.sender.prepare(player, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args")));
}
@Override
public void sendToAll(String module, String command, Map<?, ?> args)
{
this.main.execute(this.sender.prepare(null, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args")));
}
private static String require(String value, String name)
{
if (Objects.requireNonNull(value, name).isEmpty()) throw new IllegalArgumentException("'" + name + "' is empty.");
return value;
}
}
@@ -1,5 +1,6 @@
/**
* Admin commands of loaded mods: the registry that the compat hooks consult.
* Commands of loaded mods: the registry of admin commands that the compat hooks consult, and
* server commands to clients.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@@ -1,6 +1,7 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.GameVersion;
@@ -37,18 +38,19 @@ public final class ModLoader
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
private record Context(
String id,
String version,
GameVersion gameVersion,
System.Logger logger,
Path directory,
ModConfig config,
Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async,
ModStorage storage,
Commands commands
String id,
String version,
GameVersion gameVersion,
System.Logger logger,
Path directory,
ModConfig config,
Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async,
ModStorage storage,
Commands commands,
ClientCommands clientCommands
) implements ModContext {}
private ModLoader() {}
@@ -96,7 +98,8 @@ public final class ModLoader
provided.modThread(),
provided.async(),
provided.storage(),
provided.commands()
provided.commands(),
provided.clientCommands()
);
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
@@ -1,15 +1,23 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.ModThread;
import dev.overlord.zomboidforge.api.storage.ModStorage;
/** The threads, event and command registration, and storage of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage, Commands commands)
{
/** The threads, event and command registration, storage, and client commands of one mod, created before its entry point. */
public record ModServices(
Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async,
ModStorage storage,
Commands commands,
ClientCommands clientCommands
) {
/** Creates the services of one mod. */
@FunctionalInterface
public interface Factory
@@ -51,6 +51,9 @@ class ForgeTest
/** Classes that mods registered as commands, as {@code "<name> after <registered count>"}; every class is accepted. */
private final List<String> checkedCommands = new ArrayList<>();
/** Client commands that mods sent, as {@code "<player or all> <module>.<command> <args>"}. */
private final List<String> sentClientCommands = new ArrayList<>();
@BeforeEach
void setUp() throws IOException
{
@@ -64,7 +67,12 @@ class ForgeTest
private Forge forge()
{
return new Forge(this.directory, ModVersion.parse("0.3.0"), (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size()));
return new Forge(
this.directory,
ModVersion.parse("0.3.0"),
(command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size()),
(player, module, command, args) -> () -> this.sentClientCommands.add((player == null ? "all" : player.username()) + " " + module + "." + command + " " + args)
);
}
private Forge load() throws ModLoadException
@@ -133,6 +141,19 @@ class ForgeTest
assertEquals(1, forge.commands().size());
}
@Test
void modsSendClientCommandsThroughTheGameSender() throws Exception
{
TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of(
"testmods/CommandMod", TestMods.classFile(CommandMod.class),
"testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class)
));
this.load().started();
assertEquals(List.of("all Test.started {count=1}"), this.sentClientCommands);
}
@Test
void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception
{
@@ -0,0 +1,107 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.PlayerRef;
import dev.overlord.zomboidforge.core.RecordingLogger;
import dev.overlord.zomboidforge.core.runtime.MainThreadQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** The test thread is the main thread. */
class ModClientCommandsTest
{
private static final PlayerRef PLAYER = new PlayerRef(3, "alice");
/** What the sender prepared ({@code "prepare ..."}) and sent ({@code "send ... on <thread>"}). */
private final List<String> log = new CopyOnWriteArrayList<>();
/** Records both steps; rejects arguments that contain the key {@code "bad"}. */
private final ClientCommandSender sender = (player, module, command, args) ->
{
if (args.containsKey("bad")) throw new IllegalArgumentException("'args[bad]' cannot be sent.");
String target = player == null ? "all" : player.username();
this.log.add("prepare " + target + " " + module + "." + command + " " + args);
return () -> this.log.add("send " + target + " " + module + "." + command + " on " + Thread.currentThread().getName());
};
private MainThreadQueue queue;
private ClientCommands commands;
@BeforeEach
void setUp()
{
this.queue = new MainThreadQueue(Duration.ofSeconds(10));
this.queue.bindToCurrentThread();
this.commands = new ModClientCommands(this.sender, this.queue.forMod("shop", new RecordingLogger()));
}
@Test
void sendsAtOnceOnTheMainThread()
{
this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "bought", Map.of("item", "Base.Axe"));
this.commands.sendToAll("Shop", "opened", Map.of());
String main = Thread.currentThread().getName();
assertEquals(
List.of(
"prepare alice Shop.bought {item=Base.Axe}", "send alice Shop.bought on " + main,
"prepare all Shop.opened {}", "send all Shop.opened on " + main
),
this.log
);
}
@Test
void checksOnTheCallingThreadAndSendsOnTheMainThreadLater() throws InterruptedException
{
Thread other = Thread.ofPlatform().name("worker").start(() -> this.commands.sendToAll("Shop", "opened", Map.of()));
other.join();
assertEquals(List.of("prepare all Shop.opened {}"), this.log);
this.queue.drain();
assertEquals(List.of("prepare all Shop.opened {}", "send all Shop.opened on " + Thread.currentThread().getName()), this.log);
}
@Test
void rejectedArgumentsThrowToTheCallerOnAnyThread() throws InterruptedException
{
AtomicReference<Throwable> thrown = new AtomicReference<>();
Thread other = Thread.ofPlatform().start(() ->
{
try { this.commands.sendToAll("Shop", "opened", Map.of("bad", 1)); }
catch (Throwable t) { thrown.set(t); }
});
other.join();
assertInstanceOf(IllegalArgumentException.class, thrown.get());
this.queue.drain();
assertEquals(List.of(), this.log);
}
@Test
void rejectsEmptyModuleAndCommand()
{
assertThrows(IllegalArgumentException.class, () -> this.commands.sendToAll("", "opened", Map.of()));
assertThrows(IllegalArgumentException.class, () -> this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "", Map.of()));
assertEquals(List.of(), this.log);
}
}
+6 -1
View File
@@ -4,9 +4,12 @@ import dev.overlord.zomboidforge.api.Mod;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
/**
* Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()}
* and tries again in {@code onServerStarted()}, which is too late.
* and tries again in {@code onServerStarted()}, which is too late; sends a client command to
* every client there.
*/
public final class CommandMod extends Mod
{
@@ -23,5 +26,7 @@ public final class CommandMod extends Mod
{
try { this.commands().register(CommandMod.Command.class); }
catch (RuntimeException e) { this.lateRegistration = e; }
this.clientCommands().sendToAll("Test", "started", Map.of("count", 1));
}
}