Files
tidewall/test/net/test_net_snapshot.gd
T
claudeandClaude Opus 5.5 4111a285f0 N3: Client prediction, reconciliation and interpolation
The client's side of a networked match, in src/net/:

- ClientGame takes the server's notices and snapshots, generates the island
  from the seed and answers with commands. It works on packets, so it runs
  over a NetClient or a test's simulated link.
- ClientClock decides which tick the next command is for, from the server's
  echo of the newest command tick it has received, holding three commands
  waiting at the server.
- ClientPrediction runs each command on a copy of the client's own player
  with the server's movement code, and compares every snapshot with what it
  predicted. A difference is replayed from the server's state and eased in.
- SnapshotInterpolator draws everyone else four ticks in the past, between
  snapshots, on a clock steered gently by arrivals.

Snapshots now carry the client's own block: exact position and velocity,
the water around the player, stamina and state flags, so a prediction can
match the server to the bit. The command echo is now the newest tick
received rather than taken. Protocol version 2.

Snapshots go out every second tick. The interval was three ticks, which is
10 a second, not the 20 the documents claimed; 15 a second is the nearest
even spacing and what interpolation is tuned for.

Drop.ride() holds the barge ride for the server and the client alike, and
NetGame's joining, input and snapshot steps can be called without a socket.

Measured in test/net/test_prediction_link.gd over a simulated link with
100 ms each way, 20 ms jitter and 2% loss: no corrections to own movement
in about 1,400 snapshots per client, and the other player drawn 0.4 mm on
average from where a perfect link would draw them.

Closes #34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:30:00 -05:00

179 lines
9.6 KiB
GDScript

