Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ The Audio tab has master/effects volume, mute and a test sound. The Graphics tab

Changes apply immediately except anisotropic strength changes, which require restarting the game. Controls and graphics persist in `user://settings.cfg`, and existing audio preferences remain in `user://audio.cfg`. Esc returns to the previous menu. Fixed shortcuts remain available outside settings: F11 toggles fullscreen, F3 shows performance, F8 shows the netcode overlay, F4 toggles antialiasing, and F5/F6 cycle resolutions while paused. F10 quits from a menu. The server keeps running while menus are open; losing focus releases your controls, but incoming damage can continue.

For netcode debugging, the Graphics tab's **Route connections through the network simulator (debug)** option, or launching with `--netsim`, sends the next connection through a local relay that adds latency, jitter, loss and duplication in both directions. `--netsim-rtt=MS`, `--netsim-jitter=MS` (± round trip), `--netsim-loss=PERCENT` and `--netsim-duplicate=PERCENT` set starting conditions. The F8 overlay shows round-trip time, traffic, snapshot jitter and reconciliation corrections, has sliders that change the simulator's conditions live, and can draw a translucent ghost at the server's position for your ship. Normal connections never use the relay, and the option is not saved.
For netcode debugging, the Graphics tab's **Route connections through the network simulator (debug)** option, or launching with `--netsim`, sends the next connection through a local relay that adds latency, jitter, loss and duplication in both directions. `--netsim-rtt=MS`, `--netsim-jitter=MS` (± round trip), `--netsim-loss=PERCENT` and `--netsim-duplicate=PERCENT` set starting conditions. The F8 overlay shows round-trip time, traffic, snapshot jitter, unacknowledged and replayed inputs, the server's input buffer and lost, late and duplicate input counts, the simulation error at each reconciliation and the smoothed visual offset that hides it, has sliders that change the simulator's conditions live, and can draw a translucent ghost at the server's position for your ship. Normal connections never use the relay, and the option is not saved.

