# Multiplayer

> An authoritative server with client prediction, built into the ECS. Test with four players from one command.

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

- **Clients send input, and only input.** Moving, firing, buying, chat: everything a player does is a field of their input struct.
- **The server simulates** the same systems on those inputs, decides everything, and sends snapshots of the world.
- **Each client simulates its own input right away** (prediction), so the game feels instant. When a snapshot disagrees, the snapshot wins, and the client replays its input on top of it.

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

- `NET_RPC` exists for things outside the simulation (stats, a report button). Never use it for gameplay.
- A one-shot effect (a hit sound, a kill message) is derived on each client from state that changed, like a counter that went up, not sent as a message.
- Test with lag and packet loss on your own machine: `--commands "1:net_sim:lag=100,jitter=10,loss=5;60:quit" -- --clients 2`, or a preset like `net_sim:wifi`.

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