harvest/game/tests/test_coop.gd
Forrest 39f9d15cfe Co-op voice/session work, config retune, net budget tool, overhaul plan
Snapshot of in-progress work before the alien overhaul so worker
worktrees branch from current code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:35:53 -04:00

429 lines
20 KiB
GDScript

extends RefCounted
## Co-op in one process: the host's farm in the main tree and the partner's in a SubViewport
## with its own world (so the two don't share physics), joined by a loopback CoopLink and stepped
## by hand, tick by tick. Covers the join (the welcome, both scarecrows on both farms, names,
## co-op health), requests from the partner (start the day, build, buy), the partner's scarecrow
## moving, gathering, and shooting on the host (and its pick of weapon), the weapons' stabs and
## pumpkin bombs (thrown from the off-hand, not with the right click leaving build mode) reaching the replica (drawn there, doing no damage of their own), enemies, loot,
## and shots reaching the replica,
## the co-op fall rule (one down is out until morning, both down is Game Over) and Retry, message
## sizes with a crowd, dropped unreliable messages, and either side leaving. And the traffic: the
## farm state isn't resent for the clock alone, a partner standing still sends little, enemies go
## by dead reckoning, and voice chat's codec and gate (CoopVoice).
const P := CampaignController.Phase
const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0)
var r: GameTestRunner
var host_farm: Node3D
var client_farm: Node3D
var host: FarmSim
var client: FarmSim
var hs: CoopSession
var cs: CoopSession
var links: Array[CoopLink]
var _viewport: SubViewport
func run(p_r: GameTestRunner) -> void:
r = p_r
await _setup()
_join()
_requests()
_quiet_wire()
await _partner_moves_and_gathers()
_night()
_partner_shoots()
_weapons_shown()
_fall_rule()
_crowd()
_leaving()
_voice()
for l in links:
l.close()
host_farm.queue_free()
_viewport.get_parent().queue_free()
await r.process_frame
func _setup() -> void:
host_farm = (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
r.root.add_child(host_farm)
_viewport = SubViewport.new()
_viewport.own_world_3d = true
_viewport.size = Vector2i(320, 180)
var box := SubViewportContainer.new()
r.root.add_child(box)
box.add_child(_viewport)
client_farm = (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
_viewport.add_child(client_farm)
await r.process_frame
await r.physics_frame
host = host_farm.get_node("FarmSim") as FarmSim
client = client_farm.get_node("FarmSim") as FarmSim
for f: FarmSim in [host, client]:
f.set_physics_process(false)
f.coop.set_physics_process(false)
f.waves.enabled = false
host.player.global_position = AWAY
host.waves.rng.seed = 1 # repeatable arrival points
hs = host.coop
cs = client.coop
links = CoopLink.pair()
## One tick on both machines, in the order the frames would run them.
func _pump(n: int = 1) -> void:
for i in n:
for body: PlayerCharacter in _remote_bodies():
body._follow_net(DT)
host.step(DT)
hs._physics_process(DT)
client.step(DT)
cs._physics_process(DT)
func _remote_bodies() -> Array[PlayerCharacter]:
var out: Array[PlayerCharacter] = []
for f: FarmSim in [host, client]:
for a in f.avatars:
if a.body.remote_driven:
out.append(a.body)
return out
func _same_state() -> bool:
var a := host.campaign.state.to_dict()
var b := client.campaign.state.to_dict()
for d: Dictionary in [a, b]:
d.erase("phase_time_left")
d.erase("night_events")
return JSON.stringify(a, "", true, true) == JSON.stringify(b, "", true, true)
func _join() -> void:
hs.start_host(host, links[0], "Ana", "Ben")
cs.start_client(client, links[1], "Ben")
_pump(2)
r.check(hs.is_host() and cs.is_client() and client.replica and not host.replica, "the host and the partner each take their role")
r.check(host.avatars.size() == 2 and client.avatars.size() == 2 and host.partner.remote != null and not host.partner.is_local
and client.local_avatar.slot == 1 and client.avatars[0].body.remote_driven and host.partner.body.remote_driven,
"both farms have both scarecrows: the host plays P1, the partner P2")
r.check(client.player == client.avatars[1].body and client.scarecrow.slot == 1 and client.hud.kit == client.scarecrow
and (client.camera as FollowCamera).target == client.player, "the partner's HUD and camera follow P2")
r.check(host.campaign.state.coop and client.campaign.state.coop and host.campaign.state.partner_hp == host.config.scarecrow_max_hp,
"co-op is on: P2 has full health")
r.check(client.campaign.state.phase == P.MORNING and _same_state(), "the partner's farm is the host's (the welcome)")
r.check(host.avatars[0].body._tag.text == "P1 Ana" and host.avatars[1].body._tag.text == "P2 Ben"
and client.avatars[0].body._tag.text == "P1 Ana" and client.avatars[1].body._tag.text == "P2 Ben", "name tags over both")
r.check(client.campaign.save_path == "" and client.audio.remote_cues and host.audio.forward.is_valid(), "only the host saves; sounds come from the host")
func _requests() -> void:
client.review_panel._start.pressed.emit()
_pump(2)
r.check(host.campaign.state.phase == P.DAY and client.campaign.state.phase == P.DAY, "the partner can start the day (the host does it)")
host.campaign.state.resources.shed = {"wood": 40, "scrap": 30, "straw": 30}
client.player.global_position = Vector3(2.0, 0.0, 6.0)
_pump(4)
var before := host.structures.count()
client.build.place_request.call("fence", 3.5, 8.0, 0)
_pump(20)
r.check(host.structures.count() == before + 1 and client.structures.count() == before + 1 and _same_state(),
"the partner builds a fence: the host checks it, builds it, and both farms show it")
client.build.place_request.call("fence", 30.0, -30.0, 0)
_pump(20)
r.check(host.structures.count() == before + 1, "a placement out of the partner's reach is refused by the host")
client.upgrade_panel.buy_request.call("corn_shooter")
_pump(20)
r.check(Upgrades.owned(host.campaign.state, "corn_shooter") and Upgrades.owned(client.campaign.state, "corn_shooter"),
"the partner buys an upgrade at the workbench (the host does it)")
## Standing still by day: the clock runs, nothing else changes.
func _quiet_wire() -> void:
_pump(30) # the requests' news settles
var states := links[0].sent_count("state")
var inputs := links[1].sent_count("input")
var left := host.campaign.state.phase_time_left
_pump(120)
r.check(host.campaign.state.phase_time_left < left - 1.5 and links[0].sent_count("state") == states,
"the day's clock runs on both farms, but the farm state isn't resent for it")
var n := links[1].sent_count("input") - inputs
r.check(n >= 7 and n <= 9, "the partner standing still sends its input %d times in 2 s (every %.2f s, not every frame)"
% [n, CoopSession.INPUT_KEEPALIVE])
r.check(absf(client.campaign.state.phase_time_left - host.campaign.state.phase_time_left) < 0.2,
"and the partner's clock follows the host's (from the snapshots)")
func _partner_moves_and_gathers() -> void:
var tree: GatherNode
for n in host.interactions.nodes:
if n.name == "DeadTree":
tree = n
var at := tree.global_position + Vector3(tree.reach * 0.7, 0.0, 0.0)
client.player.global_position = at
_pump(10)
r.check(host.partner.body.global_position.distance_to(at) < 0.3, "the host's copy of P2 follows the partner's own moves")
host.campaign.state.resources.pouch = {"wood": 0, "scrap": 0, "straw": 0}
Input.action_press("interact")
_pump(roundi(host.config.gather_time * 60.0) - 20)
var gathering_there := client.interactions.gathering != null and String(client.interactions.gathering.name) == "DeadTree" and client.player.rooted
_pump(40)
Input.action_release("interact")
_pump(20)
r.check(gathering_there, "while P2 gathers, the partner sees it (the channel, rooted) from the host")
r.check(int(host.campaign.state.resources.pouch["wood"]) >= 2 and int(client.campaign.state.resources.pouch["wood"]) >= 2
and int(host.campaign.state.night_events.get("gathered_wood", 0)) >= 2, "P2 gathered wood into the shared pouch (%s)" % [host.campaign.state.resources.pouch])
r.check(not client.player.rooted, "and is free to move again")
await r.process_frame
func _night() -> void:
host.campaign.advance_phase()
host.campaign.advance_phase()
_pump(2)
r.check(host.campaign.state.phase == P.NIGHT and client.campaign.state.phase == P.NIGHT, "night falls on both farms")
# Far from P1 (waiting at AWAY, on the farm's edge): where the north gaps were.
host.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["north"])
host.spawn_enemy(EnemySystem.TYPE_THIEF, LootSystem.ANY, GameTestRunner.EDGE["north"])
host.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["driveway"])
_pump(30)
var types_host := _types(host.enemies)
var types_client := _types(client.enemies)
r.check(host.enemies.alive_count() == 3 and types_client == types_host, "the enemies reach the partner's farm, by type (%s)" % [types_client])
r.check(_enemies_match(0.6), "where the host has them (within 0.6 m)")
r.check(client.characters.in_use() == 2, "the partner draws the ground enemies with characters")
# A crow steals: the loot follows on the partner's farm.
var stolen := false
for i in 1800:
_pump()
if host.loot.count(LootSystem.Status.CARRIED) > 0:
stolen = true
break
_pump(8)
var carried := -1
for id in range(1, host.loot.item_count + 1):
if host.loot.status[id] == LootSystem.Status.CARRIED:
carried = id
r.check(stolen and carried > 0 and client.loot.status[carried] == LootSystem.Status.CARRIED
and client.enemies.resolve_handle(client.loot.holder[carried]) >= 0, "a carried crop is carried on both farms, by the same enemy")
var killed := host.enemies.alive_count()
for d in host.enemies.active_count:
host.enemies.apply_hit(d, 99)
_pump(6)
r.check(killed > 0 and host.enemies.alive_count() == 0 and client.enemies.alive_count() == 0, "killed on the host, gone on the partner's farm")
func _partner_shoots() -> void:
var fired := host.partner.combat.shots_fired
var heard := int(client.audio.played.get("shot", 0))
r.check(client.combat.equip(ScarecrowCombat.Weapon.CORN_SHOOTER), "the partner takes the corn shooter (bought for both)")
client.player.global_position = Vector3(8.0, 0.0, -10.0) # open ground, nothing east of it
client.combat.device = ScarecrowCombat.Device.GAMEPAD # keeps the aim it's given
_pump(10)
r.check(host.partner.combat.weapon == ScarecrowCombat.Weapon.CORN_SHOOTER and host.avatars[0].combat.weapon == ScarecrowCombat.Weapon.PITCHFORK,
"the host sees P2 holding it, and P1 still has the pitchfork")
client.combat.aim = Vector2(1.0, 0.0)
Input.action_press("fire")
_pump(30)
r.check(client.projectiles.active_count > 0, "shots in flight show on the partner's farm (the host's, %d)" % client.projectiles.active_count)
Input.action_release("fire")
_pump(10)
r.check(host.partner.combat.shots_fired > fired, "the partner holds fire: P2's gun fires on the host (%d shots)" % (host.partner.combat.shots_fired - fired))
r.check(int(client.audio.played.get("shot", 0)) > heard, "and the partner hears the shots")
r.check(client.projectiles.fired == 0, "(the partner's own gun only aims: it fired nothing itself)")
func _weapons_shown() -> void:
var p1 := client.avatars[0].combat # the host's scarecrow, on the partner's farm
p1.models._attack_t = -1.0
host.combat.equip(ScarecrowCombat.Weapon.PITCHFORK)
host.combat.reset()
host.combat.attack_toward(Vector2(host.player.global_position.x + 3.0, host.player.global_position.z))
_pump(3)
r.check(p1.weapon == ScarecrowCombat.Weapon.PITCHFORK and p1.models._attack_t >= 0.0, "P1's pitchfork stab shows on the partner's farm")
host.campaign.state.upgrades["pumpkin_bomb"] = 1
host.combat.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB)
host.combat.ready_for_morning()
var bursts := client.bombs.bursts
host.combat.offhand_toward(Vector2(host.player.global_position.x + 6.0, host.player.global_position.z))
_pump(3)
r.check(p1.weapon == ScarecrowCombat.Weapon.PITCHFORK and client.bombs.flying() == 1,
"P1's pumpkin bomb flies on the partner's farm too (from the off-hand: the pitchfork stays in hand there)")
_pump(90)
r.check(client.bombs.bursts == bursts + 1 and client.bombs.enemies_hit == 0 and host.bombs.flying() == 0,
"and bursts there, harmless (the host's burst does the damage)")
r.check(client.combat.offhand == ScarecrowCombat.Weapon.PUMPKIN_BOMB and host.partner.combat.offhand == ScarecrowCombat.Weapon.PUMPKIN_BOMB,
"the partner has bombs in its off-hand too (bought for both)")
var thrown := host.partner.combat.bombs_thrown
var attacks := host.partner.combat.attacks()
Input.action_press("offhand")
_pump(10)
Input.action_release("offhand")
_pump(4)
r.check(host.partner.combat.bombs_thrown == thrown + 1 and host.partner.combat.attacks() == attacks + 1 and client.combat.bomb_left > 0.0,
"the partner's right click throws on the host (and nothing else), and its recharge shows on the partner's HUD")
_pump(roundi(host.config.bomb_cooldown * 60.0) + 10)
client.build.set_active(true)
_pump(4)
thrown = host.partner.combat.bombs_thrown
Input.action_press("cancel") # the right mouse button: both actions
Input.action_press("offhand")
_pump(10)
var left := not client.build.active
Input.action_release("cancel")
Input.action_release("offhand")
_pump(4)
r.check(left and host.partner.combat.bombs_thrown == thrown,
"the partner's right click that leaves build mode throws nothing on the host, even held")
_pump(90)
for c: ScarecrowCombat in [host.combat, client.combat]:
c.equip(ScarecrowCombat.Weapon.PITCHFORK)
host.campaign.state.upgrades.erase("pumpkin_bomb")
_pump(4)
func _fall_rule() -> void:
host.partner.kit.invulnerable_left = 0.0
host.partner.kit.try_damage(99)
_pump(6)
r.check(not host.partner.kit.alive and host.campaign.state.phase == P.NIGHT and not host.campaign.is_over(),
"in co-op one scarecrow down is out until morning, not Game Over")
r.check(not client.scarecrow.alive and not client.player.alive, "the partner sees their own scarecrow fall")
client._process(0.0)
r.check((client.camera as FollowCamera).target == client.avatars[0].body, "and their camera watches P1 meanwhile")
host.scarecrow.invulnerable_left = 0.0
host.scarecrow.try_damage(99)
_pump(6)
r.check(host.campaign.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW and client.campaign.outcome == host.campaign.outcome
and client.campaign.state.phase == P.GAME_OVER, "both down: Game Over on both farms")
client.end_panel._process(EndPanel.DELAY + 0.1)
r.check(client.end_panel.mode == "failure", "with the failure screen on the partner's too")
client.end_panel._retry.pressed.emit()
_pump(4)
r.check(host.campaign.state.phase == P.MORNING and client.campaign.state.phase == P.MORNING and host.scarecrow.alive
and host.partner.kit.alive and client.scarecrow.alive and host.campaign.state.coop, "Retry from the partner: both back at the morning")
func _crowd() -> void:
host.campaign.begin_day()
host.campaign.advance_phase()
host.campaign.advance_phase()
for i in 90:
host.spawn_enemy([EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER][i % 3])
links[0].drop_every = 3 # a third of the unreliable messages lost
_pump(60)
r.check(client.enemies.alive_count() == host.enemies.alive_count() and host.enemies.alive_count() > 40,
"a crowd of %d enemies, with a third of the snapshots lost, all show" % host.enemies.alive_count())
r.check(_enemies_match(1.0), "close to where the host has them")
r.check(links[0].oversized == 0 and links[1].oversized == 0 and links[0].largest_unreliable <= CoopLink.UNRELIABLE_LIMIT,
"no unreliable message is too big for a datagram (largest %d bytes)" % links[0].largest_unreliable)
r.info("co-op traffic: host sent %d messages, %.1f KB in %d ticks; partner %d messages" % [links[0].sent_messages,
links[0].sent_bytes / 1024.0, hs.ticks, links[1].sent_messages])
links[0].drop_every = 0
# Dead reckoning: two seconds of the crowd, against every enemy in every snapshot.
var records := hs.foe_records
var bytes := links[0].sent_bytes
var partner_bytes := links[1].sent_bytes
var snaps := links[0].sent_count("snap")
var crowd := host.enemies.alive_count()
_pump(120)
var every := crowd * (links[0].sent_count("snap") - snaps)
r.check(hs.foe_records - records < every / 2, "the host sends %d enemy records in 2 s, not %d (only the ones the partner's guess drifted from)"
% [hs.foe_records - records, every])
r.check(_enemies_match(1.0), "and the partner's crowd still matches the host's")
r.info("crowd of %d: host %.1f KB/s, partner %.1f KB/s (before GD-Sync's wrapping)" % [crowd,
(links[0].sent_bytes - bytes) / 2048.0, (links[1].sent_bytes - partner_bytes) / 2048.0])
func _leaving() -> void:
var gone: Array[String] = []
cs.ended.connect(func(why: String) -> void: gone.append(why))
links[1].close() # the partner quits
_pump(2)
r.check(not hs.is_active() and host.partner == null and host.avatars.size() == 1 and not host.campaign.state.coop
and not is_instance_valid(host.get_parent().get_node_or_null("Player2")) or host.get_parent().get_node("Player2").is_queued_for_deletion(),
"the partner leaves: the host plays on alone")
r.check(not cs.is_active() and gone.size() == 1, "and the partner's game is told the session is over ('%s')" % (gone[0] if not gone.is_empty() else ""))
host.campaign.state.coop = true # as a co-op morning's save would have it
host.campaign.retry_night()
r.check(not host.campaign.state.coop, "a co-op morning played alone goes back to the solo rules")
## Voice chat's sending, without GD-Sync: the gate, the pieces, and the codec.
func _voice() -> void:
var v := CoopVoice.new()
var mix := 48000.0
var hum := _frames(mix, 1.0, func(t: float) -> float: return 0.003 * sin(TAU * 50.0 * t))
r.check(v.feed(hum, mix).is_empty(), "voice: a quiet microphone (room hum) sends nothing")
var click := _frames(mix, 0.03, func(t: float) -> float: return 0.6 if int(t * 4000.0) % 2 == 0 else -0.6)
var sent := v.feed(click, mix)
sent.append_array(v.feed(hum, mix))
r.check(sent.is_empty(), "a click alone doesn't open the gate")
var words := v.feed(_frames(mix, 0.6, func(t: float) -> float: return 0.2 * sin(TAU * 220.0 * t)), mix)
words.append_array(v.feed(hum, mix))
var size := 3 + CoopVoice.CHUNK / 2
var all_sized := true
for piece in words:
all_sized = all_sized and piece.size() == size
r.check(words.size() >= 12 and words.size() <= 22 and all_sized,
"speech opens it: %d pieces of %d bytes (0.6 s of voice, the piece before, and the hold)" % [words.size(), size])
r.check(v.feed(hum, mix).is_empty(), "and the gate shuts again after the hold")
var kbs := size * float(CoopVoice.RATE) / CoopVoice.CHUNK / 1024.0
r.check(kbs < 7.0, "talking costs %.1f KB/s before GD-Sync's wrapping (GD-Sync's raw VoiceChat: about 47)" % kbs)
v.free()
var tone := PackedFloat32Array()
for i in 2 * CoopVoice.CHUNK:
tone.append(0.25 * sin(TAU * 300.0 * i / CoopVoice.RATE) + 0.1 * sin(TAU * 1100.0 * i / CoopVoice.RATE))
var state := [0, 0]
var first := CoopVoice.encode(tone.slice(0, CoopVoice.CHUNK), state)
var second := CoopVoice.encode(tone.slice(CoopVoice.CHUNK), state)
var snr_first := _snr(tone.slice(0, CoopVoice.CHUNK), CoopVoice.decode(first))
var snr_second := _snr(tone.slice(CoopVoice.CHUNK), CoopVoice.decode(second))
r.check(snr_first > 15.0 and snr_second > 25.0,
"ADPCM keeps the sound: %.0f dB signal to noise from a cold start (a few samples to adapt), %.0f dB running" % [snr_first, snr_second])
r.check(CoopVoice.decode(second).size() == CoopVoice.CHUNK, "and a piece decodes on its own (a lost one before it costs nothing more)")
## Stereo microphone frames: seconds of f(t) at mix Hz.
static func _frames(mix: float, seconds: float, f: Callable) -> PackedVector2Array:
var out := PackedVector2Array()
out.resize(roundi(mix * seconds))
for i in out.size():
var s: float = f.call(i / mix)
out[i] = Vector2(s, s)
return out
static func _snr(a: PackedFloat32Array, b: PackedFloat32Array) -> float:
var sig := 0.0
var noise := 0.0
for i in mini(a.size(), b.size()):
sig += a[i] * a[i]
noise += (a[i] - b[i]) * (a[i] - b[i])
return 10.0 * log(sig / maxf(noise, 1e-12)) / log(10.0)
func _types(es: EnemySystem) -> Dictionary:
var out := {}
for d in es.active_count:
if es.alive[d] == 1:
out[es.type[d]] = int(out.get(es.type[d], 0)) + 1
return out
## Every host enemy has a partner-side copy within tolerance meters.
func _enemies_match(tolerance: float) -> bool:
var es := host.enemies
for d in es.active_count:
if es.alive[d] == 0:
continue
var h := cs._local_handle(es.handle_of(d))
var c := client.enemies.resolve_handle(h)
if c < 0:
return false
if Vector2(es.pos_x[d] - client.enemies.pos_x[c], es.pos_z[d] - client.enemies.pos_z[c]).length() > tolerance:
return false
return true