NavGrid is the map bots plan on: a point per 2 m terrain sample, solid on cliffs and where solids stand between step and head height, and costlier where the water is deeper than wading. Path search uses Godot's AStarGrid2D. The grid syncs every tick: new solids (walls, pieces) block points at once, removed ones are found by a rolling scan, and points turn wet as the tide and flood reach them. Each change is stamped with its tick. NavBot follows a path with ordinary PlayerCommands: it steers at waypoints, sprints on long dry stretches, jumps when stalled, and marks a point blocked after repeated stalls. Every half second it checks its remaining path against the change stamps and plans again if water or a wall now crosses it. One path is planned per server tick across all bots. The server builds the grid while the lobby waits and its bots now roam between random reachable places, replacing the placeholder wander bot. Tests: 150 of 150 random reachable targets reached on 50 islands in the sweep; the test runs 2 per island and needs 95%. New walls and rising water both cause a new path around them; a broken wall opens the grid again; with no dry way round, the bot swims. 23 roaming bots on an island: p99 tick 1.6 ms against the 12 ms budget. Closes #27 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
168 lines
8.6 KiB
Markdown
168 lines
8.6 KiB
Markdown
# Tidewall architecture
|
||
|
||
Tidewall is **server-authoritative from day one**. A match is always a server plus
|
||
clients. Offline play starts a local server with bots and connects to it through the
|
||
same interfaces, so there is one code path, and multiplayer is never a retrofit.
|
||
|
||
## Rules that do not bend
|
||
|
||
1. The simulation decides everything that affects the match. Clients ask; the server rules.
|
||
2. **Simulation code has no dependency on rendering, audio or UI.** `src/sim/` doesn't
|
||
use any nodes or servers from those engine areas, and a test scans it to enforce this.
|
||
3. The simulation advances only in fixed ticks of 30 Hz, and takes no input other than
|
||
commands and the seed.
|
||
4. Gameplay numbers live in `src/sim/tuning.gd`.
|
||
|
||
## Simulation and presentation
|
||
|
||
```
|
||
commands snapshots, events
|
||
Humans ─┐ ┌─ Renderer
|
||
Bots ──┼──> Server simulation (30 Hz, authoritative) ──> ├─ Audio
|
||
Net ──┘ └─ UI / HUD
|
||
```
|
||
|
||
- **Simulation (`src/sim/`)**: plain `RefCounted` objects and data arrays. Testable
|
||
without a scene tree. Runs identically on the server and in prediction on clients.
|
||
- **Presentation (`src/client/`, `src/ui/`, `src/audio/`)**: reads snapshots and events
|
||
and draws them, interpolating between ticks. It never changes simulation state.
|
||
- The simulation emits **events** (shot fired, piece built, player downed) in a per-tick
|
||
list. Presentation turns them into effects and sound.
|
||
|
||
## Tick rate
|
||
|
||
The simulation runs at `Tuning.TICK_RATE_HZ` (30 Hz, 33.33 ms). The server runs a fixed
|
||
accumulator and may run several ticks to catch up, with no more than 5 per frame.
|
||
Snapshots go out at 20 Hz. The client renders at any frame rate and interpolates
|
||
remote entities roughly 100 ms in the past.
|
||
|
||
## Player command stream
|
||
|
||
A `PlayerCommand` is one tick of one player's intent. Humans, bots and the network all
|
||
produce the same struct, so the simulation can't tell them apart.
|
||
|
||
| Field | Type | Meaning |
|
||
|---|---|---|
|
||
| `tick` | u32 | Tick the command applies to |
|
||
| `move_x`, `move_y` | i8 | Movement axes, scaled to -1..1 |
|
||
| `yaw` | u16 | Look yaw, full turn over 65536 steps |
|
||
| `pitch` | i16 | Look pitch, ±90° over ±32767 steps |
|
||
| `buttons` | u16 | Bit flags: fire, aim, jump, crouch, sprint, reload, interact, build |
|
||
| `selection` | u8 | Active inventory slot or build piece |
|
||
| `material` | u8 | Active build material |
|
||
|
||
Clients stamp commands for the tick they predict, and each packet repeats recent
|
||
commands to survive loss. The server applies the command for each tick, or a neutral
|
||
command with the player's last look direction if none has arrived.
|
||
|
||
**Look convention.** At yaw 0 the player faces +z; forward is `(sin yaw, 0, cos yaw)`.
|
||
Right is forward × up, `(-cos yaw, 0, sin yaw)`, matching Godot's right-handed, y-up
|
||
frame, so turning right *decreases* yaw. Positive pitch looks up. `Movement` and the
|
||
client's `CameraRig` both follow this, and a test checks that strafing right moves
|
||
towards the camera's screen-right.
|
||
|
||
The binary encoding is a fixed 14 bytes per command, little-endian, in the order of
|
||
the table above. See `src/sim/player_command.gd`. Decoding a truncated buffer returns
|
||
nothing, and out-of-range values are clamped, so bad input can't reach the simulation.
|
||
The player a command belongs to comes from its connection, never from the packet.
|
||
|
||
## Entity IDs
|
||
|
||
Every entity has a `u32` ID, allocated from a counter starting at 1 and **never reused
|
||
within a match**. ID 0 means "none". Snapshots refer only to IDs, which removes a whole
|
||
class of stale-reference bugs. Iteration is always in ascending ID order, so it's
|
||
deterministic.
|
||
|
||
## Seeded RNG rules
|
||
|
||
- A match has one `u64` seed, always logged.
|
||
- Gameplay randomness comes only from named streams, created from the match seed and a
|
||
stable name: `rng.stream("loot")`, `"weapons"`, `"bots"`, `"worldgen"`, and so on, on one `SimRng`.
|
||
One system's extra rolls can't disturb another's.
|
||
- Simulation code **never** calls `randf`, `randi`, `Time`, or anything else that varies
|
||
between runs. Presentation can use whatever randomness it likes, for effects.
|
||
- The same seed and the same command log produce the same state hash, on the same engine
|
||
build. Worldgen runs on both ends from the same seed, so the terrain itself is never sent.
|
||
|
||
`Simulation.state_hash()` is a SHA-256 over a canonical encoding of the tick, the next
|
||
entity ID, every RNG stream's state and every entity in ID order, with positions rounded
|
||
to millimetres.
|
||
|
||
Determinism is for tests, replays and worldgen. Clients don't rely on bit-exact matches
|
||
with the server. Reconciliation corrects any difference.
|
||
|
||
## Snapshot format
|
||
|
||
A snapshot is a binary, little-endian packet:
|
||
|
||
| Part | Contents |
|
||
|---|---|
|
||
| Header | Protocol version (u8), server tick (u32), baseline tick (u32, 0 = full), last command tick applied for this client (u32) |
|
||
| Tide | Phase (u8), level in centimetres (u16) |
|
||
| Entities | Count, then records of ID (varint), archetype (u8), changed-field mask (u8), then only the fields that changed |
|
||
| Removed | Count, then IDs |
|
||
|
||
Positions are quantized to 1.5 cm (u16 per axis, 1,024 m range), yaw to u16, health to u8.
|
||
Snapshots are deltas against the latest baseline the client acknowledged, and fall back to a full
|
||
snapshot if none. Players only receive entities in their relevance range. Building changes are also
|
||
sent on a reliable ordered event stream, since a dropped wall is a gameplay lie.
|
||
|
||
## Module map
|
||
|
||
| Path | Holds | May depend on |
|
||
|---|---|---|
|
||
| `src/sim/` | Tick loop, entities, RNG, commands, tide, combat, building | `src/sim/` only |
|
||
| `src/bots/` | Bot brains that produce `PlayerCommand`s | `src/sim/` |
|
||
| `src/net/` | Transport, snapshot encoding, prediction, lag compensation | `src/sim/` |
|
||
| `src/server/` | Headless and listen-server hosting | `src/sim/`, `src/bots/`, `src/net/` |
|
||
| `src/client/` | World rendering, camera, input, effects | `src/sim/`, `src/net/` |
|
||
| `src/ui/` | HUD, menus, map | `src/sim/` (read only), `src/client/` |
|
||
| `src/audio/` | Sound playback, music | `src/sim/` (read only) |
|
||
| `src/app/` | Startup and mode selection | Everything |
|
||
|
||
## Bots
|
||
|
||
Bots live in `src/bots/` and play through the same door as humans: each tick a bot
|
||
reads the simulation and returns one `PlayerCommand`, which the server submits like
|
||
any other. They never write to the simulation.
|
||
|
||
`NavGrid` is the shared map they plan on: one point per 2 m terrain sample, solid
|
||
where the ground is a cliff or a solid stands between step and head height, and eight
|
||
times as costly where the water is deeper than wading. Path search is Godot's
|
||
`AStarGrid2D`. The server builds the grid while the lobby waits (about 0.4 s, next to
|
||
the island's own generation) and syncs it every tick before bots think: new solids
|
||
block points at once, removed solids are found by a rolling scan within a few ticks,
|
||
and points turn wet as the tide and flood reach them. Every change is stamped with its
|
||
tick, and each bot checks its remaining path against the stamps twice a second, so a
|
||
new wall or rising water across a path makes it plan again. Only one path is planned
|
||
per server tick across all bots; others wait their turn.
|
||
|
||
`NavBot` follows a path: it steers at the next waypoint, sprints on long dry stretches,
|
||
jumps when it stops making progress, and after a few tries marks the point blocked and
|
||
plans around it. The brains in M5 choose its goals; until then the server's bots roam
|
||
between random reachable places.
|
||
|
||
## Terrain
|
||
|
||
The island's heightfield (`Island`, in `src/sim/`) is the only terrain collision, on
|
||
the server and in client prediction. Nothing in the renderer is ever used for collision.
|
||
|
||
The client draws it with `TerrainView` (`src/client/terrain/`): 64 m chunks at four
|
||
levels of detail chosen by distance to the camera. `TerrainChunkBuilder` builds chunk
|
||
geometry on `WorkerThreadPool` threads, and the main thread only uploads finished meshes,
|
||
within a per-frame budget. Each chunk hangs skirts from its edges deeper than any two
|
||
levels can disagree, so a level boundary never opens a crack. Normals come from the
|
||
full-resolution heightfield at every level, so lighting doesn't change across a boundary.
|
||
The terrain shader blends procedural sand, marsh, grass and rock layers using splat
|
||
weights from the island's elevation bands, with rock on steep ground.
|
||
|
||
## Performance budgets
|
||
|
||
| Budget | Target |
|
||
|---|---|
|
||
| Server tick | Under **12 ms** with 24 players |
|
||
| Client | **60 fps** on a GTX 1060-class GPU at medium settings |
|
||
| Terrain streaming | Under **8 ms** of main-thread work in any frame (measured headless; GPU upload unmeasured) |
|
||
|
||
Software rendering in CI can't verify the client budget. It needs a real GPU playtest.
|