Multiplayer

Kaigen's multiplayer is built on one model, used by every game:

Because clients only learn things from replicated state, late joiners and lost packets need no special code.

Declaring what goes over the wire

game.h
NET_INPUT()
typedef struct GameInput {
  NET_F(.quant = 1000, .max = 1) v2 move;
  NET_F(.max = 3) NetInputEvent fire;
} GameInput;

ECS_COMPONENT_TYPEDEF(Ship);
HZ_REFLECT()
NET_COMPONENT()
typedef struct Ship {
  v3 pos;
  v3 vel;
} Ship;

NET_GHOST(.position = ship.pos)
typedef struct ShipGhost {
  Ship ship;
} ShipGhost;

A ghost is an entity the server replicates. The server spawns it like any entity (plus a NetGhost component naming its type) and every client that can see it gets it in the next snapshot. NET_F says how to pack a field: .quant and .max keep it small, and the server clamps input that's out of range.

Your game's tick systems go in a simulate schedule that the server runs for everyone, and each client runs for itself.

Running it

Four players on one machine
hz/hzbuild run -- --clients 4

With no flag your game is a host (a server and a player). --server is a dedicated server, and --join <code> joins one; the host prints the join line. In the browser the same works with ?join=<code>.

Transports are picked for the link: QUIC and UDP on desktop, WebTransport, WebSocket and WebRTC in the browser, with NAT traversal for players at home. Online sessions, invites and friends work on Kaigen, Steam and Epic.

Start from the template

This is the one system where starting from scratch costs a lot. hz/hzbuild new my_game --template multiplayer-starting-template gives you players joining with their names, prediction and the whole frame wired up, and the multiplayer gameplay block does the session part for you.

Worth knowing

The API is hz/src/engine/netcode/netcode.h, and the ECS side hz/src/engine/ecs/ecs_netcode/ecs_netcode.h.