Skip to content

feat: add a network simulator and netcode overlay - #144

Merged
Timerk merged 4 commits into
mainfrom
feat/network-simulator
Nov 26, 2026
Merged

Timerk merged 4 commits into
mainfrom
feat/network-simulator

Conversation

@Timerk

@Timerk Timerk commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Phase 1 of 6 of the real-time netcode rework. This PR is the base of a stack; later phases branch from it.

Behavior

  • Network simulator (scripts/net_simulator.gd, NetSimulator). An in-process UDP relay sits between the client's ENet socket (on 127.0.0.1:<listen_port>) and the real server. Each direction (client→server UP, server→client DOWN) has its own one-way latency, ± jitter (uniform, can reorder datagrams), loss % and duplication %. Conditions change live behind a mutex, the RNG can be seeded, and per-direction counters track received, forwarded, dropped, duplicated and queued datagrams. stop() flushes queued datagrams first, so ENet's disconnect notice still reaches the server. One relay serves one client.
    • Timing. One thread per socket blocks in PacketPeerUDP.wait() and timestamps each datagram on arrival. A delivery thread measures how long its 1 ms sleeps really take and spins only when the next datagram is due sooner than that. On this machine, sleeps in some contexts lasted a full 15.6 ms Windows timer tick, which first quantized jittered delays. A fixed 60 ms now measures 60.1 ms, and 50 ± 20 ms spreads uniformly from 30 to 70 ms.
    • API. start(address, port, bind_port := 0), stop(), is_running(), listen_port, configure(UP|DOWN|BOTH, latency_ms, jitter_ms, loss_percent, duplicate_percent), set_round_trip(rtt_ms, jitter_ms, loss, duplicate) (split evenly per direction: "150 ± 30 ms" adds 75 ± 15 ms each way), conditions(direction), symmetric(), stats(), reset_stats(), set_seed() and configure_from_args().
  • Opt-in routing. The Graphics tab option Route connections through the network simulator (debug) (not saved), or launching with --netsim, --netsim-rtt=MS, --netsim-jitter=MS, --netsim-loss=%, --netsim-duplicate=% or --netsim-seed=N, makes the next join() start the relay. The connection menu still shows the real address and adds "Routed through the network simulator (debug)". Normal play never uses the relay. Tests set session.use_net_simulator and configure session.net_simulator before joining.
  • NetStats (scripts/net_stats.gd). A small client-side metrics object that FlightSession feeds. It tracks:
    • ENet smoothed RTT and client bytes and packets per second up and down, sampled each second.
    • Snapshot inter-arrival jitter: mean and max of |interval − 50 ms| over the last 100 intervals.
    • Prediction error and applied correction per reconciled snapshot, latest and max, with optional kept samples for percentiles.
    • The last authoritative pose, for the ghost.
    • Commands sent, and on the server, accepted commands per pilot.
      It is meant to be extended in later phases (buffer health, acks, per-client server bytes).
  • F8 netcode overlay (scripts/netcode_overlay.gd). It matches the F3 overlay's style and is a regular HUD layout panel, so it can be moved, resized and closed in the Ctrl+Alt editor. It shows:
    • The metrics above, plus relay losses and duplicates.
    • Sliders for added RTT / jitter / loss / duplicates, editing both ways (round trip) or one direction.
    • Server ghost: a translucent cyan copy of your hull at the last authoritative position and rotation, with a toggle.
    • Reset max, and Use simulator on next connection, with a note when the relay isn't in the path.
      The sliders are mouse-only (FOCUS_NONE, MOUSE_FILTER_PASS), so flight keys keep working, left clicks don't select targets, and right-drag steering still passes through. F8 is a fixed shortcut like F3. The overlay hides while the sector overview is open.
  • No gameplay authority, RPC signatures or packet contents change, so NETWORK_SCHEMA stays 23. The only server-side addition is a per-pilot counter of accepted flight commands.

Why a relay and not a MultiplayerPeerExtension wrapper

A wrapper around ENetMultiplayerPeer would sit above ENet's reliability layer. Dropping a "packet" there would drop a whole reliable message that ENet has already delivered and acknowledged, and delaying it would delay delivery to the game, not the wire. ENet's resends, acks, RTT estimate, sequencing and packet throttle would never see the loss or latency, so reliable traffic would lose data (never realistic) and unreliable traffic would skip ENet's real behavior. A UDP relay degrades the actual datagrams, so ENet reacts exactly as on a bad network. The baseline shows why that matters: at 200 ms, ENet's own throttle discards unreliable traffic. The relay also needs no engine changes and works headlessly on Linux and Windows.

Baseline (tests/netcode_benchmark.gd, also in docs/netcode-baseline.md)

One dedicated server, one measured client through the relay and three direct clients, all in one headless process (129–139 fps), flying a mirrored scripted pattern at about 30 m/s. Each condition gets a 15 s warm-up, then 20 s of measurement. Added RTT is split evenly per direction; loss applies both ways.