extends TestCase
## Issue N2: the wire format of snapshots, input packets and the match notice.
func _player(sim: Simulation, at: Vector3) -> SimEntity:
var player: SimEntity = sim.entities.find(sim.add_player())
player.position = at
return player
func test_a_record_keeps_position_to_a_sixty_fourth_of_a_metre() -> void:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var player: SimEntity = _player(sim, Vector3(511.37, -20.21, 1003.99))
player.yaw = 40000
player.pitch = -PlayerCommand.PITCH_MAX
player.health = 73
player.crouching = true
var record: PackedInt32Array = NetSnapshot.record_of(player)
assert_true(NetSnapshot.position_of(record).distance_to(player.position) < 0.014)
assert_near(NetSnapshot.yaw_radians_of(record), float(40000) / 65536.0 * TAU, 0.0001)
assert_near(NetSnapshot.pitch_radians_of(record), -PI * 0.5, 0.0001)
assert_eq(record[NetSnapshot.R_HEALTH], 73)
assert_true(record[NetSnapshot.R_FLAGS] & NetSnapshot.FLAG_CROUCHING != 0)
assert_eq(record[NetSnapshot.R_HELD], 0, "the boathook")
func test_positions_outside_the_world_are_clamped_not_wrapped() -> void:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var player: SimEntity = _player(sim, Vector3(-50.0, 5000.0, 2000.0))
var where: Vector3 = NetSnapshot.position_of(NetSnapshot.record_of(player))
assert_near(where.x, 0.0, 0.001)
assert_near(where.z, 65535.0 / 64.0, 0.001)
assert_near(where.y, 65535.0 / 64.0 - NetSnapshot.Y_OFFSET_METRES, 0.001)
func test_a_snapshot_round_trips_every_archetype_and_partial_masks() -> void:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var player: SimEntity = _player(sim, Vector3(100.0, 0.0, 100.0))
var pickup: SimEntity = sim.entities.find(Inventory.spawn_pickup(sim, Vector3(101.0, 0.0, 100.0), 1, 7, -1, 2))
var shot: SimEntity = sim.entities.create(SimEntity.ARCHETYPE_PROJECTILE)
shot.position = Vector3(120.0, 9.0, 80.0)
shot.item = 4
shot.owner_id = player.id
var before: PackedInt32Array = NetSnapshot.record_of(player)
player.position.x += 3.0
player.health = 12
var after: PackedInt32Array = NetSnapshot.record_of(player)
var mask: int = NetSnapshot.diff_mask(before, after)
assert_eq(mask, 0b101, "position and vitals changed, nothing else")
var header: Dictionary = {
"tick": 900, "baseline": 897, "sim_tick": 300, "command_tick": 298, "own_id": player.id,
"match_phase": Match.PLAY, "tide_phase": 2, "sea_cm": -150,
}
var records: Array = [
[player.id, mask, after],
[pickup.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PICKUP), NetSnapshot.record_of(pickup)],
[shot.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PROJECTILE), NetSnapshot.record_of(shot)],
]
var bytes: PackedByteArray = NetSnapshot.encode_snapshot(header, PackedInt32Array([70000, 5]), records)
# The header, the watched entity, phases and sea, the own-block flag, two removals, the count.
var expected: int = NetSnapshot.HEADER_BYTES + 1 + 4 + 1 + 1 + 4 + 2
for entry: Array in records:
expected += NetSnapshot.record_bytes(entry[0], entry[2][0], entry[1])
assert_eq(bytes.size(), expected, "record_bytes() predicts the encoded size")
var back: Dictionary = NetSnapshot.decode_snapshot(bytes)
for key: String in header:
assert_eq(back[key], header[key], key)
assert_eq(back["removed"], PackedInt32Array([70000, 5]))
assert_eq((back["records"] as Array).size(), 3)
var merged: PackedInt32Array = NetSnapshot.merge_record(before, SimEntity.ARCHETYPE_PLAYER, back["records"][0][2], back["records"][0][3])
assert_eq(merged, after)
assert_eq(NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PICKUP, back["records"][1][2], back["records"][1][3]), NetSnapshot.record_of(pickup))
assert_eq(NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PROJECTILE, back["records"][2][2], back["records"][2][3]), NetSnapshot.record_of(shot))
func test_a_partial_record_for_an_unknown_entity_is_refused() -> void:
assert_eq(NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PLAYER, 0b1, PackedInt32Array([1, 2, 3])), PackedInt32Array())
var pickup: PackedInt32Array = PackedInt32Array([SimEntity.ARCHETYPE_PICKUP, 1, 2, 3, 4, 5, 6])
assert_eq(NetSnapshot.merge_record(pickup, SimEntity.ARCHETYPE_PLAYER, 0b1, PackedInt32Array([1, 2, 3])), PackedInt32Array(), "an ID can't change archetype")
func test_truncated_and_corrupt_snapshots_decode_to_nothing_without_errors() -> void:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var records: Array = []
for index: int in 5:
var player: SimEntity = _player(sim, Vector3(100.0 + index, 0.0, 100.0))
records.append([player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), NetSnapshot.record_of(player)])
var bytes: PackedByteArray = NetSnapshot.encode_snapshot({"tick": 5, "own_id": 1}, PackedInt32Array([9]), records)
assert_false(NetSnapshot.decode_snapshot(bytes).is_empty())
for length: int in bytes.size():
assert_true(NetSnapshot.decode_snapshot(bytes.slice(0, length)).is_empty(), "cut to %d bytes" % length)
var longer: PackedByteArray = bytes.duplicate()
longer.append(0)
assert_true(NetSnapshot.decode_snapshot(longer).is_empty(), "trailing bytes")
# Every single-byte corruption either decodes to something or to nothing; none may
# raise an engine error, which would fail this test.
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
rng.seed = 77
for _round: int in 400:
var broken: PackedByteArray = bytes.duplicate()
broken[rng.randi_range(0, broken.size() - 1)] = rng.randi_range(0, 255)
NetSnapshot.decode_snapshot(broken)
for _round: int in 200:
var noise: PackedByteArray = PackedByteArray()
noise.resize(rng.randi_range(0, 80))
for index: int in noise.size():
noise[index] = rng.randi_range(0, 255)
if noise.size() > 0:
noise[0] = NetSnapshot.MSG_SNAPSHOT
NetSnapshot.decode_snapshot(noise)
NetSnapshot.decode_input(noise)
NetSnapshot.decode_match(noise)
func test_input_round_trips_and_keeps_the_newest_commands() -> void:
var commands: Array[PlayerCommand] = []
for tick: int in range(50, 62):
commands.append(PlayerCommand.from_input(tick, Vector2(0.5, -1.0), 1.0, 0.2, PlayerCommand.BUTTON_JUMP, 2, 1))
var bytes: PackedByteArray = NetSnapshot.encode_input(4321, commands)
var back: Dictionary = NetSnapshot.decode_input(bytes)
assert_eq(back["ack"], 4321)
var got: Array[PlayerCommand] = back["commands"]
assert_eq(got.size(), NetSnapshot.MAX_INPUT_COMMANDS)
assert_eq(got[0].tick, 62 - NetSnapshot.MAX_INPUT_COMMANDS)
assert_eq(got[got.size() - 1].tick, 61)
assert_eq(got[0].encode(), commands[commands.size() - NetSnapshot.MAX_INPUT_COMMANDS].encode())
assert_true(NetSnapshot.decode_input(bytes.slice(0, bytes.size() - 1)).is_empty())
var lying: PackedByteArray = bytes.duplicate()
lying[5] = 200
assert_true(NetSnapshot.decode_input(lying).is_empty(), "a count the packet doesn't hold")
assert_eq((NetSnapshot.decode_input(NetSnapshot.encode_input(0, []))["commands"] as Array).size(), 0)
func test_match_notice_round_trips_a_63_bit_seed() -> void:
var seed_value: int = 0x7FFFFFFFFFFFFFF1
var back: Dictionary = NetSnapshot.decode_match(NetSnapshot.encode_match(Match.DROP, 7, seed_value))
assert_eq(back, {"phase": Match.DROP, "index": 7, "seed": seed_value})
assert_true(NetSnapshot.decode_match(NetSnapshot.encode_match(99, 7, 1)).is_empty(), "an unknown phase")
func test_the_own_block_round_trips_exactly() -> void:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var player: SimEntity = _player(sim, Vector3(100.123456, 7.654321, 900.000123))
player.velocity = Vector3(-3.3333333, 0.1, 6.5)
player.stamina_ticks = 1234
player.swimming = true
player.on_ground = false
player.drop_state = Drop.GLIDING
var own: Dictionary = NetSnapshot.self_of(player, 2.71828, 0b101010101)
var record: PackedInt32Array = NetSnapshot.record_of(player)
var header: Dictionary = {"tick": 9, "sim_tick": 8, "command_tick": 11, "own_id": player.id, "self": own}
var bytes: PackedByteArray = NetSnapshot.encode_snapshot(header, PackedInt32Array(), [[player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), record]])
var plain: PackedByteArray = NetSnapshot.encode_snapshot({"tick": 9, "sim_tick": 8, "own_id": player.id}, PackedInt32Array(), [[player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), record]])
assert_eq(bytes.size() - plain.size(), NetSnapshot.SELF_BYTES)
var back: Dictionary = NetSnapshot.decode_snapshot(bytes)
assert_eq(back["command_tick"], 11)
assert_eq(NetSnapshot.decode_snapshot(plain)["command_tick"], -1, "no command received yet")
assert_true((NetSnapshot.decode_snapshot(plain)["self"] as Dictionary).is_empty())
# Not near: the same, to the bit, which is what lets a prediction match the server.
var copy: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER)
NetSnapshot.apply_self(copy, back["self"])
assert_eq(copy.position, player.position)
assert_eq(copy.velocity, player.velocity)
assert_eq(copy.stamina_ticks, 1234)
assert_true(copy.swimming and not copy.on_ground)
assert_eq(copy.drop_state, Drop.GLIDING)
assert_eq(back["self"]["water"], own["water"])
assert_eq(back["self"]["water_mask"], 0b101010101)
for length: int in bytes.size():
assert_true(NetSnapshot.decode_snapshot(bytes.slice(0, length)).is_empty(), "cut to %d bytes" % length)
# A position that isn't a number is refused rather than handed to the movement code.
var poisoned: PackedByteArray = bytes.duplicate()
var at: int = NetSnapshot.HEADER_BYTES + NetSnapshot.varint_bytes(player.id) + 5
poisoned.encode_float(at, NAN)
assert_true(NetSnapshot.decode_snapshot(poisoned).is_empty(), "a NaN position")
poisoned.encode_float(at, INF)
assert_true(NetSnapshot.decode_snapshot(poisoned).is_empty(), "an infinite position")