The flight quickslot bar has ten mixed, rebindable slots (`1–0` by default). Its
`+` button opens item categories and allows assigning, swapping or clearing items
Expand Down
93 changes: 91 additions & 2 deletions docs/netcode-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
Movement networking measured before the netcode rework (network schema 23),
with the network simulator from phase 1 of the
[real-time netcode rework](../GAME_PLAN.md#real-time-netcode-rework). Later
phases rerun the same benchmark unchanged; phase 6 folds these tables into
`docs/NETCODE.md`.
phases rerun the same benchmark and append their results below; phase 2
redefined three metrics, as its section explains. Phase 6 folds these tables
into `docs/NETCODE.md`.

```
godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=baseline
Expand Down Expand Up @@ -52,3 +53,91 @@ the header of `tests/netcode_benchmark.gd`.
several seconds; the benchmark's warm-up covers that.
- At 0 ms the 28 ms RTT and 16 ms jitter p95 mostly reflect frame timing in a
single process hosting five sectors: ENet is serviced once per frame.

## After phase 2: ticks, input sequencing and reconciliation

Network schema 24. The same benchmark, scripted input and conditions, plus the
150 ± 30 ms, 5% loss condition used by phase 5 (`--scenario=degraded`).
Measured on the same Windows 11 desktop (92–118 frames per second).

```
godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=baseline
godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=degraded
```

Three metrics changed meaning, because the thing they measured changed (the
benchmark header has the full definitions):

- **Sim error** replaces *prediction error*. It is how far rewinding to the
authoritative state and replaying the unacknowledged inputs moved the
predicted ship at each reconciliation. Zero means the server simulated
exactly what the client predicted. The old metric compared the predicted
ship with a round-trip-old position, which mostly measured latency.
- **Visual offset** replaces *correction*. Corrections no longer move the drawn
ship within a frame: the model and camera are drawn at a decaying offset
from the simulated ship. This is that offset, sampled every client tick.
- **Inputs** replace *commands*. Clients now send one input per 60 Hz tick
(30 packets per second, each repeating up to ten unacknowledged inputs).
*Lost* counts inputs the server skipped because they never arrived; late,
catch-up drops and starved ticks are the server's input buffer counters.

| Added RTT | Loss | ENet RTT | Client up | Client down | Server to client | Snapshot jitter mean / p95 / max | Sim error mean / p95 / max | Visual offset mean / p95 / max | Gap to server now mean / p95 | Replay mean / max | Server buffer | Inputs sent / applied / lost | Late / dropped / starved |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 0 ms | 0% | 32 ms | 2.7 KB/s | 14.4 KB/s | 14.4 KB/s | 5.8 / 16.3 / 24.9 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 2.00 / 3.44 m | 4.5 / 6 | 2.8 | 1201 / 1201 / 0 | 0 / 0 / 0 |
| 100 ms | 0% | 107 ms | 3.5 KB/s | 14.9 KB/s | 14.9 KB/s | 4.5 / 10.1 / 23.6 ms | 0.00 / 0.00 / 0.01 m | 0.00 / 0.00 / 0.01 m | 2.99 / 5.14 m | 9.0 / 10 | 2.3 | 1200 / 1200 / 0 | 0 / 0 / 0 |
| 200 ms | 0% | 205 ms | 3.5 KB/s | 14.4 KB/s | 14.4 KB/s | 5.0 / 12.1 / 19.5 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 4.59 / 7.92 m | 15.3 / 18 | 2.5 | 1200 / 1199 / 0 | 0 / 0 / 1 |
| 0 ms | 5% | 32 ms | 3.1 KB/s | 14.5 KB/s | 15.0 KB/s | 8.0 / 22.9 / 70.3 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 2.90 / 5.08 m | 6.6 / 8 | 4.6 | 1200 / 1200 / 0 | 0 / 0 / 0 |
| 100 ms | 5% | 109 ms | 3.5 KB/s | 13.9 KB/s | 14.4 KB/s | 7.5 / 18.8 / 61.8 ms | 0.00 / 0.00 / 1.21 m | 0.01 / 0.00 / 1.05 m | 4.45 / 7.65 m | 12.3 / 15 | 5.2 | 1200 / 1200 / 0 | 0 / 2 / 0 |
| 200 ms | 5% | 208 ms | 3.5 KB/s | 13.2 KB/s | 14.4 KB/s | 9.8 / 48.8 / 116.0 ms | 0.00 / 0.00 / 0.62 m | 0.01 / 0.01 / 0.54 m | 5.75 / 9.93 m | 17.8 / 20 | 4.8 | 1200 / 1199 / 0 | 0 / 1 / 1 |
| 150 ± 30 ms | 5% | 158 ms | 3.5 KB/s | 13.7 KB/s | 14.4 KB/s | 12.9 / 33.1 / 71.8 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 4.96 / 8.51 m | 14.5 / 16 | 4.7 | 1200 / 1200 / 0 | 0 / 0 / 0 |

### Observations

- **Replays match the server.** Straight flight replays bit for bit. Turning
leaves float-rounding differences of a few millimetres, too small to show
in the table's two decimals. Larger corrections come only from the server's
input buffer policy: a catch-up drop or a starved tick shifts the server by
one tick of motion (0.5–1.4 m), and the visual offset hides it over about
0.3 s.
- **No input is lost**, at any condition: each input travels in up to five
packets, so 5% loss and short bursts never leave a gap.
- **ENet's throttle no longer discards traffic at 200 ms.** The server now
sends its full snapshot rate at every condition (14.4 KB/s, against 6.3 and
10.6 KB/s before). The fix is the throttle configuration below, not the
redundancy.
- **The gap to the server grew,** from 1.6/3.3 m to 3.0/4.6 m at 100/200 ms.
That is the intended effect of prediction: the local ship now runs ahead of
the server by the upstream delay plus the server's input buffer (2–5 ticks,
33–83 ms) instead of being dragged back toward old snapshots. Controls
respond in the same frame at every latency.
- **Upload doubled** (1.1 to 3.5 KB/s) for 30 redundant input packets per
second; downstream is unchanged.

### ENet packet throttle

ENet throttles unreliable packets at the sender. Each peer keeps a packet
throttle (0–32) and drops that share of unreliable packets. Every throttle
interval (5 s) it compares the latest round trip with the previous interval's
mean: lower round trips accelerate the throttle, and a round trip above the
mean plus twice its variance decelerates it. With steady added delay the
variance is tiny, so ordinary frame-timing noise decelerates it repeatedly.
That produced the baseline's 25–35% loss of commands and snapshots at 200 ms.

Clients and the server now call `ENetPacketPeer.throttle_configure(5000, 2, 0)`
on every server/client peer (`FlightSession.ENET_THROTTLE`). Deceleration 0
keeps the throttle fully open. Dorbit's unreliable traffic is small and paced,
so it needs no congestion back-off. Reliable traffic keeps ENet's own
windowing, acknowledgements and resends, and the full suite of reliable
gameplay tests passes. Measured with the same phase 2 build, at 200 ms added
RTT:

| ENet deceleration | Loss | Server to client | Snapshot jitter p95 | Sim error max | Starved / dropped |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 2 (ENet default) | 0% | 14.9 KB/s | 19.7 ms | 0.71 m | 1 / 2 |
| 2 (ENet default) | 5% | 10.5 KB/s | 126.6 ms | 2.16 m | 11 / 11 |
| 0 (phase 2) | 0% | 14.4 KB/s | 12.1 ms | 0.00 m | 1 / 0 |
| 0 (phase 2) | 5% | 14.4 KB/s | 48.8 ms | 0.62 m | 1 / 1 |

With the default the throttle engaged at 5% loss in this run: the server
dropped 27% of its snapshot bytes, snapshot jitter rose 2.6 times, and
throttled input packets starved the input buffer.
90 changes: 90 additions & 0 deletions scripts/flight_input.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
class_name FlightInput
extends RefCounted
## Compact flight input packets from a client to the server.
##
## A client samples one input per physics tick (60 Hz): a per-connection
## sequence number, its local tick, movement, boost and the facing it requests.
## Every packet repeats the most recent unacknowledged inputs, so a lost packet
## costs nothing while a later one arrives. Sequence numbers in a packet are
## consecutive, so only the first is sent.
##
## Layout (little endian):
## u8 flags (FIRE), u32 life, i32 encounter, i32 target, u32 client tick of
## the newest input, u32 first sequence, u8 count, then per input:
## 3 x i8 movement (axis * 127), u16 yaw, i16 pitch, u8 flags (BOOST).
## Movement and facing are quantized here, and clients predict with the
## quantized values, so the server and the client simulate the same numbers.

const FIRE := 1
const BOOST := 1
## Inputs per packet: at 30 packets per second (two inputs each) ten inputs
## cover a burst of four lost packets. A playtesting setting.
const REDUNDANCY := 10
const MAX_INPUTS := 16
const HEADER_SIZE := 22
const INPUT_SIZE := 8
const MOVEMENT_SCALE := 127.0
const YAW_SCALE := 65536.0 / TAU
const PITCH_SCALE := 20000.0
const PITCH_LIMIT := 1.48


static func quantize_movement(movement: Vector3) -> Vector3:
var result := Vector3.ZERO
for axis in 3:
result[axis] = roundf(clampf(movement[axis], -1.0, 1.0) * MOVEMENT_SCALE) / MOVEMENT_SCALE
return result


## Facing as the server decodes it: yaw wrapped to [-PI, PI), pitch clamped.
static func quantize_facing(angles: Vector3) -> Vector3:
var yaw := posmod(roundi((wrapf(angles.y, -PI, PI) + PI) * YAW_SCALE), 65536)
var pitch := roundi(clampf(angles.x, -PITCH_LIMIT, PITCH_LIMIT) * PITCH_SCALE)
return Vector3(pitch / PITCH_SCALE, yaw / YAW_SCALE - PI, 0.0)


## `inputs` hold {seq, movement, boost, facing} with consecutive sequences.
static func encode(life: int, fire: bool, encounter: int, target: int, client_tick: int, inputs: Array) -> PackedByteArray:
var buffer := StreamPeerBuffer.new()
buffer.put_u8(FIRE if fire else 0)
buffer.put_u32(life)
buffer.put_32(encounter)
buffer.put_32(target)
buffer.put_u32(client_tick)
buffer.put_u32(inputs[0]["seq"] if not inputs.is_empty() else 0)
buffer.put_u8(inputs.size())
for input: Dictionary in inputs:
var movement: Vector3 = input["movement"]
for axis in 3:
buffer.put_8(roundi(clampf(movement[axis], -1.0, 1.0) * MOVEMENT_SCALE))
var facing: Vector3 = input["facing"]
buffer.put_u16(posmod(roundi((wrapf(facing.y, -PI, PI) + PI) * YAW_SCALE), 65536))
buffer.put_16(roundi(clampf(facing.x, -PITCH_LIMIT, PITCH_LIMIT) * PITCH_SCALE))
buffer.put_u8(BOOST if input["boost"] else 0)
return buffer.data_array


## Returns {fire, life, encounter, target, tick, inputs: [{seq, movement,
## boost, facing}]}, or {} for a malformed packet. Values are always finite
## and in range, whatever the sender wrote.
static func decode(packet: PackedByteArray) -> Dictionary:
if packet.size() < HEADER_SIZE:
return {}
var buffer := StreamPeerBuffer.new()
buffer.data_array = packet
var result := {"fire": buffer.get_u8() & FIRE != 0, "life": buffer.get_u32(), "encounter": buffer.get_32(),
"target": buffer.get_32(), "tick": buffer.get_u32(), "inputs": []}
var first := buffer.get_u32()
var count := buffer.get_u8()
if count < 1 or count > MAX_INPUTS or packet.size() != HEADER_SIZE + count * INPUT_SIZE:
return {}
for index in count:
var movement := Vector3.ZERO
for axis in 3:
movement[axis] = clampi(buffer.get_8(), -127, 127) / MOVEMENT_SCALE
var yaw := buffer.get_u16()
var pitch := clampi(buffer.get_16(), -roundi(PITCH_LIMIT * PITCH_SCALE), roundi(PITCH_LIMIT * PITCH_SCALE))
result["inputs"].append({"seq": first + index, "movement": movement,
"facing": Vector3(pitch / PITCH_SCALE, yaw / YAW_SCALE - PI, 0.0),
"boost": buffer.get_u8() & BOOST != 0})
return result
1 change: 1 addition & 0 deletions scripts/flight_input.gd.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://qwlgiboqby6m
102 changes: 102 additions & 0 deletions scripts/flight_prediction.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
class_name FlightPrediction
extends RefCounted
## Client-side prediction and reconciliation of the local pilot.
##
## Each client physics tick samples one input, keeps it until the server
## acknowledges it, and simulates it at once with Pilot.simulate_input(), the
## same step the server runs per consumed input. Each new owner snapshot names
## the last input the server processed: the client drops acknowledged inputs,
## resets the ship's simulation state (position, velocity, energy, facing and
## turn budget) to the authoritative state and replays the rest in the same
## physics tick. The replay never touches the view facing, so mouse steering
## stays immediate.
##
## Corrections are hidden by drawing the model and camera at a world-space
## offset from the simulated ship, which decays exponentially. The simulation
## itself is never smoothed.

## Physics ticks between input packets (30 packets per second).
const SEND_INTERVAL_TICKS := 2
## Unacknowledged inputs kept for replay (two seconds); older ones are dropped.
const MAX_PENDING := 120
## Time constant of the decaying correction offset, in seconds: about 63% of
## a correction is hidden after this long and 95% after three times as long.
## A playtesting setting.
const SMOOTHING_TIME := 0.12
## Corrections larger than this, in metres, snap instead of smoothing.
const SNAP_DISTANCE := 10.0

## Sequence of the next sampled input. Sequences rise for the whole connection.
var next_seq: int = 1
var client_tick: int = 0
## Unacknowledged inputs, oldest first: {seq, tick, movement, boost, facing}.
var pending: Array[Dictionary] = []
## Newest owner state awaiting reconciliation, or {}.
var authoritative: Dictionary = {}
var last_ack: int = 0


## Forgets inputs and the correction offset at a discontinuity (connect,
## spawn, respawn, jump, dock or launch). The next snapshot re-anchors the
## simulation.
func reset(ship: Pilot) -> void:
pending.clear()
authoritative = {}
ship.sim_rotation = ship.rotation
ship.turn_budget = Pilot.MAX_TURN_RATE * (1.0 / Engine.physics_ticks_per_second + Pilot.TURN_LATENCY_ALLOWANCE)
ship.set_visual_offset(Vector3.ZERO)


## Samples this tick's input and predicts it.
func predict(ship: Pilot, delta: float, movement: Vector3, boost: bool) -> void:
ship.apply_look(delta)
# Predict with exactly the facing the server will decode.
var facing := FlightInput.quantize_facing(ship.rotation)
ship.rotation = facing
var input := {"seq": next_seq, "tick": client_tick, "movement": FlightInput.quantize_movement(movement), "boost": boost, "facing": facing}
next_seq += 1
pending.append(input)
if pending.size() > MAX_PENDING:
pending.pop_front()
ship.simulate_input(delta, input["movement"], boost, facing)
ship.present_motion(delta, input["movement"])


## The newest unacknowledged inputs, ready to send.
func packet(life: int, fire: bool, encounter: int, target: int) -> PackedByteArray:
var inputs := pending.slice(maxi(0, pending.size() - FlightInput.REDUNDANCY))
return FlightInput.encode(life, fire, encounter, target, client_tick, inputs)


## Rewinds to the newest authoritative state and replays unacknowledged
## inputs. Call from a physics tick: move_and_slide() uses the physics delta.
func reconcile(ship: Pilot, delta: float, stats: NetStats) -> void:
if authoritative.is_empty():
return
var state := authoritative
authoritative = {}
var ack: int = state.get("ack", last_ack)
var ack_lag := -1
while not pending.is_empty() and pending[0]["seq"] <= ack:
ack_lag = client_tick - int(pending[0]["tick"])
pending.pop_front()
last_ack = maxi(last_ack, ack)
var predicted := ship.position
ship.position = state["position"]
ship.velocity = state["velocity"]
ship.energy = state["energy"]
ship.sim_rotation = state["rotation"]
ship.turn_budget = state.get("turn_budget", ship.turn_budget)
for input: Dictionary in pending:
ship.simulate_input(delta, input["movement"], input["boost"], input["facing"])
var error := predicted.distance_to(ship.position)
var offset := ship.visual_offset + predicted - ship.position
ship.set_visual_offset(Vector3.ZERO if offset.length() > SNAP_DISTANCE else offset)
stats.record_reconciliation(error, pending.size(), ack_lag, int(state.get("input_depth", -1)))


## Decays the correction offset by one tick and re-applies it under the
## current view rotation.
func smooth(ship: Pilot, delta: float) -> void:
var offset := ship.visual_offset * exp(-delta / SMOOTHING_TIME)
ship.set_visual_offset(Vector3.ZERO if offset.length_squared() < 1e-8 else offset)
1 change: 1 addition & 0 deletions scripts/flight_prediction.gd.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://lt2u101iq6mj
Loading
Loading