Added RTT Loss ENet RTT Client up Client down Server to client Snapshot jitter mean / p95 / max Prediction error mean / p95 / max Correction mean / p95 / max Gap to server now mean / p95 Commands sent / applied / lost
0 ms 0% 28 ms 1.1 KB/s 13.6 KB/s 13.6 KB/s 5.7 / 16.0 / 30.5 ms 0.24 / 0.55 / 0.87 m 0.05 / 0.11 / 0.17 m 0.20 / 0.47 m 400 / 400 / 0 (0.0%)
100 ms 0% 105 ms 1.1 KB/s 14.0 KB/s 14.0 KB/s 5.7 / 13.7 / 58.7 ms 0.15 / 0.45 / 0.81 m 0.03 / 0.09 / 0.16 m 1.55 / 2.77 m 401 / 400 / 1 (0.2%)
200 ms 0% 206 ms 0.7 KB/s 6.3 KB/s 6.3 KB/s 61.3 / 156.8 / 175.0 ms 0.82 / 1.81 / 2.78 m 0.16 / 0.36 / 0.56 m 3.26 / 6.11 m 400 / 261 / 139 (34.8%)
0 ms 5% 32 ms 1.1 KB/s 12.8 KB/s 13.6 KB/s 9.6 / 45.9 / 107.8 ms 0.24 / 0.55 / 0.79 m 0.05 / 0.11 / 0.16 m 0.22 / 0.51 m 400 / 385 / 15 (3.8%)
100 ms 5% 105 ms 1.1 KB/s 13.5 KB/s 14.4 KB/s 7.3 / 30.6 / 98.8 ms 0.15 / 0.39 / 1.57 m 0.03 / 0.08 / 0.31 m 1.55 / 2.74 m 400 / 389 / 11 (2.8%)
200 ms 5% 202 ms 0.8 KB/s 10.0 KB/s 10.6 KB/s 21.2 / 64.1 / 157.9 ms 0.37 / 0.96 / 1.42 m 0.07 / 0.19 / 0.28 m 3.05 / 5.45 m 400 / 299 / 101 (25.3%)

What these show:

  • The prediction error is small because reconciliation hides latency. Lerping 20% toward each round-trip-old snapshot drags the predicted ship onto the delayed server path. The "gap to server now" (0.2 m → 1.6 m → 3.3 m) shows the resulting control lag.
  • At 200 ms, ENet's packet throttle discards 25–35% of unreliable commands and snapshots at the sender, even with 0% simulated loss: server-side bytes drop too, so this is not the relay. Phase 2's redundant inputs, and possibly ENet throttle settings, need to handle it.
  • Lost datagrams lose inputs. At 5% loss, 3–4% of commands are lost, because commands are not resent.

Usage: godot --headless --path . --script res://tests/netcode_benchmark.gd -- [--scenario=baseline|degraded] [--condition=RTT,JITTER,LOSS[,DUP]]... [--seconds=20] [--extra-clients=3] [--seed=1]. Every metric is defined in the script header, and it also prints a NETCODE_BENCHMARK= JSON line, so phases 2–4 can rerun it unchanged. The benchmark is not in the check suites.

Validation

  • ./tools/dev.ps1 check (Windows, 2 workers): all 73 checks pass in 530 s, including the new net_simulator group and the HUD customization test, which covers the new panel's editor lifecycle.
  • New net_simulator group in both the Windows and Linux suites:
    • tests/net_simulator_test.gd (raw PacketPeerUDP) covers per-direction latency within tolerance, jitter bounds and spread, seeded loss (20% → 1590/2000 arrived) and duplication (10% → 2210/2000 delivered) with exact counters, live reconfiguration, flush on stop, and argument parsing.
    • tests/netsim_network_test.gd covers an authenticated join to a dedicated server through the relay at 80 ± 10 ms with 5% loss and 5% duplication. It also checks snapshots, RTT, traffic rates, corrections and command counts, plus F8 toggling, live round-trip and per-direction sliders, the ghost and its toggle, a prompt server-side leave on disconnect (flush), and a direct reconnect that bypasses the relay.
  • python -m unittest tests/ci_performance_test.py passes (suite layout and port blocks).
  • Visual check. I connected a windowed client launched with --netsim-rtt=150 --netsim-jitter=30 --netsim-loss=5 to a local headless dedicated server. The connection menu showed the routing note, and F8 opened the overlay with live readings. Dragging the Added RTT slider changed it to 405 ms and clicking the Loss track changed loss, without selecting targets. RTT then visibly rose and ENet traffic fell. The automation tool couldn't hold flight keys, so the ghost was captured with a scratch script that renders a relayed client while flying. The overlay and the cyan ghost render correctly, and the ghost sits close to the ship, matching the "dragged onto the server path" finding. Screenshots stay out of the repository.

Limitations

  • Linux suite not run locally (no WSL distro); CI will run it.
  • ENet's RTT is smoothed by 1/8 per reliable acknowledgement, about two per second, so the overlay's RTT lags slider changes by several seconds.
  • Ghost and correction cover the local ship only. Remote-entity interpolation metrics come in phase 3.
  • The relay spins a core only briefly before each due datagram, longer on systems where sleeps last a 15.6 ms tick. That is fine for a debug tool.
  • Benchmark coverage. It doesn't separately measure "visible per-frame displacement": the current reconciliation applies each correction within one frame, so the correction column is that jump. Phases that smooth corrections should report per-frame render offset changes.
  • Stale GAME_PLAN schema numbers left alone. The "current is 19/21" mentions are in several places, so I didn't change them (not a trivial fix).

🤖 Generated with Claude Code

Timerk and others added 4 commits November 25, 2026 18:39
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NetSimulator is a threaded UDP relay that adds per-direction latency,
jitter, loss and duplication beneath ENet, with live reconfiguration,
seeded decisions and counters. Receivers block on their sockets and the
delivery thread spins only near due times, so delays stay accurate on
Windows systems with a 15.6 ms timer tick. NetStats collects RTT,
traffic rates, snapshot jitter and reconciliation corrections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A debug setting or --netsim routes the next join through the relay;
the menu keeps the real address. FlightSession feeds NetStats with
snapshot arrivals, reconciliation corrections, accepted commands and
ENet traffic. F8 shows them with live simulator sliders and a
translucent ghost at the last authoritative position. Gameplay
authority and packet contents are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Timerk
Timerk merged commit b31c28c into main Nov 26, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant