class_name CoopSession extends Node ## Co-op for two over a CoopLink (GD-Sync, or loopback in tests). The host's farm is the real ## one: it simulates both scarecrows, every enemy, all the loot, and the campaign, and saves. ## The partner's farm is a replica (FarmSim.replica): it simulates nothing and shows what the ## host sends, except its own scarecrow, which it moves itself (so moving never waits on the ## network) and whose buttons it sends to the host. ## ## Host -> partner ## welcome (reliable, once) the farm state, the phase, tonight's time, the loot, the names ## batch (reliable, each tick with news) events in order: phase changes (with the state), ## the end of the campaign, sounds, toasts for the partner, loot and arrival news, ## breaches, fear bursts, gather popups, the workbench; enemies removed ## state (reliable, at most STATE_HZ, when it changed) the farm state ## loot (reliable, at most LOOT_HZ, when it changed) every item ## snap (unreliable, SNAP_HZ) the phase clock, both scarecrows, the animals ## foes (unreliable, SNAP_HZ, in chunks) every enemy, 16 bytes each ## shots (unreliable, SNAP_HZ) the shots in flight ## Partner -> host ## hello (reliable) its player's name ## input (unreliable, INPUT_HZ) its scarecrow's position and facing, held buttons and press ## counts, aim, build mode, the upgrade menu (RemoteControls) ## req (reliable) start the day, start the night early, retry the night, build, ## dismantle, buy an upgrade ## Unreliable messages stay under CoopLink.UNRELIABLE_LIMIT; nothing depends on any single one ## arriving (enemies missed by a snapshot appear in the next; removals are reliable). ## Voice chat (GD-Sync only, start_voice): a CoopVoice per player, owned by that player's client. enum Role { SOLO, HOST, CLIENT } signal partner_joined(name: String) signal partner_left(name: String) ## Partner: the host went away (or the session was closed). signal ended(reason: String) ## Partner: the first full state arrived; the game is on. signal welcomed const SNAP_EVERY := 3 # physics ticks: 20 Hz const INPUT_EVERY := 2 # 30 Hz const STATE_EVERY := 15 # 4 Hz const LOOT_EVERY := 6 # 10 Hz const ENEMY_CHUNK := 56 const MAX_SHOTS := 60 ## Partner: seconds without a word from the host before it counts as gone. const TIMEOUT := 8.0 var role: Role = Role.SOLO var sim: FarmSim var link: CoopLink var my_name := "" var partner_name := "" ## Ticks since the session started, and seconds since the other side was last heard. var ticks: int = 0 var quiet: float = 0.0 ## Voice chat: one per player (slot), and whether this machine's microphone is on. var voices: Array[CoopVoice] = [] var microphone := true # Host var _events: Array = [] var _removed: Array = [] var _state_hash: int = 0 var _loot_hash: int = 0 var _connections: Array = [] # [Signal, Callable] to undo # Partner var _map := {} # host enemy handle -> local handle var _gone := {} # host handles already removed (a late snapshot mustn't bring them back) var _targets := {} # local handle -> PackedFloat32Array [x, z, hx, hz, vx, vz, alt] var _sender := RemoteControls.Sender.new() var _snap_tick: int = -1 var _structures_json := "" var _shed_json := "" var _is_welcomed := false var _welcome_sent := false var _hello_wait: float = 0.0 func is_active() -> bool: return role != Role.SOLO func is_host() -> bool: return role == Role.HOST func is_client() -> bool: return role == Role.CLIENT ## The host's side: the partner (name) is in; their scarecrow joins the farm. func start_host(p_sim: FarmSim, p_link: CoopLink, p_my_name: String, p_partner_name: String) -> void: sim = p_sim link = p_link role = Role.HOST my_name = p_my_name partner_name = p_partner_name ticks = 0 quiet = 0.0 link.received.connect(_on_message) sim.avatars[0].player_name = my_name var a := sim.add_partner(false, partner_name) a.body.remote_driven = true a.body.snap_to_net(a.body.global_position, 0.0) _tag_all() _hook(sim.campaign.phase_changed, func(phase: CampaignController.Phase, previous: CampaignController.Phase) -> void: _events.append(["phase", int(phase), int(previous), sim.campaign.state.to_dict(), sim.campaign.state.phase_time_left]) if phase == CampaignController.Phase.MORNING and sim.partner != null: _ensure_coop()) _hook(sim.campaign.campaign_ended, func(outcome: CampaignController.Outcome) -> void: _events.append(["ended", int(outcome), sim.campaign.state.to_dict()])) _hook(sim.enemies.enemy_removed, func(h: int, reason: EnemySystem.Removal, x: float, z: float, _c: int, _t: int) -> void: _removed.append([h, int(reason), x, z])) _hook(sim.waves.arrived, func(h: int, at: Vector2) -> void: var d := sim.enemies.resolve_handle(h) _events.append(["arrived", sim.enemies.type[d] if d >= 0 else 0, at])) _hook(sim.loot.loot_event, func(kind: StringName, id: int, at: Vector3) -> void: _events.append(["loot", String(kind), id, at])) _hook(sim.structures.destroyed, func(id: int, type: String, at: Vector3) -> void: _events.append(["destroyed", id, type, at])) for av in sim.avatars: var slot := av.slot _hook(av.kit.fear_used, func(_p: Vector3, _n: int) -> void: _events.append(["fear", slot])) _hook(av.combat.attacked, func(w: ScarecrowCombat.Weapon) -> void: _events.append(["attack", slot, int(w)])) _hook(sim.bombs.thrown, func(from: Vector3, to: Vector3) -> void: _events.append(["bomb", from, to])) _hook(a.interactions.message, func(text: String, color: Color) -> void: _events.append(["toast", text, color])) _hook(a.interactions.workbench_requested, func() -> void: _events.append(["workbench"])) _hook(a.interactions.gathered, func(m: String, amount: int, n: GatherNode) -> void: _events.append(["popup", "+%d %s" % [amount, m], n.global_position + Vector3(0.0, n.top() + 1.4, 0.0), GatherNode.COLORS[m]])) _hook(a.kit.patch_denied, func(missing: Dictionary) -> void: _events.append(["toast", "Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5)])) if sim.audio != null: sim.audio.forward = func(cue: String, at: Vector3) -> void: _events.append(["sound", cue, at]) _ensure_coop() _state_hash = 0 _loot_hash = 0 _welcome_sent = false # sent when the partner says hello (then it is surely listening) if sim.toasts != null: sim.toasts.push("%s joined: player 2's scarecrow is on the farm" % _display(partner_name, "P2"), Avatar.COLORS[1]) partner_joined.emit(partner_name) ## The partner's side: the farm becomes a replica of the host's; player 2's scarecrow is ours. func start_client(p_sim: FarmSim, p_link: CoopLink, p_my_name: String) -> void: sim = p_sim link = p_link role = Role.CLIENT my_name = p_my_name ticks = 0 quiet = 0.0 _is_welcomed = false link.received.connect(_on_message) var c := sim.campaign c.save_path = "" # only the host saves c.remote_request = func(what: String) -> void: _request([what]) sim.replica = true sim.replica_step = _replica_tick var a := sim.add_partner(true, my_name) sim.set_local(a) a.combat.replica = true # it only aims and shows its attacks: the host attacks for it sim.bombs.replica = true var first := sim.avatars[0] first.is_local = false first.body.remote_driven = true sim.build.place_request = func(type: String, x: float, z: float, rot: int) -> void: _request(["place", type, x, z, rot]) sim.build.dismantle_request = func(id: int) -> void: _request(["dismantle", id]) if sim.upgrade_panel != null: sim.upgrade_panel.buy_request = func(id: String) -> void: _request(["buy", id]) if sim.audio != null: sim.audio.remote_cues = true if sim.tutorial != null: sim.tutorial.enabled = false # the partner joins a game in progress _hello_wait = 0.0 # hello goes out (again every second) until the welcome arrives ## Ends the session on this side. The host carries on alone; the partner's game is left as a ## replica for Main to reset (it reloads the scene). func stop(reason: String = "") -> void: if role == Role.SOLO: return var was := role role = Role.SOLO for pair: Array in _connections: if (pair[0] as Signal).is_connected(pair[1]): (pair[0] as Signal).disconnect(pair[1]) _connections.clear() if link != null: if link.received.is_connected(_on_message): link.received.disconnect(_on_message) link.close() for v in voices: if is_instance_valid(v): v.queue_free() voices.clear() if sim != null and sim.audio != null: sim.audio.forward = Callable() if was == Role.HOST: var gone_name := partner_name sim.remove_partner() sim.avatars[0].player_name = "" sim.player.set_tag("", Color.WHITE) if sim.toasts != null: sim.toasts.push("%s left: you're on your own" % _display(gone_name, "Player 2"), Color(1.0, 0.8, 0.5)) partner_left.emit(gone_name) else: ended.emit(reason) ## Voice chat over GD-Sync: owners[slot] is each player's GD-Sync client id. func start_voice(gdsync: Node, owners: Array, mic_on: bool) -> void: for v in voices: v.queue_free() voices.clear() for slot in owners.size(): var v := CoopVoice.make(slot) add_child(v) gdsync.set_gdsync_owner(v, int(owners[slot])) voices.append(v) set_microphone(mic_on) func set_microphone(on: bool) -> void: microphone = on for v in voices: if on: v.unmute_microphone() else: v.mute_microphone() ## Whether the other player's voice is coming through now. func partner_speaking() -> bool: var other := 1 if role == Role.HOST else 0 return other < voices.size() and voices[other].speaking() ## GD-Sync calls this on the other machine (GDSyncLink). func net_receive(kind: String, data: Variant) -> void: if link != null: link.received.emit(kind, data) func _physics_process(dt: float) -> void: if role == Role.SOLO or link == null: return ticks += 1 quiet += dt if role == Role.HOST: link.poll() if _welcome_sent: _host_tick() elif quiet > TIMEOUT * 2.0: stop("Your friend didn't answer") else: if not _is_welcomed: link.poll() _hello_wait -= dt if _hello_wait <= 0.0: _hello_wait = 1.0 link.send("hello", {"name": my_name}, true) elif ticks % INPUT_EVERY == 0: _send_input() if link.closed or (role == Role.CLIENT and quiet > TIMEOUT): stop("The host left the game" if link.closed else "Lost the connection to the host") # --- Host ----------------------------------------------------------------------------------- func _host_tick() -> void: if ticks % SNAP_EVERY == 0: _send_snapshot() if ticks % STATE_EVERY == 0: var d := sim.campaign.state.to_dict() var h := hash(d) if h != _state_hash: _state_hash = h link.send("state", d, true) if ticks % LOOT_EVERY == 0: var rec := sim.loot.replica_record() var h := hash(rec) if h != _loot_hash: _loot_hash = h link.send("loot", rec, true) if not _events.is_empty() or not _removed.is_empty(): link.send("batch", {"events": _events, "removed": _removed}, true) _events = [] _removed = [] func _welcome() -> Dictionary: var c := sim.campaign return {"state": c.state.to_dict(), "phase": int(c.state.phase), "time": c.state.phase_time_left, "outcome": int(c.outcome), "night_time": sim.waves.night_time, "loot": sim.loot.replica_record(), "host": my_name} func _send_snapshot() -> void: var avs: Array = [] for a in sim.avatars: avs.append(_avatar_record(a)) link.send("snap", {"t": ticks, "time": sim.campaign.state.phase_time_left, "night": sim.waves.night_time, "av": avs, "an": sim.animals.replica_record()}, false) var es := sim.enemies var chunk := PackedByteArray() for d in es.active_count: if es.alive[d] == 0: continue chunk.append_array(_enemy_bytes(es, d)) if chunk.size() >= ENEMY_CHUNK * 16: link.send("foes", chunk, false) chunk = PackedByteArray() if not chunk.is_empty(): link.send("foes", chunk, false) link.send("shots", sim.projectiles.replica_record(MAX_SHOTS), false) static func _enemy_bytes(es: EnemySystem, d: int) -> PackedByteArray: var b := PackedByteArray() b.resize(16) b.encode_s32(0, es.handle_of(d)) b[4] = es.type[d] b[5] = es.state[d] b[6] = clampi(roundi(es.hurt[d] * 255.0), 0, 255) b[7] = clampi(roundi(es.alt[d] * 40.0), 0, 255) b.encode_s16(8, clampi(roundi(es.pos_x[d] * 100.0), -32768, 32767)) b.encode_s16(10, clampi(roundi(es.pos_z[d] * 100.0), -32768, 32767)) b.encode_s8(12, clampi(roundi(es.head_x[d] * 127.0), -127, 127)) b.encode_s8(13, clampi(roundi(es.head_z[d] * 127.0), -127, 127)) b.encode_s8(14, clampi(roundi(es.vel_x[d] * 20.0), -127, 127)) b.encode_s8(15, clampi(roundi(es.vel_z[d] * 20.0), -127, 127)) return b func _avatar_record(a: Avatar) -> Dictionary: var it := a.interactions var k := a.kit return {"s": a.slot, "p": a.body.global_position, "y": a.body.model.rotation.y, "v": a.body.move_strength(), "a": k.alive, "hp": k.hp(), "inv": k.invulnerable_left, "fl": k.fear_left, "w": int(a.combat.weapon), "bl": a.combat.bomb_left, "pt": k.patch_elapsed if k.patching else -1.0, "ch": String(a.body.channel_clip) if a.body.rooted else "", "fo": String(it.focus.name) if it.focus != null else "", "ga": String(it.gathering.name) if it.gathering != null else "", "ge": it.gather_elapsed, "rt": it.repair_target, "rp": it.repairing, "re": it.repair_elapsed} func _on_message(kind: String, data: Variant) -> void: quiet = 0.0 if role == Role.HOST: _host_message(kind, data) elif role == Role.CLIENT: _client_message(kind, data) func _host_message(kind: String, data: Variant) -> void: var a := sim.partner if a == null: return match kind: "hello": partner_name = String((data as Dictionary).get("name", partner_name)) a.player_name = partner_name _tag_all() if not _welcome_sent: _welcome_sent = true _events.clear() _removed.clear() link.send("welcome", _welcome(), true) "input": var rec := data as Dictionary a.remote.apply(rec) a.body.net_position = rec.get("p", a.body.net_position) a.body.net_yaw = float(rec.get("y", a.body.net_yaw)) a.body.net_speed = float(rec.get("v", 0.0)) "req": _do_request(data as Array) func _do_request(r: Array) -> void: var c := sim.campaign var a := sim.partner match String(r[0]): "begin_day": c.begin_day() "start_night_early": c.start_night_early() "retry_night": if c.state.phase == CampaignController.Phase.GAME_OVER: c.retry_night() "place": var type := String(r[1]) var x := float(r[2]) var z := float(r[3]) var rot := int(r[4]) if not StructureSystem.ORDER.has(type): return var why := sim.structures.validate(type, x, z, rot, a.position()) if why == "": sim.structures.place(type, x, z, rot) _events.append(["toast", "Built a %s" % StructureSystem.NAMES[type].to_lower(), Color(0.6, 1.0, 0.55)]) else: _events.append(["toast", why, Color(1.0, 0.8, 0.5)]) _events.append(["sound", "error", Vector3.INF]) "dismantle": var e := c.state.structure(int(r[1])) if e.is_empty() or a.position().distance_to(Vector2(e["x"], e["z"])) > sim.config.build_range: return var back := sim.structures.dismantle(int(r[1])) _events.append(["toast", "Dismantled the %s%s" % [StructureSystem.NAMES[e["type"]].to_lower(), (": %s back in the shed" % ResourceStore.describe(back)) if not back.is_empty() else ""], Color(0.85, 0.95, 1.0)]) "buy": var text := Upgrades.buy(c, String(r[1]), sim.structures) _events.append(["toast", text, Color(0.85, 0.75, 1.0) if text.contains("done:") else Color(1.0, 0.8, 0.5)]) ## Co-op is on for the farm state (after a retry, a new vacation, or a morning). func _ensure_coop() -> void: var s := sim.campaign.state if not s.coop: s.coop = true s.partner_max_hp = s.scarecrow_max_hp s.partner_hp = s.scarecrow_max_hp # --- Partner ---------------------------------------------------------------------------------- func _client_message(kind: String, data: Variant) -> void: match kind: "welcome": _welcome_received(data as Dictionary) "state": _apply_state(data as Dictionary) "loot": sim.loot.apply_replica(data as Dictionary, _local_handle) "snap": _apply_snap(data as Dictionary) "foes": _apply_foes(data as PackedByteArray) "shots": sim.projectiles.apply_replica(data as PackedFloat32Array) "batch": var b := data as Dictionary for r: Array in b.get("removed", []): _remove_foe(int(r[0]), int(r[1])) for e: Array in b.get("events", []): _apply_event(e) func _welcome_received(w: Dictionary) -> void: var c := sim.campaign partner_name = String(w.get("host", "")) sim.avatars[0].player_name = partner_name _tag_all() var previous := c.state.phase _apply_state(w["state"], true) c.state.phase = int(w["phase"]) as CampaignController.Phase c.state.phase_time_left = float(w["time"]) c.outcome = int(w["outcome"]) as CampaignController.Outcome sim.waves.night_time = float(w["night_time"]) _reset_world() sim.loot.apply_replica(w["loot"], _local_handle) c.phase_changed.emit(c.state.phase, previous) if sim.day_night != null: sim.day_night.snap() _is_welcomed = true if sim.toasts != null: sim.toasts.push("Joined %s's farm: you're player 2" % _display(partner_name, "the host"), Avatar.COLORS[1]) welcomed.emit() ## The host's farm state, keeping this machine's phase until the phase news arrives (in order). func _apply_state(d: Dictionary, everything: bool = false) -> void: var s := FarmState.from_dict(d) if s == null: return var c := sim.campaign if not everything: s.phase = c.state.phase s.phase_time_left = c.state.phase_time_left c.state = s var structures_json := JSON.stringify(d["structures"]) if everything or structures_json != _structures_json: _structures_json = structures_json sim.structures.sync_from_state() sim.animals.update_pen_open() var shed_json := JSON.stringify(d["resources"]) if everything or shed_json != _shed_json: _shed_json = shed_json sim.shed_stock.refresh() if sim.upgrade_panel != null and sim.upgrade_panel.is_open: sim.upgrade_panel.refresh() if c.state.phase == CampaignController.Phase.MORNING and sim.review_panel != null: sim.review_panel.refresh() func _apply_event(e: Array) -> void: var c := sim.campaign match String(e[0]): "phase": var previous := c.state.phase _apply_state(e[3], true) c.state.phase = int(e[1]) as CampaignController.Phase c.state.phase_time_left = float(e[4]) if c.state.phase == CampaignController.Phase.MORNING: _map.clear() _gone.clear() _targets.clear() c.phase_changed.emit(c.state.phase, previous) "ended": _apply_state(e[2], true) c.outcome = int(e[1]) as CampaignController.Outcome var terminal := CampaignController.Phase.FARMERS_RETURN if c.outcome == CampaignController.Outcome.VACATION_COMPLETE \ else CampaignController.Phase.GAME_OVER if c.state.phase != terminal: var previous := c.state.phase c.state.phase = terminal c.phase_changed.emit(terminal, previous) c.campaign_ended.emit(c.outcome) "sound": if sim.audio != null: sim.audio.play_remote(String(e[1]), e[2]) "toast": if sim.toasts != null: sim.toasts.push(String(e[1]), e[2]) "loot": sim.loot.loot_event.emit(StringName(e[1]), int(e[2]), e[3]) "arrived": if sim.toasts != null: sim.toasts.push(FarmSim.arrival_message(int(e[1]), sim.zones.side_of(e[2])), Color(1.0, 0.75, 0.55)) "destroyed": sim.structures.show_debris(e[3]) sim.structures.destroyed.emit(int(e[1]), String(e[2]), e[3]) "fear": var slot := int(e[1]) if slot < sim.avatars.size(): sim.avatars[slot].kit.play_burst() "attack": # our own scarecrow's attacks already show here var slot := int(e[1]) if slot < sim.avatars.size() and not sim.avatars[slot].is_local: var combat := sim.avatars[slot].combat combat.show_weapon(int(e[2])) combat.models.attack(int(e[2])) "bomb": sim.bombs.throw(e[1], e[2], 0, 0.0) # drawn only (replica) "popup": sim.interactions._popup(String(e[1]), e[2], e[3]) "workbench": if sim.upgrade_panel != null and c.is_daytime(): sim.upgrade_panel.open() func _apply_snap(snap: Dictionary) -> void: var t := int(snap.get("t", 0)) if t <= _snap_tick: return # an older one, out of order _snap_tick = t sim.campaign.state.phase_time_left = float(snap["time"]) sim.waves.night_time = float(snap["night"]) for rec: Dictionary in snap["av"]: var slot := int(rec["s"]) if slot >= sim.avatars.size(): continue _apply_avatar(sim.avatars[slot], rec) sim.animals.apply_replica(snap["an"]) func _apply_avatar(a: Avatar, rec: Dictionary) -> void: var k := a.kit var body := a.body if not a.is_local: body.net_position = rec["p"] body.net_yaw = float(rec["y"]) body.net_speed = float(rec["v"]) var s := sim.campaign.state if a.slot == 0: s.scarecrow_hp = clampi(int(rec["hp"]), 0, s.scarecrow_max_hp) else: s.partner_hp = clampi(int(rec["hp"]), 0, s.partner_max_hp) var alive := bool(rec["a"]) if alive != k.alive: k.alive = alive if alive: body.revive() else: body.die() k.invulnerable_left = float(rec["inv"]) k.fear_left = float(rec["fl"]) a.combat.bomb_left = float(rec.get("bl", 0.0)) if not a.is_local: a.combat.show_weapon(int(rec.get("w", 0))) var pt := float(rec["pt"]) k.patching = pt >= 0.0 k.patch_elapsed = maxf(pt, 0.0) if a.is_local: var ch := String(rec["ch"]) if ch != "" and (not body.rooted or body.channel_clip != StringName(ch)): body.start_channel(StringName(ch)) elif ch == "" and body.rooted and not (sim.upgrade_panel != null and sim.upgrade_panel.is_open): body.stop_channel() var it := a.interactions it.focus = _gather_node(String(rec["fo"])) it.gathering = _gather_node(String(rec["ga"])) as GatherNode it.gather_elapsed = float(rec["ge"]) it.repair_target = int(rec["rt"]) it.repairing = int(rec["rp"]) it.repair_elapsed = float(rec["re"]) func _gather_node(node_name: String) -> Node3D: if node_name == "": return null var it := sim.interactions if it.workbench != null and String(it.workbench.name) == node_name: return it.workbench for n in it.nodes: if String(n.name) == node_name: return n return null func _apply_foes(chunk: PackedByteArray) -> void: var es := sim.enemies for o in range(0, chunk.size() - 15, 16): var host := chunk.decode_s32(o) if _gone.has(host): continue var type := chunk[o + 4] var x := chunk.decode_s16(o + 8) / 100.0 var z := chunk.decode_s16(o + 10) / 100.0 var h: int = _map.get(host, -1) var d := es.resolve_handle(h) if h >= 0 else -1 if d < 0: h = es.spawn(type, x, z, Vector2(chunk.decode_s8(o + 12), chunk.decode_s8(o + 13))) if h < 0: continue _map[host] = h d = es.resolve_handle(h) es.state[d] = chunk[o + 5] es.hurt[d] = chunk[o + 6] / 255.0 var t := PackedFloat32Array([x, z, chunk.decode_s8(o + 12) / 127.0, chunk.decode_s8(o + 13) / 127.0, chunk.decode_s8(o + 14) / 20.0, chunk.decode_s8(o + 15) / 20.0, chunk[o + 7] / 40.0]) _targets[h] = t func _remove_foe(host: int, reason: int) -> void: _gone[host] = true var h: int = _map.get(host, -1) _map.erase(host) if h < 0: return _targets.erase(h) var es := sim.enemies var d := es.resolve_handle(h) if d < 0: return es.carry[d] = -1 # the host settles the loot; here it's only for show es.target[d] = -1 es.queue_removal(d, reason as EnemySystem.Removal) es.commit_removals() ## This machine's handle for a host enemy (-1 if it isn't here). func _local_handle(host: int) -> int: return int(_map.get(host, -1)) ## Each partner tick (FarmSim._step_replica): the news, then the enemies and shots move on ## toward where the host last had them. func _replica_tick(dt: float) -> void: if link != null: link.poll() var es := sim.enemies for h: int in _targets: var d := es.resolve_handle(h) if d < 0: continue var t: PackedFloat32Array = _targets[h] t[0] += t[4] * dt # carry on as the host said it was moving t[1] += t[5] * dt _targets[h] = t es.prev_x[d] = es.pos_x[d] es.prev_z[d] = es.pos_z[d] var k := 0.35 if Vector2(t[0] - es.pos_x[d], t[1] - es.pos_z[d]).length() > 5.0: k = 1.0 es.pos_x[d] = lerpf(es.pos_x[d], t[0], k) es.pos_z[d] = lerpf(es.pos_z[d], t[1], k) var hv := Vector2(t[2], t[3]) if hv.length_squared() > 1e-4: hv = hv.normalized() es.head_x[d] = hv.x es.head_z[d] = hv.y es.vel_x[d] = t[4] es.vel_z[d] = t[5] es.alt[d] = lerpf(es.alt[d], t[6], 0.3) sim.projectiles.advance_replica(dt) func _reset_world() -> void: sim.enemies.clear() sim.projectiles.clear() _map.clear() _gone.clear() _targets.clear() func _send_input() -> void: var a := sim.local_avatar var build_on := sim.build.active var ui := sim.upgrade_panel != null and sim.upgrade_panel.is_open var rec := _sender.record(a.combat.aim, a.combat.aim_point, int(a.combat.device), build_on, ui) if sim.local_frozen: rec["held"] = 0 # a menu is up rec["p"] = a.body.global_position rec["y"] = a.body.model.rotation.y rec["v"] = a.body.move_strength() rec["weapon"] = int(a.combat.weapon) rec["ground"] = a.combat.ground_point link.send("input", rec, false) _close_menu_if_needed() func _unhandled_input(event: InputEvent) -> void: if role == Role.CLIENT: _sender.note(event) ## The upgrade menu closes here on the same rules as solo (Interactions): walking off, ## nightfall, build mode. func _close_menu_if_needed() -> void: var panel := sim.upgrade_panel if panel == null or not panel.is_open: return var bench := sim.interactions.workbench var p := sim.local_avatar.position() if not sim.campaign.is_daytime() or sim.build.active or bench == null \ or Vector2(bench.global_position.x, bench.global_position.z).distance_to(p) > bench.reach + 0.5: panel.close() func _request(r: Array) -> void: if link != null and role == Role.CLIENT: link.send("req", r, true) # --- Both ------------------------------------------------------------------------------------- func _hook(sig: Signal, callable: Callable) -> void: sig.connect(callable) _connections.append([sig, callable]) ## Name tags over both scarecrows ("P1 Ana", "P2 Ben"). func _tag_all() -> void: for a in sim.avatars: a.body.set_tag(a.label(), a.color()) static func _display(n: String, fallback: String) -> String: return n if n != "" else fallback