diff --git a/docs/netcode-baseline.md b/docs/netcode-baseline.md index b8b1a7e..22110a3 100644 --- a/docs/netcode-baseline.md +++ b/docs/netcode-baseline.md @@ -255,3 +255,140 @@ server's p95. - `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%). + +## After phase 4: snapshot quantization and deltas + +Network schema 26. The server packs public pilots and aliens once per +snapshot tick, then encodes a separate view for each recipient. Server tick, +sequence, visits, lives, encounters and profile revisions remain exact. +Reliable profiles still carry fitting and other infrequently changing state. +The owner retains float32 position, rotation, velocity and energy for +reconciliation and float64 hull and shields for exact repair costs. + +| Public field | Wire quantum | Maximum rounding error | +| --- | --- | --- | +| Position | Signed 24-bit per axis, 1/256 m relative to the map origin | 1/512 m per axis, 3.39 mm in 3D | +| Euler angles | Unsigned 16-bit per axis, one turn / 65,536 | 0.00275° per axis, modulo a turn | +| Hull and shields | Unsigned 24-bit each, ¼ point | ⅛ point over 0 to 4,194,303.75 | +| Pilot energy | Unsigned 16-bit, 1/256 point | 1/512 point over 0 to 100 | +| Time since hit | Unsigned 16-bit, 10 ms, capped at 6 s | 5 ms before the cap | + +The 1,200 m sector radius fits inside the ±32,768 m local position range. +An entity outside the quantized range carries its original float32 position. +The position bounds are relative to the input float32 coordinates at current +map origins. The server and owner retain the full hit timer for repair and +shield regeneration. The cap lets idle public records stop changing. +Radiation and alien respawn timers keep their existing float32 encoding. + +`FlightInput` carries a 32-bit snapshot acknowledgement. Flying clients +include it in their regular input packets, and idle clients send it on the +same channel without controls. The server accepts only acknowledgements for +that viewer's exact sent sequence in the current map visit. Both sides keep +a 32-snapshot history. Missing or expired acknowledgements and new visits +produce full snapshots. A client discards a delta if its named baseline +never arrived or has expired. + +Each part starts with four unsigned 32-bit values for sequence, visit, tick +and baseline. A baseline of zero marks a full snapshot. The header ends +with an 8-bit part index, an 8-bit part count and a 16-bit record count. +Each record has a 16-bit tag followed by a 32-bit pilot ID or 16-bit alien +ID. The tag's top two bits identify the kind. Its lower bits mark changed +field groups, from least to most significant. + +| Record | Field groups in mask order | +| --- | --- | +| Public pilot | Metadata, position, angles, hull, shields, energy, hit timer, radiation | +| Owner | Metadata, position, angles, hull, shields, energy, hit timer, radiation, velocity, input acknowledgement and buffer, input counters, progress and respawn, traffic metrics, ammunition, rockets and boosts | +| Alien | Metadata, position, angles, hull, shields, hit timer, respawn | + +New entities and changes to flags, profile revision or lifecycle metadata +send all groups. A zero mask repeats the entity's state at the new server +tick, so stationary entities keep filling their interpolation buffers. +Each snapshot lists current entities. An entity that leaves visibility +is absent from the new baseline. + +The encoder packs the owner first, then visible pilots and aliens in ID +order. It splits on record boundaries at 1,200 bytes per RPC payload. Godot +4.7.2's vendored ENet has a 1,392-byte default MTU and starts fragmenting +payloads above 1,364 bytes (1,360 with its optional checksum). The remaining +headroom covers the Godot RPC envelope, including the initial node path. +Parts can apply independently on arrival. The client acknowledges the +sequence only after every part arrives. +[ENet defaults](https://github.com/godotengine/godot/blob/4.7.2-stable/thirdparty/enet/enet/enet.h) +[Fragmentation](https://github.com/godotengine/godot/blob/4.7.2-stable/thirdparty/enet/peer.c#L98-L112) +[Godot RPC envelope](https://github.com/godotengine/godot/blob/4.7.2-stable/modules/multiplayer/scene_rpc_interface.cpp#L326-L430) + +F8 reports the viewer's server snapshot payload bytes per second, mean +bytes per snapshot tick, share of ticks using a baseline, and cumulative +full snapshots. Those counters cover world snapshot payloads before +transport overhead or loss. The existing Down rate and the relay +benchmarks measure ENet traffic, including reliable messages. + +### Relay benchmark + +Both builds used the same headless Godot 4.7.2 benchmark on Windows with +one relayed pilot and three directly connected pilots. Each condition +warmed up for 15 s and sampled for 20 s. Phase 3 is +`feat/snapshot-interpolation` at `7c9933a`. Server traffic is measured at +the relay before simulated loss and includes ENet overhead. The world-only +column uses the phase 4 server counter. Rates are decimal bytes per second. + +| Added RTT | Loss | Phase 3 server B/s / B/tick | Phase 4 server B/s / B/tick | Phase 4 world B/s / B/tick | Server rate saved | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 0 ms | 0% | 14351 / 718.6 | 5792 / 289.0 | 4959 / 247.4 | 59.6% | +| 100 ms | 0% | 14352 / 718.4 | 5287 / 263.7 | 4999 / 249.4 | 63.2% | +| 200 ms | 0% | 14356 / 718.2 | 5864 / 292.8 | 5040 / 251.6 | 59.2% | +| 0 ms | 5% | 14978 / 749.4 | 5228 / 261.4 | 4936 / 246.8 | 65.1% | +| 100 ms | 5% | 14353 / 718.6 | 5272 / 263.8 | 4985 / 249.4 | 63.3% | +| 200 ms | 5% | 14978 / 749.0 | 5863 / 293.2 | 5037 / 251.9 | 60.9% | +| 150 ± 30 ms | 5% | 14352 / 718.3 | 5229 / 265.5 | 4950 / 251.4 | 63.6% | + +Every measured phase 4 snapshot used a baseline after warm-up. Across all +seven conditions, both builds lost zero inputs and p95 reconciliation error +rounded to 0.00 m. The runs with the largest corrections also recorded +input-buffer catch-up drops or starvation. The owner packets use the same +state precision in both builds. + +| Added RTT | Loss | FPS before → after | Max reconciliation error (m) | p95 remote render-time error (m) | Drawn acceleration spikes | Extrapolated ticks | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 0 ms | 0% | 32 → 49 | 0.60 → 0.63 | 0.01 → 0.01 | 0.9% → 0.1% | 2.0% → 0.2% | +| 100 ms | 0% | 42 → 47 | 0.00 → 1.10 | 0.04 → 0.01 | 5.2% → 0.0% | 0.0% → 0.2% | +| 200 ms | 0% | 56 → 40 | 0.58 → 0.74 | 0.00 → 0.01 | 0.0% → 0.0% | 0.0% → 0.1% | +| 0 ms | 5% | 50 → 42 | 0.00 → 1.46 | 0.01 → 0.01 | 0.6% → 0.5% | 0.7% → 0.7% | +| 100 ms | 5% | 47 → 41 | 0.96 → 0.34 | 0.02 → 0.01 | 0.9% → 1.0% | 1.5% → 1.2% | +| 200 ms | 5% | 38 → 37 | 1.10 → 0.00 | 0.03 → 0.03 | 1.9% → 1.2% | 2.8% → 1.9% | +| 150 ± 30 ms | 5% | 44 → 23 | 2.11 → 1.17 | 0.01 → 0.15 | 0.3% → 5.3% | 0.6% → 9.4% | + +The four-pilot degraded run had a 357 ms maximum snapshot interval deviation +on phase 4. At 23 fps, its arrivals were less evenly paced than those in the +44 fps phase 3 run. Repeating just that condition with one extra pilot +produced comparable frame rates and the same p95 remote render error and +acceleration. Maximum render error and extrapolation still varied. + +| Two-pilot degraded repeat | FPS | Server B/s / B/tick | Max reconciliation error (m) | Remote render error p95 / max (m) | p95 drawn acceleration (m/s²) | Spikes | Extrapolated | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Phase 3 | 103 | 12,186 / 609.5 | 0.59 | 0.02 / 0.06 | 83 | 0.8% | 1.3% | +| Phase 4 | 102 | 5,211 / 260.5 | 0.62 | 0.02 / 0.15 | 83 | 1.2% | 2.1% | + +### Ten-pilot traffic + +`tests/snapshot_traffic_benchmark.gd` moves ten pilots and the five M1 aliens +on each of 100 snapshot ticks. It divides the server's ENet host counters by +the viewer and tick counts, then scales to 20 ticks/s. The fixture drives +snapshot sends directly and returns acknowledgements on schema 26. + +| Build | Server B/s per viewer at 20 Hz | Server B/tick per viewer | World B/tick per viewer | +| --- | ---: | ---: | ---: | +| Phase 3 | 22,529 | 1,126.4 | — | +| Phase 4 | 6,705 | 335.3 | 319.9 | + +ENet traffic dropped 70.2%. The phase 4 run used a baseline on every +measured tick. The separate MTU test forces a full snapshot with ten pilots +and twenty aliens, including reordered and incomplete part delivery. + +For phase 5, an initial steady-flight budget is 8,000 pre-loss ENet bytes/s +per viewer at 150 ± 30 ms and 5% loss, measured over 20 s with up to four +pilots. Both degraded runs were close to 5,200 B/s on phase 4. Joins, map +changes and prolonged gaps in acknowledgements send full snapshots. +Combat traffic adds reliable messages, so measure it separately before +setting a budget for the combined playthrough. diff --git a/scripts/flight_input.gd b/scripts/flight_input.gd index f581aa2..fbe1bf3 100644 --- a/scripts/flight_input.gd +++ b/scripts/flight_input.gd @@ -10,8 +10,11 @@ extends RefCounted ## ## Layout (little endian): ## u8 flags (FIRE), u32 life, i32 encounter, i32 target, u32 client tick of -## the newest input, u32 first sequence, u8 count, then per input: +## the newest input, u32 snapshot acknowledgement, u32 first sequence, +## u8 count, then per input: ## 3 x i8 movement (axis * 127), u16 yaw, i16 pitch, u8 flags (BOOST). +## Acknowledgement zero means no snapshot. A nonzero acknowledgement can +## travel alone while the player is docked or waiting to respawn. ## Movement and facing are quantized here, and clients predict with the ## quantized values, so the server and the client simulate the same numbers. @@ -21,7 +24,7 @@ const BOOST := 1 ## cover a burst of four lost packets. A playtesting setting. const REDUNDANCY := 10 const MAX_INPUTS := 16 -const HEADER_SIZE := 22 +const HEADER_SIZE := 26 const INPUT_SIZE := 8 const MOVEMENT_SCALE := 127.0 const YAW_SCALE := 65536.0 / TAU @@ -44,13 +47,14 @@ static func quantize_facing(angles: Vector3) -> Vector3: ## `inputs` hold {seq, movement, boost, facing} with consecutive sequences. -static func encode(life: int, fire: bool, encounter: int, target: int, client_tick: int, inputs: Array) -> PackedByteArray: +static func encode(life: int, fire: bool, encounter: int, target: int, client_tick: int, inputs: Array, snapshot_ack: int = 0) -> PackedByteArray: var buffer := StreamPeerBuffer.new() buffer.put_u8(FIRE if fire else 0) buffer.put_u32(life) buffer.put_32(encounter) buffer.put_32(target) buffer.put_u32(client_tick) + buffer.put_u32(snapshot_ack) buffer.put_u32(inputs[0]["seq"] if not inputs.is_empty() else 0) buffer.put_u8(inputs.size()) for input: Dictionary in inputs: @@ -64,7 +68,7 @@ static func encode(life: int, fire: bool, encounter: int, target: int, client_ti return buffer.data_array -## Returns {fire, life, encounter, target, tick, inputs: [{seq, movement, +## Returns {fire, life, encounter, target, tick, snapshot_ack, inputs: [{seq, movement, ## boost, facing}]}, or {} for a malformed packet. Values are always finite ## and in range, whatever the sender wrote. static func decode(packet: PackedByteArray) -> Dictionary: @@ -73,10 +77,12 @@ static func decode(packet: PackedByteArray) -> Dictionary: var buffer := StreamPeerBuffer.new() buffer.data_array = packet var result := {"fire": buffer.get_u8() & FIRE != 0, "life": buffer.get_u32(), "encounter": buffer.get_32(), - "target": buffer.get_32(), "tick": buffer.get_u32(), "inputs": []} + "target": buffer.get_32(), "tick": buffer.get_u32(), "snapshot_ack": buffer.get_u32(), "inputs": []} var first := buffer.get_u32() var count := buffer.get_u8() - if count < 1 or count > MAX_INPUTS or packet.size() != HEADER_SIZE + count * INPUT_SIZE: + if count > MAX_INPUTS or packet.size() != HEADER_SIZE + count * INPUT_SIZE: + return {} + if count == 0 and (result["snapshot_ack"] == 0 or result["fire"]): return {} for index in count: var movement := Vector3.ZERO diff --git a/scripts/flight_prediction.gd b/scripts/flight_prediction.gd index c2be169..6808a04 100644 --- a/scripts/flight_prediction.gd +++ b/scripts/flight_prediction.gd @@ -63,9 +63,9 @@ func predict(ship: Pilot, delta: float, movement: Vector3, boost: bool) -> void: ## The newest unacknowledged inputs, ready to send. -func packet(life: int, fire: bool, encounter: int, target: int) -> PackedByteArray: +func packet(life: int, fire: bool, encounter: int, target: int, snapshot_ack: int = 0) -> PackedByteArray: var inputs := pending.slice(maxi(0, pending.size() - FlightInput.REDUNDANCY)) - return FlightInput.encode(life, fire, encounter, target, client_tick, inputs) + return FlightInput.encode(life, fire, encounter, target, client_tick, inputs, snapshot_ack) ## Rewinds to the newest authoritative state and replays unacknowledged diff --git a/scripts/flight_session.gd b/scripts/flight_session.gd index 4525cc2..8e4df39 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 = 25 +const NETWORK_SCHEMA: int = 26 ## 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 @@ -48,6 +48,9 @@ var send_clock: float = 0.0 var connect_clock: float = 0.0 var received_snapshot: bool = false var snapshot_sequence: int = 0 +var sent_snapshots: Dictionary[int, SnapshotHistory] = {} +var received_snapshots := SnapshotHistory.new() +var snapshot_traffic: Dictionary[int, NetStats.SnapshotTraffic] = {} var player_sequences: Dictionary[int, int] = {} var alien_sequences: Dictionary[int, int] = {} # Client caches of rarely changing fields as [revision, profile], keyed by peer or alien ID. @@ -756,6 +759,8 @@ func despawn(id: int) -> void: ships[id].queue_free() jump_until.erase(id) sent_profiles.erase(id) + sent_snapshots.erase(id) + snapshot_traffic.erase(id) profile_revisions.erase(Vector2i(0, id)) profile_revisions.erase(Vector2i(1, id)) ships.erase(id) @@ -926,6 +931,8 @@ func predict_local(delta: float, movement: Vector3, boost: bool) -> void: var ship := sector.player if not ship.alive or sector.preflight: ship.set_visual_offset(Vector3.ZERO) + if prediction.client_tick % FlightPrediction.SEND_INTERVAL_TICKS == 0: + send_snapshot_ack() return prediction.reconcile(ship, delta, net_stats) prediction.predict(ship, delta, movement, boost) @@ -934,7 +941,7 @@ func predict_local(delta: float, movement: Vector3, boost: bool) -> void: var enemy := sector.target as Alien net_stats.input_packets_sent += 1 flight_inputs.rpc_id(1, prediction.packet(int(ship.get_meta("life", 0)), sector.auto_fire and enemy != null and not sector.paused, - enemy.life if enemy != null else -1, enemy.alien_id if enemy != null else -1)) + enemy.life if enemy != null else -1, enemy.alien_id if enemy != null else -1, snapshot_ack())) prediction.smooth(ship, delta) net_stats.unacked_inputs = prediction.pending.size() net_stats.record_visual_offset(ship.visual_offset.length()) @@ -945,7 +952,19 @@ func predict_local(delta: float, movement: Vector3, boost: bool) -> void: func send_command(movement: Vector3, angles: Vector3, boost: bool, fire: bool = false, life: int = 0, encounter: int = 0, target_id: int = -1) -> void: var input := {"seq": prediction.next_seq, "movement": movement, "boost": boost, "facing": angles} prediction.next_seq += 1 - flight_inputs.rpc_id(1, FlightInput.encode(life, fire, encounter, target_id, prediction.client_tick, [input])) + flight_inputs.rpc_id(1, FlightInput.encode(life, fire, encounter, target_id, prediction.client_tick, [input], snapshot_ack())) + + +func snapshot_ack() -> int: + received_snapshots.set_scope(sector.player.map_visit, sector.player.map_id) + return received_snapshots.acknowledged + + +## Idle clients still acknowledge snapshots through the flight input channel. +func send_snapshot_ack() -> void: + var ack := snapshot_ack() + if ack > 0: + flight_inputs.rpc_id(1, FlightInput.encode(0, false, -1, -1, prediction.client_tick, [], ack)) ## Server: forgets a pilot's intent and buffered inputs when its flight or life @@ -971,42 +990,67 @@ func send_snapshot() -> void: if multiplayer.get_peers().is_empty(): return snapshot_sequence += 1 - # Pack each entity once per tick, then batch everything on a viewer's map - # into one unreliable packet. Profiles go reliably, only when they change. + # Pack public entities once per tick. Each viewer gets its own delta, with + # the owner first. Profiles go reliably, only when they change. + var ids := ships.keys() + ids.sort() var entries: Dictionary[int, PackedByteArray] = {} var profiles: Dictionary[int, Array] = {} - for id: int in ships: + for id: int in ids: var data := player_state(id, false) profiles[id] = profile_revision(Vector2i(0, id), SnapshotCodec.player_profile(data)) entries[id] = SnapshotCodec.player_entry(id, data, profiles[id][0]) - var map_aliens: Dictionary[int, Array] = {} + var map_aliens: Dictionary[int, Dictionary] = {} var alien_profiles_by_map: Dictionary[int, Dictionary] = {} - for viewer: int in ships: + var alien_ids := sector.world_aliens.keys() + alien_ids.sort() + for viewer: int in ids: var map := ships[viewer].map_id if viewer == 1 or map_aliens.has(map): continue - var packed: Array[PackedByteArray] = [] + var packed := {} var known := {} - for enemy: Alien in sector.world_aliens.values(): + for alien_id in alien_ids: + var enemy: Alien = sector.world_aliens[alien_id] if enemy.map_id == map: var data := combat.pack_alien(enemy) known[enemy.alien_id] = profile_revision(Vector2i(2, enemy.alien_id), SnapshotCodec.alien_profile(data)) - packed.append(SnapshotCodec.alien_entry(data, known[enemy.alien_id][0])) + packed[Vector2i(SnapshotCodec.ALIEN, enemy.alien_id)] = SnapshotCodec.alien_entry(data, known[enemy.alien_id][0]) map_aliens[map] = packed alien_profiles_by_map[map] = known - for viewer: int in ships: + var now := Time.get_ticks_usec() + for viewer: int in ids: if viewer == 1: continue + var map := ships[viewer].map_id + var visit := ships[viewer].map_visit + if not sent_snapshots.has(viewer): + sent_snapshots[viewer] = SnapshotHistory.new() + snapshot_traffic[viewer] = NetStats.SnapshotTraffic.new() + var history := sent_snapshots[viewer] + var traffic := snapshot_traffic[viewer] + history.set_scope(visit, map) var own := player_state(viewer, true) var visible := {viewer: profile_revision(Vector2i(1, viewer), SnapshotCodec.player_profile(own))} - var players: Array[PackedByteArray] = [SnapshotCodec.player_entry(viewer, own, visible[viewer][0], owner_extras(viewer))] - for id: int in ships: - if id != viewer and not ships[id].get_meta("docked", false) and ships[id].map_id == ships[viewer].map_id: - players.append(entries[id]) + var extras := owner_extras(viewer) + extras["traffic"] = traffic.report + var frame := {Vector2i(SnapshotCodec.OWNER_PLAYER, viewer): SnapshotCodec.player_entry(viewer, own, visible[viewer][0], extras)} + for id: int in ids: + if id != viewer and not ships[id].get_meta("docked", false) and ships[id].map_id == map: + frame[Vector2i(SnapshotCodec.PUBLIC_PLAYER, id)] = entries[id] visible[id] = profiles[id] - var map := ships[viewer].map_id + frame.merge(map_aliens[map]) send_profiles(viewer, visible, alien_profiles_by_map[map]) - world_snapshot.rpc_id(viewer, SnapshotCodec.world(snapshot_sequence, ships[viewer].map_visit, server_tick, players, map_aliens[map])) + var baseline := history.baseline_for(snapshot_sequence) + var packets := SnapshotCodec.encode_world(snapshot_sequence, visit, server_tick, frame, baseline) + if packets.is_empty(): + continue + var bytes := 0 + for packet in packets: + world_snapshot.rpc_id(viewer, packet) + bytes += packet.size() + history.remember_sent(snapshot_sequence, frame) + traffic.record(bytes, not baseline.is_empty(), now) ## Private ammunition, rocket and boost state carried in the owner's entry. @@ -1063,6 +1107,12 @@ func flight_inputs(packet: PackedByteArray) -> void: var decoded := FlightInput.decode(packet) if not ships.has(id) or decoded.is_empty(): return + if sent_snapshots.has(id): + var history := sent_snapshots[id] + history.set_scope(ships[id].map_visit, ships[id].map_id) + history.acknowledge(decoded["snapshot_ack"]) + if decoded["inputs"].is_empty(): + return if ships[id].get_meta("docked", false): return if not ships[id].alive or combat.records[id]["life"] != decoded["life"]: @@ -1093,16 +1143,22 @@ 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"]): + var header := SnapshotCodec.header(packet) + if header.is_empty() or not receives_map(header["visit"]): + return + received_snapshots.set_scope(sector.player.map_visit, sector.player.map_id) + var world := received_snapshots.receive(packet, header) + if world.is_empty(): return 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"]) + if world["first_part"]: + net_stats.record_snapshot_arrival() + 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(): + net_stats.record_server_snapshot_traffic(sequence, owner["traffic"]) combat.ammo_snapshot(owner["rounds"], sequence, owner["rockets"], visit) if owner.has("boosts"): combat.boost_state(owner["boosts"], sequence, owner["revision"]) @@ -1237,6 +1293,9 @@ func disconnect_session(message: String) -> void: player_profiles.clear() alien_profiles.clear() sent_profiles.clear() + sent_snapshots.clear() + received_snapshots = SnapshotHistory.new() + snapshot_traffic.clear() profile_revisions.clear() jump_pending = false jump_until.clear() diff --git a/scripts/net_stats.gd b/scripts/net_stats.gd index 3ecd6ef..0ca3a06 100644 --- a/scripts/net_stats.gd +++ b/scripts/net_stats.gd @@ -1,6 +1,6 @@ class_name NetStats extends RefCounted -## Client-side netcode measurements fed by FlightSession, shown by the F8 +## 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. ## @@ -9,6 +9,9 @@ extends RefCounted ## (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). +## - server_snapshot_traffic: this viewer's world snapshot payload bytes per +## second and per snapshot tick, share of ticks using a baseline, and total +## full snapshots. The server measures these before ENet or relay loss. ## - 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. @@ -50,6 +53,8 @@ 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 server_snapshot_traffic: Dictionary = {} +var _traffic_sequence := 0 var snapshots_received: int = 0 ## Recent snapshot inter-arrival times in milliseconds, oldest first. var snapshot_intervals: PackedFloat32Array = [] @@ -108,6 +113,8 @@ func reset() -> void: down_packets_per_second = 0.0 total_up_bytes = 0 total_down_bytes = 0 + server_snapshot_traffic = {} + _traffic_sequence = 0 snapshots_received = 0 snapshot_intervals = PackedFloat32Array() has_server_state = false @@ -134,6 +141,43 @@ func reset() -> void: reset_extremes() +func record_server_snapshot_traffic(sequence: int, traffic: Dictionary) -> void: + if sequence > _traffic_sequence: + _traffic_sequence = sequence + server_snapshot_traffic = traffic + + +class SnapshotTraffic: + ## One server-side counter per viewer. Publish the latest complete window + ## in the owner's entry, where the readings themselves delta-compress. + var total_bytes := 0 + var full_fallbacks := 0 + var report: Dictionary = {} + var _window_start := -1 + var _window_bytes := 0 + var _window_ticks := 0 + var _window_deltas := 0 + + func record(bytes: int, delta_encoded: bool, now_usec: int) -> void: + if _window_start < 0: + _window_start = now_usec + total_bytes += bytes + _window_bytes += bytes + _window_ticks += 1 + _window_deltas += int(delta_encoded) + full_fallbacks += int(not delta_encoded) + var elapsed := now_usec - _window_start + if elapsed >= NetStats.SAMPLE_USEC: + report = {"bytes_per_second": roundi(_window_bytes * 1_000_000.0 / elapsed), + "bytes_per_tick": roundi(float(_window_bytes) / _window_ticks), + "delta_permille": roundi(_window_deltas * 1000.0 / _window_ticks), + "full_fallbacks": full_fallbacks} + _window_start = now_usec + _window_bytes = 0 + _window_ticks = 0 + _window_deltas = 0 + + ## Clears correction extremes and kept samples, keeping transport rates. func reset_extremes() -> void: latest_error_m = 0.0 diff --git a/scripts/netcode_overlay.gd b/scripts/netcode_overlay.gd index 17c7c44..9eac175 100644 --- a/scripts/netcode_overlay.gd +++ b/scripts/netcode_overlay.gd @@ -6,7 +6,7 @@ extends Control const SIZE := Vector2(340, 372) # Readings start here; the controls sit below them. -const LINE_HEIGHT := 16 +const LINE_HEIGHT := 14 const CONTROLS_TOP := 162 const REFRESH := 0.25 const DIRECTION_LABELS := ["Both ways (round trip)", "Upstream only", "Downstream only"] @@ -198,6 +198,10 @@ 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))]) + var traffic := stats.server_snapshot_traffic + lines.append("World %s/s %d B/tick %.1f%% delta %d full" % [ + String.humanize_size(traffic.get("bytes_per_second", 0)), traffic.get("bytes_per_tick", 0), + traffic.get("delta_permille", 0) / 10.0, traffic.get("full_fallbacks", 0)]) 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 "-"]) @@ -210,7 +214,7 @@ func _draw() -> void: 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 * LINE_HEIGHT), lines[index], HORIZONTAL_ALIGNMENT_LEFT, SIZE.x - 24, 14, FlightHud.INK if index == 0 else FlightHud.MUTED) + draw_string(font, Vector2(12, 42 + index * LINE_HEIGHT), lines[index], HORIZONTAL_ALIGNMENT_LEFT, SIZE.x - 24, 14, FlightHud.INK if index == 0 else FlightHud.MUTED) func update_ghost(shown: bool) -> void: diff --git a/scripts/snapshot_codec.gd b/scripts/snapshot_codec.gd index 7e9f91e..2089b9b 100644 --- a/scripts/snapshot_codec.gd +++ b/scripts/snapshot_codec.gd @@ -1,6 +1,6 @@ class_name SnapshotCodec extends RefCounted -## Compact binary world snapshot: one unreliable packet per viewer and tick. +## Compact binary world snapshots, sent unreliably. ## Frequently changing state is packed once per entity. Rarely changing profile ## fields (model, stats, fitting, contracts, alien kind and home) travel ## separately as reliable arrays only when they change; see FlightSession. @@ -14,6 +14,27 @@ const REPAIRING := 8 const BOOSTS := 16 const RETURNING := 4 const ENGAGED := 8 +const MAX_PACKET_BYTES := 1200 +const HEADER_BYTES := 20 +const PUBLIC_PLAYER := 0 +const OWNER_PLAYER := 1 +const ALIEN := 2 +const KIND_SHIFT := 14 +const POSITION_SCALE := 256.0 +const ANGLE_SCALE := 65536.0 / TAU +const HEALTH_SCALE := 4.0 +const ENERGY_SCALE := 256.0 +const HIT_TIME_SCALE := 100.0 +const HIT_TIME_LIMIT := 6.0 + +# Mask bits follow field order. Metadata (bit 0) includes flags, revision and +# identity epochs. A change there starts a full entity record. Zero widths are +# variable fields with a leading u8 length (position escape and private extras). +const FIELDS := [ + [12, 0, 6, 3, 3, 2, 2, 4], # public pilot + [12, 12, 12, 8, 8, 4, 4, 4, 12, 9, 24, 13, 12, 0], # owner + [8, 0, 6, 3, 3, 2, 4], # alien +] ## Server input counters carried in the owner entry; see InputBuffer. const INPUT_COUNTERS := ["applied", "duplicates", "late", "lost", "dropped", "starved"] @@ -35,15 +56,19 @@ static func player_entry(id: int, data: Dictionary, revision: int, extras: Dicti buffer.put_u32(data["life"]) buffer.put_u8(data["map"]) buffer.put_u32(data["visit"]) + if not owner: + put_public_pose(buffer, data) + buffer.put_u16(roundi(clampf(data["energy"], 0.0, 100.0) * ENERGY_SCALE)) + put_hit_time(buffer, data["since_hit"]) + buffer.put_float(systems[0]) + return buffer.data_array put_vector(buffer, data["position"]) put_vector(buffer, data["rotation"]) - # Health stays 64-bit so repair costs and HUD thresholds match the server exactly. + # Owner values retain the precision used for reconciliation and repair costs. buffer.put_double(data["hull"]) buffer.put_double(data["shield"]) for value: float in [data["energy"], data["since_hit"], systems[0]]: buffer.put_float(value) - if not owner: - return buffer.data_array put_vector(buffer, data["velocity"]) buffer.put_u32(extras.get("ack", 0)) buffer.put_u8(clampi(extras.get("depth", 0), 0, 255)) @@ -55,6 +80,13 @@ static func player_entry(id: int, data: Dictionary, revision: int, extras: Dicti buffer.put_u32(data["kills"]) buffer.put_u8(data["stage"]) buffer.put_float(data["respawn"]) + var traffic: Dictionary = extras.get("traffic", {}) + buffer.put_u32(traffic.get("bytes_per_second", 0)) + buffer.put_u16(traffic.get("bytes_per_tick", 0)) + buffer.put_u16(traffic.get("delta_permille", 0)) + buffer.put_u32(traffic.get("full_fallbacks", 0)) + var length_offset := buffer.get_position() + buffer.put_u8(0) var rounds: PackedInt32Array = extras.get("rounds", PackedInt32Array()) buffer.put_u8(rounds.size()) for value in rounds: @@ -78,7 +110,9 @@ static func player_entry(id: int, data: Dictionary, revision: int, extras: Dicti buffer.put_u8(ResourceBoosts.GROUPS.keys().find(group)) buffer.put_u8(ResourceBoosts.BONUSES.keys().find(boosts[group]["resource"])) buffer.put_double(boosts[group]["remaining"]) - return buffer.data_array + var entry := buffer.data_array + entry[length_offset] = entry.size() - length_offset - 1 + return entry ## Fields that change only with fitting, hull, repair extras or contracts. @@ -96,11 +130,8 @@ static func alien_entry(data: Dictionary, revision: int) -> PackedByteArray: buffer.put_u16(revision) buffer.put_u8(data["map"]) buffer.put_u32(data["encounter"]) - put_vector(buffer, data["position"]) - put_vector(buffer, data["rotation"]) - buffer.put_double(data["hull"]) - buffer.put_double(data["shield"]) - buffer.put_float(data["since_hit"]) + put_public_pose(buffer, data) + put_hit_time(buffer, data["since_hit"]) buffer.put_float(data["respawn"]) return buffer.data_array @@ -109,84 +140,305 @@ static func alien_profile(data: Dictionary) -> Array: return [data["kind"], data["home"]] -## `tick` is the server simulation tick the snapshot was taken after. -static func world(sequence: int, visit: int, tick: int, players: Array[PackedByteArray], aliens: Array[PackedByteArray]) -> PackedByteArray: - var buffer := StreamPeerBuffer.new() - buffer.put_u32(sequence) - buffer.put_u32(visit) - buffer.put_u32(tick) - buffer.put_u8(players.size()) - buffer.put_u8(aliens.size()) - var packet := buffer.data_array - for entry in players: - packet.append_array(entry) - for entry in aliens: - packet.append_array(entry) - return packet - - -## Returns {sequence, visit, tick, players: {id: state}, aliens: {id: state}, owner}. -## Each state's `profile` names its profile revision. States lack profile fields -## until merged with `player_state` or `alien_state`. `owner` holds ammunition, rockets and boosts, or is empty. -static func decode_world(packet: PackedByteArray) -> Dictionary: - if packet.size() < 14: +static func put_public_pose(buffer: StreamPeerBuffer, data: Dictionary) -> void: + var position: Vector3 = data["position"] - SectorMaps.origin(data["map"]) + var magnitude := position.abs() + if roundi(magnitude[magnitude.max_axis_index()] * POSITION_SCALE) <= 0x7fffff: + buffer.put_u8(9) + for axis in 3: + put_u24(buffer, roundi(position[axis] * POSITION_SCALE)) + else: + buffer.put_u8(12) + put_vector(buffer, data["position"]) + var rotation: Vector3 = data["rotation"] + for axis in 3: + buffer.put_u16(roundi(wrapf(rotation[axis], 0.0, TAU) * ANGLE_SCALE) & 0xffff) + for value: float in [data["hull"], data["shield"]]: + put_u24(buffer, clampi(roundi(value * HEALTH_SCALE), 0, 0xffffff)) + + +static func get_public_pose(buffer: StreamPeerBuffer, data: Dictionary) -> void: + var length := buffer.get_u8() + if length == 9: + var position := Vector3.ZERO + for axis in 3: + var value := get_u24(buffer) + position[axis] = (value - 0x1000000 if value & 0x800000 else value) / POSITION_SCALE + data["position"] = SectorMaps.origin(data["map"]) + position + else: + data["position"] = get_vector(buffer) + var rotation := Vector3.ZERO + for axis in 3: + var value := buffer.get_u16() + rotation[axis] = (value - 65536 if value >= 32768 else value) / ANGLE_SCALE + data["rotation"] = rotation + data["hull"] = get_u24(buffer) / HEALTH_SCALE + data["shield"] = get_u24(buffer) / HEALTH_SCALE + + +static func put_hit_time(buffer: StreamPeerBuffer, value: float) -> void: + # Only the local pilot needs the exact timer for repair eligibility. + buffer.put_u16(roundi(clampf(value, 0.0, HIT_TIME_LIMIT) * HIT_TIME_SCALE)) + + +static func put_u24(buffer: StreamPeerBuffer, value: int) -> void: + buffer.put_u16(value & 0xffff) + buffer.put_u8((value >> 16) & 0xff) + + +static func get_u24(buffer: StreamPeerBuffer) -> int: + return buffer.get_u16() | (buffer.get_u8() << 16) + + +## Entries are keyed by (record kind, entity ID). Owner and public entries +## always have distinct keys, including in the baseline. +static func player_key(entry: PackedByteArray) -> Vector2i: + return Vector2i(OWNER_PLAYER if entry[4] & OWNER else PUBLIC_PLAYER, entry.decode_u32(0)) + + +static func alien_key(entry: PackedByteArray) -> Vector2i: + return Vector2i(ALIEN, entry.decode_u16(0)) + + +## A part carries an exact sequence, visit, tick and baseline sequence (zero +## for full state). Parts can be applied as they arrive. Only a complete set +## can be acknowledged and used as a baseline. +static func encode_world(sequence: int, visit: int, tick: int, entries: Dictionary, baseline: Dictionary = {}) -> Array[PackedByteArray]: + var packets: Array[PackedByteArray] = [] + var packet := PackedByteArray() + packet.resize(HEADER_BYTES) + var old: Dictionary = baseline.get("entries", {}) + var count := 0 + for key: Vector2i in entries: + var record := encode_record(key.x, entries[key], old.get(key, PackedByteArray())) + if record.size() > MAX_PACKET_BYTES - HEADER_BYTES: + push_error("Snapshot entity exceeds the packet budget") + return [] + if packet.size() + record.size() > MAX_PACKET_BYTES: + packet.encode_u16(18, count) + packets.append(packet) + packet = PackedByteArray() + packet.resize(HEADER_BYTES) + count = 0 + packet.append_array(record) + count += 1 + packet.encode_u16(18, count) + packets.append(packet) + if packets.size() > 255: + push_error("Snapshot exceeds the part count limit") + return [] + for index in packets.size(): + packet = packets[index] + packet.encode_u32(0, sequence) + packet.encode_u32(4, visit) + packet.encode_u32(8, tick) + packet.encode_u32(12, baseline.get("sequence", 0)) + packet[16] = index + packet[17] = packets.size() + packets[index] = packet + return packets + + +static func encode_record(kind: int, entry: PackedByteArray, old: PackedByteArray) -> PackedByteArray: + var id_size := 2 if kind == ALIEN else 4 + var widths: Array = FIELDS[kind] + var record := PackedByteArray([0, 0]) + var mask := kind << KIND_SHIFT + if entry == old: + record.encode_u16(0, mask) + record.append_array(entry.slice(0, id_size)) + return record + if old.is_empty() or entry.slice(id_size, id_size + widths[0]) != old.slice(id_size, id_size + widths[0]): + record.encode_u16(0, mask | ((1 << widths.size()) - 1)) + record.append_array(entry) + return record + record.append_array(entry.slice(0, id_size)) + var offset := id_size + var previous := id_size + for bit in widths.size(): + var width: int = widths[bit] if widths[bit] != 0 else entry[offset] + 1 + var old_width: int = widths[bit] if widths[bit] != 0 else old[previous] + 1 + var field := entry.slice(offset, offset + width) + if width != old_width or field != old.slice(previous, previous + old_width): + mask |= 1 << bit + record.append_array(field) + offset += width + previous += old_width + record.encode_u16(0, mask) + return record + + +static func header(packet: PackedByteArray) -> Dictionary: + if packet.size() < HEADER_BYTES or packet.size() > MAX_PACKET_BYTES or packet[16] >= packet[17]: + return {} + var sequence := packet.decode_u32(0) + var baseline := packet.decode_u32(12) + if sequence == 0 or baseline >= sequence: return {} + return {"sequence": sequence, "visit": packet.decode_u32(4), "tick": packet.decode_u32(8), + "baseline": baseline, "part": packet[16], "parts": packet[17]} + + +## Reconstructs this part's packed entries using the exact acknowledged state. +## An entity with a zero mask still yields a sample for this server tick. +static func decode_world(packet: PackedByteArray, baseline: Dictionary = {}) -> Dictionary: + var result := header(packet) + if result.is_empty() or result["baseline"] != baseline.get("sequence", 0): + return {} + if not baseline.is_empty() and result["visit"] != baseline["visit"]: + return {} + var old: Dictionary = baseline.get("entries", {}) + var entries := {} + var offset := HEADER_BYTES + for index in packet.decode_u16(18): + if offset + 2 > packet.size(): + return {} + var tag := packet.decode_u16(offset) + var kind := tag >> KIND_SHIFT + var mask := tag & ((1 << KIND_SHIFT) - 1) + var id_size := 2 if kind == ALIEN else 4 + offset += 2 + if kind >= FIELDS.size() or offset + id_size > packet.size(): + return {} + var id := packet.decode_u16(offset) if kind == ALIEN else packet.decode_u32(offset) + var key := Vector2i(kind, id) + if entries.has(key): + return {} + var widths: Array = FIELDS[kind] + var full_mask := (1 << widths.size()) - 1 + if mask > full_mask: + return {} + var entry := packet.slice(offset, offset + id_size) + offset += id_size + var previous: PackedByteArray = old.get(key, PackedByteArray()) + if mask != full_mask and previous.is_empty(): + return {} + if mask == 0: + entries[key] = previous + continue + var old_offset := id_size + for bit in widths.size(): + var width: int = widths[bit] + var old_width := width + if not previous.is_empty() and width == 0: + old_width = previous[old_offset] + 1 + if mask & (1 << bit): + if width == 0: + if offset >= packet.size(): + return {} + width = packet[offset] + 1 + if bit == 1 and width not in [10, 13]: + return {} + if offset + width > packet.size(): + return {} + entry.append_array(packet.slice(offset, offset + width)) + offset += width + else: + entry.append_array(previous.slice(old_offset, old_offset + old_width)) + old_offset += old_width + entries[key] = entry + if offset != packet.size(): + return {} + result["entries"] = entries + result["players"] = {} + result["aliens"] = {} + result["owner"] = {} + for key: Vector2i in entries: + if not decode_entry(key, entries[key], result): + return {} + return result + + +static func decode_entry(key: Vector2i, entry: PackedByteArray, result: Dictionary) -> bool: var buffer := StreamPeerBuffer.new() - buffer.data_array = packet - var result := {"sequence": buffer.get_u32(), "visit": buffer.get_u32(), "tick": buffer.get_u32(), "players": {}, "aliens": {}, "owner": {}} - var player_count := buffer.get_u8() - var alien_count := buffer.get_u8() - for index in range(player_count): - var id := buffer.get_u32() + buffer.data_array = entry + if key.x == ALIEN: + buffer.seek(2) var flags := buffer.get_u8() + var data := {"id": key.y, "profile": buffer.get_u16(), "alive": flags & ALIVE != 0, "returning": flags & RETURNING != 0, + "engaged": flags & ENGAGED != 0, "map": buffer.get_u8(), "encounter": buffer.get_u32()} + get_public_pose(buffer, data) + data["since_hit"] = buffer.get_u16() / HIT_TIME_SCALE + data["respawn"] = buffer.get_float() + result["aliens"][key.y] = data + else: + buffer.seek(4) + var flags := buffer.get_u8() + if (flags & OWNER != 0) != (key.x == OWNER_PLAYER) or result["players"].has(key.y): + return false var data := {"profile": buffer.get_u16(), "life": buffer.get_u32(), "map": buffer.get_u8(), "visit": buffer.get_u32(), - "position": get_vector(buffer), "rotation": get_vector(buffer), "hull": buffer.get_double(), - "shield": buffer.get_double(), "energy": buffer.get_float(), "since_hit": buffer.get_float()} - data["alive"] = flags & ALIVE != 0 - data["docked"] = flags & DOCKED != 0 - data["radiation"] = buffer.get_float() - data["repairing"] = flags & REPAIRING != 0 - if flags & OWNER: + "alive": flags & ALIVE != 0, "docked": flags & DOCKED != 0, "repairing": flags & REPAIRING != 0} + if key.x == PUBLIC_PLAYER: + get_public_pose(buffer, data) + data["energy"] = buffer.get_u16() / ENERGY_SCALE + data["since_hit"] = buffer.get_u16() / HIT_TIME_SCALE + data["radiation"] = buffer.get_float() + else: + if not result["owner"].is_empty(): + return false + data["position"] = get_vector(buffer) + data["rotation"] = get_vector(buffer) + data["hull"] = buffer.get_double() + data["shield"] = buffer.get_double() + data["energy"] = buffer.get_float() + data["since_hit"] = buffer.get_float() + data["radiation"] = buffer.get_float() data["velocity"] = get_vector(buffer) data["ack"] = buffer.get_u32() data["input_depth"] = buffer.get_u8() data["turn_budget"] = buffer.get_float() var inputs := {} - for key: String in INPUT_COUNTERS: - inputs[key] = buffer.get_u32() + for counter: String in INPUT_COUNTERS: + inputs[counter] = buffer.get_u32() data["inputs"] = inputs data["credits"] = buffer.get_u32() data["kills"] = buffer.get_u32() data["stage"] = buffer.get_u8() data["respawn"] = buffer.get_float() - var owner := {"rounds": PackedInt32Array(), "rockets": {}} - for count in range(buffer.get_u8()): + var traffic := {"bytes_per_second": buffer.get_u32(), "bytes_per_tick": buffer.get_u16(), + "delta_permille": buffer.get_u16(), "full_fallbacks": buffer.get_u32()} + var owner := {"rounds": PackedInt32Array(), "rockets": {}, "traffic": traffic} + var length := buffer.get_u8() + if length < 2 or buffer.get_available_bytes() != length: + return false + var rounds := buffer.get_u8() + if buffer.get_available_bytes() < rounds * 4 + 1: + return false + for count in rounds: owner["rounds"].append(buffer.get_32()) if buffer.get_u8() == 1: - owner["rockets"] = {"single_type": Ammunition.ROCKETS.keys()[buffer.get_u8()], - "launcher_type": Ammunition.ROCKETS.keys()[buffer.get_u8()], + if buffer.get_available_bytes() < 19: + return false + var single := buffer.get_u8() + var launcher := buffer.get_u8() + if single >= Ammunition.ROCKETS.size() or launcher >= Ammunition.ROCKETS.size(): + return false + owner["rockets"] = {"single_type": Ammunition.ROCKETS.keys()[single], + "launcher_type": Ammunition.ROCKETS.keys()[launcher], "single_cooldown": buffer.get_float(), "launcher_cooldown": buffer.get_float(), "capacity": buffer.get_u16(), "loaded": buffer.get_u16(), "loading": buffer.get_u8() == 1, "load_clock": buffer.get_float()} if flags & BOOSTS: + if buffer.get_available_bytes() < 5: + return false owner["revision"] = buffer.get_u32() var boosts := {} - for count in range(buffer.get_u8()): - var group: String = ResourceBoosts.GROUPS.keys()[buffer.get_u8()] - var resource: String = ResourceBoosts.BONUSES.keys()[buffer.get_u8()] + var boost_count := buffer.get_u8() + if buffer.get_available_bytes() != boost_count * 10: + return false + for count in boost_count: + var group_id := buffer.get_u8() + var resource_id := buffer.get_u8() + if group_id >= ResourceBoosts.GROUPS.size() or resource_id >= ResourceBoosts.BONUSES.size(): + return false + var group: String = ResourceBoosts.GROUPS.keys()[group_id] + var resource: String = ResourceBoosts.BONUSES.keys()[resource_id] var remaining := buffer.get_double() boosts[group] = {"resource": resource, "remaining": int(remaining) if group in ["lasers", "rockets"] else remaining} owner["boosts"] = boosts result["owner"] = owner - result["players"][id] = data - for index in range(alien_count): - var id := buffer.get_u16() - var flags := buffer.get_u8() - result["aliens"][id] = {"id": id, "profile": buffer.get_u16(), "alive": flags & ALIVE != 0, "returning": flags & RETURNING != 0, - "engaged": flags & ENGAGED != 0, "map": buffer.get_u8(), "encounter": buffer.get_u32(), - "position": get_vector(buffer), "rotation": get_vector(buffer), "hull": buffer.get_double(), - "shield": buffer.get_double(), "since_hit": buffer.get_float(), "respawn": buffer.get_float()} - return result if buffer.get_position() == packet.size() else {} + result["players"][key.y] = data + return buffer.get_available_bytes() == 0 ## Rebuilds the same dictionary as `FlightSession.player_state`. diff --git a/scripts/snapshot_history.gd b/scripts/snapshot_history.gd new file mode 100644 index 0000000..e80342a --- /dev/null +++ b/scripts/snapshot_history.gd @@ -0,0 +1,81 @@ +class_name SnapshotHistory +extends RefCounted +## One viewer's packed snapshot states, scoped to its map visit. Both ends +## retain a 32-snapshot window (1.6 s at 20 Hz). A ring slot always names its +## exact sequence, so loss, reordering and slot reuse cannot substitute a base. + +const CAPACITY := 32 + +var acknowledged := 0 +var visit := -1 +var map := -1 +var newest := 0 +var frames: Dictionary[int, Dictionary] = {} + + +func set_scope(next_visit: int, next_map: int) -> void: + if visit == next_visit and map == next_map: + return + visit = next_visit + map = next_map + acknowledged = 0 + newest = 0 + frames.clear() + + +func find(sequence: int) -> Dictionary: + if sequence <= 0 or newest - sequence >= CAPACITY: + return {} + var frame: Dictionary = frames.get(sequence % CAPACITY, {}) + return frame if frame.get("sequence") == sequence else {} + + +func remember_sent(sequence: int, entries: Dictionary) -> void: + frames[sequence % CAPACITY] = {"sequence": sequence, "visit": visit, "entries": entries} + newest = sequence + + +func acknowledge(sequence: int) -> void: + if sequence > acknowledged and not find(sequence).is_empty(): + acknowledged = sequence + + +func baseline_for(sequence: int) -> Dictionary: + var age := sequence - acknowledged + if age <= 0 or age >= CAPACITY: + return {} + return find(acknowledged) + + +func receive(packet: PackedByteArray, header: Dictionary) -> Dictionary: + if header.is_empty() or header["visit"] != visit: + return {} + var sequence: int = header["sequence"] + var part: int = header["part"] + if newest - sequence >= CAPACITY: + return {} + var frame := find(sequence) + if not frame.is_empty() and (frame["received"].has(part) or frame["parts"] != header["parts"] + or frame["tick"] != header["tick"] or frame["baseline"] != header["baseline"]): + return {} + var baseline := find(header["baseline"]) + if header["baseline"] != 0 and (baseline.is_empty() or baseline["received"].size() != baseline["parts"]): + return {} + var world := SnapshotCodec.decode_world(packet, baseline) + if world.is_empty(): + return {} + world["first_part"] = frame.is_empty() + if frame.is_empty(): + frame = header.duplicate() + frame["received"] = {} + frame["entries"] = {} + for key: Vector2i in world["entries"]: + if frame["entries"].has(key): + return {} + frame["entries"].merge(world["entries"]) + frame["received"][part] = true + frames[sequence % CAPACITY] = frame + newest = maxi(newest, sequence) + if frame["received"].size() == frame["parts"]: + acknowledged = maxi(acknowledged, sequence) + return world diff --git a/scripts/snapshot_history.gd.uid b/scripts/snapshot_history.gd.uid new file mode 100644 index 0000000..afcbdb6 --- /dev/null +++ b/scripts/snapshot_history.gd.uid @@ -0,0 +1 @@ +uid://4uudwiae3mug diff --git a/tests/alien_sector_test.gd b/tests/alien_sector_test.gd index c38f401..58b5a01 100644 --- a/tests/alien_sector_test.gd +++ b/tests/alien_sector_test.gd @@ -117,7 +117,10 @@ func run() -> void: await replicate(server) for enemy: Alien in server.aliens.values(): var copy := late.aliens[enemy.alien_id] - check(copy.kind == enemy.kind and copy.life == enemy.life and copy.alive == enemy.alive and copy.returning == enemy.returning and copy.hull == enemy.hull and copy.shield == enemy.shield and is_equal_approx(copy.respawn, enemy.respawn) and copy.position.is_equal_approx(enemy.position), "Late join receives current identity, position, health, reset and respawn state") + check(copy.kind == enemy.kind and copy.life == enemy.life and copy.alive == enemy.alive and copy.returning == enemy.returning + and absf(copy.hull - enemy.hull) <= 0.125 and absf(copy.shield - enemy.shield) <= 0.125 + and is_equal_approx(copy.respawn, enemy.respawn) and copy.position.distance_to(enemy.position) <= 0.0034, + "Late join receives exact identity and respawn state and bounded public pose and health") # Reject stale snapshots independently; another entity's older chunk is still useful. var newer := combat.pack_alien(heavy) newer["hull"] = 200.0 diff --git a/tests/input_buffer_test.gd b/tests/input_buffer_test.gd index 89b38b1..e4b3c03 100644 --- a/tests/input_buffer_test.gd +++ b/tests/input_buffer_test.gd @@ -142,10 +142,11 @@ func run() -> void: var inputs: Array = [] for seq in range(100, 100 + FlightInput.REDUNDANCY): inputs.append({"seq": seq, "movement": Vector3(0.5, -1.0, 0.25), "boost": seq % 2 == 0, "facing": Vector3(1.2, -2.5, 0)}) - var packet := FlightInput.encode(7, true, 12, 3, 999, inputs) - check(packet.size() == FlightInput.HEADER_SIZE + inputs.size() * FlightInput.INPUT_SIZE and packet.size() <= 102, "Input packets stay compact (%d bytes)" % packet.size()) + var packet := FlightInput.encode(7, true, 12, 3, 999, inputs, 4_000_000_000) + check(packet.size() == FlightInput.HEADER_SIZE + inputs.size() * FlightInput.INPUT_SIZE and packet.size() <= 106, "Input packets with a snapshot acknowledgement stay compact (%d bytes)" % packet.size()) var decoded := FlightInput.decode(packet) check(decoded["life"] == 7 and decoded["fire"] and decoded["encounter"] == 12 and decoded["target"] == 3 and decoded["tick"] == 999, "Packet header fields round trip") + check(decoded["snapshot_ack"] == 4_000_000_000, "Flight packets carry the full unsigned snapshot acknowledgement") var exact := true for index in inputs.size(): var original: Dictionary = inputs[index] @@ -157,6 +158,9 @@ func run() -> void: check(is_equal_approx(FlightInput.quantize_facing(Vector3(9.0, 4.0, 0)).x, 1.48) and absf(FlightInput.quantize_facing(Vector3(0, 4.0, 0)).y - wrapf(4.0, -PI, PI)) < 0.0001, "Facing is clamped and wrapped like server validation") check(FlightInput.decode(packet.slice(0, packet.size() - 1)).is_empty() and FlightInput.decode(packet + PackedByteArray([0])).is_empty() and FlightInput.decode(PackedByteArray()).is_empty(), "Truncated or oversized packets are rejected") var empty := FlightInput.encode(1, false, 0, 0, 0, []) - check(FlightInput.decode(empty).is_empty(), "Packets without inputs are rejected") + check(FlightInput.decode(empty).is_empty(), "Packets without inputs or a snapshot acknowledgement are rejected") + var ack_only := FlightInput.decode(FlightInput.encode(1, false, -1, -1, 0, [], 42)) + check(ack_only.get("snapshot_ack") == 42 and ack_only["inputs"].is_empty(), "An idle pilot acknowledges snapshots without inputs") + check(FlightInput.decode(FlightInput.encode(1, true, -1, -1, 0, [], 42)).is_empty(), "An acknowledgement alone cannot request fire") print("Input buffer checks: %d passed, %d failed" % [checks - failures, failures]) quit(0 if failures == 0 else 1) diff --git a/tests/netcode_benchmark.gd b/tests/netcode_benchmark.gd index a31d3ad..8849380 100644 --- a/tests/netcode_benchmark.gd +++ b/tests/netcode_benchmark.gd @@ -30,6 +30,10 @@ extends "res://tests/network_test.gd" ## - 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. +## - server_bytes_per_snapshot: the relay's server bytes divided by the number +## of server snapshot ticks. On schema 26+, world_bps and +## world_bytes_per_snapshot count only this viewer's snapshot payloads. +## delta_share and full_fallbacks describe baseline use in the sample. ## - 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: simulation error at each reconciliation: how far rewinding to @@ -176,6 +180,11 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> var inputs_before: Dictionary = server.session.input_buffers[id].counters() var up_before := net.total_up_bytes var down_before := net.total_down_bytes + var snapshots_before := server.session.snapshot_sequence + var traffic: Variant = server.session.get("snapshot_traffic") + var viewer: Variant = traffic.get(id) if traffic != null else null + var payload_before: int = viewer.total_bytes if viewer != null else 0 + var full_before: int = viewer.full_fallbacks if viewer != null else 0 var host: ENetConnection = (server.multiplayer.multiplayer_peer as ENetMultiplayerPeer).host host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) var started := Time.get_ticks_usec() @@ -196,6 +205,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] + var sent_snapshots := server.session.snapshot_sequence - snapshots_before 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), @@ -203,6 +213,7 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> "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_bytes_per_snapshot": snappedf(float(relay_stats["down"]["received_bytes"]) / maxi(1, sent_snapshots), 0.1), "server_avg_bps": roundi(server_bytes / seconds / clients), "snapshots": net.jitter_samples.size(), "jitter_mean_ms": snappedf(NetStats.mean(net.jitter_samples), 0.1), @@ -225,6 +236,12 @@ 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"], } + if viewer != null and sent_snapshots > 0: + var payload: int = viewer.total_bytes - payload_before + row["world_bps"] = roundi(payload / seconds) + row["world_bytes_per_snapshot"] = snappedf(float(payload) / sent_snapshots, 0.1) + row["full_fallbacks"] = viewer.full_fallbacks - full_before + row["delta_share"] = 1.0 - float(row["full_fallbacks"]) / sent_snapshots row.merge(remote_metrics(net)) return row diff --git a/tests/netsim_network_test.gd b/tests/netsim_network_test.gd index 3b9b614..13e1a57 100644 --- a/tests/netsim_network_test.gd +++ b/tests/netsim_network_test.gd @@ -38,7 +38,11 @@ func run() -> void: 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.up_bytes_per_second > 0.0 and net.down_bytes_per_second > 0.0, "Client traffic rates are sampled") + var traffic := net.server_snapshot_traffic + check(traffic.get("bytes_per_second", 0) > 0 and traffic.get("bytes_per_tick", 0) > 0 + and traffic.get("delta_permille", 0) > 0 and traffic.get("full_fallbacks", 0) > 0, + "The server reports bytes and baseline use to the relayed viewer") 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 applied: int = inputs.get("applied", 0) diff --git a/tests/network_combat_test.gd b/tests/network_combat_test.gd index 0b756cb..bfdc655 100644 --- a/tests/network_combat_test.gd +++ b/tests/network_combat_test.gd @@ -124,7 +124,7 @@ func run() -> void: alien.home_position = alien.position await physics_frame await replicate(host) - check(client.alien.position.is_equal_approx(alien.position), "Client receives the host's alien position") + check(client.alien.position.distance_to(alien.position) <= 0.0034, "Client receives the host's alien position within the public wire quantum") client.alien.take_damage(client.alien.max_hull + client.alien.max_shield + 1.0, client.player) check(client.alien.alive and client.alien.hull == alien.hull, "Client cannot apply local damage") check(not client.player.try_fire(client.alien), "Client cannot simulate an authoritative shot") @@ -187,7 +187,7 @@ func run() -> void: late.session.join("127.0.0.1", test_port(24681)) await settle(0.5) await replicate(host) - check(late.alien.shield == damaged_shield and alien.shield == damaged_shield, "Late join preserves and receives current alien health") + check(absf(late.alien.shield - damaged_shield) <= 0.125 and alien.shield == damaged_shield, "Late join preserves server health and receives the quantized shield") var late_id := late.multiplayer.get_unique_id() check(host.player in host.session.ships.values(), "Host retains its own ship") # The client is closer, so the alien attacks it rather than always targeting the host. diff --git a/tests/rpc_compatibility_test.gd b/tests/rpc_compatibility_test.gd index 2d48846..199122a 100644 --- a/tests/rpc_compatibility_test.gd +++ b/tests/rpc_compatibility_test.gd @@ -66,7 +66,9 @@ 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 == 25, "Profile revisions change the protocol fingerprint") + check(preview != server.session.protocol_fingerprint(), "Profile revisions change the protocol fingerprint") + check(FlightSession.NETWORK_SCHEMA == 26 and server.session.protocol_fingerprint(25) != server.session.protocol_fingerprint(), + "Delta snapshots and their input acknowledgements 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)) diff --git a/tests/snapshot_codec_test.gd b/tests/snapshot_codec_test.gd index 2192c1c..0efca52 100644 --- a/tests/snapshot_codec_test.gd +++ b/tests/snapshot_codec_test.gd @@ -16,7 +16,8 @@ func same(a: Variant, b: Variant) -> bool: func round_trip_player(id: int, data: Dictionary, extras: Dictionary = {}) -> Dictionary: - var packet := SnapshotCodec.world(7, 3, 4242, [SnapshotCodec.player_entry(id, data, 65535, extras)], []) + var entry := SnapshotCodec.player_entry(id, data, 65535, extras) + var packet := SnapshotCodec.encode_world(7, 3, 4242, {SnapshotCodec.player_key(entry): entry})[0] var world := SnapshotCodec.decode_world(packet) check(world.get("sequence") == 7 and world.get("visit") == 3 and world["players"].has(id) and world["players"][id]["profile"] == 65535, "World header, player ID and profile revision decode") return world @@ -62,7 +63,7 @@ func run() -> void: var other := second.multiplayer.get_unique_id() var ship := session.ships[id] - # Public player state survives the binary entry and the reliable profile. + # Public player state combines quantized fields with the reliable profile. session.ships[other].position = Vector3(12.5, -40.25, 1999.75) session.ships[other].rotation = Vector3(0.3, -2.1, 0.0) session.ships[other].radiation_exposure = 4.5 @@ -72,6 +73,9 @@ func run() -> void: var world := round_trip_player(other, public) var decoded := SnapshotCodec.player_state(world["players"][other], SnapshotCodec.player_profile(public)) public.erase("velocity") # Only owners use their velocity; viewers interpolate positions. + public["rotation"] = Vector3(0.3, -2.1, 0.0).snapped(Vector3.ONE / SnapshotCodec.ANGLE_SCALE) + public["hull"] = snappedf(public["hull"], 0.25) + public["since_hit"] = minf(public["since_hit"], SnapshotCodec.HIT_TIME_LIMIT) check(same(decoded, public), "Public player state packs and unpacks") check(world["owner"].is_empty() and SessionCombat.PRIVATE_FIELDS.all(func(field: String) -> bool: return not decoded.has(field)), "Public entries carry no private progress") check(SnapshotCodec.player_profile(public).size() == 4, "Public profiles omit contracts") @@ -109,19 +113,24 @@ func run() -> void: enemy.engaged = true enemy.respawn = 2.5 var alien := combat.pack_alien(enemy) - var alien_packet := SnapshotCodec.world(9, 0, 1, [], [SnapshotCodec.alien_entry(alien, 9)]) + var alien_entry := SnapshotCodec.alien_entry(alien, 9) + var alien_packet := SnapshotCodec.encode_world(9, 0, 1, {SnapshotCodec.alien_key(alien_entry): alien_entry})[0] world = SnapshotCodec.decode_world(alien_packet) + alien["position"] = alien["position"].snapped(Vector3.ONE / SnapshotCodec.POSITION_SCALE) + alien["since_hit"] = minf(alien["since_hit"], SnapshotCodec.HIT_TIME_LIMIT) check(world["aliens"][enemy.alien_id]["profile"] == 9 and same(SnapshotCodec.alien_state(world["aliens"][enemy.alien_id], SnapshotCodec.alien_profile(alien)), alien), "Alien state and profile revision pack and unpack") check(SnapshotCodec.decode_world(alien_packet.slice(0, 8)).is_empty() and SnapshotCodec.decode_world(alien_packet + PackedByteArray([0])).is_empty(), "Short or oversized packets are rejected") # Ten pilots and five aliens fit one datagram and shrink at least fivefold. - var players: Array[PackedByteArray] = [SnapshotCodec.player_entry(id, owner, 1, extras)] + var owner_entry := SnapshotCodec.player_entry(id, owner, 1, extras) + var entries := {SnapshotCodec.player_key(owner_entry): owner_entry} for index in range(9): - players.append(SnapshotCodec.player_entry(other, session.player_state(other, false), 1)) - var aliens: Array[PackedByteArray] = [] + var entry := SnapshotCodec.player_entry(index + 1, session.player_state(other, false), 1) + entries[SnapshotCodec.player_key(entry)] = entry for each: Alien in server.map_rosters[0].values(): - aliens.append(SnapshotCodec.alien_entry(combat.pack_alien(each), 1)) - var batch := var_to_bytes(SnapshotCodec.world(1, 0, 1, players, aliens)).size() + var entry := SnapshotCodec.alien_entry(combat.pack_alien(each), 1) + entries[SnapshotCodec.alien_key(entry)] = entry + var batch := var_to_bytes(SnapshotCodec.encode_world(1, 0, 1, entries)[0]).size() var legacy := legacy_bytes(server, id) + 8 * var_to_bytes([{other: session.player_state(other, false)}, {}, 1, 0]).size() print("SNAPSHOT_PAYLOAD=", JSON.stringify({"legacy_bytes": legacy, "batched_bytes": batch, "ratio": snappedf(float(legacy) / batch, 0.01)})) check(batch < 1200, "Ten pilots and five aliens fit below the ENet datagram budget") @@ -147,10 +156,11 @@ func run() -> void: var sequence := session.snapshot_sequence var applied: int = first.session.player_sequences.get(other, -1) var entry := SnapshotCodec.player_entry(other, changed, (cached[0] + 1) % 65536) - first.session.world_snapshot(SnapshotCodec.world(sequence + 1, ship.map_visit, 0, [entry], [])) + var changed_entry := {SnapshotCodec.player_key(entry): entry} + first.session.world_snapshot(SnapshotCodec.encode_world(sequence + 1, ship.map_visit, 0, changed_entry)[0]) check(first.session.player_sequences.get(other, -1) == applied and first.session.ships[other].laser_damage == 4321.0, "State packed with a newer profile waits instead of using the cached profile") first.session.entity_profiles({other: [(cached[0] + 1) % 65536, SnapshotCodec.player_profile(changed)]}, {}) - first.session.world_snapshot(SnapshotCodec.world(sequence + 2, ship.map_visit, 0, [entry], [])) + first.session.world_snapshot(SnapshotCodec.encode_world(sequence + 2, ship.map_visit, 0, changed_entry)[0]) check(first.session.player_sequences.get(other, -1) == sequence + 2 and first.session.ships[other].laser_damage == 5000.0, "State applies once its profile revision arrives") await replicate(server) check(session.profile_revision(Vector2i(0, other), SnapshotCodec.player_profile(session.player_state(other, false)))[0] == (cached[0] + 1) % 65536, "The server advances the profile revision once per change") diff --git a/tests/snapshot_delta_test.gd b/tests/snapshot_delta_test.gd new file mode 100644 index 0000000..adade80 --- /dev/null +++ b/tests/snapshot_delta_test.gd @@ -0,0 +1,143 @@ +extends SceneTree +## Schema 26 wire bounds and baseline behavior without sockets or frame timing. + +var failures := 0 + + +func _initialize() -> void: + test_quantization() + test_baselines() + test_mtu() + quit(failures) + + +func check(condition: bool, message: String) -> void: + if not condition: + failures += 1 + push_error(message) + + +func player(map: int = 0) -> Dictionary: + return {"map": map, "visit": 4, "life": 8, "alive": true, "docked": false, + "position": SectorMaps.origin(map) + Vector3(715.123, -388.123, 901.987), + "rotation": Vector3(-1.111111, PI - 0.00001, TAU - 0.00003), + "hull": 999999.127, "shield": 43000.123, "energy": 81.23456, "since_hit": 3.1234, + "systems": PackedFloat32Array([2.75, 0.0, 0.0])} + + +func test_quantization() -> void: + var data := player(6) + var entry := SnapshotCodec.player_entry(9, data, 12) + var key := SnapshotCodec.player_key(entry) + var packet := SnapshotCodec.encode_world(1, 4, 987654, {key: entry})[0] + var world := SnapshotCodec.decode_world(packet) + var state: Dictionary = world["players"][9] + check(world["tick"] == 987654 and state["map"] == 6 and state["life"] == 8 and state["visit"] == 4, + "Exact tick, life, map and visit survive quantization") + var input_position: Vector3 = data["position"] + var input_rotation: Vector3 = data["rotation"] + for axis in 3: + check(absf(state["position"][axis] - input_position[axis]) <= 1.0 / 512.0, "Position error is at most half a quantum") + check(absf(angle_difference(state["rotation"][axis], input_rotation[axis])) <= TAU / 131072.0, "Wrapped angle error is at most half a quantum") + check(absf(state["hull"] - data["hull"]) <= 0.125 and absf(state["shield"] - data["shield"]) <= 0.125, "Health error is at most one eighth of a point") + check(absf(state["energy"] - data["energy"]) <= 1.0 / 512.0, "Energy error is at most half a quantum") + check(absf(state["since_hit"] - data["since_hit"]) <= 0.005, "Public hit timer error is at most 5 ms") + data["position"] = SectorMaps.origin(6) + Vector3(-35000.5, 53000.125, 900.25) + data["since_hit"] = 100.0 + entry = SnapshotCodec.player_entry(9, data, 12) + state = SnapshotCodec.decode_world(SnapshotCodec.encode_world(2, 4, 987657, {key: entry})[0])["players"][9] + check(state["position"] == data["position"] and state["since_hit"] == 6.0, "Distant positions escape to float32 and public hit timers cap at six seconds") + data.merge({"credits": 7, "kills": 1, "stage": 1, "respawn": 0.0, "velocity": Vector3(7.125, 1.25, -3.5)}) + entry = SnapshotCodec.player_entry(9, data, 12) + state = SnapshotCodec.decode_world(SnapshotCodec.encode_world(3, 4, 987660, {SnapshotCodec.player_key(entry): entry})[0])["players"][9] + check(state["position"] == data["position"] and state["rotation"] == data["rotation"] and state["velocity"] == data["velocity"] + and state["energy"] == float(PackedFloat32Array([data["energy"]])[0]) and state["hull"] == data["hull"] and state["shield"] == data["shield"], + "Owner reconciliation and health keep schema 25 precision") + + +func test_baselines() -> void: + var sent := SnapshotHistory.new() + var received := SnapshotHistory.new() + sent.set_scope(4, 0) + received.set_scope(4, 0) + var data := player() + var key := Vector2i(SnapshotCodec.PUBLIC_PLAYER, 9) + var removed := Vector2i(SnapshotCodec.PUBLIC_PLAYER, 10) + var first := {key: SnapshotCodec.player_entry(9, data, 7), removed: SnapshotCodec.player_entry(10, data, 7)} + var full := SnapshotCodec.encode_world(10, 4, 30, first, sent.baseline_for(10))[0] + check(full.decode_u32(12) == 0, "First packet is full when no acknowledgement exists") + sent.remember_sent(10, first) + sent.acknowledge(11) + check(sent.acknowledged == 0, "The sender ignores acknowledgements for unsent packets") + check(not receive(received, full).is_empty(), "Client stores a full baseline") + sent.acknowledge(received.acknowledged) + var second := {key: first[key]} + var delta := SnapshotCodec.encode_world(11, 4, 33, second, sent.baseline_for(11))[0] + check(delta.decode_u16(SnapshotCodec.HEADER_BYTES) == 0 and delta.size() == SnapshotCodec.HEADER_BYTES + 6, + "Unchanged player uses a zero mask and only its ID") + data["hull"] = 1000.0 + var third := {key: SnapshotCodec.player_entry(9, data, 7), Vector2i(SnapshotCodec.PUBLIC_PLAYER, 12): SnapshotCodec.player_entry(12, data, 7)} + var later := SnapshotCodec.encode_world(12, 4, 36, third, sent.baseline_for(12))[0] + check(later.decode_u16(SnapshotCodec.HEADER_BYTES) == 1 << 3, "Only the changed hull bit is transmitted") + check(SnapshotCodec.decode_world(later).is_empty(), "Loss of the required baseline rejects a delta") + var current := receive(received, later) + check(current.get("entries") == third and current["players"][9]["hull"] == 1000.0, "Sending against one acknowledged base tolerates a lost intermediate packet") + var older := receive(received, delta) + check(older.get("entries") == second and older["tick"] == 33 and not older["players"].has(10), + "Reordered deltas use their named base, retain the tick sample, and exclude absent entities") + check(received.acknowledged == 12 and receive(received, delta).is_empty(), "An older or duplicated packet cannot regress the acknowledgement") + check(not current["players"][9].has("velocity") and not current["players"][9].has("credits") and current["owner"].is_empty(), + "Viewer deltas carry no owner's private state") + data["life"] += 1 + var respawn := {key: SnapshotCodec.player_entry(9, data, 7)} + var lifecycle := SnapshotCodec.encode_world(13, 4, 39, respawn, sent.baseline_for(13))[0] + check(lifecycle.decode_u16(SnapshotCodec.HEADER_BYTES) == 255, "A new life sends a full entity record") + var expired := SnapshotCodec.encode_world(42, 4, 126, respawn, sent.baseline_for(42))[0] + check(expired.decode_u32(12) == 0, "An expired acknowledgement falls back to full") + check(not receive(received, expired).is_empty() and received.find(10).is_empty() and receive(received, later).is_empty(), + "An overwritten ring slot cannot substitute for an old sequence") + sent.set_scope(5, 1) + received.set_scope(5, 1) + sent.acknowledge(10) + check(sent.baseline_for(43).is_empty() and received.acknowledged == 0 and receive(received, expired).is_empty(), + "Changing map visits clears baselines and rejects in-flight packets from the old visit") + sent.remember_sent(43, first) + sent.acknowledge(43) + sent.set_scope(5, 0) + check(sent.baseline_for(44).is_empty(), "Changing map resets scope even with a matching visit value") + + +func test_mtu() -> void: + var data := player(6) + var own := data.duplicate() + own.merge({"credits": 7, "kills": 1, "stage": 1, "respawn": 0.0, "velocity": Vector3.ZERO}) + var owner := SnapshotCodec.player_entry(10, own, 12) + var entries := {SnapshotCodec.player_key(owner): owner} + for id in range(1, 10): + var entry := SnapshotCodec.player_entry(id, data, 12) + entries[SnapshotCodec.player_key(entry)] = entry + var alien := data.duplicate() + alien.merge({"encounter": 1, "returning": false, "engaged": true, "respawn": 0.0}) + for id in range(1, 21): + alien["id"] = id + var entry := SnapshotCodec.alien_entry(alien, 8) + entries[SnapshotCodec.alien_key(entry)] = entry + var packets := SnapshotCodec.encode_world(20, 4, 60, entries) + check(packets.size() > 1 and packets.all(func(packet: PackedByteArray) -> bool: return packet.size() <= SnapshotCodec.MAX_PACKET_BYTES), + "Ten pilots and the largest arena roster split below the MTU guard") + var received := SnapshotHistory.new() + received.set_scope(4, 6) + var partial := receive(received, packets[-1]) + check(not partial.is_empty() and partial["owner"].is_empty() and received.acknowledged == 0, + "A reordered part applies without the owner or acknowledgement of the incomplete tick") + var baseline := {"sequence": 20, "visit": 4, "entries": entries} + var delta := SnapshotCodec.encode_world(21, 4, 63, entries, baseline)[0] + check(receive(received, delta).is_empty(), "A partially received tick cannot serve as a baseline") + for index in range(packets.size() - 1): + check(not receive(received, packets[index]).is_empty(), "Remaining parts decode independently") + check(received.acknowledged == 20 and received.find(20)["entries"] == entries, "All parts together restore the full roster") + check(receive(received, delta).get("entries") == entries and received.acknowledged == 21, "Delta against the completed multipart baseline restores every entity") + + +func receive(history: SnapshotHistory, packet: PackedByteArray) -> Dictionary: + return history.receive(packet, SnapshotCodec.header(packet)) diff --git a/tests/snapshot_delta_test.gd.uid b/tests/snapshot_delta_test.gd.uid new file mode 100644 index 0000000..0637c15 --- /dev/null +++ b/tests/snapshot_delta_test.gd.uid @@ -0,0 +1 @@ +uid://pugvucx7mqld diff --git a/tests/snapshot_traffic_benchmark.gd b/tests/snapshot_traffic_benchmark.gd index 89129dc..390bf3d 100644 --- a/tests/snapshot_traffic_benchmark.gd +++ b/tests/snapshot_traffic_benchmark.gd @@ -1,6 +1,6 @@ extends "res://tests/network_test.gd" ## Measures server snapshot traffic with ten pilots and five aliens on M1. -## Uses only the ENet host counters, so the same script measures older builds. +## Measures ENet host counters on every schema and world payloads on schema 26+. const SNAPSHOTS := 100 @@ -31,10 +31,12 @@ func run() -> void: for frame in range(20): server.session.send_snapshot() await process_frame + acknowledge(clients) await settle(0.3) var host: ENetConnection = (server.multiplayer.multiplayer_peer as ENetMultiplayerPeer).host host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_PACKETS) + var before := payload_counters(server) var moved := 0 for index in range(SNAPSHOTS): # Keep every pilot and alien moving so no entity state is repeated. @@ -46,6 +48,7 @@ func run() -> void: server.session.send_snapshot() moved += 1 await process_frame + acknowledge(clients) await settle(0.3) var bytes := host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) var packets := host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_PACKETS) @@ -53,10 +56,36 @@ func run() -> void: var result := { "pilots": server.session.ships.size(), "aliens_on_map": on_map, "snapshots": moved, "enet_bytes_per_client_per_snapshot": snappedf(per_client_snapshot, 0.1), + "enet_bytes_per_client_per_second_at_20hz": roundi(per_client_snapshot * 20), "enet_packets_per_client_per_snapshot": snappedf(float(packets) / moved / clients.size(), 0.01), "client_kbit_per_second_at_20hz": snappedf(per_client_snapshot * 20 * 8 / 1000.0, 0.1), "server_mbit_per_second_at_20hz": snappedf(float(bytes) / moved * 20 * 8 / 1_000_000.0, 0.01), } + if not before.is_empty(): + var after := payload_counters(server) + var payload_per_tick := float(after["bytes"] - before["bytes"]) / moved / clients.size() + result["world_bytes_per_client_per_snapshot"] = snappedf(payload_per_tick, 0.1) + result["world_bytes_per_client_per_second_at_20hz"] = roundi(payload_per_tick * 20) + result["full_fallbacks"] = after["full"] - before["full"] + result["delta_share"] = 1.0 - float(result["full_fallbacks"]) / moved / clients.size() print("SNAPSHOT_TRAFFIC=", JSON.stringify(result)) finish() + +func acknowledge(clients: Array[Sector]) -> void: + # This benchmark drives snapshots directly with client simulation disabled. + for client in clients: + if client.session.has_method("send_snapshot_ack"): + client.session.call("send_snapshot_ack") + + +func payload_counters(server: Sector) -> Dictionary: + var traffic: Variant = server.session.get("snapshot_traffic") + if traffic == null: + return {} + var result := {"bytes": 0, "full": 0} + for viewer in traffic.values(): + result["bytes"] += viewer.total_bytes + result["full"] += viewer.full_fallbacks + return result + diff --git a/tools/check-suites.json b/tools/check-suites.json index 8b15dca..8530ed7 100644 --- a/tools/check-suites.json +++ b/tools/check-suites.json @@ -20,6 +20,7 @@ {"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"]]}, + {"name": "snapshot_delta_test", "checks": [["snapshot_delta_test.gd"]]}, {"name": "rpc_compatibility_test", "checks": [["rpc_compatibility_test.gd"]]}, {"name": "dedicated_server_test", "checks": [["dedicated_server_test.gd"]]}, {"name": "alien_assets_test", "checks": [["alien_assets_test.gd"]]}, @@ -90,6 +91,7 @@ {"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"]]}, + {"name": "snapshot_delta_test", "checks": [["snapshot_delta_test.gd"]]}, {"name": "rpc_compatibility_test", "checks": [["rpc_compatibility_test.gd"]]}, {"name": "hunting_contracts_test", "checks": [["hunting_contracts_test.gd"]]}, {"name": "economy_test", "checks": [["economy_test.gd"]]},