N4: Lag-compensated hit validation

A network client draws other players in the past and its commands take time
to arrive, so by the time the server fires a shot the target has moved on:
8 ticks at a 50 ms round trip, 12 at 200 ms.

Each PlayerCommand now carries view_lag: how far back its player was seeing
everyone else, in quarter ticks. The simulation keeps where every player's
body has been for the last 15 ticks (HitHistory), and a hitscan shot is
traced against other players where they were at the moment the shooter saw,
and against the world as it is now. Projectiles aren't rewound.

The client claims only when it was looking and where it aimed; the server
works out the hit from its own record. The moment is never more than
Tuning.LAG_COMPENSATION_MAX_TICKS back, never in the future, and never
earlier than a moment the same player has already claimed.

Commands are 15 bytes, so the command log's version is 2. The lag is in the
log, and replays judge every shot as the match did.

Measured in test/net/test_lag_compensation_link.gd over a simulated link:
a client firing at a walking target as drawn on its own screen hits 41 of
41 shots at 50, 100 and 200 ms round trips, 0 of 41 with the lag ignored,
and 0 of 41 at 500 ms, past the cap.

Closes #35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 11:45:23 -05:00
co-authored by Claude Opus 5.5
parent 4111a285f0
commit 5e1704e224
16 changed files with 510 additions and 15 deletions
+38 -4
View File
@@ -50,6 +50,7 @@ produce the same struct, so the simulation can't tell them apart.
| `buttons` | u16 | Bit flags: fire, aim, jump, crouch, sprint, reload, interact, build |
| `selection` | u8 | Active inventory slot or build piece |
| `material` | u8 | Active build material |
| `view_lag` | u8 | How far in the past the player was seeing everyone else, back from `tick`, in quarter ticks. 0 for bots and local play |
Clients stamp commands for the tick they predict, and each packet repeats recent
commands to survive loss. The server applies the command for each tick, or a neutral
@@ -61,7 +62,7 @@ frame, so turning right *decreases* yaw. Positive pitch looks up. `Movement` and
client's `CameraRig` both follow this, and a test checks that strafing right moves
towards the camera's screen-right.
The binary encoding is a fixed 14 bytes per command, little-endian, in the order of
The binary encoding is a fixed 15 bytes per command, little-endian, in the order of
the table above. See `src/sim/player_command.gd`. Decoding a truncated buffer returns
nothing, and out-of-range values are clamped, so bad input can't reach the simulation.
The player a command belongs to comes from its connection, never from the packet.
@@ -97,7 +98,7 @@ with the server. Reconciliation corrects any difference.
`CommandLog` (`src/server/`) holds a match's seed, its rules and every command the
server was given: the simulation tick it arrived on, the handle it came from and the
command's 14 bytes. `ServerLoop.submit()` is the one way commands get in, for people,
command's 15 bytes. `ServerLoop.submit()` is the one way commands get in, for people,
scripts and bots alike, so a recording server logs them all, accepted or not. On disk
it is a JSON header and the records compressed with Zstandard, about 0.6 MB for a
24-player match.
@@ -198,6 +199,39 @@ on channel 0, the match phase, index and seed, so the client can generate the is
Building changes will also travel on a reliable ordered event stream (N5), since a
dropped wall is a gameplay lie.
## Lag compensation
A client draws other players about 130 ms in the past, and its commands take the
trip to the server and wait their turn, so when the server fires a shot the target is
no longer where the shooter saw it: 8 ticks on at a 50 ms round trip, 12 at 200 ms.
Without help, nobody could hit a walking target.
So every command says how far back its player was seeing (`view_lag`), and the
simulation keeps where every player's body has been for the last
`Tuning.LAG_COMPENSATION_MAX_TICKS` (15 ticks, half a second) in `HitHistory`
(`src/sim/`). A hitscan shot is traced against other players where they were at the
moment the shooter saw, between ticks if need be, and against terrain, props and built
pieces as they are now. Projectiles fly in the server's present and aren't rewound.
The client claims only *when* it was looking and where it aimed. Whether that is a
hit is worked out by the server, from its own record. Three limits bound the claim:
- Never more than the cap back. A round trip much over 300 ms needs more than the
cap, and that shooter has to lead the target.
- Never the future: the lag can't be negative.
- Never earlier than a moment the same player has already claimed. A view only moves
forward, so nobody can fire at the present and the past by turns and keep whichever
hits.
Because the lag travels in the command, it is in the command log, and a replay
judges every shot exactly as the match did. `HitHistory` itself isn't in the state
hash: a replay rebuilds it from the same ticks.
Measured (`test/net/test_lag_compensation_link.gd`, simulated link, headless): a
client firing a signal revolver once a second at the middle of a target walking
across at 4 m/s, 25 m away, as drawn on its own screen. At 50, 100 and 200 ms round
trips, 41 of 41 shots hit; with the lag ignored, 0 of 41. At 500 ms, past the cap,
0 of 41.
## The client: prediction, reconciliation and interpolation
`ClientGame` (`src/net/`) is a client's side of a match. It works on packets, so it
@@ -253,9 +287,9 @@ the hand, which needs a real playtest.
| Path | Holds | May depend on |
|---|---|---|
| `src/sim/` | Tick loop, entities, RNG, commands, tide, combat, building | `src/sim/` only |
| `src/sim/` | Tick loop, entities, RNG, commands, tide, combat and its lag compensation, building | `src/sim/` only |
| `src/bots/` | Bot brains that produce `PlayerCommand`s | `src/sim/` |
| `src/net/` | Transport, snapshot encoding, the client's side of a match (prediction, interpolation), lag compensation | `src/sim/` |
| `src/net/` | Transport, snapshot encoding, the client's side of a match (prediction, interpolation) | `src/sim/` |
| `src/server/` | Headless and listening servers, joining the network to the match | `src/sim/`, `src/bots/`, `src/net/` |
| `src/client/` | World rendering, camera, input, effects | `src/sim/`, `src/net/` |
| `src/ui/` | HUD, menus, map | `src/sim/` (read only), `src/client/` |
+4
View File
@@ -165,6 +165,10 @@ func _input_for(tick: int) -> PlayerCommand:
command.yaw = _last_yaw
command.pitch = _last_pitch
command.tick = tick
if remote.started:
# How far back everyone else is being drawn right now, for the server to judge
# shots by.
command.view_lag = clampi(roundi((float(tick) - remote.time) * PlayerCommand.VIEW_LAG_STEPS_PER_TICK), 0, 255)
_last_yaw = command.yaw
_last_pitch = command.pitch
return command
+1 -1
View File
@@ -17,7 +17,7 @@
## then the fields of each group in the mask
## client -> INPUT (channel 1, unreliable)
## u8 type, u32 tick of the newest snapshot it holds (0 = send a full one),
## u8 command count, then that many 14-byte PlayerCommands, oldest first
## u8 command count, then that many 15-byte PlayerCommands, oldest first
## server -> MATCH (channel 0, reliable)
## u8 type, u8 match phase, u32 match index, s64 match seed
##
+2 -2
View File
@@ -3,7 +3,7 @@
## the simulation takes nothing else in. See MatchReplay.
##
## Each record is the simulation tick the command arrived on, the handle it came from
## and the command's own 14 bytes. Commands are logged whether or not the simulation
## and the command's own 15 bytes. Commands are logged whether or not the simulation
## accepted them, so a replay turns the same ones down.
##
## On disk: "TWCL", a u32 header length, the header as JSON, a u32 length of the raw
@@ -13,7 +13,7 @@ class_name CommandLog
extends RefCounted
const MAGIC: String = "TWCL"
const VERSION: int = 1
const VERSION: int = 2
## at-tick u32, handle s32, then the command.
const RECORD_SIZE: int = 8 + PlayerCommand.ENCODED_SIZE
## Refuse files that claim more than this many raw bytes: about four full matches.
+74
View File
@@ -0,0 +1,74 @@
## Where every player's body has been over the last few ticks, so a shot can be judged
## against the moment the shooter saw. See "Lag compensation" in Weapons.
##
## note() stores a player's state before a tick runs, which is what a snapshot of that
## tick carries, so the moment a client was drawing and the moment looked up here are on
## the same clock.
class_name HitHistory
extends RefCounted
## Ticks kept per player: as far back as compensation goes, and the tick under way.
const SIZE: int = Tuning.LAG_COMPENSATION_MAX_TICKS + 2
class Track:
extends RefCounted
var ticks: PackedInt32Array = PackedInt32Array()
var positions: PackedVector3Array = PackedVector3Array()
var heights: PackedFloat32Array = PackedFloat32Array()
func _init() -> void:
ticks.resize(SIZE)
ticks.fill(-1)
positions.resize(SIZE)
heights.resize(SIZE)
## Player entity ID -> Track.
var _tracks: Dictionary = {}
## Stores where `player` is before `tick` runs.
func note(tick: int, player: SimEntity) -> void:
var track: Track = _tracks.get(player.id)
if track == null:
track = Track.new()
_tracks[player.id] = track
var slot: int = tick % SIZE
track.ticks[slot] = tick
track.positions[slot] = player.position
track.heights[slot] = Movement.body_height(player)
func forget(player_id: int) -> void:
_tracks.erase(player_id)
## The box `player`'s body occupied at `time`, in ticks, between the two ticks around
## it. Where nothing was stored for that moment, the nearest stored tick stands in, and
## failing that the player as they are now.
func box_at(player: SimEntity, time: float) -> AABB:
var track: Track = _tracks.get(player.id)
if track == null:
return Weapons.body_box(player)
var from: int = floori(time)
var weight: float = time - from
var a: int = from % SIZE if from >= 0 else -1
var b: int = (from + 1) % SIZE
var has_a: bool = a >= 0 and track.ticks[a] == from
var has_b: bool = weight > 0.0 and track.ticks[b] == from + 1
var feet: Vector3
var height: float
if has_a and has_b:
feet = track.positions[a].lerp(track.positions[b], weight)
height = track.heights[a] if weight < 0.5 else track.heights[b]
elif has_a:
feet = track.positions[a]
height = track.heights[a]
elif has_b:
feet = track.positions[b]
height = track.heights[b]
else:
return Weapons.body_box(player)
var radius: float = Tuning.PLAYER_RADIUS
return AABB(feet - Vector3(radius, 0.0, radius), Vector3(radius * 2.0, height, radius * 2.0))
+1
View File
@@ -0,0 +1 @@
uid://c2l66rp08rbww
+10 -1
View File
@@ -3,7 +3,7 @@
class_name PlayerCommand
extends RefCounted
const ENCODED_SIZE: int = 14
const ENCODED_SIZE: int = 15
const BUTTON_FIRE: int = 1 << 0
const BUTTON_AIM: int = 1 << 1
@@ -19,6 +19,8 @@ const BUTTON_DROP: int = 1 << 8
const AXIS_MAX: int = 127
const YAW_STEPS: int = 65536
const PITCH_MAX: int = 32767
## view_lag counts in steps of this fraction of a tick.
const VIEW_LAG_STEPS_PER_TICK: int = 4
var tick: int = 0
var move_x: int = 0
@@ -28,6 +30,11 @@ var pitch: int = 0
var buttons: int = 0
var selection: int = 0
var material: int = 0
## How far in the past the player was seeing everyone else when this command was made,
## counted back from `tick` in quarter ticks. A network client draws others late, and
## says how late here, so the server can judge a shot against what was on its screen.
## 0 for bots and anyone playing on the server itself. See Weapons and HitHistory.
var view_lag: int = 0
## Builds a command from real-valued input, clamping every field into range.
@@ -81,6 +88,7 @@ func encode() -> PackedByteArray:
bytes.encode_u16(10, buttons & 0xFFFF)
bytes.encode_u8(12, selection & 0xFF)
bytes.encode_u8(13, material & 0xFF)
bytes.encode_u8(14, clampi(view_lag, 0, 255))
return bytes
@@ -98,4 +106,5 @@ static func decode(bytes: PackedByteArray, offset: int = 0) -> PlayerCommand:
command.buttons = bytes.decode_u16(offset + 10)
command.selection = bytes.decode_u8(offset + 12)
command.material = bytes.decode_u8(offset + 13)
command.view_lag = bytes.decode_u8(offset + 14)
return command
+3
View File
@@ -58,6 +58,9 @@ var use_ticks: int = 0
var bloom: float = 0.0
## Buttons held last tick, so pick up and drop act once per press.
var prev_buttons: int = 0
## The latest moment this player has claimed to be seeing, in quarter ticks. It only
## moves forward, so nobody can look further back than they already have. See Weapons.
var view_quarters: int = 0
## Set once health reaches 0. Eliminated players take no more commands.
var eliminated: bool = false
## The player who last damaged this one, or 0.
+12
View File
@@ -50,6 +50,10 @@ var projectiles: Array[int] = []
## Each is a Dictionary with a "type". Cleared at the start of every step.
var events: Array[Dictionary] = []
## Where every player has been over the last half second, for judging shots against
## what a network client saw. Rebuilt identically by a replay, so not part of the hash.
var hit_history: HitHistory = HitHistory.new()
## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {}
## How many entries of props.destroyed have been checked for crate loot.
@@ -103,6 +107,7 @@ func add_player() -> int:
## Removes a player and any commands queued for it.
func remove_player(player_id: int) -> void:
entities.remove(player_id)
hit_history.forget(player_id)
_players.erase(player_id)
_pending.erase(player_id)
@@ -172,6 +177,10 @@ func step() -> void:
structures.advance_building()
if tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1:
structures.tide_damage(sea_level, ground, events, flood)
for player_id: int in _players:
var standing: SimEntity = entities.find(player_id)
if not standing.eliminated:
hit_history.note(tick, standing)
for player_id: int in _players:
var queued: Dictionary = _pending[player_id]
var command: PlayerCommand = queued.get(tick)
@@ -203,6 +212,8 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Water.update(player, water_level_at(player.position), drown_dps, sprinting)
if player.action_cooldown > 0:
player.action_cooldown -= 1
if command != null:
Weapons.note_view(player, command, tick)
Weapons.update(player)
Consumables.update(self, player, command)
var held: int = command.buttons if command != null else 0
@@ -343,6 +354,7 @@ func state_hash() -> String:
buffer.put_64(roundi(entity.bloom * 1000.0))
buffer.put_32(entity.prev_buttons)
buffer.put_u8(1 if entity.eliminated else 0)
buffer.put_64(entity.view_quarters)
buffer.put_32(entity.last_attacker)
buffer.put_u8(entity.last_cause)
buffer.put_32(entity.item)
+4
View File
@@ -434,6 +434,10 @@ const WEAPONS: Dictionary = {
"spread": 0.0, "bloom": 0.0,
},
}
## A network client sees other players late. The server judges a hitscan shot against
## where they were when the shooter saw them, going back at most this many ticks (half
## a second). Past that the shooter has to lead the target.
const LAG_COMPENSATION_MAX_TICKS: int = 15
## Spread multiplier while aiming, unless a weapon sets its own `aim_spread`.
const AIM_SPREAD_FACTOR: float = 0.4
## Extra spread while moving, and while airborne or swimming, in degrees.
+33 -6
View File
@@ -10,6 +10,16 @@
## air. Hitscan pellets trace at once to the weapon's range; projectile pellets become
## entities that fly under gravity and trace each tick's path.
##
## Lag compensation. A network client draws other players a little in the past, and its
## commands take time to arrive, so by the time the server fires a shot the target has
## moved on. Each command says how far back the shooter was seeing (view_lag). A hitscan
## shot is traced against other players where HitHistory had them at that moment, and
## against the world as it is now. Three limits keep that honest: the moment is never
## more than Tuning.LAG_COMPENSATION_MAX_TICKS back, never in the future, and never
## earlier than a moment the same player has already claimed. The client says only when
## it was looking and where it aimed; whether that hit is the server's to work out.
## Projectiles fly in the server's present and aren't rewound.
##
## A trace stops at the first of terrain, a solid (a built piece, a prop or a point of
## interest) or another player's body. Players lose armor first, then health; the top
## Tuning.HEAD_HEIGHT of the body takes the weapon's headshot multiplier. Damage falls
@@ -79,6 +89,21 @@ static func _finish_reload(player: SimEntity) -> void:
player.ammo[index] -= loaded
## Takes a command's word for when its player was seeing the others, within the limits.
static func note_view(player: SimEntity, command: PlayerCommand, tick: int) -> void:
var steps: int = PlayerCommand.VIEW_LAG_STEPS_PER_TICK
var lag: int = clampi(command.view_lag, 0, Tuning.LAG_COMPENSATION_MAX_TICKS * steps)
player.view_quarters = maxi(player.view_quarters, tick * steps - lag)
## The moment a player's shots are judged against, in ticks, or -1 for the present.
static func view_time(player: SimEntity, tick: int) -> float:
var steps: int = PlayerCommand.VIEW_LAG_STEPS_PER_TICK
var earliest: int = (tick - Tuning.LAG_COMPENSATION_MAX_TICKS) * steps
var quarters: int = maxi(player.view_quarters, earliest)
return -1.0 if quarters >= tick * steps else float(quarters) / steps
## Fires the held weapon if it's ready. Returns true if a shot was fired. An empty
## magazine starts a reload instead. Thrown weapons are handled by explosives (B8).
static func fire(sim: Simulation, player: SimEntity, aiming: bool) -> bool:
@@ -99,6 +124,7 @@ static func fire(sim: Simulation, player: SimEntity, aiming: bool) -> bool:
var from: Vector3 = Harvest.eye(player)
var look: Vector3 = Harvest.look_direction(player)
var stream: RandomNumberGenerator = sim.rng.stream("weapons")
var seen_at: float = view_time(player, sim.tick)
sim.events.append({"type": "shot", "player": player.id, "item": def.code, "from": from, "direction": look})
for _pellet: int in def.pellets:
var direction: Vector3 = scatter(look, cone, stream)
@@ -106,7 +132,7 @@ static func fire(sim: Simulation, player: SimEntity, aiming: bool) -> bool:
_launch(sim, player, def, slot, from, direction)
else:
var to: Vector3 = from + direction * def.range_max
var hit: Hit = trace(sim, from, to, player.id)
var hit: Hit = trace(sim, from, to, player.id, seen_at)
_apply_hit(sim, player.id, def, player.slot_tiers[slot], hit, from.distance_to(hit.point))
return true
@@ -139,14 +165,15 @@ static func scatter(look: Vector3, cone_degrees: float, stream: RandomNumberGene
return (look * cos(angle) + offset).normalized()
## The first thing between `from` and `to`, skipping the player `ignore_id`.
static func trace(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int = 0) -> Hit:
## The first thing between `from` and `to`, skipping the player `ignore_id`. With
## `seen_at` set, other players are where they were at that tick; the world is as it is.
static func trace(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int = 0, seen_at: float = -1.0) -> Hit:
var length: float = from.distance_to(to)
var pieces: int = maxi(ceili(length / TRACE_SEGMENT_METRES), 1)
for index: int in pieces:
var start: float = float(index) / pieces
var end: float = float(index + 1) / pieces
var hit: Hit = _trace_segment(sim, from.lerp(to, start), from.lerp(to, end), ignore_id)
var hit: Hit = _trace_segment(sim, from.lerp(to, start), from.lerp(to, end), ignore_id, seen_at)
if hit.kind != HIT_NONE:
hit.fraction = lerpf(start, end, hit.fraction)
return hit
@@ -155,7 +182,7 @@ static func trace(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int =
return miss
static func _trace_segment(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int) -> Hit:
static func _trace_segment(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int, seen_at: float) -> Hit:
var hit: Hit = Hit.new()
var ground: SimGround = sim.ground
# The nearest solid, and what it belongs to.
@@ -186,7 +213,7 @@ static func _trace_segment(sim: Simulation, from: Vector3, to: Vector3, ignore_i
continue
if entity.drop_state == Drop.ABOARD:
continue
var box: AABB = body_box(entity)
var box: AABB = body_box(entity) if seen_at < 0.0 else sim.hit_history.box_at(entity, seen_at)
var t: float = ground.ray_box(from, to, box)
if t < hit.fraction:
hit.fraction = t
+129
View File
@@ -0,0 +1,129 @@
extends TestCase
## Issue N4 end to end: a client aims at another player where it draws them, through a
## link with latency, and the server judges the shots.
##
## The shooter stands still with a signal revolver. The target walks back and forth
## across its view 25 m away at 4 m/s. Once a second the client fires at the middle of
## the target as its SnapshotInterpolator shows it. With the client's view_lag honoured
## the shots should land; with it ignored they should fall behind the target.
const HANDLE: int = 1
const SEED: int = 12
const TICK_MS: float = 1000.0 / Tuning.TICK_RATE_HZ
const FRAME_MS: float = 1000.0 / 60.0
const SHOOTER_FEET: Vector3 = Vector3(500.0, 0.0, 500.0)
const RANGE: float = 25.0
const SECONDS: int = 45
## Ticks the target walks each way.
const LEG_TICKS: int = 75
## Plays `SECONDS` of it with `one_way_ms` of latency in each direction. Returns
## {"shots", "hits", "lag": the mean view lag the client reported, in ticks}.
func _play(one_way_ms: float, compensate: bool) -> Dictionary:
var sim: Simulation = Simulation.new(SEED, SimGround.flat())
var shooter: SimEntity = sim.entities.find(sim.add_player())
shooter.position = SHOOTER_FEET
shooter.on_ground = true
var revolver: int = ItemCatalog.code_of("signal_revolver")
Inventory.give(shooter, revolver, 1)
Inventory.give(shooter, ItemCatalog.get_def(revolver).ammo_code, 200)
shooter.selected = 1
var target: SimEntity = sim.entities.find(sim.add_player())
target.position = SHOOTER_FEET + Vector3(-5.0, 0.0, RANGE)
target.on_ground = true
var sender: SnapshotSender = SnapshotSender.new()
sender.add_client(HANDLE)
var client: ClientGame = ClientGame.new()
client.make_world = func(match_seed: int) -> Simulation: return Simulation.new(match_seed, SimGround.flat())
client.receive(NetProtocol.CHANNEL_CONTROL, NetSnapshot.encode_match(Match.PLAY, 0, SEED))
client.sample_input = func(tick: int) -> PlayerCommand:
var shown: Dictionary = client.remote.sample(target.id)
if shown.is_empty():
return null
var eye: Vector3 = Harvest.eye(client.prediction.player)
var to: Vector3 = (shown["position"] as Vector3) + Vector3(0.0, 1.0, 0.0) - eye
var buttons: int = PlayerCommand.BUTTON_AIM
if tick % Tuning.TICK_RATE_HZ == 0 and tick > 3 * Tuning.TICK_RATE_HZ:
buttons |= PlayerCommand.BUTTON_FIRE
return PlayerCommand.from_input(tick, Vector2.ZERO, atan2(to.x, to.z), atan2(to.y, Vector2(to.x, to.z).length()), buttons, 1)
var down: LinkSim = LinkSim.new(one_way_ms, 5.0, 0.0, 31)
var up: LinkSim = LinkSim.new(one_way_ms, 5.0, 0.0, 32)
var shots: int = 0
var hits: int = 0
var lag_sum: float = 0.0
var lag_count: int = 0
var last_command: int = -1
var server_ticks: int = 0
var next_tick_ms: float = 0.0
var next_frame_ms: float = 5.0
var now: float = 0.0
while sim.tick < SECONDS * Tuning.TICK_RATE_HZ:
if now >= next_tick_ms:
next_tick_ms += TICK_MS
for bytes: PackedByteArray in up.receive(now):
var input: Dictionary = NetSnapshot.decode_input(bytes)
sender.acknowledge(HANDLE, int(input["ack"]))
for command: PlayerCommand in input["commands"]:
if command.tick <= last_command:
continue
last_command = command.tick
sender.note_command(HANDLE, command.tick)
lag_sum += float(command.view_lag) / PlayerCommand.VIEW_LAG_STEPS_PER_TICK
lag_count += 1
if not compensate:
command.view_lag = 0
sim.submit_command(shooter.id, command)
# Facing +z, right is -x.
var strafe: float = -1.0 if (sim.tick / LEG_TICKS) % 2 == 0 else 1.0
sim.submit_command(target.id, PlayerCommand.from_input(sim.tick, Vector2(strafe, 0.0), 0.0, 0.0))
sim.step()
server_ticks += 1
for event: Dictionary in sim.events:
if event["type"] == "shot" and event["player"] == shooter.id:
shots += 1
elif event["type"] == "player_hit" and event["victim"] == target.id:
hits += 1
target.health = Tuning.PLAYER_MAX_HEALTH
if shooter.slot_rounds[0] == 0:
shooter.slot_rounds[0] = 6
if server_ticks % Tuning.NET_SNAPSHOT_INTERVAL_TICKS == 0:
down.send(sender.build(HANDLE, sim, shooter.id, server_ticks, Match.PLAY, shooter.id), now)
if now >= next_frame_ms:
next_frame_ms += FRAME_MS
for bytes: PackedByteArray in down.receive(now):
client.receive(NetProtocol.CHANNEL_STATE, bytes)
client.advance(FRAME_MS / 1000.0)
for bytes: PackedByteArray in client.outbox:
up.send(bytes, now)
client.outbox.clear()
now += 1.0
var result: Dictionary = {"shots": shots, "hits": hits, "lag": lag_sum / maxi(lag_count, 1)}
# The sampler holds the client and the client holds the sampler: let both go.
client.sample_input = Callable()
print(" %3.0f ms round trip, view lag %s: %d of %d shots hit; the client drew the target %.1f ticks (%.0f ms) behind the tick its commands were for" % [
one_way_ms * 2.0, "honoured" if compensate else "ignored", hits, shots, result["lag"], float(result["lag"]) * TICK_MS,
])
return result
func test_shots_land_at_50_100_and_200_ms() -> void:
for round_trip: float in [50.0, 100.0, 200.0]:
var with: Dictionary = _play(round_trip * 0.5, true)
assert_true(with["shots"] >= 38, "%d shots fired" % with["shots"])
assert_true(with["hits"] >= with["shots"] - 1, "%.0f ms: %d of %d hit" % [round_trip, with["hits"], with["shots"]])
assert_true(with["lag"] <= Tuning.LAG_COMPENSATION_MAX_TICKS, "%.0f ms needs %.1f ticks of rewind, inside the cap" % [round_trip, with["lag"]])
# The same shots judged against the present fall behind a walking target.
var without: Dictionary = _play(round_trip * 0.5, false)
assert_true(without["hits"] <= without["shots"] / 4, "%.0f ms uncompensated: %d of %d hit" % [round_trip, without["hits"], without["shots"]])
func test_beyond_the_cap_the_shooter_has_to_lead() -> void:
# A 500 ms round trip needs more rewind than the server allows.
var result: Dictionary = _play(250.0, true)
assert_true(result["lag"] > Tuning.LAG_COMPENSATION_MAX_TICKS + 4.0, "needs %.1f ticks" % result["lag"])
assert_true(result["shots"] >= 38)
assert_true(result["hits"] <= result["shots"] / 4, "%d of %d hit" % [result["hits"], result["shots"]])
@@ -0,0 +1 @@
uid://bt1u386uvlyer
+186
View File
@@ -0,0 +1,186 @@
extends TestCase
## Issue N4, in the simulation: hitscan shots judged against where the target was when
## the shooter saw it, and the limits on what a shooter may claim to have seen.
##
## A shooter stands still with a signal revolver, facing +z. A target 20 m away walks
## across at 4 m/s. The shooter aims at where the target was some ticks ago, as a
## client drawing the past would, and says how far back that was.
const SHOOTER_FEET: Vector3 = Vector3(500.0, 0.0, 500.0)
const RANGE: float = 20.0
const CAP: int = Tuning.LAG_COMPENSATION_MAX_TICKS
const STEPS: int = PlayerCommand.VIEW_LAG_STEPS_PER_TICK
var sim: Simulation
var shooter: SimEntity
var target: SimEntity
## Where the target was before each tick.
var path: Array[Vector3] = []
func before_each() -> void:
sim = Simulation.new(5, SimGround.flat())
shooter = sim.entities.find(sim.add_player())
shooter.position = SHOOTER_FEET
shooter.on_ground = true
var revolver: int = ItemCatalog.code_of("signal_revolver")
Inventory.give(shooter, revolver, 1)
Inventory.give(shooter, ItemCatalog.get_def(revolver).ammo_code, 60)
shooter.selected = 1
target = sim.entities.find(sim.add_player())
target.position = SHOOTER_FEET + Vector3(-7.0, 0.0, RANGE)
target.on_ground = true
path.clear()
## Runs a tick: the target walks towards +x (or does `target_buttons` on the spot), and
## the shooter looks at `aim` saying it sees `lag` quarter ticks back, firing if asked.
## Returns the damage done to the target.
func _tick(aim: Vector3, lag: int, fire: bool, target_moves: bool = true, target_buttons: int = 0) -> int:
path.append(target.position)
var eye: Vector3 = Harvest.eye(shooter)
var to: Vector3 = aim - eye
var buttons: int = PlayerCommand.BUTTON_AIM | (PlayerCommand.BUTTON_FIRE if fire else 0)
var command: PlayerCommand = PlayerCommand.from_input(sim.tick, Vector2.ZERO, atan2(to.x, to.z), atan2(to.y, Vector2(to.x, to.z).length()), buttons, 1)
command.view_lag = lag
assert_true(sim.submit_command(shooter.id, command))
# Facing +z, right is -x, so a negative strafe walks towards +x.
sim.submit_command(target.id, PlayerCommand.from_input(sim.tick, Vector2(-1.0 if target_moves else 0.0, 0.0), 0.0, 0.0, target_buttons))
sim.step()
var damage: int = 0
for event: Dictionary in sim.events:
if event["type"] == "player_hit" and event["victim"] == target.id:
damage += int(event["health"]) + int(event["armor"])
target.health = Tuning.PLAYER_MAX_HEALTH
return damage
## The middle of the target's chest where it was `ticks` before the tick about to run.
func _chest(ticks: float) -> Vector3:
var at: float = sim.tick - ticks
var from: int = floori(at)
var feet: Vector3 = target.position if from >= path.size() else path[from]
if from + 1 < path.size():
feet = feet.lerp(path[from + 1], at - from)
elif from + 1 == path.size():
feet = feet.lerp(target.position, at - from)
return feet + Vector3(0.0, 1.0, 0.0)
## Lets the target walk for `ticks` while the shooter watches, seeing `lag` quarter
## ticks back, as a client's every command says.
func _walk(ticks: int, lag: int = 0) -> void:
for _tick_index: int in ticks:
_tick(SHOOTER_FEET + Vector3(0.0, 1.0, RANGE), lag, false)
func test_the_target_really_walks_across() -> void:
_walk(30)
assert_near(target.position.x - path[0].x, Tuning.WALK_SPEED, 0.2)
assert_near(target.position.z, SHOOTER_FEET.z + RANGE, 0.001)
func test_a_shot_at_where_the_target_was_seen_hits_and_the_same_shot_unrewound_misses() -> void:
for lag_ticks: float in [6.0, 9.25, 12.5, float(CAP)]:
var lag: int = roundi(lag_ticks * STEPS)
before_each()
_walk(45, lag)
assert_near(Weapons.view_time(shooter, sim.tick - 1), sim.tick - 1 - lag_ticks, 0.001)
assert_true(_tick(_chest(lag_ticks), lag, true) > 0, "seen %.2f ticks back: a hit" % lag_ticks)
before_each()
_walk(45)
var behind: float = _chest(lag_ticks).distance_to(_chest(0.0))
assert_true(behind > 0.75)
assert_eq(_tick(_chest(lag_ticks), 0, true), 0, "the same aim judged in the present misses by %.2f m" % behind)
func test_aiming_at_the_present_with_no_lag_still_hits() -> void:
_walk(45)
assert_true(_tick(_chest(0.0), 0, true) > 0)
assert_eq(Weapons.view_time(shooter, sim.tick - 1), -1.0, "nothing to rewind")
func test_beyond_the_cap_the_claim_is_cut_to_the_cap() -> void:
# Thirty ticks back the target was 4 m from where it is now and 2 m from where it
# was at the cap. Claiming to see that far back doesn't make the shot land.
_walk(45, 30 * STEPS)
assert_near(Weapons.view_time(shooter, sim.tick - 1), float(sim.tick - 1 - CAP), 0.001, "judged at the cap, not at the claim")
assert_eq(_tick(_chest(30.0), 30 * STEPS, true), 0, "30 ticks back")
_walk(20, 255)
assert_eq(_tick(_chest(30.0), 255, true), 0, "the largest claim a command can hold")
# What the server did was judge both at the cap, where a shot does land.
_walk(20, 255)
assert_true(_tick(_chest(float(CAP)), 255, true) > 0)
func test_nobody_can_look_further_back_than_they_already_have() -> void:
_walk(45)
# Seeing the present all along, then one shot claiming to see ten ticks back.
assert_eq(_tick(_chest(10.0), 10 * STEPS, true), 0, "a sudden claim of the past is not believed")
assert_true(Weapons.view_time(shooter, sim.tick - 1) >= sim.tick - 2.0, "still judged within a tick of the present")
# A client really seeing ten ticks back says so with every command. Its view
# stands still until time has caught up with the claim, then moves with it.
_walk(20, 10 * STEPS)
assert_near(Weapons.view_time(shooter, sim.tick - 1), sim.tick - 1 - 10.0, 0.001)
assert_true(_tick(_chest(10.0), 10 * STEPS, true) > 0)
func test_the_world_is_judged_as_it_is_now() -> void:
_walk(45, 40)
# A wall goes up between them after the shooter's view of the target was drawn.
var wall: Vector3 = SHOOTER_FEET + Vector3(-20.0, 0.0, RANGE * 0.5)
sim.ground.add_solid(AABB(wall, Vector3(40.0, 4.0, 0.4)))
assert_eq(_tick(_chest(10.0), 40, true), 0, "the wall stops the shot")
func test_a_target_eliminated_since_is_not_hit() -> void:
_walk(45, 40)
target.eliminated = true
assert_eq(_tick(_chest(10.0), 40, true), 0)
var hits: int = 0
for event: Dictionary in sim.events:
if event["type"] == "impact" and event["hit"] == Weapons.HIT_PLAYER:
hits += 1
assert_eq(hits, 0)
func test_the_body_is_as_tall_as_it_was_then() -> void:
# The target crouches on the spot, then stands up.
for _crouched: int in 20:
_tick(SHOOTER_FEET + Vector3(0.0, 1.0, RANGE), 0, false, false, PlayerCommand.BUTTON_CROUCH)
for _standing: int in 6:
_tick(SHOOTER_FEET + Vector3(0.0, 1.0, RANGE), 0, false, false)
var head: Vector3 = target.position + Vector3(0.0, Tuning.PLAYER_HEIGHT - 0.15, 0.0)
assert_true(_tick(head, 0, true, false) > 0, "standing now: the head is there")
before_each()
for _crouched: int in 20:
_tick(SHOOTER_FEET + Vector3(0.0, 1.0, RANGE), 12 * STEPS, false, false, PlayerCommand.BUTTON_CROUCH)
for _standing: int in 6:
_tick(head, 12 * STEPS, false, false)
assert_eq(_tick(head, 12 * STEPS, true, false), 0, "twelve ticks ago it was crouched: nothing at head height")
func test_history_is_kept_only_as_far_back_as_the_cap_and_forgotten_with_the_player() -> void:
_walk(60)
var now: AABB = Weapons.body_box(target)
var then: AABB = sim.hit_history.box_at(target, float(sim.tick - CAP))
assert_near(now.position.x - then.position.x, Tuning.WALK_SPEED * CAP / Tuning.TICK_RATE_HZ, 0.05)
assert_eq(sim.hit_history.box_at(target, float(sim.tick - 40)), now, "too old to be stored: the present stands in")
var half: AABB = sim.hit_history.box_at(target, sim.tick - 4.5)
var a: AABB = sim.hit_history.box_at(target, float(sim.tick - 5))
var b: AABB = sim.hit_history.box_at(target, float(sim.tick - 4))
assert_near(half.position.x, (a.position.x + b.position.x) * 0.5, 0.0001, "between ticks")
sim.remove_player(target.id)
assert_eq(sim.hit_history._tracks.has(target.id), false)
func test_a_replay_of_the_same_commands_ends_in_the_same_state() -> void:
var hashes: Array[String] = []
for _run: int in 2:
before_each()
_walk(40, 8 * STEPS)
for round: int in 60:
_tick(_chest(8.0), 8 * STEPS, round % 20 == 5)
hashes.append(sim.state_hash())
assert_eq(hashes[0], hashes[1])
+1
View File
@@ -0,0 +1 @@
uid://bq2vtw33eqjor
+11 -1
View File
@@ -26,7 +26,17 @@ func test_round_trip_preserves_every_field() -> void:
func test_encoding_is_compact_and_fixed_size() -> void:
assert_eq(PlayerCommand.new().encode().size(), PlayerCommand.ENCODED_SIZE)
assert_eq(PlayerCommand.ENCODED_SIZE, 14)
assert_eq(PlayerCommand.ENCODED_SIZE, 15)
func test_view_lag_round_trips_and_is_clamped_to_a_byte() -> void:
var command: PlayerCommand = PlayerCommand.new()
command.view_lag = 37
assert_eq(PlayerCommand.decode(command.encode()).view_lag, 37)
command.view_lag = 9000
assert_eq(PlayerCommand.decode(command.encode()).view_lag, 255)
command.view_lag = -5
assert_eq(PlayerCommand.decode(command.encode()).view_lag, 0)
func test_decode_at_an_offset() -> void: