From 6623e27d95d353748e9af62cb1cdd87e80a5bd01 Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:37:25 +0100 Subject: [PATCH 1/8] feat: add a snapshot interpolation buffer and server clock SnapshotBuffer keeps a remote entity's transforms by server tick and samples them at a render tick: Hermite interpolation between bracketing samples, linear extrapolation for at most 250 ms, then hold. ServerClock estimates server time from the median snapshot offset over 2 s and slews the render time, 100 ms behind it, by at most 5%. Co-Authored-By: Claude Opus 5.5 --- scripts/server_clock.gd | 129 ++++++++++++++++++++++++ scripts/server_clock.gd.uid | 1 + scripts/snapshot_buffer.gd | 156 ++++++++++++++++++++++++++++++ scripts/snapshot_buffer.gd.uid | 1 + tests/snapshot_buffer_test.gd | 133 +++++++++++++++++++++++++ tests/snapshot_buffer_test.gd.uid | 1 + 6 files changed, 421 insertions(+) create mode 100644 scripts/server_clock.gd create mode 100644 scripts/server_clock.gd.uid create mode 100644 scripts/snapshot_buffer.gd create mode 100644 scripts/snapshot_buffer.gd.uid create mode 100644 tests/snapshot_buffer_test.gd create mode 100644 tests/snapshot_buffer_test.gd.uid diff --git a/scripts/server_clock.gd b/scripts/server_clock.gd new file mode 100644 index 0000000..dd1cf50 --- /dev/null +++ b/scripts/server_clock.gd @@ -0,0 +1,129 @@ +class_name ServerClock +extends RefCounted +## Client estimate of the server's simulation time, and the render time remote +## entities are drawn at (see SnapshotBuffer). +## +## Each world snapshot carries the server tick it was sent on. Its offset +## sample is `tick / 60 - local arrival time`: late packets give smaller +## offsets, and the least-delayed packets the largest. The clock uses the +## median sample of the last OFFSET_WINDOW seconds, so single late or early +## packets barely move it, while lasting latency changes and clock drift are +## followed within one window. Estimated server time is local time plus that +## offset: the server's clock as seen through a typical recent packet. (The +## largest sample would follow the fastest path instead, but it is set by +## outliers, including frame and tick timing, and left less buffer for typical +## packets in measurements.) +## +## The render time trails it by INTERPOLATION_DELAY. advance() moves it by each +## physics tick's delta, so remote entities step in time with the local ship +## and camera, and time-scales it by at most MAX_SLEW to close any error over +## about CORRECTION_TIME. Only an error above SNAP_ERROR (connect, a stall or a +## large route change) jumps. + +## Server simulation ticks per second. +const TICK_RATE := 60.0 +## How far behind the estimated server time remote entities are drawn, in +## seconds: two snapshot intervals, so one lost or late snapshot still leaves +## a sample to interpolate toward. A playtesting setting. +const INTERPOLATION_DELAY := 0.1 +## Seconds of offset samples the median is taken from. +const OFFSET_WINDOW := 2.0 +## Largest time-scale change used to correct the render time (±5%). +const MAX_SLEW := 0.05 +## Seconds over which a render time error is closed, before the slew limit. +const CORRECTION_TIME := 1.0 +## Render time errors larger than this (seconds) snap instead of slewing. +const SNAP_ERROR := 0.25 +## Time constant (seconds) of the low-pass filter on the render time error. +## Physics ticks run at frame boundaries, so each tick's wall-clock time is +## off by up to a frame; filtering keeps that noise out of the time-scale, +## where it would shake remote entities' drawn velocity. +const ERROR_SMOOTHING := 0.5 + +var synced: bool = false +## Server seconds minus local seconds: the median sample in the window. +var offset: float = 0.0 +## Recent offset samples and their local arrival times, oldest first. Float64: +## server and client uptimes can be large. +var window_offsets := PackedFloat64Array() +var window_times := PackedFloat64Array() +## Render time on the server's timeline, in seconds. +var render_time: float = 0.0 +## Newest server tick received. +var latest_tick: int = -1 +## Latest render-time error (target minus render time) and time-scale, for stats. +var error: float = 0.0 +## Low-pass filtered render time error, which sets the time-scale. +var filtered_error: float = 0.0 +var time_scale: float = 1.0 +var snaps: int = 0 +var delay: float = INTERPOLATION_DELAY + + +func reset() -> void: + synced = false + offset = 0.0 + window_offsets.clear() + window_times.clear() + render_time = 0.0 + latest_tick = -1 + error = 0.0 + filtered_error = 0.0 + time_scale = 1.0 + snaps = 0 + + +static func now_seconds() -> float: + return Time.get_ticks_usec() / 1_000_000.0 + + +## Records a snapshot sent on server `tick` arriving at local time `now`. +func observe(tick: int, now: float = now_seconds()) -> void: + latest_tick = maxi(latest_tick, tick) + var sample := tick / TICK_RATE - now + window_offsets.append(sample) + window_times.append(now) + var expired := 0 + while expired < window_times.size() - 1 and window_times[expired] < now - OFFSET_WINDOW: + expired += 1 + if expired > 0: + window_offsets = window_offsets.slice(expired) + window_times = window_times.slice(expired) + var sorted := window_offsets.duplicate() + sorted.sort() + offset = sorted[sorted.size() / 2] + if not synced: + synced = true + render_time = now + offset - delay + + +## Estimated current server time, in seconds. +func server_time(now: float = now_seconds()) -> float: + return now + offset + + +## Advances the render time by one physics tick of `delta` seconds. +func advance(delta: float, now: float = now_seconds()) -> void: + if not synced: + return + var target := server_time(now) - delay + error = target - (render_time + delta) + if absf(error) > SNAP_ERROR: + render_time = target + time_scale = 1.0 + snaps += 1 + error = 0.0 + filtered_error = 0.0 + return + filtered_error = lerpf(filtered_error, error, 1.0 - exp(-delta / ERROR_SMOOTHING)) + time_scale = 1.0 + clampf(filtered_error / CORRECTION_TIME, -MAX_SLEW, MAX_SLEW) + render_time += delta * time_scale + + +func render_tick() -> float: + return render_time * TICK_RATE + + +## How far the newest received snapshot is ahead of the render time, in seconds. +func buffer_depth() -> float: + return latest_tick / TICK_RATE - render_time if synced else 0.0 diff --git a/scripts/server_clock.gd.uid b/scripts/server_clock.gd.uid new file mode 100644 index 0000000..65cb740 --- /dev/null +++ b/scripts/server_clock.gd.uid @@ -0,0 +1 @@ +uid://loag5cm03qjd diff --git a/scripts/snapshot_buffer.gd b/scripts/snapshot_buffer.gd new file mode 100644 index 0000000..9c5476f --- /dev/null +++ b/scripts/snapshot_buffer.gd @@ -0,0 +1,156 @@ +class_name SnapshotBuffer +extends RefCounted +## Client-side interpolation buffer for one remote entity (a pilot or an alien). +## +## Holds the entity's recent authoritative transforms keyed by the server tick +## they were simulated on, oldest first. sample() returns the transform at a +## fractional render tick: it interpolates along a smooth curve between the two +## samples that bracket it, extrapolates from the newest two for at most +## MAX_EXTRAPOLATION_TICKS when the buffer runs dry, and then holds. Callers clear() it at every +## discontinuity (spawn, new life, map visit, dock or launch, alien reset), so +## samples never blend across a teleport. + +enum Mode { EMPTY, INTERPOLATED, EXTRAPOLATED, HELD } + +## Samples kept: 1.6 s of 20 Hz snapshots, far more than the render delay needs. +const CAPACITY := 32 +## Extrapolation cap: 250 ms of server ticks past the newest sample. After that +## the entity holds still until fresh state arrives. A playtesting setting. +const MAX_EXTRAPOLATION_TICKS := 15 +## Samples further apart than this (1 s) are not treated as one motion. +const MAX_VELOCITY_GAP_TICKS := 60 + +## Samples, oldest first: {tick: int, position: Vector3, rotation: Vector3}. +var samples: Array[Dictionary] = [] +## Mode of the latest sample() call. +var mode: int = Mode.EMPTY +## Times sample() ran past the newest sample after interpolating (underruns). +var underruns: int = 0 +## Ticks already rendered past; samples at or before it are stale. +var rendered_tick: float = -INF + + +func clear() -> void: + samples.clear() + mode = Mode.EMPTY + rendered_tick = -INF + + +func is_empty() -> bool: + return samples.is_empty() + + +func newest_tick() -> int: + return samples[-1]["tick"] if not samples.is_empty() else -1 + + +func newest_position() -> Vector3: + return samples[-1]["position"] if not samples.is_empty() else Vector3.ZERO + + +## Adds a sample, keeping tick order so out-of-order arrivals still fill gaps. +## Returns false for ticks already rendered past and for duplicates of a held +## tick. `replace` marks state from a newer packet: it overwrites a sample with +## the same tick (only scripted tests resend a tick with different state). +func push(tick: int, position: Vector3, rotation: Vector3, replace: bool = false) -> bool: + if tick <= rendered_tick and not replace and not samples.is_empty(): + return false + var index := samples.size() + while index > 0 and int(samples[index - 1]["tick"]) >= tick: + index -= 1 + var sample := {"tick": tick, "position": position, "rotation": rotation} + if index < samples.size() and int(samples[index]["tick"]) == tick: + if not replace: + return false + samples[index] = sample + return true + samples.insert(index, sample) + if samples.size() > CAPACITY: + samples.pop_front() + return true + + +## The transform at `render_tick`: {position, rotation, mode}. Empty buffers +## return {} so the caller leaves the entity where it is. +func sample(render_tick: float) -> Dictionary: + if samples.is_empty(): + mode = Mode.EMPTY + return {} + # Drop samples the render time has passed, keeping two at or before it: + # the bracket's older sample and its predecessor, for the curve's tangent. + while samples.size() > 3 and float(samples[2]["tick"]) <= render_tick: + samples.pop_front() + var previous := mode + var result: Dictionary + var first: Dictionary = samples[0] + var last: Dictionary = samples[-1] + if render_tick <= float(first["tick"]) or samples.size() == 1: + # Before the oldest sample (just after a reset) or a single sample: hold it. + var held: Dictionary = first if render_tick <= float(first["tick"]) else last + result = {"position": held["position"], "rotation": held["rotation"]} + mode = Mode.INTERPOLATED if render_tick <= float(last["tick"]) else Mode.HELD + elif render_tick <= float(last["tick"]): + var index := 0 + while float(samples[index + 1]["tick"]) < render_tick: + index += 1 + result = interpolate(index, render_tick) + mode = Mode.INTERPOLATED + else: + var older: Dictionary = samples[-2] + var gap := int(last["tick"]) - int(older["tick"]) + var ahead := render_tick - float(last["tick"]) + if gap > MAX_VELOCITY_GAP_TICKS: + result = {"position": last["position"], "rotation": last["rotation"]} + mode = Mode.HELD + else: + # blend() with a weight above 1 continues the last motion linearly. + result = blend(older, last, 1.0 + minf(ahead, MAX_EXTRAPOLATION_TICKS) / gap) + mode = Mode.EXTRAPOLATED if ahead <= MAX_EXTRAPOLATION_TICKS else Mode.HELD + if mode != Mode.INTERPOLATED and previous == Mode.INTERPOLATED: + underruns += 1 + rendered_tick = maxf(rendered_tick, minf(render_tick, float(last["tick"]))) + result["mode"] = mode + return result + + +## Position on a cubic Hermite curve between samples `index` and `index + 1`, +## with each tangent the slope across that sample's neighbours (one-sided at +## the ends), so drawn velocity stays continuous where linear interpolation +## would change it abruptly at every snapshot. Angles interpolate linearly. +func interpolate(index: int, render_tick: float) -> Dictionary: + var older: Dictionary = samples[index] + var newer: Dictionary = samples[index + 1] + var span := float(int(newer["tick"]) - int(older["tick"])) + var weight := (render_tick - float(older["tick"])) / span + var result := blend(older, newer, weight) + var start := slope(index) + var finish := slope(index + 1) + var squared := weight * weight + var cubed := squared * weight + result["position"] = (older["position"] as Vector3) * (2.0 * cubed - 3.0 * squared + 1.0) \ + + start * span * (cubed - 2.0 * squared + weight) \ + + (newer["position"] as Vector3) * (-2.0 * cubed + 3.0 * squared) \ + + finish * span * (cubed - squared) + return result + + +## Velocity in metres per tick at sample `index`, across its neighbours. +func slope(index: int) -> Vector3: + var before: Dictionary = samples[maxi(0, index - 1)] + var after: Dictionary = samples[mini(samples.size() - 1, index + 1)] + var ticks := int(after["tick"]) - int(before["tick"]) + if ticks <= 0 or ticks > MAX_VELOCITY_GAP_TICKS: + return Vector3.ZERO + return ((after["position"] as Vector3) - (before["position"] as Vector3)) / ticks + + +## Position lerp and shortest-path angle lerp per axis. Weights above 1 +## extrapolate. +static func blend(older: Dictionary, newer: Dictionary, weight: float) -> Dictionary: + var from: Vector3 = older["rotation"] + var to: Vector3 = newer["rotation"] + var rotation := Vector3( + from.x + angle_difference(from.x, to.x) * weight, + from.y + angle_difference(from.y, to.y) * weight, + from.z + angle_difference(from.z, to.z) * weight) + return {"position": (older["position"] as Vector3).lerp(newer["position"], weight), "rotation": rotation} diff --git a/scripts/snapshot_buffer.gd.uid b/scripts/snapshot_buffer.gd.uid new file mode 100644 index 0000000..e88e063 --- /dev/null +++ b/scripts/snapshot_buffer.gd.uid @@ -0,0 +1 @@ +uid://duhnjmkq54tds diff --git a/tests/snapshot_buffer_test.gd b/tests/snapshot_buffer_test.gd new file mode 100644 index 0000000..c8049e6 --- /dev/null +++ b/tests/snapshot_buffer_test.gd @@ -0,0 +1,133 @@ +extends SceneTree +## SnapshotBuffer bracketing, ordering, extrapolation cap and reset, and +## ServerClock stability under ±30 ms arrival jitter. + +var failures: int = 0 +var checks: int = 0 + + +func _initialize() -> void: + run() + + +func check(condition: bool, description: String) -> void: + checks += 1 + if not condition: + failures += 1 + push_error(description) + + +func at(x: float) -> Vector3: + return Vector3(x, 0, 0) + + +func run() -> void: + # Bracketing: samples every 3 ticks, rendered between them. + var buffer := SnapshotBuffer.new() + check(buffer.sample(10.0).is_empty() and buffer.mode == SnapshotBuffer.Mode.EMPTY, "An empty buffer draws nothing") + buffer.push(30, at(30), Vector3(0, 3.0, 0)) + buffer.push(33, at(33), Vector3(0, -3.0, 0)) + var middle := buffer.sample(31.5) + check(middle["position"].is_equal_approx(at(31.5)) and middle["mode"] == SnapshotBuffer.Mode.INTERPOLATED, "Positions interpolate between the bracketing ticks") + # 3.0 to -3.0 rad is 0.28 rad the short way, across ±PI. + check(absf(angle_difference(middle["rotation"].y, PI)) < 0.01, "Angles interpolate along the shortest path (%.3f)" % middle["rotation"].y) + check(buffer.sample(29.0)["position"].is_equal_approx(at(30)), "Render times before the oldest sample hold it") + + # Out-of-order and duplicate ticks. + buffer = SnapshotBuffer.new() + for tick in [6, 0, 3, 3, 9]: + buffer.push(tick, at(tick), Vector3.ZERO) + check(buffer.samples.size() == 4 and buffer.samples.map(func(entry: Dictionary): return entry["tick"]) == [0, 3, 6, 9], "Samples stay in tick order and duplicates are ignored") + check(not buffer.push(6, at(99), Vector3.ZERO) and buffer.push(6, at(6.5), Vector3.ZERO, true) and buffer.samples[2]["position"] == at(6.5), "A duplicate tick is ignored unless a newer packet replaces it") + buffer.sample(7.0) + check(not buffer.push(5, at(5), Vector3.ZERO), "Ticks the render time already passed are stale") + check(buffer.push(8, at(8), Vector3.ZERO) and buffer.sample(8.0)["position"].is_equal_approx(at(8)), "A late tick still ahead of the render time fills the gap") + buffer = SnapshotBuffer.new() + for tick in range(0, 300, 3): + buffer.push(tick, at(tick), Vector3.ZERO) + check(buffer.samples.size() == SnapshotBuffer.CAPACITY, "The buffer keeps at most %d samples" % SnapshotBuffer.CAPACITY) + + # Extrapolation from the newest two samples, capped, then held. + buffer = SnapshotBuffer.new() + buffer.push(0, at(0), Vector3(0, 0, 0)) + buffer.push(3, at(3), Vector3(0, 0.3, 0)) + buffer.sample(2.0) + var ahead := buffer.sample(9.0) + check(ahead["mode"] == SnapshotBuffer.Mode.EXTRAPOLATED and ahead["position"].is_equal_approx(at(9)) and is_equal_approx(ahead["rotation"].y, 0.9), "A dry buffer extrapolates the last motion") + check(buffer.underruns == 1, "Running past the newest sample counts one underrun") + var cap := 3 + SnapshotBuffer.MAX_EXTRAPOLATION_TICKS + var held := buffer.sample(cap + 30.0) + check(held["mode"] == SnapshotBuffer.Mode.HELD and held["position"].is_equal_approx(at(cap)), "Extrapolation stops after 250 ms and holds") + check(buffer.sample(cap + 60.0)["position"].is_equal_approx(at(cap)) and buffer.underruns == 1, "A held entity stays put without counting new underruns") + buffer.push(40, at(40), Vector3.ZERO) + buffer.push(43, at(43), Vector3.ZERO) + check(buffer.sample(41.0)["mode"] == SnapshotBuffer.Mode.INTERPOLATED, "Fresh samples resume interpolation") + var single := SnapshotBuffer.new() + single.push(10, at(10), Vector3.ZERO) + check(single.sample(20.0)["position"].is_equal_approx(at(10)), "One sample cannot extrapolate and holds") + + # Reset at a discontinuity: nothing blends across it. + buffer.clear() + check(buffer.is_empty() and buffer.push(44, at(500), Vector3.ZERO), "Clearing accepts a new motion at any tick") + check(buffer.sample(41.0)["position"].is_equal_approx(at(500)), "After a reset the new state is held, not blended with the old motion") + + check_clock() + if failures == 0: + print("Snapshot buffer tests passed: %d checks." % checks) + quit(1 if failures > 0 else 0) + + +## Snapshots every 3 server ticks with a 75 ± 30 ms one-way delay and 5% loss. +## The render time must advance smoothly (no snaps, bounded time-scale) and +## stay close to the server time of a typical path minus the delay. +func check_clock() -> void: + var clock := ServerClock.new() + var random := RandomNumberGenerator.new() + random.seed = 7 + var arrivals: Array[Vector2] = [] # (local arrival time, tick) + var base := 0.075 + for tick in range(0, 60 * 40, 3): + if random.randf() < 0.05: + continue + arrivals.append(Vector2(tick / 60.0 + base + random.randf_range(-0.03, 0.03), tick)) + arrivals.sort_custom(func(a: Vector2, b: Vector2): return a.x < b.x) + var next := 0 + var largest_step := 0.0 + var smallest_step := INF + var largest_error := 0.0 + var previous := -INF + var backwards := false + var step := 1.0 / 60.0 + for frame in range(60 * 40): + var now := frame * step + while next < arrivals.size() and arrivals[next].x <= now: + clock.observe(int(arrivals[next].y), arrivals[next].x) + next += 1 + clock.advance(step, now) + if not clock.synced: + continue + if frame > 60 * 10: + var advanced := clock.render_time - previous + largest_step = maxf(largest_step, advanced) + smallest_step = minf(smallest_step, advanced) + backwards = backwards or advanced < 0.0 + # Server time over a typical (median) path is now - base. + var ideal := now - base - ServerClock.INTERPOLATION_DELAY + largest_error = maxf(largest_error, absf(clock.render_time - ideal)) + previous = clock.render_time + check(clock.snaps == 0, "Jitter never snaps the render clock") + check(not backwards and smallest_step >= step * (1.0 - ServerClock.MAX_SLEW) - 1e-6 and largest_step <= step * (1.0 + ServerClock.MAX_SLEW) + 1e-6, + "The render time advances every tick within ±5%% (%.4f..%.4f s per %.4f s)" % [smallest_step, largest_step, step]) + check(largest_error < 0.03, "The render time stays within 30 ms of a typical path minus the delay (%.1f ms)" % (largest_error * 1000.0)) + + # A lasting latency increase is followed gently; a stall snaps once. + var later := ServerClock.new() + later.observe(0, 0.05) + for frame in range(1, 600): + var now := frame * step + if frame % 3 == 0: + later.observe(frame, now + (0.05 if frame < 300 else 0.15)) + later.advance(step, now) + check(later.snaps == 0 and later.time_scale >= 1.0 - ServerClock.MAX_SLEW, "A lasting 100 ms latency rise is absorbed by slewing, not snapping") + later.advance(step, 60.0) + check(later.snaps == 1, "A long stall snaps the render clock once") diff --git a/tests/snapshot_buffer_test.gd.uid b/tests/snapshot_buffer_test.gd.uid new file mode 100644 index 0000000..4d1735e --- /dev/null +++ b/tests/snapshot_buffer_test.gd.uid @@ -0,0 +1 @@ +uid://1g2yxc7ndska From 42e7a890bc07739ea33527c4ee032f02d1c909e3 Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:37:28 +0100 Subject: [PATCH 2/8] feat: draw remote pilots and aliens from buffered snapshots Remote pilots and aliens are drawn at the render time each physics tick instead of lerping toward the newest snapshot. Buffers clear on spawn, despawn, new lives, map changes, dock and launch, and alien resets; late packets of the same life still fill gaps. Lasers and explosions anchor to the drawn ships. Network schema 25. Co-Authored-By: Claude Opus 5.5 --- scripts/alien.gd | 9 +++ scripts/flight_session.gd | 137 +++++++++++++++++++++++++++----- scripts/sector.gd | 3 +- scripts/session_combat.gd | 34 +++++--- tests/autopilot_test.gd | 6 +- tests/rpc_compatibility_test.gd | 2 +- 6 files changed, 157 insertions(+), 34 deletions(-) diff --git a/scripts/alien.gd b/scripts/alien.gd index da3c32c..3dd4c7b 100644 --- a/scripts/alien.gd +++ b/scripts/alien.gd @@ -82,6 +82,15 @@ var contributors: Array[int] = [] # Weapons outrange detection; whoever damaged this life stays a target while eligible. var last_attacker: Pilot = null var snapshot_goal: Dictionary = {} +## Client: buffered snapshot transforms drawn by SessionCombat.interpolate(). +var snapshot_buffer := SnapshotBuffer.new() + + +## Client: forgets replicated state at a discontinuity (session start or end, +## or a map change); the next snapshot snaps to the server's state. +func clear_snapshots() -> void: + snapshot_goal.clear() + snapshot_buffer.clear() func tuning() -> Dictionary: diff --git a/scripts/flight_session.gd b/scripts/flight_session.gd index 299b48a..4525cc2 100644 --- a/scripts/flight_session.gd +++ b/scripts/flight_session.gd @@ -8,7 +8,7 @@ const MAX_PLAYERS: int = 10 const INPUT_TIMEOUT_TICKS: int = InputBuffer.TIMEOUT_TICKS const CONNECT_TIMEOUT: float = 10.0 # Bump when packet contents or shared physics change without an RPC signature change. -const NETWORK_SCHEMA: int = 24 +const NETWORK_SCHEMA: int = 25 ## ENet packet throttle for every server/client peer: [interval ms, ## acceleration, deceleration]. ENet's default deceleration (2) discards ## unreliable packets at the sender whenever one round trip exceeds the @@ -17,6 +17,9 @@ const NETWORK_SCHEMA: int = 24 ## are redundant, so deceleration 0 keeps the throttle open. Reliable traffic ## keeps ENet's own windowing and resends. const ENET_THROTTLE := [5000, 2, 0] +## Laser and explosion points within this distance (m) of an entity's newest +## received position are moved onto where that entity is drawn. +const ANCHOR_RADIUS := 8.0 const BUILD_MISMATCH := "Client and server builds are incompatible. Use the matching client and server from the same release or PR preview." var sector: Sector @@ -34,7 +37,13 @@ var input_buffers: Dictionary[int, InputBuffer] = {} var server_tick: int = 0 ## Client: local pilot inputs, prediction and reconciliation. var prediction := FlightPrediction.new() +## Client: newest applied state of each pilot, keyed by peer. var goals: Dictionary[int, Dictionary] = {} +## Client: estimated server time and the render time remote entities use. +var clock := ServerClock.new() +## Client: interpolation buffers of remote pilots, keyed by peer. Cleared +## with `goals` at every discontinuity. +var remote_buffers: Dictionary[int, SnapshotBuffer] = {} var send_clock: float = 0.0 var connect_clock: float = 0.0 var received_snapshot: bool = false @@ -569,6 +578,7 @@ func spawn(id: int, location: Vector3, docked: bool = false, map: int = 0) -> vo ship.position = location ship.map_id = map ships[id] = ship + remote_buffers.erase(id) combat.add_player(id, location) ship.set_meta("docked", docked) if docked: @@ -752,6 +762,7 @@ func despawn(id: int) -> void: commands.erase(id) input_buffers.erase(id) goals.erase(id) + remote_buffers.erase(id) player_sequences.erase(id) combat.remove_player(id) @@ -812,18 +823,81 @@ func tick(delta: float) -> void: disconnect_session("Connected, but no sector arrived. Check that client and server builds match, then try again.") return predict_local(delta, movement, boost) - combat.interpolate(delta) - for id: int in goals: - if not ships.has(id) or ships[id].map_id != sector.map_id: - continue - var ship := ships[id] - var goal: Dictionary = goals[id] - if ship == sector.player: - continue - ship.position = ship.position.lerp(goal["position"], minf(1.0, delta * 15.0)) - var angles: Vector3 = goal["rotation"] - ship.rotation.x = lerp_angle(ship.rotation.x, angles.x, minf(1.0, delta * 15.0)) - ship.rotation.y = lerp_angle(ship.rotation.y, angles.y, minf(1.0, delta * 15.0)) + render_remote(delta) + + +## Client: draws remote pilots and aliens at the render time, between buffered +## snapshots (see ServerClock and SnapshotBuffer). Runs once per physics tick, +## so they step in time with the local ship and camera. +func render_remote(delta: float) -> void: + clock.advance(delta) + if not clock.synced: + return + var render_tick := clock.render_tick() + var counts := PackedInt32Array([0, 0, 0, 0]) + for id: int in remote_buffers: + var ship: Pilot = ships.get(id) + if ship == null or ship == sector.player or ship.map_id != sector.map_id: + continue + draw_sample(ship, remote_buffers[id], render_tick, counts, false) + combat.interpolate(render_tick, counts) + net_stats.record_interpolation(clock, counts[0], counts[1], counts[2], counts[3]) + + +## Moves one entity to its buffered transform at `render_tick` and counts the +## SnapshotBuffer mode used in `counts`: [interpolated, extrapolated, held, +## underruns]. +static func draw_sample(node: Node3D, buffer: SnapshotBuffer, render_tick: float, counts: PackedInt32Array, all_axes: bool) -> void: + var underruns := buffer.underruns + var result := buffer.sample(render_tick) + if result.is_empty(): + return + node.position = result["position"] + var angles: Vector3 = result["rotation"] + if all_axes: + node.rotation = angles + else: + # Pilots replicate pitch and yaw; roll is cosmetic banking on the model. + node.rotation.x = angles.x + node.rotation.y = angles.y + match int(result["mode"]): + SnapshotBuffer.Mode.INTERPOLATED: counts[0] += 1 + SnapshotBuffer.Mode.EXTRAPOLATED: counts[1] += 1 + SnapshotBuffer.Mode.HELD: counts[2] += 1 + counts[3] += buffer.underruns - underruns + + +## Client: moves a world-space effect point the server placed at an entity's +## position onto where that entity is drawn. Remote entities are drawn about +## ServerClock.INTERPOLATION_DELAY in the past and the local ship ahead of the +## server, so lasers would otherwise start and end beside their ships. +func drawn_point(point: Vector3) -> Vector3: + if not active or multiplayer.is_server(): + return point + var best := ANCHOR_RADIUS + var shift := Vector3.ZERO + if net_stats.has_server_state and sector.player.alive: + var distance := point.distance_to(net_stats.server_position) + if distance < best: + best = distance + shift = sector.player.position + sector.player.visual_offset - net_stats.server_position + for id: int in remote_buffers: + var ship: Pilot = ships.get(id) + var buffer := remote_buffers[id] + if ship == null or ship == sector.player or not ship.visible or buffer.is_empty(): + continue + var distance := point.distance_to(buffer.newest_position()) + if distance < best: + best = distance + shift = ship.position - buffer.newest_position() + for alien: Alien in sector.aliens.values(): + if not alien.visible or alien.snapshot_buffer.is_empty(): + continue + var distance := point.distance_to(alien.snapshot_buffer.newest_position()) + if distance < best: + best = distance + shift = alien.position - alien.snapshot_buffer.newest_position() + return point + shift ## Server: consumes this tick's input for a remote pilot and simulates it with @@ -1026,6 +1100,7 @@ func world_snapshot(packet: PackedByteArray) -> void: var sequence: int = world["sequence"] var visit: int = world["visit"] net_stats.server_tick = maxi(net_stats.server_tick, world["tick"]) + clock.observe(world["tick"]) var owner: Dictionary = world["owner"] if not owner.is_empty(): combat.ammo_snapshot(owner["rounds"], sequence, owner["rockets"], visit) @@ -1039,28 +1114,41 @@ func world_snapshot(packet: PackedByteArray) -> void: var profile: Array = player_profiles.get(id, [-1]) if profile[0] == state["profile"]: players[id] = SnapshotCodec.player_state(state, profile[1]) - snapshot(players, {}, sequence, visit) + snapshot(players, {}, sequence, visit, world["tick"]) for id: int in world["aliens"]: var state: Dictionary = world["aliens"][id] var profile: Array = alien_profiles.get(id, [-1]) if profile[0] == state["profile"]: - snapshot({}, SnapshotCodec.alien_state(state, profile[1]), sequence, visit) + snapshot({}, SnapshotCodec.alien_state(state, profile[1]), sequence, visit, world["tick"]) -## Applies decoded world state. Each entity rejects state older than its last update. -func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: int = -1) -> void: +## Applies decoded world state sent on server `tick`. Each entity rejects state +## older than its last update, though an older packet's transform can still +## fill a remote entity's interpolation buffer. Direct calls without a tick +## (tests) reuse the newest received tick. +func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: int = -1, tick: int = -1) -> void: if not active or not receives_map(visit): return + if tick < 0: + tick = maxi(clock.latest_tick, 0) # Packets may arrive out of order. Reject stale state per entity, not per whole packet. if not alien_state.is_empty(): var alien_id: int = alien_state["id"] if sequence > alien_sequences.get(alien_id, -1): - combat.apply_alien(alien_state) + combat.apply_alien(alien_state, tick) alien_sequences[alien_id] = sequence + else: + combat.buffer_late_alien(alien_state, tick) for id: int in state: - if not ships.has(id) or sequence <= player_sequences.get(id, -1): + if not ships.has(id): continue var data: Dictionary = state[id] + if sequence <= player_sequences.get(id, -1): + # Same life and state: the transform still belongs to the current motion. + var late := ships[id] + if late != sector.player and remote_buffers.has(id) and int(data["life"]) == int(late.get_meta("life", 0)) and bool(data["alive"]) == late.alive: + remote_buffers[id].push(tick, data["position"], data["rotation"]) + continue if int(data["life"]) < int(ships[id].get_meta("life", 0)): continue # Reliable dock/launch acknowledgements and snapshots travel on different channels. @@ -1075,6 +1163,14 @@ func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: ship.rotation = data["rotation"] if ship != sector.player: ship.energy = data["energy"] + # A new life, or the first state after a spawn or launch, starts a new motion. + var buffer: SnapshotBuffer = remote_buffers.get_or_add(id, SnapshotBuffer.new()) + if reset or buffer.is_empty(): + buffer.clear() + ship.position = data["position"] + ship.rotation.x = data["rotation"].x + ship.rotation.y = data["rotation"].y + buffer.push(tick, data["position"], data["rotation"], true) else: var authoritative := {"position": data["position"], "rotation": data["rotation"], "energy": data["energy"], "velocity": data["velocity"] if ship.alive else Vector3.ZERO} @@ -1132,6 +1228,8 @@ func disconnect_session(message: String) -> void: input_buffers.clear() server_tick = 0 goals.clear() + remote_buffers.clear() + clock.reset() received_snapshot = false snapshot_sequence = 0 player_sequences.clear() @@ -1347,6 +1445,7 @@ func map_changed(id: int, data: Dictionary, sequence: int) -> void: prediction.reset(ship) ship.sim_rotation = data["rotation"] goals.erase(id) + remote_buffers.erase(id) player_sequences[id] = maxi(player_sequences.get(id, -1), sequence) if ship == sector.player: sector.activate_map(ship.map_id) diff --git a/scripts/sector.gd b/scripts/sector.gd index e3a1a19..ff2d9a1 100644 --- a/scripts/sector.gd +++ b/scripts/sector.gd @@ -728,7 +728,7 @@ func activate_map(map: int) -> void: node.visible = key == map for enemy: Alien in world_aliens.values(): if changed and is_instance_valid(session) and session.active and not multiplayer.is_server(): - enemy.snapshot_goal.clear() + enemy.clear_snapshots() var client := is_instance_valid(session) and session.active and not multiplayer.is_server() enemy.visible = enemy.map_id == map and enemy.alive and (not client and not client_only or not enemy.snapshot_goal.is_empty()) enemy.collision_layer = 2 if enemy.alive and (enemy.simulation_authority or enemy.visible) else 0 @@ -736,6 +736,7 @@ func activate_map(map: int) -> void: var client := session.active and not multiplayer.is_server() if changed and client: session.goals.clear() + session.remote_buffers.clear() for ship: Pilot in session.ships.values(): ship.visible = ship.map_id == map and ship.alive and not ship.get_meta("docked", false) and (not client or ship == player or session.goals.has(session.ships.find_key(ship))) ship.collision_layer = 2 if ship.alive and not ship.get_meta("docked", false) and (ship.simulation_authority or ship.visible) else 0 diff --git a/scripts/session_combat.gd b/scripts/session_combat.gd index 0361caf..d7710dc 100644 --- a/scripts/session_combat.gd +++ b/scripts/session_combat.gd @@ -169,7 +169,7 @@ func begin() -> void: alien.returning = false alien.engaged = false alien.contributors.clear() - alien.snapshot_goal.clear() + alien.clear_snapshots() alien.reset_health() alien.set_meta("feedback_health_received", false) alien.visible = multiplayer.is_server() and alien.map_id == sector.map_id @@ -850,7 +850,10 @@ func update_local(data: Dictionary, sequence: int = -1) -> void: session.sector.player_respawn = data["respawn"] -func apply_alien(data: Dictionary) -> void: +## Applies an alien's newest state, sent on server `tick`. Its transform goes +## into the alien's interpolation buffer; a reset (new encounter, death, +## respawn or the end of a return home) snaps to it and starts a new buffer. +func apply_alien(data: Dictionary, tick: int = 0) -> void: var alien: Alien = session.sector.world_aliens.get(data["id"]) if alien == null or alien.kind != data["kind"] or alien.map_id != session.sector.map_id: return @@ -864,6 +867,8 @@ func apply_alien(data: Dictionary) -> void: if reset or alien.snapshot_goal.is_empty() or alien.returning != data["returning"]: alien.position = data["position"] alien.rotation = data["rotation"] + alien.snapshot_buffer.clear() + alien.snapshot_buffer.push(tick, data["position"], data["rotation"], true) alien.life = data["encounter"] alien.home_position = data["home"] alien.returning = data["returning"] @@ -873,14 +878,23 @@ func apply_alien(data: Dictionary) -> void: alien.snapshot_goal = data -func interpolate(delta: float) -> void: +## Buffers the transform of an alien state that arrived after a newer one, +## when it belongs to the same encounter and state as the current motion. +func buffer_late_alien(data: Dictionary, tick: int) -> void: + var alien: Alien = session.sector.world_aliens.get(data["id"]) + if alien == null or alien.kind != data["kind"] or alien.map_id != session.sector.map_id or alien.snapshot_buffer.is_empty(): + return + if alien.life == data["encounter"] and alien.alive == data["alive"] and alien.returning == data["returning"]: + alien.snapshot_buffer.push(tick, data["position"], data["rotation"]) + + +## Draws this map's aliens at `render_tick` (see FlightSession.render_remote), +## adding to `counts`: [interpolated, extrapolated, held, underruns]. +func interpolate(render_tick: float, counts: PackedInt32Array = PackedInt32Array([0, 0, 0, 0])) -> void: for alien: Alien in session.sector.aliens.values(): if alien.snapshot_goal.is_empty(): continue - alien.position = alien.position.lerp(alien.snapshot_goal["position"], minf(1.0, delta * 15.0)) - var angles: Vector3 = alien.snapshot_goal["rotation"] - for axis in range(3): - alien.rotation[axis] = lerp_angle(alien.rotation[axis], angles[axis], minf(1.0, delta * 15.0)) + FlightSession.draw_sample(alien, alien.snapshot_buffer, render_tick, counts, true) func message(id: int, text: String, sound_cue: String = "") -> void: @@ -901,13 +915,13 @@ func receive_message(text: String, sound_cue: String = "") -> void: @rpc("authority", "call_local", "unreliable", 3) func show_laser(start: Vector3, finish: Vector3, hostile: bool, ammo_type: String = "x1", visit: int = -1) -> void: if session.active and not session.sector.dedicated_server and session.receives_map(visit): - SectorVisuals.laser(session.sector, start, finish, hostile, ammo_type) + SectorVisuals.laser(session.sector, session.drawn_point(start), session.drawn_point(finish), hostile, ammo_type) @rpc("authority", "call_local", "reliable") func show_explosion(location: Vector3, diameter: float, visit: int = -1) -> void: if session.active and not session.sector.dedicated_server and session.receives_map(visit): - SectorVisuals.explosion(session.sector, location, diameter) + SectorVisuals.explosion(session.sector, session.drawn_point(location), diameter) func finish() -> void: @@ -952,7 +966,7 @@ func finish() -> void: records.clear() for alien: Alien in session.sector.world_aliens.values(): alien.contributors.clear() - alien.snapshot_goal.clear() + alien.clear_snapshots() alien.simulation_authority = true if not session.sector.dedicated_server: session.sector.player.simulation_authority = true diff --git a/tests/autopilot_test.gd b/tests/autopilot_test.gd index bb721a2..1bf3e1c 100644 --- a/tests/autopilot_test.gd +++ b/tests/autopilot_test.gd @@ -328,9 +328,9 @@ func network_checks() -> void: server.aliens[1].position = Vector3(400, 250, -120) server.aliens[1].home_position = server.aliens[1].position await replicate(server) - # Replication updates alien interpolation goals, not their visible positions. - # Start planning only after applying the fixture's freshly relocated target. - client.session.combat.interpolate(0.1) + # Replication fills alien interpolation buffers, not their visible positions. + # Start planning only after drawing the fixture's freshly relocated target. + client.session.combat.interpolate(float(client.session.clock.latest_tick)) client.select_target(client.aliens[1]) client.autopilot.toggle() var start := ship.position diff --git a/tests/rpc_compatibility_test.gd b/tests/rpc_compatibility_test.gd index 96e8729..2d48846 100644 --- a/tests/rpc_compatibility_test.gd +++ b/tests/rpc_compatibility_test.gd @@ -66,7 +66,7 @@ func run() -> void: # Schema 17 previews share this RPC table but pack world entries and profiles # without revisions, so only the schema separates their fingerprints. var preview := server.session.protocol_fingerprint(17) - check(preview != server.session.protocol_fingerprint() and FlightSession.NETWORK_SCHEMA == 24, "Profile revisions change the protocol fingerprint") + check(preview != server.session.protocol_fingerprint() and FlightSession.NETWORK_SCHEMA == 25, "Profile revisions change the protocol fingerprint") var preview_server := func(id: int): server.multiplayer.send_auth(id, JSON.stringify({"nonce": "00".repeat(32), "protocol": preview}).to_utf8_buffer()) server.multiplayer.peer_authenticating.connect(preview_server) client.session.join("127.0.0.1", test_port(24683)) From fd66111864b4ad12c60accea56b719cd8d0c8a0d Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:37:31 +0100 Subject: [PATCH 3/8] feat: show interpolation delay, buffer depth and underruns in the F8 overlay Co-Authored-By: Claude Opus 5.5 --- scripts/net_stats.gd | 80 ++++++++++++++++++++++++++++++++++++++ scripts/netcode_overlay.gd | 7 +++- 2 files changed, 85 insertions(+), 2 deletions(-) diff --git a/scripts/net_stats.gd b/scripts/net_stats.gd index 2cac64f..3ecd6ef 100644 --- a/scripts/net_stats.gd +++ b/scripts/net_stats.gd @@ -25,10 +25,23 @@ extends RefCounted ## packet repeats recent unacknowledged inputs. ## - server_inputs: the server's counters for this pilot's inputs (see ## InputBuffer): applied, duplicates, late, lost, dropped and starved. +## - interpolation_delay_ms: how far behind the estimated server time remote +## pilots and aliens are drawn (ServerClock.delay). +## - buffer depth: once per client physics tick, how far the newest received +## snapshot tick is ahead of the render time, in ms. Below zero the buffers +## have run dry. The minimum and mean cover the last DEPTH_WINDOW ticks. +## - entity ticks: remote entities drawn per client physics tick, by +## SnapshotBuffer mode: interpolated, extrapolated (past the newest sample, +## at most 250 ms) or held (past the cap, or a single sample). underruns +## counts entities that ran past their newest sample after interpolating. +## - clock offset: estimated server time minus local time (ms); drift is how +## far it moved since the clock synchronized. clock error is how far the +## render time trails its target, and time scale how fast it is closing it. const SNAPSHOT_INTERVAL_MS := 50.0 const JITTER_WINDOW := 100 const SAMPLE_USEC := 1_000_000 +const DEPTH_WINDOW := 120 var rtt_ms: float = 0.0 var up_bytes_per_second: float = 0.0 @@ -58,12 +71,26 @@ var server_position: Vector3 = Vector3.ZERO var server_rotation: Vector3 = Vector3.ZERO var inputs_sent: int = 0 var input_packets_sent: int = 0 +var interpolation_delay_ms: float = ServerClock.INTERPOLATION_DELAY * 1000.0 +## Recent buffer depths in ms, oldest first. +var buffer_depths: PackedFloat32Array = [] +var interpolated_ticks: int = 0 +var extrapolated_ticks: int = 0 +var held_ticks: int = 0 +var underruns: int = 0 +var clock_offset_ms: float = 0.0 +var clock_drift_ms: float = 0.0 +var clock_error_ms: float = 0.0 +var clock_scale: float = 1.0 +var clock_snaps: int = 0 +var _clock_origin_ms: float = NAN ## When true, every error, correction and jitter sample is kept for percentiles. var keep_samples: bool = false var error_samples: PackedFloat32Array = [] var offset_samples: PackedFloat32Array = [] var replay_samples: PackedFloat32Array = [] var jitter_samples: PackedFloat32Array = [] +var depth_samples: PackedFloat32Array = [] var _last_arrival_usec: int = -1 var _sample_started_usec: int = -1 @@ -91,6 +118,13 @@ func reset() -> void: server_inputs = {} server_input_depth = -1 ack_lag_ticks = 0 + buffer_depths = PackedFloat32Array() + clock_offset_ms = 0.0 + clock_drift_ms = 0.0 + clock_error_ms = 0.0 + clock_scale = 1.0 + clock_snaps = 0 + _clock_origin_ms = NAN _last_arrival_usec = -1 _sample_started_usec = -1 _window_up_bytes = 0 @@ -113,6 +147,11 @@ func reset_extremes() -> void: offset_samples = PackedFloat32Array() replay_samples = PackedFloat32Array() jitter_samples = PackedFloat32Array() + depth_samples = PackedFloat32Array() + interpolated_ticks = 0 + extrapolated_ticks = 0 + held_ticks = 0 + underruns = 0 func record_snapshot_arrival(now_usec: int = Time.get_ticks_usec()) -> void: @@ -171,6 +210,47 @@ func record_server_state(position: Vector3, rotation: Vector3) -> void: server_rotation = rotation +## Records one client physics tick of remote rendering: the clock's state and +## how many entities each SnapshotBuffer mode drew. +func record_interpolation(clock: ServerClock, interpolated: int, extrapolated: int, held: int, new_underruns: int) -> void: + if not clock.synced: + return + interpolation_delay_ms = clock.delay * 1000.0 + var depth := clock.buffer_depth() * 1000.0 + buffer_depths.append(depth) + if buffer_depths.size() > DEPTH_WINDOW: + buffer_depths = buffer_depths.slice(buffer_depths.size() - DEPTH_WINDOW) + if keep_samples: + depth_samples.append(depth) + interpolated_ticks += interpolated + extrapolated_ticks += extrapolated + held_ticks += held + underruns += new_underruns + clock_offset_ms = clock.offset * 1000.0 + if is_nan(_clock_origin_ms): + _clock_origin_ms = clock_offset_ms + clock_drift_ms = clock_offset_ms - _clock_origin_ms + clock_error_ms = clock.error * 1000.0 + clock_scale = clock.time_scale + clock_snaps = clock.snaps + + +## Returns Vector2(min, mean) buffer depth over the window, in ms. +func buffer_depth() -> Vector2: + if buffer_depths.is_empty(): + return Vector2.ZERO + var lowest := INF + for depth in buffer_depths: + lowest = minf(lowest, depth) + return Vector2(lowest, mean(buffer_depths)) + + +## Share of remote entity ticks drawn past the newest sample (extrapolated or held). +func extrapolation_share() -> float: + var total := interpolated_ticks + extrapolated_ticks + held_ticks + return float(extrapolated_ticks + held_ticks) / total if total > 0 else 0.0 + + ## 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. diff --git a/scripts/netcode_overlay.gd b/scripts/netcode_overlay.gd index 7d7bda0..c286206 100644 --- a/scripts/netcode_overlay.gd +++ b/scripts/netcode_overlay.gd @@ -4,10 +4,10 @@ extends Control ## 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 SIZE := Vector2(340, 388) # Readings start here; the controls sit below them. const LINE_HEIGHT := 16 -const CONTROLS_TOP := 146 +const CONTROLS_TOP := 178 const REFRESH := 0.25 const DIRECTION_LABELS := ["Both ways (round trip)", "Upstream only", "Downstream only"] # Slider limits per mode: [round trip, one way]. @@ -202,6 +202,9 @@ func _draw() -> void: lines.append("Inputs %d unacked, replayed %d (max %d)" % [stats.unacked_inputs, stats.replayed_ticks, stats.max_replayed_ticks]) lines.append("Ack lag %d ticks, server buffer %s" % [stats.ack_lag_ticks, str(stats.server_input_depth) if stats.server_input_depth >= 0 else "-"]) lines.append("Sim error %.2f / %.2f m max, offset %.2f m" % [stats.latest_error_m, stats.max_error_m, stats.latest_offset_m]) + var depth := stats.buffer_depth() + lines.append("Interp delay %d ms, buffer %d min / %d avg ms" % [roundi(stats.interpolation_delay_ms), roundi(depth.x), roundi(depth.y)]) + lines.append("Extrap %.1f%% %.1f s, underruns %d, drift %+d ms" % [stats.extrapolation_share() * 100.0, (stats.extrapolated_ticks + stats.held_ticks) / 60.0, stats.underruns, roundi(stats.clock_drift_ms)]) var inputs := stats.server_inputs lines.append("Server lost %d late %d dup %d starved %d" % [inputs.get("lost", 0), inputs.get("late", 0), inputs.get("duplicates", 0), inputs.get("starved", 0)]) if simulator.is_running(): From b0b7f0794df467329c2f6efae23a384f7819d9ee Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:37:33 +0100 Subject: [PATCH 4/8] test: cover remote interpolation through the relay Co-Authored-By: Claude Opus 5.5 --- tests/interpolation_network_test.gd | 179 ++++++++++++++++++++++++ tests/interpolation_network_test.gd.uid | 1 + tools/check-suites.json | 2 + 3 files changed, 182 insertions(+) create mode 100644 tests/interpolation_network_test.gd create mode 100644 tests/interpolation_network_test.gd.uid diff --git a/tests/interpolation_network_test.gd b/tests/interpolation_network_test.gd new file mode 100644 index 0000000..f9c4b97 --- /dev/null +++ b/tests/interpolation_network_test.gd @@ -0,0 +1,179 @@ +extends "res://tests/network_test.gd" +## Snapshot interpolation through the network simulator: an observer behind +## 150 ± 30 ms round trip with 5% loss watches a directly connected pilot fly +## a scripted, turning pattern on a dedicated server. The observer draws it +## close to the server's path at the render time, with acceleration near the +## server's own and little extrapolation. The test also replays the previous +## per-tick lerp toward the newest snapshot from the same packets and checks +## that interpolation removes the stutter that lerp shows. + +const PORT := 24931 +## Bounds, against two runs over 12 s on a Windows desktop: render-time error +## p95 0.03-0.04 m and max 0.1-0.25 m; drawn acceleration p95 1.7-2.0x the +## server's; spikes (above 3x the server's p95) on 0-3% of ticks, against 86% +## for the per-tick lerp; 2-3% of entity ticks extrapolated. Limits leave room +## for slower CI hosts. +const RENDER_P95_ERROR := 0.5 +const RENDER_MAX_ERROR := 3.0 +const ACCEL_P95_RATIO := 3.0 +const MAX_SPIKE_SHARE := 0.1 +const MAX_EXTRAPOLATED_SHARE := 0.12 +# Scripted input cycle: [seconds, actions, yaw radians per second]. +const PATTERN := [ + [0.7, ["forward"], 0.0], [0.5, ["forward", "boost"], 0.0], [0.4, ["strafe_right"], 0.0], + [0.6, ["forward", "strafe_left"], 1.6], [0.4, [], 0.0], + [0.7, ["backward"], 0.0], [0.5, ["backward", "boost"], 0.0], [0.4, ["strafe_left"], 0.0], + [0.6, ["backward", "strafe_right"], -1.6], [0.4, [], 0.0], +] +const ACTIONS := ["forward", "backward", "strafe_left", "strafe_right", "boost"] + +var server: Sector +var observer: Sector +var mover: Sector +var mover_id := 0 +var drawn: Array[Vector3] = [] +var legacy: Array[Vector3] = [] +var legacy_position := Vector3.ZERO +var render_errors := PackedFloat32Array() +var path: Dictionary[int, Vector3] = {} +var ticks := PackedInt32Array() + + +func run() -> void: + server = make_sector("InterpServer", true, PORT) + observer = make_sector("InterpObserver") + mover = make_sector("InterpMover") + for index in 2: + var peer: Sector = [observer, mover][index] + peer.session.credential_id = "pilot%d" % index + peer.session.credential_token = test_token(index) + for peer: Sector in [server, observer, mover]: + peer.set_physics_process(true) + await settle() + observer.session.use_net_simulator = true + observer.session.net_simulator.set_seed(5) + observer.session.net_simulator.set_round_trip(150.0, 30.0, 5.0) + check(observer.session.join("127.0.0.1", test_port(PORT)) == OK and mover.session.join("127.0.0.1", test_port(PORT)) == OK, "Both pilots start joining") + var deadline := Time.get_ticks_msec() + 15000 + while not (observer.session.received_snapshot and mover.session.received_snapshot) and Time.get_ticks_msec() < deadline: + await process_frame + mover_id = mover.multiplayer.get_unique_id() + check(observer.session.received_snapshot and mover.session.received_snapshot and server.session.ships.has(mover_id), "Both pilots join the dedicated server") + if failures > 0: + finish() + return + await fly(3.0) + check(observer.session.remote_buffers.has(mover_id) and observer.session.clock.synced, "The observer buffers the remote pilot and synchronizes its clock") + var net := observer.session.net_stats + net.reset_extremes() + net.keep_samples = true + legacy_position = observer.session.ships[mover_id].position + physics_frame.connect(sample) + await fly(12.0) + physics_frame.disconnect(sample) + net.keep_samples = false + release_inputs() + + var accelerations := second_differences(drawn) + var legacy_accelerations := second_differences(legacy) + var truth := PackedFloat32Array() + for tick: int in path: + if path.has(tick + 1) and path.has(tick + 2): + truth.append((path[tick + 2] - 2.0 * path[tick + 1] + path[tick]).length() * 3600.0) + var server_max := NetStats.percentile(truth, 1.0) + # Three times the server's p95: a collision can make its maximum an outlier. + var spike_limit := NetStats.percentile(truth, 0.95) * 3.0 + var spikes := spike_share(accelerations, spike_limit) + var legacy_spikes := spike_share(legacy_accelerations, spike_limit) + print("Render-time error p95 %.3f m, max %.3f m; accel p95 %.0f (server %.0f, max %.0f) m/s^2; spikes %.1f%% (per-tick lerp %.1f%%, accel p95 %.0f); extrapolated %.1f%%, %d underruns, depth %s ms" % [ + NetStats.percentile(render_errors, 0.95), NetStats.percentile(render_errors, 1.0), + NetStats.percentile(accelerations, 0.95), NetStats.percentile(truth, 0.95), server_max, + spikes * 100.0, legacy_spikes * 100.0, NetStats.percentile(legacy_accelerations, 0.95), + net.extrapolation_share() * 100.0, net.underruns, net.buffer_depth()]) + check(render_errors.size() > 500, "The remote pilot is drawn every tick while measured") + check(NetStats.percentile(render_errors, 0.95) <= RENDER_P95_ERROR and NetStats.percentile(render_errors, 1.0) <= RENDER_MAX_ERROR, "The drawn pilot follows the server's path at the render time") + check(NetStats.percentile(accelerations, 0.95) <= NetStats.percentile(truth, 0.95) * ACCEL_P95_RATIO, "Drawn acceleration stays near the server's own") + check(spikes <= MAX_SPIKE_SHARE, "Few ticks show acceleration spikes (%.1f%%)" % (spikes * 100.0)) + check(legacy_spikes > MAX_SPIKE_SHARE and legacy_spikes > spikes * 3.0, "The previous per-tick lerp stutters on the same packets (%.1f%% spikes)" % (legacy_spikes * 100.0)) + check(net.extrapolation_share() <= MAX_EXTRAPOLATED_SHARE, "The buffer rarely runs dry (%.1f%% extrapolated)" % (net.extrapolation_share() * 100.0)) + check(net.buffer_depth().y > 0.0 and net.interpolation_delay_ms == ServerClock.INTERPOLATION_DELAY * 1000.0, "Buffer depth and delay are reported") + # A stall over ServerClock.SNAP_ERROR (a slow CI host) may snap once; jitter must not. + check(observer.session.clock.snaps <= 1, "Jitter does not snap the observer's render clock (%d snaps)" % observer.session.clock.snaps) + + # Leaving forgets the remote pilot's buffer. + mover.session.disconnect_session("Test leave") + deadline = Time.get_ticks_msec() + 5000 + while observer.session.ships.has(mover_id) and Time.get_ticks_msec() < deadline: + await process_frame + check(not observer.session.ships.has(mover_id) and not observer.session.remote_buffers.has(mover_id), "A departed pilot's interpolation buffer is cleared") + observer.session.disconnect_session("Test leave") + check(not observer.session.clock.synced and observer.session.remote_buffers.is_empty(), "Disconnecting resets the clock and buffers") + finish() + + +## Records, once per physics tick, the drawn remote pilot, the server's path +## and a replay of the previous lerp (25% per tick toward the newest snapshot). +func sample() -> void: + if not server.session.ships.has(mover_id) or not observer.session.ships.has(mover_id): + return + var tick := server.session.server_tick + path[tick] = server.session.ships[mover_id].position + ticks.append(tick) + drawn.append(observer.session.ships[mover_id].position) + if observer.session.goals.has(mover_id): + legacy_position = legacy_position.lerp(observer.session.goals[mover_id]["position"], 0.25) + legacy.append(legacy_position) + var render := observer.session.clock.render_tick() + var low := floori(render) + if path.has(low) and path.has(low + 1): + render_errors.append(drawn[-1].distance_to(path[low].lerp(path[low + 1], render - low))) + + +func second_differences(points: Array[Vector3]) -> PackedFloat32Array: + var values := PackedFloat32Array() + for index in range(2, points.size()): + if ticks[index] - ticks[index - 2] == 2: + values.append((points[index] - 2.0 * points[index - 1] + points[index - 2]).length() * 3600.0) + return values + + +func spike_share(values: PackedFloat32Array, limit: float) -> float: + var spikes := 0 + for value in values: + if value > limit: + spikes += 1 + return float(spikes) / maxi(1, values.size()) + + +func fly(seconds: float) -> void: + var cycle := 0.0 + for segment: Array in PATTERN: + cycle += segment[0] + var started := Time.get_ticks_msec() + 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) + mover.player.pending_look.x += segment[2] * (now - last) / 1000.0 + last = now + # Keep combat from interrupting the flight; positions stay authoritative. + for ship: Pilot in server.session.ships.values(): + ship.hull = ship.max_hull + ship.shield = ship.max_shield + await process_frame + + +func release_inputs() -> void: + for action: String in ACTIONS: + Input.action_release(action) diff --git a/tests/interpolation_network_test.gd.uid b/tests/interpolation_network_test.gd.uid new file mode 100644 index 0000000..7f69fbe --- /dev/null +++ b/tests/interpolation_network_test.gd.uid @@ -0,0 +1 @@ +uid://dc655fa0ls8d4 diff --git a/tools/check-suites.json b/tools/check-suites.json index 585e80a..8b15dca 100644 --- a/tools/check-suites.json +++ b/tools/check-suites.json @@ -16,6 +16,7 @@ {"name": "network_combat_test", "checks": [["network_combat_test.gd"]]}, {"name": "net_simulator", "checks": [["net_simulator_test.gd"], ["netsim_network_test.gd"]]}, {"name": "netcode_reconciliation", "checks": [["input_buffer_test.gd"], ["reconciliation_test.gd"]]}, + {"name": "snapshot_interpolation", "checks": [["snapshot_buffer_test.gd"], ["interpolation_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"]]}, @@ -69,6 +70,7 @@ {"name": "dedicated_server_test", "checks": [["dedicated_server_test.gd"]]}, {"name": "net_simulator", "checks": [["net_simulator_test.gd"], ["netsim_network_test.gd"]]}, {"name": "netcode_reconciliation", "checks": [["input_buffer_test.gd"], ["reconciliation_test.gd"]]}, + {"name": "snapshot_interpolation", "checks": [["snapshot_buffer_test.gd"], ["interpolation_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"]]}, From 0979575bdcfd1d7e824853a702f23520ac776ea0 Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:37:35 +0100 Subject: [PATCH 5/8] test: measure remote smoothness in the netcode benchmark Co-Authored-By: Claude Opus 5.5 --- tests/netcode_benchmark.gd | 160 ++++++++++++++++++++++++++++++++++++- 1 file changed, 159 insertions(+), 1 deletion(-) diff --git a/tests/netcode_benchmark.gd b/tests/netcode_benchmark.gd index 54138b9..a31d3ad 100644 --- a/tests/netcode_benchmark.gd +++ b/tests/netcode_benchmark.gd @@ -52,6 +52,30 @@ extends "res://tests/network_test.gd" ## dropped (catch-up) and starved (ticks reusing the last input) are the ## server's InputBuffer counters. Before phase 2 these columns counted 20 Hz ## flight commands, each lost with its datagram. +## +## Remote smoothness (phase 3), needing at least one extra client: the measured +## client watches the first extra pilot, which flies the same pattern and also +## turns. Once per physics tick the benchmark records where the measured client +## draws it and where the server has it, on the server's tick. +## - remote_path_*_m: distance from the drawn ship to the server's path over +## the last 1.5 s (the nearest point on the polyline of its tick positions): +## how far the drawn motion strays from a path the ship really flew, at any +## delay. remote_lag_ms is how far behind the server's current tick that +## nearest point is, on average. +## - remote_render_*_m: distance from the drawn ship to the server's position +## at the client's render tick (ServerClock): the interpolation error proper. +## Only builds with snapshot interpolation report it. +## - remote_accel_p95/max: acceleration of the drawn ship, from second +## differences of its position per physics tick, in m/s^2. Stutter shows as +## spikes far above server_accel_p95/max, the same measure of the server's +## own path. +## - remote_spikes: share of ticks whose drawn acceleration exceeds three +## times the server's p95 acceleration (a collision can make the server's +## maximum an outlier). +## - extrapolated_share, underruns, depth_min/mean_ms: NetStats interpolation +## counters over the window: share of remote entity ticks drawn past their +## newest sample, buffers that ran dry, and how far the newest snapshot was +## ahead of the render time (min and mean, ms). const BASE_PORT := 24911 # ENet smooths its RTT by 1/8 per reliable acknowledgement, about two per @@ -121,11 +145,14 @@ func run() -> void: if failures > 0: finish() return + if everyone.size() > 1: + watched = everyone[1] var results: Array[Dictionary] = [] for condition: Array in conditions: results.append(await measure(server, client, everyone.size(), condition)) release_inputs() print_table(results) + print_remote_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() @@ -153,7 +180,13 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) var started := Time.get_ticks_usec() var frames := Engine.get_process_frames() + clear_remote_samples() + var sampler := sample_remote.bind(server, client) + if watched != null: + physics_frame.connect(sampler) var rtts := await fly(client, float(options["seconds"]), server) + if watched != null: + physics_frame.disconnect(sampler) var seconds := (Time.get_ticks_usec() - started) / 1_000_000.0 frames = Engine.get_process_frames() - frames net.keep_samples = false @@ -163,7 +196,7 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> var inputs: Dictionary = server.session.input_buffers[id].counters() for key: String in inputs: inputs[key] -= inputs_before[key] - return { + var row := { "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), @@ -192,11 +225,115 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> "input_packets": net.input_packets_sent - packets_before, "relay_dropped": relay_stats["up"]["dropped_packets"] + relay_stats["down"]["dropped_packets"], } + row.merge(remote_metrics(net)) + return row var speeds := PackedFloat32Array() var gaps := PackedFloat32Array() var depths := PackedFloat32Array() +## The extra pilot the measured client watches, or null without extra clients. +var watched: Sector = null +# Per physics tick while measuring: the watched ship as drawn by the measured +# client, the client's render tick (or -1), and the server's tick. +var drawn: Array[Vector3] = [] +var render_ticks := PackedFloat64Array() +var sample_ticks := PackedInt32Array() +# Server position of the watched ship per server tick. +var server_path: Dictionary[int, Vector3] = {} + + +func clear_remote_samples() -> void: + drawn.clear() + render_ticks = PackedFloat64Array() + sample_ticks = PackedInt32Array() + server_path.clear() + + +func sample_remote(server: Sector, client: Sector) -> void: + var id := watched.multiplayer.get_unique_id() + if not server.session.ships.has(id) or not client.session.ships.has(id): + return + var tick := server.session.server_tick + server_path[tick] = server.session.ships[id].position + drawn.append(client.session.ships[id].position) + sample_ticks.append(tick) + # Builds before snapshot interpolation have no render clock. + var clock: Object = client.session.get("clock") + render_ticks.append(clock.call("render_tick") if clock != null and clock.get("synced") else -1.0) + + +## Server position at fractional `tick`, or null outside the recorded path. +func server_at(tick: float) -> Variant: + var low := floori(tick) + if not server_path.has(low) or not server_path.has(low + 1): + return server_path.get(low) if is_equal_approx(tick, low) else null + return server_path[low].lerp(server_path[low + 1], tick - low) + + +func remote_metrics(net: NetStats) -> Dictionary: + var path_errors := PackedFloat32Array() + var lags := PackedFloat32Array() + var render_errors := PackedFloat32Array() + var accelerations := PackedFloat32Array() + var server_accelerations := PackedFloat32Array() + var rate := float(Engine.physics_ticks_per_second) + for index in drawn.size(): + var now := sample_ticks[index] + var point := drawn[index] + # Nearest point on the server's path over the last 1.5 s. + var best := INF + var best_tick := float(now) + for tick in range(now - 90, now): + if not server_path.has(tick) or not server_path.has(tick + 1): + continue + var from: Vector3 = server_path[tick] + var segment: Vector3 = server_path[tick + 1] - from + var along := clampf((point - from).dot(segment) / segment.length_squared(), 0.0, 1.0) if segment.length_squared() > 1e-8 else 0.0 + var distance := point.distance_to(from + segment * along) + if distance < best: + best = distance + best_tick = tick + along + if best < INF: + path_errors.append(best) + lags.append((now - best_tick) * 1000.0 / rate) + if render_ticks[index] >= 0.0: + var truth: Variant = server_at(render_ticks[index]) + if truth != null: + render_errors.append(point.distance_to(truth)) + # Second differences need three consecutive ticks. + if index >= 2 and sample_ticks[index] - sample_ticks[index - 2] == 2: + accelerations.append((drawn[index] - 2.0 * drawn[index - 1] + drawn[index - 2]).length() * rate * rate) + for tick: int in server_path: + if server_path.has(tick + 1) and server_path.has(tick + 2): + server_accelerations.append((server_path[tick + 2] - 2.0 * server_path[tick + 1] + server_path[tick]).length() * rate * rate) + var server_max := NetStats.percentile(server_accelerations, 1.0) + var spike_limit := NetStats.percentile(server_accelerations, 0.95) * 3.0 + var spikes := 0 + for value in accelerations: + if value > spike_limit: + spikes += 1 + var has_interpolation := net.get("extrapolated_ticks") != null + var depth_samples: PackedFloat32Array = net.get("depth_samples") if has_interpolation else PackedFloat32Array() + return { + "remote_samples": drawn.size(), + "remote_path_mean_m": snappedf(NetStats.mean(path_errors), 0.01), + "remote_path_p95_m": snappedf(NetStats.percentile(path_errors, 0.95), 0.01), + "remote_path_max_m": snappedf(NetStats.percentile(path_errors, 1.0), 0.01), + "remote_lag_ms": roundi(NetStats.mean(lags)), + "remote_render_mean_m": snappedf(NetStats.mean(render_errors), 0.01) if not render_errors.is_empty() else -1.0, + "remote_render_p95_m": snappedf(NetStats.percentile(render_errors, 0.95), 0.01) if not render_errors.is_empty() else -1.0, + "remote_render_max_m": snappedf(NetStats.percentile(render_errors, 1.0), 0.01) if not render_errors.is_empty() else -1.0, + "remote_accel_p95": roundi(NetStats.percentile(accelerations, 0.95)), + "remote_accel_max": roundi(NetStats.percentile(accelerations, 1.0)), + "server_accel_p95": roundi(NetStats.percentile(server_accelerations, 0.95)), + "server_accel_max": roundi(server_max), + "remote_spikes": snappedf(float(spikes) / maxi(1, accelerations.size()), 0.001), + "extrapolated_share": snappedf(net.call("extrapolation_share"), 0.001) if has_interpolation else -1.0, + "underruns": net.get("underruns") if has_interpolation else -1, + "depth_min_ms": roundi(NetStats.percentile(depth_samples, 0.0)) if not depth_samples.is_empty() else -1, + "depth_mean_ms": roundi(NetStats.mean(depth_samples)) if not depth_samples.is_empty() else -1, + } ## Flies the input pattern for `seconds`; returns RTT samples taken every 0.5 s. @@ -227,6 +364,9 @@ func fly(client: Sector, seconds: float, server: Sector = null) -> PackedFloat32 else: Input.action_release(action) client.player.pending_look.x += segment[2] * (now - last) / 1000.0 + if watched != null: + # The watched pilot turns too, so its drawn path curves. + watched.player.pending_look.x += segment[2] * (now - last) / 1000.0 last = now if server != null: # Keep combat from interrupting the measurement; positions stay authoritative. @@ -265,3 +405,21 @@ func print_table(results: Array[Dictionary]) -> void: row["gap_mean_m"], row["gap_p95_m"], row["replay_mean"], row["replay_max"], row["depth_mean"], row["inputs_sent"], row["inputs_applied"], row["inputs_lost"], row["inputs_late"], row["inputs_dropped"], row["inputs_starved"]]) + + +func print_remote_table(results: Array[Dictionary]) -> void: + if watched == null: + return + print("\nRemote smoothness: the measured client watching one extra pilot, sampled every physics tick.") + print("| Added RTT | Loss | Path error mean / p95 / max | Lag behind server | Render-time error mean / p95 / max | Drawn accel p95 / max | Server accel p95 / max | Spikes | Extrapolated | Underruns | Buffer depth min / mean |") + print("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") + for row: Dictionary in results: + var jitter := "" if row["jitter_ms"] == 0.0 else " ± %d" % row["jitter_ms"] + var render := "-" if row["remote_render_mean_m"] < 0.0 else "%.2f / %.2f / %.2f m" % [row["remote_render_mean_m"], row["remote_render_p95_m"], row["remote_render_max_m"]] + var extrapolated := "-" if row["extrapolated_share"] < 0.0 else "%.1f%%" % (row["extrapolated_share"] * 100.0) + var depth := "-" if row["depth_mean_ms"] < 0 else "%d / %d ms" % [row["depth_min_ms"], row["depth_mean_ms"]] + print("| %d%s ms | %s%% | %.2f / %.2f / %.2f m | %d ms | %s | %d / %d m/s² | %d / %d m/s² | %.1f%% | %s | %s | %s |" % [ + row["rtt_added_ms"], jitter, str(row["loss_percent"]), + row["remote_path_mean_m"], row["remote_path_p95_m"], row["remote_path_max_m"], row["remote_lag_ms"], render, + row["remote_accel_p95"], row["remote_accel_max"], row["server_accel_p95"], row["server_accel_max"], + row["remote_spikes"] * 100.0, extrapolated, "-" if row["underruns"] < 0 else str(row["underruns"]), depth]) From fbf7e90725de3376da965f2353df97465bdfe2f8 Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:37:38 +0100 Subject: [PATCH 6/8] chore: add the extras batch test uid Co-Authored-By: Claude Opus 5.5 --- tests/extras_batch_test.gd.uid | 1 + 1 file changed, 1 insertion(+) create mode 100644 tests/extras_batch_test.gd.uid diff --git a/tests/extras_batch_test.gd.uid b/tests/extras_batch_test.gd.uid new file mode 100644 index 0000000..bc56839 --- /dev/null +++ b/tests/extras_batch_test.gd.uid @@ -0,0 +1 @@ +uid://cksca7wikllc4 From 1929aea260845094a28ca1409cda5d9b973c7352 Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:50:43 +0100 Subject: [PATCH 7/8] fix: keep the netcode overlay within small layouts Fold the interpolation readings into one line and clock drift into the jitter line, so the overlay still fits at 960x600. Loosen the relay test's acceleration bound for the 60 fps suite runner. Co-Authored-By: Claude Opus 5.5 --- scripts/netcode_overlay.gd | 9 ++++----- tests/interpolation_network_test.gd | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/scripts/netcode_overlay.gd b/scripts/netcode_overlay.gd index c286206..17c7c44 100644 --- a/scripts/netcode_overlay.gd +++ b/scripts/netcode_overlay.gd @@ -4,10 +4,10 @@ extends Control ## 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, 388) +const SIZE := Vector2(340, 372) # Readings start here; the controls sit below them. const LINE_HEIGHT := 16 -const CONTROLS_TOP := 178 +const CONTROLS_TOP := 162 const REFRESH := 0.25 const DIRECTION_LABELS := ["Both ways (round trip)", "Upstream only", "Downstream only"] # Slider limits per mode: [round trip, one way]. @@ -198,13 +198,12 @@ func _draw() -> void: else: var jitter := stats.snapshot_jitter() lines.append("RTT %d ms Up %s/s Down %s/s" % [roundi(stats.rtt_ms), 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("Snapshot jitter %.1f / %.1f ms max, clock drift %+d ms" % [jitter.x, jitter.y, roundi(stats.clock_drift_ms)]) lines.append("Inputs %d unacked, replayed %d (max %d)" % [stats.unacked_inputs, stats.replayed_ticks, stats.max_replayed_ticks]) lines.append("Ack lag %d ticks, server buffer %s" % [stats.ack_lag_ticks, str(stats.server_input_depth) if stats.server_input_depth >= 0 else "-"]) lines.append("Sim error %.2f / %.2f m max, offset %.2f m" % [stats.latest_error_m, stats.max_error_m, stats.latest_offset_m]) var depth := stats.buffer_depth() - lines.append("Interp delay %d ms, buffer %d min / %d avg ms" % [roundi(stats.interpolation_delay_ms), roundi(depth.x), roundi(depth.y)]) - lines.append("Extrap %.1f%% %.1f s, underruns %d, drift %+d ms" % [stats.extrapolation_share() * 100.0, (stats.extrapolated_ticks + stats.held_ticks) / 60.0, stats.underruns, roundi(stats.clock_drift_ms)]) + lines.append("Interp %d ms, buffer %d/%d ms, extrap %.1f%%, %d dry" % [roundi(stats.interpolation_delay_ms), roundi(depth.x), roundi(depth.y), stats.extrapolation_share() * 100.0, stats.underruns]) var inputs := stats.server_inputs lines.append("Server lost %d late %d dup %d starved %d" % [inputs.get("lost", 0), inputs.get("late", 0), inputs.get("duplicates", 0), inputs.get("starved", 0)]) if simulator.is_running(): diff --git a/tests/interpolation_network_test.gd b/tests/interpolation_network_test.gd index f9c4b97..f8c453b 100644 --- a/tests/interpolation_network_test.gd +++ b/tests/interpolation_network_test.gd @@ -10,12 +10,12 @@ extends "res://tests/network_test.gd" const PORT := 24931 ## Bounds, against two runs over 12 s on a Windows desktop: render-time error ## p95 0.03-0.04 m and max 0.1-0.25 m; drawn acceleration p95 1.7-2.0x the -## server's; spikes (above 3x the server's p95) on 0-3% of ticks, against 86% +## server's (2.5x in the suite at 60 fps); spikes (above 3x the server's p95) on 0-3% of ticks, against 86% ## for the per-tick lerp; 2-3% of entity ticks extrapolated. Limits leave room ## for slower CI hosts. const RENDER_P95_ERROR := 0.5 const RENDER_MAX_ERROR := 3.0 -const ACCEL_P95_RATIO := 3.0 +const ACCEL_P95_RATIO := 4.0 const MAX_SPIKE_SHARE := 0.1 const MAX_EXTRAPOLATED_SHARE := 0.12 # Scripted input cycle: [seconds, actions, yaw radians per second]. From 7f7ec3147356f042122016e3bdfbb32721af53b1 Mon Sep 17 00:00:00 2001 From: Timerk <149791526+Timerk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:06:10 +0100 Subject: [PATCH 8/8] docs: record phase 3 snapshot interpolation results Co-Authored-By: Claude Opus 5.5 --- docs/netcode-baseline.md | 114 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/docs/netcode-baseline.md b/docs/netcode-baseline.md index 68821ba..b8b1a7e 100644 --- a/docs/netcode-baseline.md +++ b/docs/netcode-baseline.md @@ -141,3 +141,117 @@ RTT: 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. + +## After phase 3: snapshot interpolation + +Network schema 25. Remote pilots and aliens are no longer lerped toward the +newest snapshot (25% of the remaining distance per tick). Each one has a +`SnapshotBuffer` of transforms keyed by server tick. Once per client physics +tick, `FlightSession.render_remote()` draws them at a render time on the +server's timeline, which `ServerClock` keeps: + +- **Clock.** Each snapshot gives an offset sample: its server tick / 60 minus + its local arrival time. The clock uses the median of the last 2 s of + samples, so single late or early packets barely move it. The render time + trails that estimate by `ServerClock.INTERPOLATION_DELAY` (100 ms, two + snapshot intervals; a playtesting setting). It advances by each physics + tick, time-scaled by at most ±5% to close a low-pass-filtered error, and + snaps only past 250 ms (connecting, or a stall). The largest sample (the + fastest path) was tried first. Frame and tick timing outliers set it, and it + left typical packets about 30 ms less buffer (4.8% against 1.2% of entity + ticks extrapolated at 150 ± 30 ms). +- **Interpolation.** Positions follow a cubic Hermite curve between the two + bracketing samples, with tangents taken across neighbouring samples. Angles + take the shortest path. Linear interpolation changed the drawn velocity at + every snapshot, which showed as acceleration spikes on about 10% of ticks. +- **Dry buffers.** Past the newest sample, the entity extrapolates its last + motion for at most `SnapshotBuffer.MAX_EXTRAPOLATION_TICKS` (250 ms), then + holds. Out-of-order packets of the same life still fill gaps; stale and + duplicate ticks are ignored. +- **Discontinuities** clear the buffer and snap to the new state: spawn and + launch (a new buffer), despawn and dock, a new life or alive state + (respawn, death, jump), map changes and visits, alien encounter resets and + the end of a return home, and session start or end. The per-entity + sequence, visit and life checks are unchanged. +- **Immediate state.** Health, shields, alive, docked and energy apply on + arrival. Death and respawn are not delayed to the render time: the server + has already decided them, and targeting and the HUD must not show a + destroyed ship as attackable. A ship can therefore vanish up to the delay + plus jitter early, about 3 m at cruise speed. Its explosion is drawn at the + authoritative position, well within its diameter. +- **Effects.** Laser and explosion points within 8 m of an entity's newest + received position move by that entity's drawn offset + (`FlightSession.drawn_point`). Beams join the drawn ships: remote ships in + the past, the local ship ahead of the server. + +Tradeoff: remote ships are drawn about 100 ms plus the one-way latency in the +past. The server still decides hits on its current positions with no lag +compensation, so a pilot aims at a target that is further along than it is +drawn. Lag compensation, rewinding targets to the shooter's render time, is +out of scope and a possible later step. + +The F8 overlay adds one line: interpolation delay, buffer depth (how far the +newest snapshot is ahead of the render time, min / mean over 2 s), the share +of remote entity ticks extrapolated, and underruns ("dry"). The jitter line +now also shows clock drift. + +### Remote smoothness, before and after + +The benchmark now has the measured client, routed through the relay, watch +the first extra pilot, which flies the same pattern and turns. Once per +physics tick it compares the drawn ship with the server's path (definitions in +`tests/netcode_benchmark.gd`). *Before* is the phase 2 build +(`feat/netcode-ticks`, 8a63bb0) running the same benchmark file. The earlier +metrics keep their definitions. + +These runs shared the desktop with an unrelated heavy workload. The benchmark +process ran at 13–38 frames per second with three extra clients, not the +92–118 of phase 2. ENet is serviced once per frame, so snapshots arrived in +bursts. That inflates underruns and the main table's RTT column, which is why +the earlier tables are not repeated here. Both builds ran under the same load. +The last pair used one extra client, at 52 and 78 fps. + +| Added RTT | Loss | Build | Path error mean / p95 / max | Lag behind server | Drawn accel p95 / max | Spikes | Render-time error mean / p95 / max | Extrapolated | Buffer depth min / mean | +| ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 0 ms | 0% | before | 0.03 / 0.10 / 0.33 m | 113 ms | 1994 / 6707 m/s² | 86.1% | - | - | - | +| 0 ms | 0% | after | 0.00 / 0.01 / 0.18 m | 104 ms | 83 / 1136 m/s² | 1.8% | 0.00 / 0.01 / 0.21 m | 3.2% | -62 / 57 ms | +| 100 ms | 0% | before | 0.03 / 0.09 / 1.23 m | 158 ms | 1592 / 4618 m/s² | 86.5% | - | - | - | +| 100 ms | 0% | after | 0.00 / 0.01 / 0.66 m | 164 ms | 111 / 1015 m/s² | 2.6% | 0.00 / 0.01 / 0.19 m | 4.9% | -57 / 54 ms | +| 200 ms | 0% | before | 0.03 / 0.09 / 1.46 m | 211 ms | 1568 / 4514 m/s² | 85.9% | - | - | - | +| 200 ms | 0% | after | 0.01 / 0.01 / 1.14 m | 235 ms | 99 / 889 m/s² | 2.6% | 0.00 / 0.01 / 0.19 m | 6.9% | -72 / 56 ms | +| 0 ms | 5% | before | 0.03 / 0.10 / 0.50 m | 124 ms | 1990 / 4843 m/s² | 85.6% | - | - | - | +| 0 ms | 5% | after | 0.00 / 0.01 / 0.70 m | 120 ms | 115 / 882 m/s² | 3.4% | 0.01 / 0.03 / 0.15 m | 5.7% | -65 / 59 ms | +| 100 ms | 5% | before | 0.03 / 0.09 / 0.46 m | 165 ms | 1800 / 4868 m/s² | 84.8% | - | - | - | +| 100 ms | 5% | after | 0.00 / 0.01 / 0.41 m | 163 ms | 111 / 2328 m/s² | 3.0% | 0.01 / 0.03 / 0.52 m | 6.4% | -123 / 55 ms | +| 200 ms | 5% | before | 0.03 / 0.10 / 0.92 m | 213 ms | 1649 / 6602 m/s² | 85.0% | - | - | - | +| 200 ms | 5% | after | 0.01 / 0.01 / 1.14 m | 235 ms | 131 / 927 m/s² | 3.6% | 0.01 / 0.03 / 0.18 m | 6.4% | -73 / 54 ms | +| 150 ± 30 ms | 5% | before | 0.04 / 0.12 / 2.44 m | 215 ms | 2999 / 11859 m/s² | 83.9% | - | - | - | +| 150 ± 30 ms | 5% | after | 0.01 / 0.03 / 1.95 m | 203 ms | 118 / 2522 m/s² | 3.6% | 0.01 / 0.04 / 0.54 m | 8.5% | -127 / 60 ms | +| 150 ± 30 ms, 1 extra client | 5% | before | 0.03 / 0.10 / 0.81 m | 166 ms | 1610 / 4454 m/s² | 86.7% | - | - | - | +| 150 ± 30 ms, 1 extra client | 5% | after | 0.00 / 0.01 / 0.75 m | 185 ms | 81 / 2139 m/s² | 0.4% | 0.00 / 0.02 / 0.41 m | 1.0% | -96 / 64 ms | + +The server's own path measures 60 / 80 m/s² (p95 / max) in nearly every run. +A brush with the station's collision envelope can push its maximum toward +1000 m/s². Spikes are ticks whose drawn acceleration exceeds three times the +server's p95. + +### Observations + +- **The stutter is gone.** The old lerp chased a target that stepped at every + snapshot, so its drawn velocity jumped on most ticks. Its p95 acceleration + was 1.6–3.0 km/s², 25–50 times the real motion, even on a clean link. + Buffered Hermite interpolation draws within 1.3–2.2 times the server's own + p95, and the drawn path stays within centimetres of a path the ship really + flew. +- **The delay is similar.** The drawn ship trails the server by about 100 ms + plus the one-way latency (104–235 ms here). The old lerp trailed by a + similar amount through its smoothing lag, but its drawn path cut corners + and never sat on the real one. +- **Extrapolation is rare but sensitive to load.** At about 50 fps, 1% of + entity ticks are drawn past the newest sample. At 13–38 fps, arrivals + bunched into frames raise that to 3–9%. The peaks in the maximum columns + are the corrections when fresh samples replace an extrapolation. If + playtests on real links show underruns, raise the interpolation delay. +- `tests/interpolation_network_test.gd` checks the same measures through the + relay at 150 ± 30 ms with 5% loss. It also replays the old lerp from the same + packets and asserts that it stutters (80–86% spike ticks against 0–5%).