diff --git a/GAME_PLAN.md b/GAME_PLAN.md index 0266c4f..9a55ce9 100644 --- a/GAME_PLAN.md +++ b/GAME_PLAN.md @@ -932,6 +932,48 @@ does not start at boot. No CPU or memory limits are needed for the current solo development phase; both instances share host resources. Production deployment remains a separate manual action. See DEPLOYMENT.md for setup and recovery. +### Real-time netcode rework + +The user agreed to rework client/server movement networking into a measurable, +demonstrable system. The work spans six stacked PRs, measuring first. Gameplay +stays server-authoritative. Clients never send wallet, health, hit or reward +outcomes. + +1. **Network simulator and netcode overlay.** An in-process threaded UDP relay + sits between the client's ENet socket and the server. It adds latency, + jitter, loss and duplication in both directions, so ENet's real reliability + and ordering still apply. It is opt-in: a debug setting or `--netsim`, + applied on the next connection. Once it's on, the sliders change conditions + live. F8 toggles an overlay in the F3 style showing the sliders, RTT, bytes/s + up and down, snapshot arrival jitter, the latest and largest correction, and + a translucent server ghost. Baseline numbers are recorded at 0, 100 and + 200 ms, each with 0% and 5% loss. +2. **Ticks, input sequencing and reconciliation.** The 60 Hz simulation tick is + numbered. Each client input carries its tick, sequence number, movement, + boost and requested facing, and sends are redundant so loss doesn't drop + inputs. The server buffers inputs per pilot and consumes exactly one per + tick. Snapshots carry the server tick and each pilot's last processed + sequence. The client rewinds to the authoritative state, replays + unacknowledged inputs, and hides corrections with a decaying render offset. + The 720°/s facing limit and life checks remain. +3. **Snapshot interpolation.** Remote pilots and aliens render about 100 ms in + the past, between two buffered server-tick snapshots. When the buffer runs + dry they extrapolate for at most 250 ms. The overlay shows buffer depth and + underruns. +4. **Snapshot encoding.** Positions, angles and health are quantized. Each + viewer gets fields delta-encoded against the last snapshot it acknowledged, + falling back to full state, and packets stay under the ENet MTU. Bytes per + client per second are reported before and after. +5. **Degraded-network tests.** Headless multi-client playthroughs run through + the relay at 150 ± 30 ms with 5% loss in both CI jobs. They assert limits on + worst correction, lost inputs and bandwidth, and that hits and rewards stay + authoritative. +6. **docs/NETCODE.md.** Architecture, a timeline, tradeoffs and before/after + tables. The README portfolio section waits for the user's approval. + +The interpolation delay, extrapolation cap, correction smoothing and the +redundancy count are playtesting settings. Each PR bumps the network schema. + ## Ship visual refinement The user requested a visual refinement of the existing twelve playable ships diff --git a/README.md b/README.md index de836c1..54f7b75 100644 --- a/README.md +++ b/README.md @@ -316,7 +316,9 @@ Esc opens the flight menu and releases the mouse. Choose **Settings** there or i The Audio tab has master/effects volume, mute and a test sound. The Graphics tab contains fullscreen, VSync, a typed frame rate limit, antialiasing, the performance overlay and window resolution. Enter a whole-number FPS limit from 1 to 1000, or 0 for unlimited, then press Enter or leave the field to apply and save it. The default is unlimited. VSync is off by default; enable it to synchronize rendering with your screen's refresh rate and reduce tearing. VSync may limit FPS below the entered cap. Resolution choices fit the current screen with room for borders and the taskbar. Selecting one switches to windowed mode; fullscreen uses the desktop resolution. You can also resize the window manually. Mouse steering uses unscaled screen motion so viewport scaling does not change sensitivity. -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, 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. +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. 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 diff --git a/docs/netcode-baseline.md b/docs/netcode-baseline.md new file mode 100644 index 0000000..54e4c78 --- /dev/null +++ b/docs/netcode-baseline.md @@ -0,0 +1,54 @@ +# Netcode baseline + +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`. + +``` +godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=baseline +``` + +Setup: one dedicated server, one measured client routed through the relay and +three clients connected directly, all in one headless process on a Windows 11 +desktop (129–139 frames per second). Every pilot flies the same scripted input: +thrust, boost, strafe and turns in a mirrored 6-second cycle, about 30 m/s on +average. Each condition gets a 15-second warm-up and is then measured for +20 seconds. Added RTT is split evenly per direction (100 ms adds 50 ms each +way); loss applies independently in both directions. Metric definitions are in +the header of `tests/netcode_benchmark.gd`. + +| 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%) | + +## Observations + +- **Prediction error looks small because reconciliation hides latency.** Each + snapshot pulls the local ship 20% toward the authoritative position, which + is about one round trip old. At steady speed this drags the predicted ship + back onto the delayed server path instead of correcting real mispredictions. + The gap to the server's current position grows with latency (0.2 m at 0 ms, + 1.6 m at 100 ms, 3.3 m at 200 ms), so the controls feel delayed even though + the per-snapshot correction stays under 0.6 m. +- **ENet's packet throttle drops unreliable traffic at 200 ms.** Commands and + snapshots are unreliable, and ENet discards unreliable packets at the sender + when its round-trip variance suggests congestion. At 200 ms added RTT, 25–35% + of flight commands never left the client and the server sent up to half its usual + snapshot bytes, even with no simulated loss. Snapshot jitter rises + accordingly. Phase 2's redundant inputs, and possibly ENet throttle settings, + need to account for this. +- **Lost datagrams lose inputs.** At 5% loss, 3–4% of flight commands never + reach the server. Commands are not resent, so each loss leaves the server on + the previous input until the next command 50 ms later. +- **ENet RTT is a smoothed estimate.** ENet adjusts it by 1/8 per reliable + acknowledgement, about two per second here, so it lags condition changes by + 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. diff --git a/scripts/flight_session.gd b/scripts/flight_session.gd index efa2e1c..e5b257a 100644 --- a/scripts/flight_session.gd +++ b/scripts/flight_session.gd @@ -61,6 +61,13 @@ var lab_clock: float = 0.0 var jump_pending := false var jump_cover: CanvasLayer var jump_until: Dictionary[int, int] = {} +## Netcode measurements; see NetStats. Clients feed and the F8 overlay reads them. +var net_stats := NetStats.new() +## Debug relay between this client and the server. Its conditions persist +## between connections; it runs only while a connection uses it. +var net_simulator := NetSimulator.new() +## Route the next join() through net_simulator. Off for normal play. +var use_net_simulator := false func _ready() -> void: @@ -79,6 +86,7 @@ func _ready() -> void: multiplayer.connection_failed.connect(func(): disconnect_session("Connection failed. Check the address and UDP port, then try again.")) multiplayer.server_disconnected.connect(func(): disconnect_session("Connection to the server was lost. You can try connecting again.")) if not sector.dedicated_server: + use_net_simulator = net_simulator.configure_from_args(OS.get_cmdline_user_args()) build_menu() if "--print-protocol" in OS.get_cmdline_user_args(): # Operator/CI diagnostic. No network connection or pilot credentials are needed. @@ -180,11 +188,15 @@ func _process(_delta: float) -> void: print("Server shutdown requested; closing pilot store.") get_tree().quit() return + if active and not multiplayer.is_server(): + net_stats.sample_transport(multiplayer.multiplayer_peer) if menu.visible: layout_menu() status_label.text = status if not attempted_address.is_empty(): status_label.text = "%s | UDP %d\n%s" % [attempted_address, attempted_port, status] + if net_simulator.is_running(): + status_label.text += "\nRouted through the network simulator (debug)." if connecting: status_label.text += "\nWaiting for the server, up to %d seconds." % int(CONNECT_TIMEOUT) preference_label.text = "Could not save this connection for the next launch." if preferences.save_failed else "Remembers the last successful connection on this device." @@ -263,11 +275,23 @@ func join(host_address: String, port: int = PORT) -> Error: if sector.client_only and (not PilotStore.valid_id(credential_id) or not PilotStore.valid_hex(credential_token)): status = "Set DORBIT_PILOT_FILE to the pilot credential file supplied by the server operator." return ERR_UNAUTHORIZED + # The debug relay is opt-in; the menu and status keep the real address. + var connect_address := host_address + var connect_port := port + if use_net_simulator: + var relay_error := net_simulator.start(host_address, port) + if relay_error != OK: + status = "Could not start the network simulator: %s." % error_string(relay_error) + return relay_error + connect_address = "127.0.0.1" + connect_port = net_simulator.listen_port var peer := ENetMultiplayerPeer.new() - var error := peer.create_client(host_address, port) + var error := peer.create_client(connect_address, connect_port) if error != OK: + net_simulator.stop() status = "Could not start the connection: %s. Check the address and UDP port." % error_string(error) return error + net_stats.reset() multiplayer.multiplayer_peer = peer connecting = true auth_proof_sent = false @@ -762,6 +786,7 @@ func tick(delta: float) -> void: send_clock = 0.0 var enemy := sector.target as Alien if not sector.preflight: + net_stats.commands_sent += 1 command_flight.rpc_id(1, movement, sector.player.rotation, boost, sector.auto_fire and enemy != null and not sector.paused, int(sector.player.get_meta("life", 0)), enemy.life if enemy != null else -1, enemy.alien_id if enemy != null else -1) combat.interpolate(delta) for id: int in goals: @@ -878,6 +903,7 @@ func command_flight(movement: Vector3, angles: Vector3, boost: bool, fire: bool return if not ships[id].alive or combat.records[id]["life"] != life: return + net_stats.record_command_received(id) commands[id] = { "movement": movement.limit_length(), "rotation": Vector3(clampf(angles.x, -1.48, 1.48), wrapf(angles.y, -PI, PI), 0), @@ -900,6 +926,7 @@ func entity_profiles(players: Dictionary, aliens: Dictionary) -> void: func world_snapshot(packet: PackedByteArray) -> void: if not active: return + net_stats.record_snapshot_arrival() var world := SnapshotCodec.decode_world(packet) if world.is_empty() or not receives_map(world["visit"]): return @@ -956,10 +983,14 @@ func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: if ship == sector.player: # Predict locally for immediate controls; reconcile against host position. var location: Vector3 = data["position"] + var predicted := ship.position if not received_snapshot or ship.position.distance_to(location) > 10.0: ship.position = location else: ship.position = ship.position.lerp(location, 0.2) + if received_snapshot and not reset: + net_stats.record_correction(predicted.distance_to(location), predicted.distance_to(ship.position)) + net_stats.record_server_state(location, data["rotation"]) ship.velocity = data["velocity"] if ship.alive else Vector3.ZERO received_snapshot = true status = "Connected. Players: %d/%d" % [ships.size(), MAX_PLAYERS] @@ -983,6 +1014,8 @@ func disconnect_session(message: String) -> void: combat.finish() multiplayer.multiplayer_peer.close() multiplayer.multiplayer_peer = OfflineMultiplayerPeer.new() + net_simulator.stop() + net_stats.has_server_state = false for ship: Pilot in ships.values(): if ship != sector.player: ship.queue_free() @@ -1020,6 +1053,7 @@ func _exit_tree() -> void: if not store.close() and not already_failed: get_tree().quit(1) if active or connecting: multiplayer.multiplayer_peer.close() + net_simulator.stop() func receives_map(visit: int) -> bool: diff --git a/scripts/game_settings.gd b/scripts/game_settings.gd index 7252bf1..5085f19 100644 --- a/scripts/game_settings.gd +++ b/scripts/game_settings.gd @@ -50,7 +50,7 @@ const SHORTCUTS := { "quality": KEY_F4, "quit_game": KEY_F10, "resolution_down": KEY_F5, "resolution_up": KEY_F6, "multiplayer_menu": KEY_F7, "contracts": KEY_C, "station_shop": KEY_B, "ship_equipment": KEY_I, - "sector_map": KEY_M, + "sector_map": KEY_M, "netcode": KEY_F8, } var sensitivity: float = DEFAULT_SENSITIVITY diff --git a/scripts/hud.gd b/scripts/hud.gd index 34610c1..bfaa0b1 100644 --- a/scripts/hud.gd +++ b/scripts/hud.gd @@ -67,6 +67,7 @@ var tip_keys: Array[Array] = [] var tip_keys_key := Vector2i(-1, -1) var navigation: FlightNavigation var ammo_bar: AmmoBar +var netcode: NetcodeOverlay var layout: HudLayout # Binding phrases and control hints are rebuilt after any rebind. var phrases: Dictionary[String, String] = {} @@ -89,6 +90,9 @@ func _ready() -> void: ammo_bar = AmmoBar.new() ammo_bar.sector = sector add_child(ammo_bar) + netcode = NetcodeOverlay.new() + netcode.hud = self + add_child(netcode) layout = HudLayout.new() layout.hud = self add_child(layout) @@ -764,6 +768,8 @@ func _draw() -> void: draw_gate_countdown() draw_tutorial() draw_performance() + if netcode.visible: + marker_labels.append(layout.rect_for("netcode")) if layout.begin_draw(self, "ship"): draw_ship_panel() layout.end_draw(self) diff --git a/scripts/hud_layout.gd b/scripts/hud_layout.gd index 49b8eda..0e193ba 100644 --- a/scripts/hud_layout.gd +++ b/scripts/hud_layout.gd @@ -13,7 +13,7 @@ const ITEMS := { "station": ["Station actions", "shop"], "radiation": ["Radiation", "shield"], "reticle": ["Reticle", "damage"], "autopilot": ["Autopilot status", "speed"], "performance": ["Performance", "settings"], "ammo": ["Quickslots", "damage"], - "tutorial": ["Control tips", "settings"] + "tutorial": ["Control tips", "settings"], "netcode": ["Netcode", "connection"] } # Read-only default, so per-frame layout lookups do not allocate a Dictionary. const NO_ENTRY := {} @@ -108,6 +108,7 @@ func default_rect(id: String) -> Rect2: "autopilot": return Rect2(hud.navigation.radar_rect().position + Vector2(14, 190), Vector2(170, 26)) "performance": return Rect2(FlightHud.SIDE_MARGIN, hud.objectives_rect().end.y + 192, 350, 26) "tutorial": return hud.tutorial_rect() + "netcode": return Rect2(Vector2(size.x - FlightHud.SIDE_MARGIN - NetcodeOverlay.SIZE.x, hud.navigation.radar_rect().end.y + 14), NetcodeOverlay.SIZE) return Rect2() @@ -198,6 +199,8 @@ func reopen(id: String) -> void: hud.sector.settings.show_performance = true hud.sector.show_performance = true hud.sector.settings.save() + if id == "netcode": + hud.sector.show_netcode = true # Hide the rail when it covers the selected panel, so its full saved position # can be edited without relocating it just by opening the editor. if rect_for(id).intersects(sidebar.get_rect()): diff --git a/scripts/net_simulator.gd b/scripts/net_simulator.gd new file mode 100644 index 0000000..811fd59 --- /dev/null +++ b/scripts/net_simulator.gd @@ -0,0 +1,324 @@ +class_name NetSimulator +extends RefCounted +## Debug UDP relay that degrades one client's connection to a server. +## +## The client's ENet socket talks to `listen_port` on 127.0.0.1; the relay +## forwards each datagram to the real server and back after applying the +## conditions of its direction. Because it works on raw datagrams below ENet, +## ENet's own acknowledgements, resends, ordering and throttling react to the +## loss exactly as on a real network. +## +## Conditions are per direction (UP is client to server, DOWN is server to +## client) and can change while the relay runs: +## - latency_ms: one-way delay added to every datagram. +## - jitter_ms: each datagram's delay varies uniformly by up to this many +## milliseconds either way (never below zero). Jitter can reorder datagrams. +## - loss_percent: chance that a datagram is dropped. +## - duplicate_percent: chance that a datagram is delivered twice. The copy +## draws its own jitter. +## `set_round_trip()` sets both directions from round-trip figures: half of the +## added round trip and half of its jitter each way, so "150 ± 30 ms" adds +## 75 ± 15 ms per direction. +## +## Timing does not depend on frames or on the OS sleep granularity (a 15.6 ms +## timer tick on some Windows systems): one thread per socket blocks until a +## datagram arrives and timestamps it. The delivery thread measures how long its +## 1 ms sleeps really take and spins instead of sleeping when the next datagram +## is due sooner than that. One relay serves one client. + +const UP := 0 +const DOWN := 1 +const BOTH := -1 +# Spin margin added to the measured sleep length. +const SPIN_USEC := 500 +const MAX_QUEUE := 4096 +const FLUSH := 9223372036854775807 + +## Port the client connects to on 127.0.0.1. Zero while stopped. +var listen_port: int = 0 +var server_address: String = "" +var server_port: int = 0 + +# Guards everything below that more than one thread touches. +var _mutex := Mutex.new() +var _listeners: Array[Thread] = [] +var _pump: Thread +var _running := false +var _pumping := false +var _rng := RandomNumberGenerator.new() +var _client := PacketPeerUDP.new() +var _upstream := PacketPeerUDP.new() +var _waker := PacketPeerUDP.new() +var _client_port := 0 +var _conditions: Array[Dictionary] = [blank_conditions(), blank_conditions()] +var _stats: Array[Dictionary] = [blank_stats(), blank_stats()] +# Pending datagrams per direction, sorted by due time; equal times keep arrival order. +var _due: Array[Array] = [[], []] +var _packets: Array[Array] = [[], []] + + +static func blank_conditions() -> Dictionary: + return {"latency_ms": 0.0, "jitter_ms": 0.0, "loss_percent": 0.0, "duplicate_percent": 0.0} + + +static func blank_stats() -> Dictionary: + # received: datagrams entering the relay; forwarded: datagrams sent on, + # including duplicates; dropped: simulated losses (plus queue overflow). + return {"received_packets": 0, "received_bytes": 0, "forwarded_packets": 0, "forwarded_bytes": 0, + "dropped_packets": 0, "duplicated_packets": 0, "queued_packets": 0} + + +## Starts relaying to `address`:`port`, listening on 127.0.0.1:`bind_port` +## (0 picks a free port; read `listen_port` afterwards). +func start(address: String, port: int, bind_port: int = 0) -> Error: + if is_running(): + return ERR_ALREADY_IN_USE + if port < 1 or port > 65535: + return ERR_INVALID_PARAMETER + var resolved := address if address.is_valid_ip_address() else IP.resolve_hostname(address) + if resolved.is_empty(): + return ERR_CANT_RESOLVE + _client = PacketPeerUDP.new() + _upstream = PacketPeerUDP.new() + _waker = PacketPeerUDP.new() + var error := _client.bind(bind_port, "127.0.0.1") + if error == OK: + error = _upstream.bind(0, "*") + if error == OK: + error = _upstream.set_dest_address(resolved, port) + if error == OK: + error = _waker.bind(0, "127.0.0.1") + if error != OK: + _client.close() + _upstream.close() + _waker.close() + return error + server_address = resolved + server_port = port + listen_port = _client.get_local_port() + _client_port = 0 + _mutex.lock() + _due = [[], []] + _packets = [[], []] + _stats = [blank_stats(), blank_stats()] + _running = true + _pumping = true + _mutex.unlock() + _listeners = [Thread.new(), Thread.new()] + _listeners[UP].start(_listen.bind(UP)) + _listeners[DOWN].start(_listen.bind(DOWN)) + _pump = Thread.new() + _pump.start(_deliver_loop) + return OK + + +## Stops the relay. Datagrams already received, including ones still delayed, +## are delivered immediately first, so a disconnect notice sent just before +## stopping still reaches the server. +func stop() -> void: + if _pump == null: + return + _mutex.lock() + _running = false + _mutex.unlock() + # Wake the blocked receivers; they skip these datagrams. + _waker.set_dest_address("127.0.0.1", listen_port) + _waker.put_packet(PackedByteArray([0])) + _waker.set_dest_address("127.0.0.1", _upstream.get_local_port()) + _waker.put_packet(PackedByteArray([0])) + for listener in _listeners: + listener.wait_to_finish() + _listeners.clear() + _mutex.lock() + _pumping = false + _mutex.unlock() + _pump.wait_to_finish() + _pump = null + _client.close() + _upstream.close() + _waker.close() + listen_port = 0 + + +func is_running() -> bool: + return _pump != null + + +## Seeds loss, duplication and jitter decisions. Call before start() for a +## repeatable sequence of decisions on the same traffic. +func set_seed(value: int) -> void: + _mutex.lock() + _rng.seed = value + _mutex.unlock() + + +## Sets one direction (UP, DOWN) or both (BOTH) to the given one-way conditions. +func configure(direction: int, latency_ms: float, jitter_ms: float = 0.0, loss_percent: float = 0.0, duplicate_percent: float = 0.0) -> void: + var values := { + "latency_ms": clampf(latency_ms, 0.0, 5000.0), "jitter_ms": clampf(jitter_ms, 0.0, 5000.0), + "loss_percent": clampf(loss_percent, 0.0, 100.0), "duplicate_percent": clampf(duplicate_percent, 0.0, 100.0), + } + _mutex.lock() + for index in ([UP, DOWN] if direction == BOTH else [direction]): + _conditions[index] = values.duplicate() + _mutex.unlock() + + +## Adds `round_trip_ms` ± `jitter_ms` of round trip, split evenly between the +## directions, with the same loss and duplication chance each way. +func set_round_trip(round_trip_ms: float, jitter_ms: float = 0.0, loss_percent: float = 0.0, duplicate_percent: float = 0.0) -> void: + configure(BOTH, round_trip_ms * 0.5, jitter_ms * 0.5, loss_percent, duplicate_percent) + + +## One-way conditions of a direction, as in blank_conditions(). +func conditions(direction: int) -> Dictionary: + _mutex.lock() + var result := _conditions[direction].duplicate() + _mutex.unlock() + return result + + +## Whether both directions currently use the same conditions. +func symmetric() -> bool: + return conditions(UP) == conditions(DOWN) + + +## Copies of the counters as {"up": blank_stats(), "down": blank_stats()}. +func stats() -> Dictionary: + _mutex.lock() + var result := {"up": _stats[UP].duplicate(), "down": _stats[DOWN].duplicate()} + _mutex.unlock() + return result + + +func reset_stats() -> void: + _mutex.lock() + for direction in 2: + _stats[direction] = blank_stats() + _stats[direction]["queued_packets"] = _due[direction].size() + _mutex.unlock() + + +## Applies `--netsim`, `--netsim-rtt=MS`, `--netsim-jitter=MS` (± round trip), +## `--netsim-loss=PERCENT`, `--netsim-duplicate=PERCENT` and `--netsim-seed=N`. +## Returns whether any of them asked to route connections through the relay. +func configure_from_args(args: PackedStringArray) -> bool: + var enabled := false + var values := {"rtt": 0.0, "jitter": 0.0, "loss": 0.0, "duplicate": 0.0} + for argument in args: + if argument == "--netsim": + enabled = true + elif argument.begins_with("--netsim-seed="): + set_seed(int(argument.trim_prefix("--netsim-seed="))) + else: + for key: String in values: + var prefix := "--netsim-%s=" % key + if argument.begins_with(prefix) and argument.trim_prefix(prefix).is_valid_float(): + values[key] = float(argument.trim_prefix(prefix)) + enabled = true + set_round_trip(values["rtt"], values["jitter"], values["loss"], values["duplicate"]) + return enabled + + +# Receiver thread: blocks on one socket and schedules each datagram on arrival. +func _listen(direction: int) -> void: + var socket := _client if direction == UP else _upstream + var waker_port := _waker.get_local_port() + while true: + if socket.wait() != OK: + OS.delay_usec(1000) + var now := Time.get_ticks_usec() + while socket.get_available_packet_count() > 0: + var packet := socket.get_packet() + if socket.get_packet_error() != OK: + continue + if socket.get_packet_port() == waker_port and socket.get_packet_ip() in ["127.0.0.1", "::ffff:127.0.0.1"]: + continue + if direction == UP and socket.get_packet_port() != _client_port: + # Follow the client's socket, including after it reconnects. + _mutex.lock() + _client_port = socket.get_packet_port() + _client.set_dest_address(socket.get_packet_ip(), _client_port) + _mutex.unlock() + _schedule(direction, now, packet) + _mutex.lock() + var running := _running + _mutex.unlock() + if not running: + return + + +func _schedule(direction: int, now: int, packet: PackedByteArray) -> void: + _mutex.lock() + var settings := _conditions[direction] + var counters := _stats[direction] + counters["received_packets"] += 1 + counters["received_bytes"] += packet.size() + var copies := 1 + if _rng.randf() * 100.0 < settings["loss_percent"]: + copies = 0 + counters["dropped_packets"] += 1 + elif _rng.randf() * 100.0 < settings["duplicate_percent"]: + copies = 2 + counters["duplicated_packets"] += 1 + var dues: Array = _due[direction] + for _copy in copies: + if dues.size() >= MAX_QUEUE: + counters["dropped_packets"] += 1 + continue + var jitter: float = settings["jitter_ms"] + var delay := maxf(0.0, settings["latency_ms"] + _rng.randf_range(-jitter, jitter)) + var due := now + int(delay * 1000.0) + var index := dues.bsearch(due, false) + dues.insert(index, due) + _packets[direction].insert(index, packet) + counters["queued_packets"] = dues.size() + _mutex.unlock() + + +# Delivery thread: sends datagrams when due; a final pass flushes the queues. +func _deliver_loop() -> void: + # Longest recent sleep, decaying so a single stall does not cause spinning forever. + var sleep_usec := 2000.0 + while true: + _mutex.lock() + var pumping := _pumping + _mutex.unlock() + var now := Time.get_ticks_usec() if pumping else FLUSH + var next := FLUSH + for direction in 2: + next = mini(next, _deliver(direction, now)) + if not pumping: + return + var before := Time.get_ticks_usec() + if next - before > sleep_usec + SPIN_USEC: + OS.delay_usec(1000) + sleep_usec = maxf(sleep_usec * 0.999, Time.get_ticks_usec() - before) + + +# Sends what is due in one direction; returns the next due time, or FLUSH. +func _deliver(direction: int, now: int) -> int: + _mutex.lock() + var dues: Array = _due[direction] + var count := 0 + while count < dues.size() and dues[count] <= now: + count += 1 + var ready: Array = _packets[direction].slice(0, count) + if count > 0: + _due[direction] = dues.slice(count) + _packets[direction] = _packets[direction].slice(count) + var next: int = _due[direction][0] if not _due[direction].is_empty() else FLUSH + # Server replies before the client's first datagram have nowhere to go. + var socket := _upstream if direction == UP else (_client if _client_port != 0 else null) + var sent := 0 + var bytes := 0 + if socket != null: + for packet: PackedByteArray in ready: + if socket.put_packet(packet) == OK: + sent += 1 + bytes += packet.size() + _stats[direction]["forwarded_packets"] += sent + _stats[direction]["forwarded_bytes"] += bytes + _stats[direction]["queued_packets"] = _due[direction].size() + _mutex.unlock() + return next diff --git a/scripts/net_simulator.gd.uid b/scripts/net_simulator.gd.uid new file mode 100644 index 0000000..1fb6919 --- /dev/null +++ b/scripts/net_simulator.gd.uid @@ -0,0 +1 @@ +uid://n6ct2gdds80f diff --git a/scripts/net_stats.gd b/scripts/net_stats.gd new file mode 100644 index 0000000..c41b705 --- /dev/null +++ b/scripts/net_stats.gd @@ -0,0 +1,201 @@ +class_name NetStats +extends RefCounted +## Client-side netcode measurements fed by FlightSession, shown by the F8 +## overlay and read by tests/netcode_benchmark.gd. Measuring never changes +## gameplay: the server stays authoritative. +## +## Metrics: +## - rtt_ms: ENet's smoothed round-trip time to the server peer +## (ENetPacketPeer.PEER_ROUND_TRIP_TIME), sampled once per second. +## - up/down_bytes_per_second: UDP payload bytes the client's ENet host sent and +## received over the last whole second (ENet headers included, IP/UDP not). +## - snapshot jitter: for each world snapshot, |time since the previous one - +## 50 ms|, as handled by the client (so it includes frame quantization). The +## mean and maximum cover the last JITTER_WINDOW intervals. +## - error_m: distance between the predicted local ship and the authoritative +## position in a snapshot, before reconciliation. +## - correction_m: how far reconciliation then moved the local ship. +## - commands_sent: flight commands the client sent. The server counts the +## commands it accepted per pilot in commands_received. + +const SNAPSHOT_INTERVAL_MS := 50.0 +const JITTER_WINDOW := 100 +const SAMPLE_USEC := 1_000_000 + +var rtt_ms: float = 0.0 +var up_bytes_per_second: float = 0.0 +var down_bytes_per_second: float = 0.0 +var up_packets_per_second: float = 0.0 +var down_packets_per_second: float = 0.0 +var total_up_bytes: int = 0 +var total_down_bytes: int = 0 +var snapshots_received: int = 0 +## Recent snapshot inter-arrival times in milliseconds, oldest first. +var snapshot_intervals: PackedFloat32Array = [] +var latest_error_m: float = 0.0 +var max_error_m: float = 0.0 +var latest_correction_m: float = 0.0 +var max_correction_m: float = 0.0 +var corrections: int = 0 +## Last authoritative state of the local ship, for the server ghost. +var has_server_state: bool = false +var server_position: Vector3 = Vector3.ZERO +var server_rotation: Vector3 = Vector3.ZERO +var commands_sent: int = 0 +## Server only: accepted flight commands per peer. +var commands_received: Dictionary[int, int] = {} +## When true, every error, correction and jitter sample is kept for percentiles. +var keep_samples: bool = false +var error_samples: PackedFloat32Array = [] +var correction_samples: PackedFloat32Array = [] +var jitter_samples: PackedFloat32Array = [] + +var _last_arrival_usec: int = -1 +var _sample_started_usec: int = -1 +var _window_up_bytes: int = 0 +var _window_down_bytes: int = 0 +var _window_up_packets: int = 0 +var _window_down_packets: int = 0 + + +func reset() -> void: + rtt_ms = 0.0 + up_bytes_per_second = 0.0 + down_bytes_per_second = 0.0 + up_packets_per_second = 0.0 + down_packets_per_second = 0.0 + total_up_bytes = 0 + total_down_bytes = 0 + snapshots_received = 0 + snapshot_intervals = PackedFloat32Array() + has_server_state = false + commands_sent = 0 + commands_received.clear() + _last_arrival_usec = -1 + _sample_started_usec = -1 + _window_up_bytes = 0 + _window_down_bytes = 0 + _window_up_packets = 0 + _window_down_packets = 0 + reset_extremes() + + +## Clears correction extremes and kept samples, keeping transport rates. +func reset_extremes() -> void: + latest_error_m = 0.0 + max_error_m = 0.0 + latest_correction_m = 0.0 + max_correction_m = 0.0 + corrections = 0 + error_samples = PackedFloat32Array() + correction_samples = PackedFloat32Array() + jitter_samples = PackedFloat32Array() + + +func record_snapshot_arrival(now_usec: int = Time.get_ticks_usec()) -> void: + snapshots_received += 1 + if _last_arrival_usec >= 0: + var interval := (now_usec - _last_arrival_usec) / 1000.0 + snapshot_intervals.append(interval) + if snapshot_intervals.size() > JITTER_WINDOW: + snapshot_intervals = snapshot_intervals.slice(snapshot_intervals.size() - JITTER_WINDOW) + if keep_samples: + jitter_samples.append(absf(interval - SNAPSHOT_INTERVAL_MS)) + _last_arrival_usec = now_usec + + +## Returns Vector2(mean, max) of |interval - 50 ms| over the window, in ms. +func snapshot_jitter() -> Vector2: + if snapshot_intervals.is_empty(): + return Vector2.ZERO + var total := 0.0 + var largest := 0.0 + for interval in snapshot_intervals: + var deviation := absf(interval - SNAPSHOT_INTERVAL_MS) + total += deviation + largest = maxf(largest, deviation) + return Vector2(total / snapshot_intervals.size(), largest) + + +## Records one reconciliation of the local ship against authoritative state. +func record_correction(error_m: float, correction_m: float) -> void: + latest_error_m = error_m + latest_correction_m = correction_m + max_error_m = maxf(max_error_m, error_m) + max_correction_m = maxf(max_correction_m, correction_m) + corrections += 1 + if keep_samples: + error_samples.append(error_m) + correction_samples.append(correction_m) + + +func record_server_state(position: Vector3, rotation: Vector3) -> void: + has_server_state = true + server_position = position + server_rotation = rotation + + +func record_command_received(id: int) -> void: + commands_received[id] = commands_received.get(id, 0) + 1 + + +## Reads RTT and host traffic from a client's ENet peer, at most once per +## second. Takes ENet's host counters (pop_statistic), so call it from one +## place per host. Returns whether the rates were refreshed. +func sample_transport(peer: MultiplayerPeer, now_usec: int = Time.get_ticks_usec()) -> bool: + var enet := peer as ENetMultiplayerPeer + if enet == null or enet.host == null: + return false + var host := enet.host + var sent := host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) + var received := host.pop_statistic(ENetConnection.HOST_TOTAL_RECEIVED_DATA) + var sent_packets := host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_PACKETS) + var received_packets := host.pop_statistic(ENetConnection.HOST_TOTAL_RECEIVED_PACKETS) + total_up_bytes += sent + total_down_bytes += received + _window_up_bytes += sent + _window_down_bytes += received + _window_up_packets += sent_packets + _window_down_packets += received_packets + if _sample_started_usec < 0: + _sample_started_usec = now_usec + _window_up_bytes = 0 + _window_down_bytes = 0 + _window_up_packets = 0 + _window_down_packets = 0 + return false + var elapsed := now_usec - _sample_started_usec + if elapsed < SAMPLE_USEC: + return false + var seconds := elapsed / 1_000_000.0 + up_bytes_per_second = _window_up_bytes / seconds + down_bytes_per_second = _window_down_bytes / seconds + up_packets_per_second = _window_up_packets / seconds + down_packets_per_second = _window_down_packets / seconds + _window_up_bytes = 0 + _window_down_bytes = 0 + _window_up_packets = 0 + _window_down_packets = 0 + _sample_started_usec = now_usec + var server := enet.get_peer(1) + if server != null: + rtt_ms = server.get_statistic(ENetPacketPeer.PEER_ROUND_TRIP_TIME) + return true + + +## Value at `fraction` (0..1) of the sorted samples, or 0 without samples. +static func percentile(values: PackedFloat32Array, fraction: float) -> float: + if values.is_empty(): + return 0.0 + var sorted := values.duplicate() + sorted.sort() + return sorted[clampi(int(ceil(fraction * sorted.size())) - 1, 0, sorted.size() - 1)] + + +static func mean(values: PackedFloat32Array) -> float: + if values.is_empty(): + return 0.0 + var total := 0.0 + for value in values: + total += value + return total / values.size() diff --git a/scripts/net_stats.gd.uid b/scripts/net_stats.gd.uid new file mode 100644 index 0000000..ba658e7 --- /dev/null +++ b/scripts/net_stats.gd.uid @@ -0,0 +1 @@ +uid://civ2lfpab8tby diff --git a/scripts/netcode_overlay.gd b/scripts/netcode_overlay.gd new file mode 100644 index 0000000..e2e7fbe --- /dev/null +++ b/scripts/netcode_overlay.gd @@ -0,0 +1,239 @@ +class_name NetcodeOverlay +extends Control +## F8 netcode overlay: live NetStats readings, network simulator sliders and a +## translucent ghost at the last authoritative position of the local ship. +## Client-side diagnostics only; nothing here is sent to the server. + +const SIZE := Vector2(340, 356) +const REFRESH := 0.25 +const DIRECTION_LABELS := ["Both ways (round trip)", "Upstream only", "Downstream only"] +# Slider limits per mode: [round trip, one way]. +const DELAY_MAX := [600.0, 300.0] +const JITTER_MAX := [200.0, 100.0] + +var hud: FlightHud +var show_ghost := true +var ghost: Node3D +var ghost_model := "" +var refresh_clock := 0.0 +var direction: OptionButton +var sliders: Dictionary[String, HSlider] = {} +var values: Dictionary[String, Label] = {} +var titles: Dictionary[String, Label] = {} +var ghost_toggle: CheckBox +var next_toggle: CheckBox +var note: Label + + +func _ready() -> void: + mouse_filter = Control.MOUSE_FILTER_IGNORE + size = SIZE + var rows := VBoxContainer.new() + rows.position = Vector2(12, 138) + rows.size = Vector2(SIZE.x - 24, SIZE.y - 146) + rows.add_theme_constant_override("separation", 2) + add_child(rows) + direction = OptionButton.new() + for entry: String in DIRECTION_LABELS: + direction.add_item(entry) + direction.focus_mode = Control.FOCUS_NONE + direction.add_theme_font_size_override("font_size", 14) + direction.item_selected.connect(func(_index: int): sync_sliders()) + rows.add_child(direction) + for key: String in ["latency_ms", "jitter_ms", "loss_percent", "duplicate_percent"]: + add_slider(rows, key) + var tools := HBoxContainer.new() + rows.add_child(tools) + ghost_toggle = add_check(tools, "Server ghost", show_ghost, func(value: bool): show_ghost = value) + var reset := Button.new() + reset.text = "Reset max" + reset.focus_mode = Control.FOCUS_NONE + reset.mouse_filter = Control.MOUSE_FILTER_PASS + reset.add_theme_font_size_override("font_size", 14) + reset.pressed.connect(func(): session().net_stats.reset_extremes(); queue_redraw()) + tools.add_child(reset) + next_toggle = add_check(rows, "Use simulator on next connection", false, func(value: bool): session().use_net_simulator = value) + note = Label.new() + note.add_theme_font_size_override("font_size", 13) + note.add_theme_color_override("font_color", FlightHud.AMBER) + note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + rows.add_child(note) + visible = false + + +func add_slider(parent: Node, key: String) -> void: + var row := HBoxContainer.new() + parent.add_child(row) + var title := Label.new() + title.custom_minimum_size.x = 112 + title.add_theme_font_size_override("font_size", 14) + title.add_theme_color_override("font_color", FlightHud.MUTED) + row.add_child(title) + var slider := HSlider.new() + slider.size_flags_horizontal = Control.SIZE_EXPAND_FILL + slider.size_flags_vertical = Control.SIZE_SHRINK_CENTER + # Mouse-only: flight keys keep working, and right-drag steering passes through. + slider.focus_mode = Control.FOCUS_NONE + slider.mouse_filter = Control.MOUSE_FILTER_PASS + slider.step = 5.0 if key.ends_with("_ms") else 0.5 + slider.max_value = 30.0 if key == "loss_percent" else 20.0 + slider.value_changed.connect(func(_value: float): apply_sliders()) + row.add_child(slider) + var value := Label.new() + value.custom_minimum_size.x = 64 + value.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT + value.add_theme_font_size_override("font_size", 14) + row.add_child(value) + sliders[key] = slider + values[key] = value + titles[key] = title + + +func add_check(parent: Node, title: String, pressed: bool, action: Callable) -> CheckBox: + var check := CheckBox.new() + check.text = title + check.button_pressed = pressed + check.focus_mode = Control.FOCUS_NONE + check.mouse_filter = Control.MOUSE_FILTER_PASS + check.size_flags_horizontal = Control.SIZE_EXPAND_FILL + check.add_theme_font_size_override("font_size", 14) + check.toggled.connect(action) + parent.add_child(check) + return check + + +func session() -> FlightSession: + return hud.sector.session + + +## Simulator direction the sliders edit, or NetSimulator.BOTH. +func edited_direction() -> int: + return [NetSimulator.BOTH, NetSimulator.UP, NetSimulator.DOWN][direction.selected] + + +func sync_sliders() -> void: + var round_trip := edited_direction() == NetSimulator.BOTH + var mode := 0 if round_trip else 1 + var current := session().net_simulator.conditions(NetSimulator.DOWN if edited_direction() == NetSimulator.DOWN else NetSimulator.UP) + sliders["latency_ms"].max_value = DELAY_MAX[mode] + sliders["jitter_ms"].max_value = JITTER_MAX[mode] + var factor := 2.0 if round_trip else 1.0 + sliders["latency_ms"].set_value_no_signal(current["latency_ms"] * factor) + sliders["jitter_ms"].set_value_no_signal(current["jitter_ms"] * factor) + sliders["loss_percent"].set_value_no_signal(current["loss_percent"]) + sliders["duplicate_percent"].set_value_no_signal(current["duplicate_percent"]) + titles["latency_ms"].text = "Added RTT" if round_trip else "One-way delay" + titles["jitter_ms"].text = "RTT jitter ±" if round_trip else "Jitter ±" + titles["loss_percent"].text = "Loss" + titles["duplicate_percent"].text = "Duplicates" + update_values() + + +func apply_sliders() -> void: + var simulator := session().net_simulator + var delay := sliders["latency_ms"].value + var jitter := sliders["jitter_ms"].value + var loss := sliders["loss_percent"].value + var duplicate := sliders["duplicate_percent"].value + if edited_direction() == NetSimulator.BOTH: + simulator.set_round_trip(delay, jitter, loss, duplicate) + else: + simulator.configure(edited_direction(), delay, jitter, loss, duplicate) + update_values() + + +func update_values() -> void: + values["latency_ms"].text = "%d ms" % sliders["latency_ms"].value + values["jitter_ms"].text = "%d ms" % sliders["jitter_ms"].value + values["loss_percent"].text = "%.1f %%" % sliders["loss_percent"].value + values["duplicate_percent"].text = "%.1f %%" % sliders["duplicate_percent"].value + + +func wanted() -> bool: + var sector := hud.sector + if sector.preflight or not is_instance_valid(sector.player) or (is_instance_valid(sector.main_menu) and sector.main_menu.visible): + return false + if hud.navigation.overview.visible: + return false + return (sector.show_netcode or hud.layout.editing) and hud.layout.shown("netcode") + + +func _process(delta: float) -> void: + var shown := wanted() + if shown != visible: + visible = shown + if shown: + sync_sliders() + queue_redraw() + if shown: + var rect := hud.layout.rect_for("netcode") + size = SIZE + position = rect.position + scale = Vector2.ONE * (rect.size.x / SIZE.x) + next_toggle.set_pressed_no_signal(session().use_net_simulator) + var running := session().net_simulator.is_running() + note.visible = not running + note.text = "Simulator not in the path. Enable it, then reconnect (%s)." % GameSettings.binding_text("multiplayer_menu") if session().active else "Simulator not in the path. Enable it, then connect." + refresh_clock += delta + if refresh_clock >= REFRESH: + refresh_clock = 0.0 + queue_redraw() + update_ghost(shown) + + +func _draw() -> void: + var font := hud.font + draw_style_box(hud.background, Rect2(Vector2.ZERO, SIZE)) + var stats := session().net_stats + var simulator := session().net_simulator + draw_string(StationUi.tracked(true, 1), Vector2(12, 20), "NETCODE / %s" % GameSettings.binding_text("netcode"), HORIZONTAL_ALIGNMENT_LEFT, -1, 14, FlightHud.AMBER) + var state := "SIMULATOR ON" if simulator.is_running() else "DIRECT" + draw_string(font, Vector2(12, 20), state, HORIZONTAL_ALIGNMENT_RIGHT, SIZE.x - 24, 14, FlightHud.GREEN if simulator.is_running() else FlightHud.MUTED) + var lines: Array[String] = [] + if not session().active or session().multiplayer.is_server(): + lines.append("Not connected to a server.") + else: + var jitter := stats.snapshot_jitter() + lines.append("RTT %d ms" % roundi(stats.rtt_ms)) + lines.append("Up %s/s Down %s/s" % [String.humanize_size(int(stats.up_bytes_per_second)), String.humanize_size(int(stats.down_bytes_per_second))]) + lines.append("Snapshot jitter %.1f ms mean / %.1f ms max" % [jitter.x, jitter.y]) + lines.append("Correction %.2f m last / %.2f m max" % [stats.latest_correction_m, stats.max_correction_m]) + lines.append("Prediction error %.2f m last / %.2f m max" % [stats.latest_error_m, stats.max_error_m]) + if simulator.is_running(): + var relay := simulator.stats() + lines.append("Relay lost %d up / %d down, dup %d / %d" % [relay["up"]["dropped_packets"], relay["down"]["dropped_packets"], relay["up"]["duplicated_packets"], relay["down"]["duplicated_packets"]]) + for index in lines.size(): + draw_string(font, Vector2(12, 44 + index * 18), lines[index], HORIZONTAL_ALIGNMENT_LEFT, SIZE.x - 24, 14, FlightHud.INK if index == 0 else FlightHud.MUTED) + + +func update_ghost(shown: bool) -> void: + var sector := hud.sector + var stats := session().net_stats + var wanted_ghost: bool = shown and show_ghost and session().active and not session().multiplayer.is_server() and stats.has_server_state and sector.player.alive and not sector.player.get_meta("docked", false) + if not wanted_ghost: + if is_instance_valid(ghost): + ghost.hide() + return + if not is_instance_valid(ghost) or ghost_model != sector.player.ship_model: + if is_instance_valid(ghost): + ghost.queue_free() + ghost_model = sector.player.ship_model + ghost = Node3D.new() + ghost.name = "ServerGhost" + var model := ShipCatalog.model_scene(ghost_model) + var surface := StandardMaterial3D.new() + surface.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + surface.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA + surface.albedo_color = Color(FlightHud.CYAN, 0.3) + surface.cull_mode = BaseMaterial3D.CULL_DISABLED + SectorVisuals.apply_surface(model, surface) + ghost.add_child(model) + sector.add_child(ghost) + ghost.show() + ghost.position = stats.server_position + ghost.rotation = stats.server_rotation + + +func _exit_tree() -> void: + if is_instance_valid(ghost): + ghost.queue_free() diff --git a/scripts/netcode_overlay.gd.uid b/scripts/netcode_overlay.gd.uid new file mode 100644 index 0000000..b30eacd --- /dev/null +++ b/scripts/netcode_overlay.gd.uid @@ -0,0 +1 @@ +uid://di5bjsa53lklf diff --git a/scripts/sector.gd b/scripts/sector.gd index 3766c5c..e3a1a19 100644 --- a/scripts/sector.gd +++ b/scripts/sector.gd @@ -42,6 +42,8 @@ var toast: String = "Welcome to Outpost 01. Hold right mouse to steer." var toast_time: float = 8.0 var objective_stage: int = 0 var show_performance: bool = false +## F8 netcode overlay; a debugging aid that is not saved between launches. +var show_netcode: bool = false var low_quality: bool = false var weapon_status: String = "NO TARGET" var session: FlightSession @@ -216,6 +218,8 @@ func _unhandled_input(event: InputEvent) -> void: settings.show_performance = not show_performance apply_graphics(false) settings.save() + if event.is_action_pressed("netcode"): + show_netcode = not show_netcode if event.is_action_pressed("quality"): settings.low_quality = not low_quality apply_graphics(false) diff --git a/scripts/settings_menu.gd b/scripts/settings_menu.gd index 5945e2a..4caa91f 100644 --- a/scripts/settings_menu.gd +++ b/scripts/settings_menu.gd @@ -23,6 +23,7 @@ var filtering_status: Label var bloom: CheckButton var ssao: CheckButton var performance: CheckButton +var net_simulator: CheckButton var resolution: OptionButton var resolutions: Array[Vector2i] = [] var binding_buttons: Dictionary[String, Button] = {} @@ -307,6 +308,9 @@ func build_graphics(rows: VBoxContainer) -> void: sector.settings.show_performance = value sector.apply_graphics(false) sector.settings.save()) + net_simulator = checkbox(rows, "Route connections through the network simulator (debug)", func(value: bool): + sector.session.use_net_simulator = value) + label(rows, "Applies on the next connection and is not saved. F8 shows the netcode overlay with the simulator controls.", 14) rows = section(page_rows, "IMAGE QUALITY") rows.add_theme_constant_override("separation", 4) graphics_choice(rows, "render_scale", "3D render scale", ["Off / Native (100%)", "85%", "75%", "50%"], @@ -447,6 +451,7 @@ func sync_controls() -> void: bloom.set_pressed_no_signal(sector.settings.bloom) ssao.set_pressed_no_signal(sector.settings.ssao) performance.set_pressed_no_signal(sector.show_performance) + net_simulator.set_pressed_no_signal(sector.session.use_net_simulator) sync_resolution() binding_help.text = "" binding_help.hide() diff --git a/tests/net_simulator_test.gd b/tests/net_simulator_test.gd new file mode 100644 index 0000000..44815e2 --- /dev/null +++ b/tests/net_simulator_test.gd @@ -0,0 +1,127 @@ +extends "res://tests/network_test.gd" +## NetSimulator relay with raw UDP sockets: delay, jitter, loss, duplication, +## live reconfiguration and flushing on stop, in both directions. + +var server := PacketPeerUDP.new() +var client := PacketPeerUDP.new() +var relay := NetSimulator.new() +var relay_ip := "" +var relay_port := 0 + + +func run() -> void: + check(server.bind(0, "127.0.0.1") == OK, "Server socket binds") + check(relay.start("127.0.0.1", server.get_local_port()) == OK, "Relay starts") + check(relay.is_running() and relay.listen_port > 0, "Relay reports its listening port") + check(relay.start("127.0.0.1", server.get_local_port()) == ERR_ALREADY_IN_USE, "A running relay cannot start twice") + check(client.bind(0, "127.0.0.1") == OK, "Client socket binds") + client.set_dest_address("127.0.0.1", relay.listen_port) + relay.set_seed(1234) + # The server learns the relay's upstream address from the first datagram. + client.put_packet(PackedByteArray([0])) + check(not receive(server, 500).is_empty(), "A datagram reaches the server unchanged in time") + relay_ip = server.get_packet_ip() + relay_port = server.get_packet_port() + server.set_dest_address(relay_ip, relay_port) + server.put_packet(PackedByteArray([1])) + check(receive(client, 500) == PackedByteArray([1]), "Replies return to the client") + + relay.configure(NetSimulator.UP, 60.0) + relay.configure(NetSimulator.DOWN, 25.0) + var up := delays(client, server, 8) + var down := delays(server, client, 8) + print("Relay delays: up %s ms, down %s ms" % [up, down]) + check(within(up, 59.0, 75.0), "Upstream latency is applied within tolerance") + check(within(down, 24.0, 40.0), "Downstream latency is applied independently") + + # Live changes apply to datagrams that arrive afterwards. + relay.configure(NetSimulator.UP, 0.0) + var live := delays(client, server, 5) + check(within(live, 0.0, 12.0), "Lowering latency while running takes effect immediately") + relay.set_round_trip(100.0, 40.0) + check(relay.symmetric() and is_equal_approx(relay.conditions(NetSimulator.DOWN)["latency_ms"], 50.0), "Round-trip settings split evenly per direction") + var jittered := delays(client, server, 30) + print("Jittered delays: %s ms" % jittered) + check(within(jittered, 29.0, 80.0) and NetStats.percentile(jittered, 0.9) - jittered[0] > 15.0, "Jitter spreads delays within its bound") + + relay.configure(NetSimulator.BOTH, 0.0) + relay.reset_stats() + relay.configure(NetSimulator.UP, 0.0, 0.0, 20.0) + var arrived := burst(client, server, 2000) + var stats: Dictionary = relay.stats() + print("Upstream loss: %d of 2000 arrived, stats %s" % [arrived, stats["up"]]) + check(arrived >= 1540 and arrived <= 1660, "Upstream loss rate stays near 20%") + check(stats["up"]["dropped_packets"] == 2000 - arrived and stats["up"]["received_packets"] == 2000, "Loss statistics account for every datagram") + + relay.configure(NetSimulator.UP, 0.0) + relay.configure(NetSimulator.DOWN, 0.0, 0.0, 0.0, 10.0) + relay.reset_stats() + arrived = burst(server, client, 2000) + stats = relay.stats() + print("Downstream duplication: %d datagrams from 2000, stats %s" % [arrived, stats["down"]]) + check(arrived >= 2140 and arrived <= 2260, "Downstream duplication rate stays near 10%") + check(stats["down"]["forwarded_packets"] == arrived and stats["down"]["duplicated_packets"] == arrived - 2000, "Duplication statistics match deliveries") + check(stats["up"]["received_packets"] == 0, "Each direction keeps its own statistics") + + # Stopping delivers queued datagrams at once, so disconnect notices are not lost. + relay.configure(NetSimulator.UP, 2000.0) + client.put_packet(PackedByteArray([7])) + OS.delay_msec(20) + var stopped_at := Time.get_ticks_msec() + relay.stop() + check(receive(server, 300) == PackedByteArray([7]) and Time.get_ticks_msec() - stopped_at < 300, "Stopping flushes queued datagrams") + check(not relay.is_running() and relay.listen_port == 0, "The relay stops cleanly") + var scripted := NetSimulator.new() + check(scripted.configure_from_args(PackedStringArray(["--netsim-rtt=150", "--netsim-jitter=30", "--netsim-loss=5"])), "Simulator arguments enable the relay") + check(scripted.conditions(NetSimulator.UP) == {"latency_ms": 75.0, "jitter_ms": 15.0, "loss_percent": 5.0, "duplicate_percent": 0.0}, "Simulator arguments set round-trip conditions") + check(not NetSimulator.new().configure_from_args(PackedStringArray(["--offline"])), "The relay stays off without simulator arguments") + server.close() + client.close() + print("Network simulator checks: %d passed, %d failed" % [checks - failures, failures]) + quit(0 if failures == 0 else 1) + + +## Waits up to `timeout_ms` for one datagram. +func receive(socket: PacketPeerUDP, timeout_ms: int) -> PackedByteArray: + var deadline := Time.get_ticks_msec() + timeout_ms + while Time.get_ticks_msec() < deadline: + if socket.get_available_packet_count() > 0: + return socket.get_packet() + pass # Spin: OS sleeps can last a 15.6 ms timer tick on Windows. + return PackedByteArray() + + +## Sends `count` datagrams one at a time; returns the sorted delays in ms. +func delays(sender: PacketPeerUDP, receiver: PacketPeerUDP, count: int) -> PackedFloat32Array: + var result := PackedFloat32Array() + for index in count: + var sent := Time.get_ticks_usec() + sender.put_packet(PackedByteArray([index])) + result.append((Time.get_ticks_usec() - sent) / 1000.0 if not receive(receiver, 1000).is_empty() else INF) + result.sort() + return result + + +## No delay below `low`, and 90% of them at most `high`; the slack absorbs +## occasional scheduler stalls on busy CI machines. +func within(samples: PackedFloat32Array, low: float, high: float) -> bool: + return samples[0] >= low and NetStats.percentile(samples, 0.9) <= high + + +## Sends `count` datagrams in small batches and returns how many arrived. +func burst(sender: PacketPeerUDP, receiver: PacketPeerUDP, count: int) -> int: + var arrived := 0 + for index in count: + sender.put_packet(PackedByteArray([index & 255, index >> 8])) + if index % 20 == 19: + OS.delay_usec(2000) + while receiver.get_available_packet_count() > 0: + receiver.get_packet() + arrived += 1 + var deadline := Time.get_ticks_msec() + 300 + while Time.get_ticks_msec() < deadline: + while receiver.get_available_packet_count() > 0: + receiver.get_packet() + arrived += 1 + OS.delay_usec(500) + return arrived diff --git a/tests/net_simulator_test.gd.uid b/tests/net_simulator_test.gd.uid new file mode 100644 index 0000000..7656901 --- /dev/null +++ b/tests/net_simulator_test.gd.uid @@ -0,0 +1 @@ +uid://sgufcxs4uru3 diff --git a/tests/netcode_benchmark.gd b/tests/netcode_benchmark.gd new file mode 100644 index 0000000..62069c9 --- /dev/null +++ b/tests/netcode_benchmark.gd @@ -0,0 +1,247 @@ +extends "res://tests/network_test.gd" +## Netcode measurement tool (not part of the check suites). Runs a dedicated +## server, one measured client routed through NetSimulator and a few extra +## clients connected directly, all flying the same scripted input, then prints a +## markdown table and a NETCODE_BENCHMARK= JSON line per run. +## +## Usage (from the project root): +## godot --headless --path . --script res://tests/netcode_benchmark.gd -- [options] +## Options: +## --scenario=baseline 0, 100 and 200 ms added RTT, each at 0% and 5% loss (default) +## --scenario=degraded 150 ± 30 ms added RTT with 5% loss +## --condition=RTT,JITTER,LOSS[,DUPLICATE] add a custom condition (repeatable; +## replaces the scenario) +## --seconds=20 measured seconds per condition (after a 15 s warm-up) +## --extra-clients=3 directly connected pilots flying alongside +## --seed=1 relay random seed +## +## Conditions: "RTT" is round trip added by the relay, split evenly per +## direction ("100 ms" adds 50 ms each way). "JITTER" is ± round-trip jitter, +## also split evenly. LOSS and DUPLICATE apply independently in both directions. +## +## Metrics, all for the measured client over the measured window: +## - speed_mps: mean speed of the predicted local ship, sampled every frame. +## - fps: frames per second of the benchmark process, which hosts the server +## and every client; ENet is serviced once per frame. +## - rtt_ms: mean of ENet's smoothed round trip to the server, sampled every 0.5 s. +## ENet updates it by 1/8 per reliable acknowledgement, so it lags changes. +## - up_bps / down_bps: UDP payload bytes per second sent and received by the +## client's ENet host (ENet headers included; IP/UDP headers excluded). +## - server_bps: bytes per second the server sent toward this client, counted +## by the relay before simulated loss. server_avg_bps is the server host's +## total sent bytes per second divided by the number of connected clients. +## - jitter_mean_ms / jitter_p95_ms / jitter_max_ms: |snapshot inter-arrival +## time - 50 ms| as handled by the client, so frame timing is included. +## - error_*_m: distance from the predicted local ship to the authoritative +## position in each applied snapshot, before reconciliation (mean/p95/max). +## - correction_*_m: distance reconciliation moved the local ship for each +## snapshot. The current reconciliation applies it within one frame, so this +## is also the visible jump beyond expected motion. +## - gap_*_m: distance from the client's ship to the server's current position +## of the same ship, sampled every frame (possible because both run in this +## process). Accurate prediction leads the server by the upstream delay times +## speed; dragging the ship toward old snapshots shows up as error staying +## small while this gap reflects the delay instead. +## - commands_sent / commands_applied: flight commands the client sent and the +## server accepted; commands_lost is their difference, as a count and percent. +## ENet discards duplicated and out-of-order sequenced commands itself. + +const BASE_PORT := 24911 +# ENet smooths its RTT by 1/8 per reliable acknowledgement, about two per +# second here, so each condition settles before it is measured. +const WARM_UP := 15.0 +const SCENARIOS := { + "baseline": [[0.0, 0.0, 0.0, 0.0], [100.0, 0.0, 0.0, 0.0], [200.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 5.0, 0.0], [100.0, 0.0, 5.0, 0.0], [200.0, 0.0, 5.0, 0.0]], + "degraded": [[150.0, 30.0, 5.0, 0.0]], +} +# Scripted input cycle: [seconds, actions, yaw radians per second]. The second +# half mirrors the first so the pilot stays near the protected station. +const PATTERN := [ + [0.8, ["forward"], 0.0], [0.6, ["forward", "boost"], 0.0], [0.5, ["strafe_right"], 0.0], + [0.6, ["forward", "strafe_left"], 1.6], [0.5, [], 0.0], + [0.8, ["backward"], 0.0], [0.6, ["backward", "boost"], 0.0], [0.5, ["strafe_left"], 0.0], + [0.6, ["backward", "strafe_right"], -1.6], [0.5, [], 0.0], +] +const ACTIONS := ["forward", "backward", "strafe_left", "strafe_right", "boost"] + +var options := {"scenario": "baseline", "seconds": 20.0, "extra-clients": 3, "seed": 1} +var custom: Array = [] + + +func run() -> void: + for argument in OS.get_cmdline_user_args(): + if argument.begins_with("--condition="): + var parts := argument.trim_prefix("--condition=").split(",") + var condition := [0.0, 0.0, 0.0, 0.0] + for index in mini(parts.size(), 4): + condition[index] = float(parts[index]) + custom.append(condition) + elif argument.begins_with("--") and "=" in argument: + var key := argument.trim_prefix("--").get_slice("=", 0) + if options.has(key): + var value := argument.get_slice("=", 1) + if key == "scenario": + options[key] = value + else: + options[key] = float(value) + var conditions: Array = custom if not custom.is_empty() else SCENARIOS.get(options["scenario"], []) + if conditions.is_empty(): + push_error("Unknown scenario %s" % options["scenario"]) + quit(1) + return + var server := make_sector("BenchServer", true, BASE_PORT) + server.multiplayer.auth_timeout = 15.0 + server.set_physics_process(true) + var client := make_sector("BenchClient") + var everyone: Array[Sector] = [client] + for index in range(int(options["extra-clients"])): + everyone.append(make_sector("BenchExtra%d" % index)) + for index in everyone.size(): + everyone[index].session.credential_id = "pilot%d" % index + everyone[index].session.credential_token = test_token(index) + everyone[index].multiplayer.auth_timeout = 15.0 + everyone[index].set_physics_process(true) + await settle() + client.session.use_net_simulator = true + client.session.net_simulator.set_seed(int(options["seed"])) + for sector in everyone: + check(sector.session.join("127.0.0.1", test_port(BASE_PORT)) == OK, "%s starts joining" % sector.name) + var deadline := Time.get_ticks_msec() + 20000 + while everyone.any(func(peer: Sector): return not peer.session.received_snapshot) and Time.get_ticks_msec() < deadline: + await process_frame + check(everyone.all(func(peer: Sector): return peer.session.received_snapshot), "Every pilot joins and receives snapshots") + if failures > 0: + finish() + return + var results: Array[Dictionary] = [] + for condition: Array in conditions: + results.append(await measure(server, client, everyone.size(), condition)) + release_inputs() + print_table(results) + print("Process frame rate: %s fps (server and all clients share one process)." % ", ".join(results.map(func(row: Dictionary): return str(row["fps"])))) + print("NETCODE_BENCHMARK=", JSON.stringify({"options": options, "results": results})) + finish() + + +func measure(server: Sector, client: Sector, clients: int, condition: Array) -> Dictionary: + var relay := client.session.net_simulator + relay.set_round_trip(condition[0], condition[1], condition[2], condition[3]) + # Restart every pilot at its spawn point, outside the measured window. + for ship: Pilot in server.session.ships.values(): + ship.position = server.session.combat.records[server.session.ships.find_key(ship)]["spawn"] + ship.velocity = Vector3.ZERO + await fly(client, WARM_UP) + var net := client.session.net_stats + net.reset_extremes() + net.keep_samples = true + relay.reset_stats() + var id := client.multiplayer.get_unique_id() + var sent_before := net.commands_sent + var applied_before: int = server.session.net_stats.commands_received.get(id, 0) + var up_before := net.total_up_bytes + var down_before := net.total_down_bytes + var host: ENetConnection = (server.multiplayer.multiplayer_peer as ENetMultiplayerPeer).host + host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) + var started := Time.get_ticks_usec() + var frames := Engine.get_process_frames() + var rtts := await fly(client, float(options["seconds"]), server) + var seconds := (Time.get_ticks_usec() - started) / 1_000_000.0 + frames = Engine.get_process_frames() - frames + net.keep_samples = false + var server_bytes := host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) + var relay_stats: Dictionary = relay.stats() + var sent := net.commands_sent - sent_before + var applied: int = server.session.net_stats.commands_received.get(id, 0) - applied_before + return { + "rtt_added_ms": condition[0], "jitter_ms": condition[1], "loss_percent": condition[2], "duplicate_percent": condition[3], + "seconds": snappedf(seconds, 0.01), "rtt_ms": snappedf(NetStats.mean(rtts), 0.1), + "fps": roundi(frames / seconds), "speed_mps": snappedf(NetStats.mean(speeds), 0.1), + "up_bps": roundi((net.total_up_bytes - up_before) / seconds), + "down_bps": roundi((net.total_down_bytes - down_before) / seconds), + "server_bps": roundi(relay_stats["down"]["received_bytes"] / seconds), + "server_avg_bps": roundi(server_bytes / seconds / clients), + "snapshots": net.jitter_samples.size(), + "jitter_mean_ms": snappedf(NetStats.mean(net.jitter_samples), 0.1), + "jitter_p95_ms": snappedf(NetStats.percentile(net.jitter_samples, 0.95), 0.1), + "jitter_max_ms": snappedf(NetStats.percentile(net.jitter_samples, 1.0), 0.1), + "error_mean_m": snappedf(NetStats.mean(net.error_samples), 0.01), + "error_p95_m": snappedf(NetStats.percentile(net.error_samples, 0.95), 0.01), + "error_max_m": snappedf(NetStats.percentile(net.error_samples, 1.0), 0.01), + "correction_mean_m": snappedf(NetStats.mean(net.correction_samples), 0.01), + "correction_p95_m": snappedf(NetStats.percentile(net.correction_samples, 0.95), 0.01), + "correction_max_m": snappedf(NetStats.percentile(net.correction_samples, 1.0), 0.01), + "gap_mean_m": snappedf(NetStats.mean(gaps), 0.01), + "gap_p95_m": snappedf(NetStats.percentile(gaps, 0.95), 0.01), + "commands_sent": sent, "commands_applied": applied, "commands_lost": sent - applied, + "commands_lost_percent": snappedf(100.0 * (sent - applied) / maxi(sent, 1), 0.1), + "relay_dropped": relay_stats["up"]["dropped_packets"] + relay_stats["down"]["dropped_packets"], + } + + +var speeds := PackedFloat32Array() +var gaps := PackedFloat32Array() + + +## Flies the input pattern for `seconds`; returns RTT samples taken every 0.5 s. +func fly(client: Sector, seconds: float, server: Sector = null) -> PackedFloat32Array: + var rtts := PackedFloat32Array() + speeds = PackedFloat32Array() + gaps = PackedFloat32Array() + var id := client.multiplayer.get_unique_id() + var started := Time.get_ticks_msec() + var next_rtt := 500 + var cycle := 0.0 + for segment: Array in PATTERN: + cycle += segment[0] + var last := started + while Time.get_ticks_msec() - started < seconds * 1000.0: + var now := Time.get_ticks_msec() + var phase := fmod((now - started) / 1000.0, cycle) + var segment: Array = PATTERN[-1] + for candidate: Array in PATTERN: + if phase < candidate[0]: + segment = candidate + break + phase -= candidate[0] + for action: String in ACTIONS: + if action in segment[1]: + Input.action_press(action) + else: + Input.action_release(action) + client.player.pending_look.x += segment[2] * (now - last) / 1000.0 + last = now + if server != null: + # Keep combat from interrupting the measurement; positions stay authoritative. + for ship: Pilot in server.session.ships.values(): + ship.hull = ship.max_hull + ship.shield = ship.max_shield + speeds.append(client.player.velocity.length()) + if server != null and server.session.ships.has(id): + gaps.append(client.player.position.distance_to(server.session.ships[id].position)) + if now - started >= next_rtt: + next_rtt += 500 + rtts.append(client.session.net_stats.rtt_ms) + await process_frame + return rtts + + +func release_inputs() -> void: + for action: String in ACTIONS: + Input.action_release(action) + + +func print_table(results: Array[Dictionary]) -> void: + print("\nAdded RTT is split evenly per direction (100 ms = +50 ms each way); loss and duplication apply both ways.") + print("| Added RTT | Loss | RTT | Speed | 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 |") + print("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") + for row: Dictionary in results: + var jitter := "" if row["jitter_ms"] == 0.0 else " ± %d" % row["jitter_ms"] + print("| %d%s ms | %s%% | %.0f ms | %.1f m/s | %.1f KB/s | %.1f KB/s | %.1f KB/s | %.1f / %.1f / %.1f ms | %.2f / %.2f / %.2f m | %.2f / %.2f / %.2f m | %.2f / %.2f m | %d / %d / %d (%.1f%%) |" % [ + row["rtt_added_ms"], jitter, str(row["loss_percent"]), row["rtt_ms"], row["speed_mps"], + row["up_bps"] / 1000.0, row["down_bps"] / 1000.0, row["server_bps"] / 1000.0, + row["jitter_mean_ms"], row["jitter_p95_ms"], row["jitter_max_ms"], + row["error_mean_m"], row["error_p95_m"], row["error_max_m"], + row["correction_mean_m"], row["correction_p95_m"], row["correction_max_m"], + row["gap_mean_m"], row["gap_p95_m"], + row["commands_sent"], row["commands_applied"], row["commands_lost"], row["commands_lost_percent"]]) diff --git a/tests/netcode_benchmark.gd.uid b/tests/netcode_benchmark.gd.uid new file mode 100644 index 0000000..504252b --- /dev/null +++ b/tests/netcode_benchmark.gd.uid @@ -0,0 +1 @@ +uid://ccjnt2b1j8bv7 diff --git a/tests/netsim_network_test.gd b/tests/netsim_network_test.gd new file mode 100644 index 0000000..e43c664 --- /dev/null +++ b/tests/netsim_network_test.gd @@ -0,0 +1,84 @@ +extends "res://tests/network_test.gd" +## An authenticated client joins a dedicated server through the network +## simulator at moderate latency and loss, flies, and disconnects cleanly. + + +func run() -> void: + var server := make_sector("SimServer", true, 24901) + var client := make_sector("SimClient") + client.session.credential_id = "pilot0" + client.session.credential_token = test_token(0) + server.set_physics_process(true) + client.set_physics_process(true) + await settle() + client.session.use_net_simulator = true + client.session.net_simulator.set_seed(7) + client.session.net_simulator.set_round_trip(80.0, 10.0, 5.0, 5.0) + check(client.session.join("127.0.0.1", test_port(24901)) == OK, "Client joins through the simulator") + check(client.session.net_simulator.is_running(), "Joining starts the relay") + check(client.session.attempted_address == "127.0.0.1" and client.session.attempted_port == test_port(24901), "The session keeps the real server address") + var deadline := Time.get_ticks_msec() + 10000 + while not client.session.received_snapshot and Time.get_ticks_msec() < deadline: + await process_frame + check(client.session.active and client.session.received_snapshot, "Authentication and snapshots succeed through the relay") + var id := client.multiplayer.get_unique_id() + check(server.session.ships.has(id), "The server spawns the relayed pilot") + Input.action_press("forward") + await settle(3.0) + Input.action_release("forward") + var stats: Dictionary = client.session.net_simulator.stats() + var net := client.session.net_stats + print("Relay stats: ", stats) + print("Client stats: rtt %.1f ms, up %.0f B/s, down %.0f B/s, snapshots %d, jitter %s, max error %.2f m, commands %d sent / %d accepted" % [ + net.rtt_ms, net.up_bytes_per_second, net.down_bytes_per_second, net.snapshots_received, + net.snapshot_jitter(), net.max_error_m, net.commands_sent, server.session.net_stats.commands_received.get(id, 0)]) + check(stats["up"]["forwarded_packets"] > 30 and stats["down"]["forwarded_packets"] > 30, "Traffic flows both ways through the relay") + check(stats["up"]["dropped_packets"] + stats["down"]["dropped_packets"] > 0, "The relay drops datagrams") + check(stats["up"]["duplicated_packets"] + stats["down"]["duplicated_packets"] > 0, "The relay duplicates datagrams") + check(net.snapshots_received > 30, "Snapshots keep arriving despite loss") + check(net.rtt_ms >= 60.0 and net.rtt_ms < 400.0, "ENet measures the added round trip") + check(net.up_bytes_per_second > 0.0 and net.down_bytes_per_second > net.up_bytes_per_second, "Client traffic rates are sampled") + check(net.corrections > 0 and net.has_server_state, "Reconciliation against server state is measured") + check(server.session.ships[id].position.z < Sector.SPAWN_POSITION.z, "Relayed flight commands move the pilot on the server") + var accepted: int = server.session.net_stats.commands_received.get(id, 0) + check(accepted > 0 and accepted <= net.commands_sent, "The server counts accepted flight commands") + # The F8 overlay edits the running relay and shows the server ghost. + var toggle := InputEventAction.new() + toggle.action = "netcode" + toggle.pressed = true + client._unhandled_input(toggle) + check(client.show_netcode, "F8 toggles the netcode overlay") + await process_frame + await process_frame + var overlay := client.hud.netcode + check(overlay.visible and overlay.size == NetcodeOverlay.SIZE, "The overlay opens while connected") + check(is_equal_approx(overlay.sliders["latency_ms"].value, 80.0) and is_equal_approx(overlay.sliders["loss_percent"].value, 5.0), "Sliders show the relay's round-trip conditions") + overlay.sliders["latency_ms"].value = 200.0 + check(is_equal_approx(client.session.net_simulator.conditions(NetSimulator.UP)["latency_ms"], 100.0) and client.session.net_simulator.symmetric(), "Round-trip sliders change both directions live") + overlay.direction.select(2) + overlay.sync_sliders() + overlay.sliders["loss_percent"].value = 10.0 + check(client.session.net_simulator.conditions(NetSimulator.DOWN)["loss_percent"] == 10.0 and client.session.net_simulator.conditions(NetSimulator.UP)["loss_percent"] == 5.0, "Per-direction sliders change one direction") + check(not overlay.note.visible, "No reconnect note while the relay is in the path") + await process_frame + check(is_instance_valid(overlay.ghost) and overlay.ghost.visible and overlay.ghost.position.is_equal_approx(net.server_position), "The server ghost marks the authoritative position") + overlay.ghost_toggle.button_pressed = false + await process_frame + check(not overlay.ghost.visible, "The ghost can be hidden") + client.session.net_simulator.set_round_trip(80.0, 10.0, 5.0, 5.0) + # The relay flushes ENet's disconnect notice before it stops. + client.session.disconnect_session("Test leave") + check(not client.session.net_simulator.is_running(), "Disconnecting stops the relay") + deadline = Time.get_ticks_msec() + 3000 + while server.session.ships.has(id) and Time.get_ticks_msec() < deadline: + await process_frame + check(not server.session.ships.has(id), "The server sees the relayed pilot leave promptly") + client.session.use_net_simulator = false + check(client.session.join("127.0.0.1", test_port(24901)) == OK and not client.session.net_simulator.is_running(), "Normal joins bypass the relay") + deadline = Time.get_ticks_msec() + 5000 + while not client.session.active and Time.get_ticks_msec() < deadline: + await process_frame + check(client.session.active, "The client reconnects directly") + await process_frame + check(overlay.note.visible, "The overlay asks to reconnect when the relay is not in the path") + finish() diff --git a/tests/netsim_network_test.gd.uid b/tests/netsim_network_test.gd.uid new file mode 100644 index 0000000..fac22d7 --- /dev/null +++ b/tests/netsim_network_test.gd.uid @@ -0,0 +1 @@ +uid://b55fdklufcbjs diff --git a/tools/check-suites.json b/tools/check-suites.json index 336edcc..35a5db6 100644 --- a/tools/check-suites.json +++ b/tools/check-suites.json @@ -14,6 +14,7 @@ {"name": "targeting_test", "checks": [["targeting_test.gd"]]}, {"name": "network_test", "checks": [["network_test.gd"]]}, {"name": "network_combat_test", "checks": [["network_combat_test.gd"]]}, + {"name": "net_simulator", "checks": [["net_simulator_test.gd"], ["netsim_network_test.gd"]]}, {"name": "private_snapshot_test", "checks": [["private_snapshot_test.gd"]]}, {"name": "wallet_ordering_test", "checks": [["wallet_ordering_test.gd"]]}, {"name": "snapshot_codec_test", "checks": [["snapshot_codec_test.gd"]]}, @@ -65,6 +66,7 @@ {"name": "asset_budgets_test", "checks": [["asset_budgets_test.gd"]]}, {"name": "benchmark_packet_accounting", "checks": [["tests/benchmark_server_test.py"]]}, {"name": "dedicated_server_test", "checks": [["dedicated_server_test.gd"]]}, + {"name": "net_simulator", "checks": [["net_simulator_test.gd"], ["netsim_network_test.gd"]]}, {"name": "sector_visuals_test", "checks": [["sector_visuals_test.gd"]]}, {"name": "station_assets_test", "checks": [["station_assets_test.gd"]]}, {"name": "combat_effects_test", "checks": [["combat_effects_test.gd"]]},