Each scarecrow carries its own pouch (ResourceStore.pouches by avatar slot; slot 0 is the solo player / host, `pouch` stays slot 0's), with one shared pouch_capacity so a Bigger pouch grows both. The shed stays shared. - Gathering, the shed drop-off, repair, upgrade-in-place, patching, building and buying all act on the acting avatar's slot. The host pays the partner's "place" and "buy" requests from P2's pouch and the shed. - The partner's build mode, build hotbar, shop menus and materials HUD check affordability against P2's pouch (FarmSim.set_local). - Alien Goop goes to the killer's pouch: FarmSim sets EnemySystem.attacker around each avatar's combat step and shots carry their shooter's slot; bomb/turret kills go to the nearest scarecrow. The replica no longer rolls goop locally. - When the partner leaves, their pouch goes into the shed (and is named in the toast); a co-op save continued alone banks P2's pouch at morning. - FarmState.VERSION 7 (resources.partner_pouch) with a v6 migration; CoopSession.PROTOCOL 4. - Tests: per-slot store rules, v6 save migration, and test_coop cases for separate gathering, no cross-banking in the shed, own-pouch paying, shared capacity, goop credit and leaving. test_coop's crowd case now resets the loopback's drop counter so earlier traffic can't change which messages it loses. - Docs: COOP.md and RULES.md no longer say the pouch is shared. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
872 lines
33 KiB
GDScript
872 lines
33 KiB
GDScript
class_name StructureSystem
|
|
extends Node3D
|
|
## Player-built defenses. The records live in FarmState.structures; this system validates and
|
|
## places them, builds their views, keeps the navigation's structure layer in sync, and runs them:
|
|
## fence 2 m segment that ground enemies can't walk through.
|
|
## gate a fence segment the scarecrow walks through (it swings open as the
|
|
## scarecrow nears; it has no collision for the scarecrow) but enemies can't.
|
|
## slowing_trap 1.5 m patch (at L1): a ground enemy stepping on it moves at trap_slow_factor
|
|
## speed for trap_slow_time, using up one of its trap_triggers. Doesn't block.
|
|
## automated_defense 1 m post that shoots the nearest enemy within turret_range with a clear
|
|
## line, from the shared shot pool, every turret_fire_interval (leading the
|
|
## target). Flying enemies are hit too (Step 9); fences, gates, and traps
|
|
## don't affect them.
|
|
## Barriers (everything but traps) are high-cost cells for enemy navigation; an enemy whose route
|
|
## runs into one hits it (damage) until it breaks, then carries on. Damaged structures show an HP
|
|
## bar, a red tint, and wobble on each hit; a broken one leaves debris and emits destroyed
|
|
## ("breach"). Positions snap to a 0.5 m grid, rotations to 45 degree steps (fences run 2 m along
|
|
## the grid, 1.5 x 1.5 m on the diagonal, so chains line up either way).
|
|
##
|
|
## Leveling (#10): a turret or a tar patch (LEVELABLE) can be upgraded independently, L1-L3, from
|
|
## L1 (Interactions, holding interact at that specific structure; it must be undamaged and the
|
|
## cost affordable -- see upgrade_blocker). A turret at L2 fires turret_level_fire_mult times as
|
|
## often (3x, the same live multiplier as the player's Rapid Fire upgrade); L3 keeps that rate but
|
|
## fires turret_l3_projectiles shots at once in a fan. A tar patch's footprint and visual grow by
|
|
## trap_level_size_mult[level - 1] (L2 double, L3 triple its L1 size); upgrading refuses with a
|
|
## reason if the bigger footprint would overlap another structure or the world.
|
|
##
|
|
## workbench (#9): not built by the player -- not in ORDER, never validated or paid for. Granted
|
|
## once (grant_workbench(), idempotent) at the scene's Workbench node when Night 1 is survived
|
|
## (CampaignController.night_ending), and derived again on load/retry (sync_from_state(), when
|
|
## FarmState.nights_survived >= 1 and no "workbench" record exists yet) in case it was missed.
|
|
## Its view is the existing Workbench scene node (hidden until granted), not a built mesh, so it
|
|
## shares every other structure's damage/repair/HP bar/tint/wobble/nav/save pipeline for free.
|
|
## Repair-only: at 0 HP it's "broken" (Interactions refuses to open its shop) but, unlike every
|
|
## other structure, damage() never removes its record -- there's no rebuilding it from scratch.
|
|
|
|
signal layout_changed
|
|
signal built(id: int, type: String)
|
|
signal destroyed(id: int, type: String, position: Vector3)
|
|
## Damaged but still standing; repaired fully; leveled up; an automated defense shot; a trap
|
|
## slowed someone.
|
|
signal hurt(id: int, position: Vector3)
|
|
signal repaired(id: int)
|
|
signal leveled_up(id: int, level: int)
|
|
signal turret_fired(position: Vector3)
|
|
signal trap_sprung(position: Vector3)
|
|
|
|
const PREF := "res://assets/farm/ithappy/farm/prefabs/assets/"
|
|
const ORDER: Array[String] = ["fence", "gate", "slowing_trap", "automated_defense"]
|
|
const NAMES := {
|
|
"fence": "Fence",
|
|
"gate": "Gate",
|
|
"slowing_trap": "Tar patch",
|
|
"automated_defense": "Turret",
|
|
"workbench": "Workbench",
|
|
}
|
|
## Structure types with a per-instance level (#10); every other type is always level 1.
|
|
const LEVELABLE: Array[String] = ["automated_defense", "slowing_trap"]
|
|
const MAX_LEVEL := 3
|
|
const GRID := 0.5
|
|
const FENCE_LENGTH := 2.0
|
|
const DIAGONAL_FENCE_LENGTH := 2.1213 # 1.5 * sqrt(2)
|
|
const FENCE_THICKNESS := 0.2
|
|
## Clear space kept around each gap in the remaining perimeter fence (the scarecrow's ways out to
|
|
## the gathering areas) and in front of the barn doors.
|
|
const GAP_CLEAR := 2.5
|
|
const DOOR_RECT := Rect2(-0.8, -21.2, 3.6, 3.4)
|
|
const WOBBLE_TIME := 0.35
|
|
|
|
var campaign: CampaignController
|
|
var config: GameConfig
|
|
var nav: FarmNavigation
|
|
var zones: FarmZones
|
|
var enemies: EnemySystem
|
|
var projectiles: FarmProjectiles
|
|
var player: PlayerCharacter
|
|
## Co-op: player 2's scarecrow (gates open for it too, and nothing is built onto it).
|
|
var partner: Node3D
|
|
|
|
## The scene's Workbench node (Zones/WorkArea/Workbench), found in setup(): its view once
|
|
## granted, not built -- see grant_workbench().
|
|
var _workbench_node: Workbench
|
|
|
|
var _views := {} # id -> Node3D
|
|
var _bars := {} # id -> MeshInstance3D
|
|
var _bodies := {} # id -> Array[RID] (physics bodies to leave out of placement queries)
|
|
var _tints := {} # id -> StandardMaterial3D
|
|
var _wobble := {} # id -> seconds left
|
|
var _turret_cd := {} # id -> seconds left
|
|
var _heads := {} # id -> Node3D (turret head)
|
|
var _gate_open := {} # id -> 0..1
|
|
var _crop_rects: Array[Rect2] = []
|
|
var _gap_points := PackedVector2Array()
|
|
var _query := PhysicsShapeQueryParameters3D.new()
|
|
var _query_box := BoxShape3D.new()
|
|
var _bar_shader: Shader
|
|
|
|
|
|
func setup(p_campaign: CampaignController, p_nav: FarmNavigation, p_zones: FarmZones, p_enemies: EnemySystem,
|
|
p_projectiles: FarmProjectiles, p_player: PlayerCharacter) -> void:
|
|
campaign = p_campaign
|
|
config = p_campaign.config
|
|
nav = p_nav
|
|
zones = p_zones
|
|
enemies = p_enemies
|
|
projectiles = p_projectiles
|
|
player = p_player
|
|
nav.set_barrier_cost(roundi(config.barrier_detour / nav.cell_size * FarmNavigation.COST_ORTH))
|
|
_bar_shader = load("res://game/resources/hp_bar.gdshader") as Shader
|
|
for n in zones.find_children("*", "Node3D", true, false):
|
|
if n is Workbench:
|
|
_workbench_node = n
|
|
break
|
|
campaign.night_ending.connect(_on_night_ending)
|
|
for u in zones.crop_units():
|
|
var lo := Vector2(INF, INF)
|
|
var hi := Vector2(-INF, -INF)
|
|
for plant in u.get_children():
|
|
var p := Vector2((plant as Node3D).global_position.x, (plant as Node3D).global_position.z)
|
|
lo = lo.min(p)
|
|
hi = hi.max(p)
|
|
_crop_rects.append(Rect2(lo, hi - lo).grow(0.5))
|
|
var map := zones.playable
|
|
for m in zones.gaps():
|
|
var g := Vector2(m.global_position.x, m.global_position.z)
|
|
_gap_points.append(Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y)))
|
|
_query.shape = _query_box
|
|
_query.collision_mask = 1
|
|
_query.collide_with_areas = false
|
|
sync_from_state()
|
|
|
|
|
|
## Full health of a structure type, with upgrades (reinforced fences and gates).
|
|
func max_hp(type: String) -> int:
|
|
var hp := config.structure_hp(type)
|
|
if type == "fence" or type == "gate":
|
|
hp = roundi(hp * Upgrades.value(config, campaign.state, "barrier_hp"))
|
|
return hp
|
|
|
|
|
|
## The automated defense's range and the traps' slow time, with upgrades.
|
|
func turret_range() -> float:
|
|
return Upgrades.value(config, campaign.state, "turret_range")
|
|
|
|
|
|
func trap_slow_time() -> float:
|
|
return Upgrades.value(config, campaign.state, "trap_slow_time")
|
|
|
|
|
|
func blocks(type: String) -> bool:
|
|
return type != "slowing_trap"
|
|
|
|
|
|
func count() -> int:
|
|
return campaign.state.structures.size()
|
|
|
|
|
|
## Snaps a world point onto the build grid.
|
|
static func snap(p: Vector2) -> Vector2:
|
|
return Vector2(roundf(p.x / GRID) * GRID, roundf(p.y / GRID) * GRID)
|
|
|
|
|
|
## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z). level
|
|
## only matters for a slowing_trap (trap_level_size_mult); every other type ignores it.
|
|
func footprint(type: String, x: float, z: float, rot: int, level: int = 1) -> Dictionary:
|
|
var half := Vector2(0.75, 0.75) * trap_size_mult(level) if type == "slowing_trap" else Vector2(0.5, 0.5)
|
|
var angle := 0.0
|
|
if type == "fence" or type == "gate":
|
|
half = Vector2((DIAGONAL_FENCE_LENGTH if rot % 2 == 1 else FENCE_LENGTH) * 0.5, FENCE_THICKNESS * 0.5)
|
|
angle = rot * PI / 4.0
|
|
return {"center": Vector2(x, z), "half": half, "angle": angle}
|
|
|
|
|
|
## A slowing trap's footprint/visual size at level (1-3), relative to its L1 size.
|
|
func trap_size_mult(level: int) -> float:
|
|
var mults := config.trap_level_size_mult
|
|
return float(mults[clampi(level - 1, 0, mults.size() - 1)]) if not mults.is_empty() else 1.0
|
|
|
|
|
|
func is_levelable(type: String) -> bool:
|
|
return LEVELABLE.has(type)
|
|
|
|
|
|
func level_of(id: int) -> int:
|
|
var e := campaign.state.structure(id)
|
|
return int(e.get("level", 1)) if not e.is_empty() else 1
|
|
|
|
|
|
## Closed outline (5 points) of a footprint, optionally shrunk along its length / width.
|
|
static func corners(fp: Dictionary, shrink_long: float = 0.0, shrink_wide: float = 0.0) -> PackedVector2Array:
|
|
var c: Vector2 = fp["center"]
|
|
var h: Vector2 = fp["half"] - Vector2(shrink_long, shrink_wide)
|
|
var u := Vector2(cos(fp["angle"]), sin(fp["angle"]))
|
|
var v := Vector2(-u.y, u.x)
|
|
var pts := PackedVector2Array([c + u * h.x + v * h.y, c - u * h.x + v * h.y, c - u * h.x - v * h.y, c + u * h.x - v * h.y])
|
|
pts.append(pts[0])
|
|
return pts
|
|
|
|
|
|
## Why a structure can't go here ("" if it can). Space first, then daytime, then the cost (from
|
|
## the builder's pouch, its avatar slot, and the shed).
|
|
func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2, slot: int = 0) -> String:
|
|
var fp := footprint(type, x, z, rot)
|
|
var outline := corners(fp)
|
|
var inside := zones.playable.grow(-0.3)
|
|
for i in 4:
|
|
if not inside.has_point(outline[i]):
|
|
return "Build inside the farm"
|
|
for g in _gap_points:
|
|
if _distance_to_outline(g, outline) < GAP_CLEAR:
|
|
return "Keep the gap clear"
|
|
if _overlaps_rect(outline, DOOR_RECT):
|
|
return "Keep the barn doors clear"
|
|
for r in _crop_rects:
|
|
if _overlaps_rect(outline, r):
|
|
return "Not on the crops"
|
|
var tight := corners(fp, 0.2, 0.02)
|
|
for e in campaign.state.structures:
|
|
if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1))), 0.2, 0.02)):
|
|
return "Something is built here already"
|
|
if _world_blocked(fp):
|
|
return "Blocked"
|
|
if _distance_to_outline(scarecrow, outline) < 0.45 and blocks(type) and type != "gate":
|
|
return "The scarecrow is in the way"
|
|
if partner != null and blocks(type) and type != "gate" \
|
|
and _distance_to_outline(Vector2(partner.global_position.x, partner.global_position.z), outline) < 0.45:
|
|
return "The other scarecrow is in the way"
|
|
for d in enemies.active_count:
|
|
if enemies.alive[d] == 1 and _distance_to_outline(Vector2(enemies.pos_x[d], enemies.pos_z[d]), outline) < config.enemy_radius:
|
|
return "An enemy is in the way"
|
|
if scarecrow.distance_to(Vector2(x, z)) > config.build_range:
|
|
return "Too far from the scarecrow"
|
|
if not campaign.is_daytime():
|
|
return "Building is for daytime"
|
|
var cost: Dictionary = config.costs.get(type, {})
|
|
if not campaign.state.resources.can_afford(cost, slot):
|
|
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost, slot))
|
|
return ""
|
|
|
|
|
|
## Builds after validate() passed: pays (from the builder's pouch, its avatar slot, and the shed),
|
|
## records, shows, and updates navigation. Returns the id.
|
|
func place(type: String, x: float, z: float, rot: int, slot: int = 0) -> int:
|
|
var s := campaign.state
|
|
if not s.pay(config.costs.get(type, {}), slot):
|
|
return -1
|
|
var id := s.next_structure_id
|
|
s.next_structure_id += 1
|
|
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type), "level": 1})
|
|
s.record_event("structures_built")
|
|
_add_view(s.structures[s.structures.size() - 1])
|
|
_update_nav()
|
|
built.emit(id, type)
|
|
return id
|
|
|
|
|
|
## A non-purchased, unvalidated place(): adds a structure record at (x, z) without validate() or
|
|
## pay(), through the rest of the normal pipeline (record, view, nav, built). For structures the
|
|
## game grants itself (the Workbench -- grant_workbench()), not ones the player builds.
|
|
func grant(type: String, x: float, z: float, rot: int) -> int:
|
|
var s := campaign.state
|
|
var id := s.next_structure_id
|
|
s.next_structure_id += 1
|
|
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type), "level": 1})
|
|
_add_view(s.structures[s.structures.size() - 1])
|
|
_update_nav()
|
|
built.emit(id, type)
|
|
return id
|
|
|
|
|
|
## Idempotent: grants the Workbench at the scene node's position if it isn't a structure record
|
|
## yet. Called when Night 1 is survived (_on_night_ending) and, to derive it on load/retry, from
|
|
## sync_from_state() (guarded there to FarmState.nights_survived >= 1); tests may call it directly
|
|
## to have the workbench from the start, regardless of the night.
|
|
func grant_workbench() -> void:
|
|
if has_workbench() or _workbench_node == null:
|
|
return
|
|
var p := _workbench_node.global_position
|
|
grant("workbench", p.x, p.z, 0)
|
|
|
|
|
|
func has_workbench() -> bool:
|
|
return workbench_id() >= 0
|
|
|
|
|
|
## The granted Workbench's structure id, or -1 before it exists.
|
|
func workbench_id() -> int:
|
|
for e in campaign.state.structures:
|
|
if e["type"] == "workbench":
|
|
return int(e["id"])
|
|
return -1
|
|
|
|
|
|
## 0 HP: still a record (repair-only, never removed -- see damage()), but its shop can't be opened.
|
|
func is_broken(id: int) -> bool:
|
|
var e := campaign.state.structure(id)
|
|
return not e.is_empty() and int(e["hp"]) <= 0
|
|
|
|
|
|
## Granted and not broken: whether its shop (and a co-op "buy" request for one of its items) may
|
|
## open right now.
|
|
func workbench_available() -> bool:
|
|
var id := workbench_id()
|
|
return id >= 0 and not is_broken(id)
|
|
|
|
|
|
func _on_night_ending() -> void:
|
|
grant_workbench()
|
|
|
|
|
|
## Takes a structure down, refunding dismantle_refund of its cost into the shed. Returns the
|
|
## refund. The Workbench is never dismantlable (it isn't built in the first place).
|
|
func dismantle(id: int) -> Dictionary:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty() or e["type"] == "workbench":
|
|
return {}
|
|
var refund := {}
|
|
var cost: Dictionary = config.costs.get(e["type"], {})
|
|
for m in cost:
|
|
var back := floori(int(cost[m]) * config.dismantle_refund)
|
|
if back > 0:
|
|
refund[m] = back
|
|
campaign.state.resources.shed[m] = int(campaign.state.resources.shed[m]) + back
|
|
_remove(id)
|
|
return refund
|
|
|
|
|
|
## Damages a structure; at 0 HP it breaks (debris, destroyed). Returns true if it broke. The
|
|
## Workbench is repair-only: at 0 HP it's "broken" (hurt, not destroyed) and its record stays.
|
|
func damage(id: int, amount: int) -> bool:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty():
|
|
return false
|
|
campaign.state.record_event("structures_damaged", mini(amount, int(e["hp"])))
|
|
e["hp"] = maxi(int(e["hp"]) - amount, 0)
|
|
_wobble[id] = WOBBLE_TIME
|
|
if int(e["hp"]) > 0 or e["type"] == "workbench":
|
|
hurt.emit(id, Vector3(e["x"], 0.0, e["z"]))
|
|
return false
|
|
campaign.state.record_event("structures_destroyed")
|
|
var at := Vector3(e["x"], 0.0, e["z"])
|
|
var type: String = e["type"]
|
|
_debris(at)
|
|
_remove(id)
|
|
destroyed.emit(id, type, at)
|
|
return true
|
|
|
|
|
|
## Co-op partner: the broken bits where a structure fell on the host.
|
|
func show_debris(at: Vector3) -> void:
|
|
_debris(at)
|
|
|
|
|
|
## What a full repair costs now (empty if nothing is missing).
|
|
func repair_cost(id: int) -> Dictionary:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty():
|
|
return {}
|
|
var top := max_hp(e["type"])
|
|
var missing := top - int(e["hp"])
|
|
if missing <= 0:
|
|
return {}
|
|
var out := {}
|
|
var cost: Dictionary = config.costs.get(e["type"], {})
|
|
for m in cost:
|
|
out[m] = ceili(int(cost[m]) * missing / float(top))
|
|
return out
|
|
|
|
|
|
## Pays (from the repairer's pouch, its avatar slot, and the shed) and repairs fully. Returns
|
|
## false if there was nothing to repair or it couldn't be paid.
|
|
func repair(id: int, slot: int = 0) -> bool:
|
|
var cost := repair_cost(id)
|
|
if cost.is_empty() or not campaign.state.pay(cost, slot):
|
|
return false
|
|
var e := campaign.state.structure(id)
|
|
e["hp"] = max_hp(e["type"])
|
|
campaign.state.record_event("repairs")
|
|
repaired.emit(id)
|
|
return true
|
|
|
|
|
|
## What upgrading this structure to its next level costs now (empty if it isn't levelable or is
|
|
## already at MAX_LEVEL, regardless of whether it's otherwise affordable or in reach).
|
|
func upgrade_cost(id: int) -> Dictionary:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty() or not is_levelable(e["type"]):
|
|
return {}
|
|
var level := int(e.get("level", 1))
|
|
if level >= MAX_LEVEL:
|
|
return {}
|
|
var tiers: Array = config.structure_level_costs.get(e["type"], [])
|
|
var idx := level - 1 # 0: L1 -> L2, 1: L2 -> L3
|
|
return tiers[idx] if idx >= 0 and idx < tiers.size() else {}
|
|
|
|
|
|
## Why id can't be upgraded right now ("" if it can): levelable, undamaged (repair takes
|
|
## priority), under MAX_LEVEL, a bigger tar patch footprint clear of neighbors and the world, and
|
|
## the cost affordable (from the upgrader's pouch, its avatar slot, and the shed). Doesn't check
|
|
## the time of day (Interactions, like the build-mode rules).
|
|
func upgrade_blocker(id: int, slot: int = 0) -> String:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty() or not is_levelable(e["type"]):
|
|
return "Can't be upgraded"
|
|
if int(e["hp"]) < max_hp(e["type"]):
|
|
return "Repair it first"
|
|
var level := int(e.get("level", 1))
|
|
var cost := upgrade_cost(id)
|
|
if level >= MAX_LEVEL or cost.is_empty():
|
|
return "Max level"
|
|
if e["type"] == "slowing_trap":
|
|
var fp := footprint(e["type"], e["x"], e["z"], e["rot"], level + 1)
|
|
var tight := corners(fp, 0.2, 0.02)
|
|
for other in campaign.state.structures:
|
|
if int(other["id"]) == id:
|
|
continue
|
|
var other_fp := footprint(other["type"], other["x"], other["z"], other["rot"], int(other.get("level", 1)))
|
|
if _overlap(tight, corners(other_fp, 0.2, 0.02)):
|
|
return "Not enough room to upgrade"
|
|
if _world_blocked(fp):
|
|
return "Not enough room to upgrade"
|
|
if not campaign.state.resources.can_afford(cost, slot):
|
|
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost, slot))
|
|
return ""
|
|
|
|
|
|
## Pays and levels a structure up by one (see upgrade_blocker). Returns false if it couldn't be.
|
|
func upgrade(id: int, slot: int = 0) -> bool:
|
|
if upgrade_blocker(id, slot) != "":
|
|
return false
|
|
var cost := upgrade_cost(id)
|
|
if not campaign.state.pay(cost, slot):
|
|
return false
|
|
var e := campaign.state.structure(id)
|
|
e["level"] = int(e.get("level", 1)) + 1
|
|
campaign.state.record_event("upgrades_bought")
|
|
_rebuild_view(id)
|
|
_update_nav()
|
|
leveled_up.emit(id, int(e["level"]))
|
|
return true
|
|
|
|
|
|
## The structure whose footprint is within reach of p, preferring damaged ones, or -1.
|
|
func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int:
|
|
var best := -1
|
|
var best_d := INF
|
|
for e in campaign.state.structures:
|
|
if damaged_only and int(e["hp"]) >= max_hp(e["type"]):
|
|
continue
|
|
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1)))))
|
|
if d <= reach and d < best_d:
|
|
best = int(e["id"])
|
|
best_d = d
|
|
return best
|
|
|
|
|
|
## The nearest levelable structure (turret, tar patch) whose footprint is within reach of p, or -1
|
|
## (whether or not it can actually be upgraded right now -- see upgrade_blocker).
|
|
func upgradeable_near(p: Vector2, reach: float) -> int:
|
|
var best := -1
|
|
var best_d := INF
|
|
for e in campaign.state.structures:
|
|
if not is_levelable(e["type"]):
|
|
continue
|
|
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1)))))
|
|
if d <= reach and d < best_d:
|
|
best = int(e["id"])
|
|
best_d = d
|
|
return best
|
|
|
|
|
|
## A ground enemy at (x, z) steps on a slowing trap with triggers left: uses one up. Returns true
|
|
## if the enemy is slowed.
|
|
func try_trap(x: float, z: float) -> bool:
|
|
for e in campaign.state.structures:
|
|
if e["type"] != "slowing_trap" or int(e["hp"]) <= 0:
|
|
continue
|
|
var half := 0.75 * trap_size_mult(int(e.get("level", 1)))
|
|
if absf(x - float(e["x"])) <= half and absf(z - float(e["z"])) <= half:
|
|
e["hp"] = int(e["hp"]) - 1
|
|
trap_sprung.emit(Vector3(e["x"], 0.0, e["z"]))
|
|
return true
|
|
return false
|
|
|
|
|
|
## Physics tick: the automated defenses shoot.
|
|
func step(dt: float) -> void:
|
|
for e in campaign.state.structures:
|
|
if e["type"] != "automated_defense":
|
|
continue
|
|
var id: int = e["id"]
|
|
var cd := maxf(float(_turret_cd.get(id, 0.0)) - dt, 0.0)
|
|
if cd > 0.0:
|
|
_turret_cd[id] = cd
|
|
continue
|
|
var from := Vector2(e["x"], e["z"])
|
|
var target := -1
|
|
var best := turret_range()
|
|
for d in enemies.active_count:
|
|
if enemies.alive[d] == 0:
|
|
continue
|
|
var p := Vector2(enemies.pos_x[d], enemies.pos_z[d])
|
|
var dist := p.distance_to(from)
|
|
if dist < best and nav.line_clear(from.x, from.y, p.x, p.y, true):
|
|
best = dist
|
|
target = d
|
|
if target < 0:
|
|
_turret_cd[id] = 0.0
|
|
continue
|
|
var lead := best / config.projectile_speed
|
|
var aim := Vector2(enemies.pos_x[target] + enemies.vel_x[target] * lead, enemies.pos_z[target] + enemies.vel_z[target] * lead) - from
|
|
var dir := Vector3(aim.x, 0.0, aim.y).normalized()
|
|
var origin := Vector3(from.x, config.combat_height, from.y)
|
|
var level := int(e.get("level", 1))
|
|
if level >= 3:
|
|
# L3: turret_l3_projectiles shots at once, fanned turret_l3_spread_deg apart (a
|
|
# triangle spread: the center shot plus one off either side of dir).
|
|
var shots: int = config.turret_l3_projectiles
|
|
var spread := deg_to_rad(config.turret_l3_spread_deg)
|
|
for i in shots:
|
|
var offset := (float(i) - float(shots - 1) * 0.5) * spread
|
|
var shot_dir := dir.rotated(Vector3.UP, offset)
|
|
projectiles.fire(origin, origin + shot_dir * 0.6, shot_dir)
|
|
else:
|
|
projectiles.fire(origin, origin + dir * 0.6, dir)
|
|
turret_fired.emit(origin)
|
|
var interval := config.turret_fire_interval
|
|
if level >= 2:
|
|
interval /= config.turret_level_fire_mult
|
|
_turret_cd[id] = interval
|
|
var head: Node3D = _heads.get(id)
|
|
if head != null:
|
|
head.rotation.y = atan2(-dir.x, -dir.z)
|
|
|
|
|
|
## Rebuilds every view and the navigation layer from the farm state (new vacation, retry). The
|
|
## Workbench's view is the scene's own node, not a built one: hide it rather than free it, and
|
|
## derive its presence again (nights_survived >= 1, no record yet -- an older save, or a retry
|
|
## that somehow missed it) once the state's own structures are back.
|
|
func sync_from_state() -> void:
|
|
for id in _views.keys():
|
|
var v: Node3D = _views[id]
|
|
if v == _workbench_node:
|
|
v.visible = false
|
|
var old_bar: MeshInstance3D = _bars.get(id)
|
|
if old_bar != null: # its own HP bar is a real child of the scene node: free it by hand
|
|
old_bar.queue_free()
|
|
else:
|
|
v.queue_free()
|
|
_views.clear()
|
|
_bars.clear()
|
|
_bodies.clear()
|
|
_tints.clear()
|
|
_wobble.clear()
|
|
_heads.clear()
|
|
_turret_cd.clear()
|
|
_gate_open.clear()
|
|
for e in campaign.state.structures:
|
|
_add_view(e)
|
|
if campaign.state.nights_survived >= 1:
|
|
grant_workbench()
|
|
_update_nav()
|
|
|
|
|
|
## A display-only copy of a structure (no collision), for the build preview.
|
|
func make_ghost(type: String, rot: int) -> Node3D:
|
|
var root := _build_view(type, rot)
|
|
_strip_collision(root)
|
|
return root
|
|
|
|
|
|
func body_rids() -> Array[RID]:
|
|
var out: Array[RID] = []
|
|
for id in _bodies:
|
|
out.append_array(_bodies[id])
|
|
return out
|
|
|
|
|
|
func _process(delta: float) -> void:
|
|
var near := player.global_position if player != null else Vector3(INF, 0.0, INF)
|
|
var near2 := partner.global_position if partner != null else Vector3(INF, 0.0, INF)
|
|
for e in campaign.state.structures:
|
|
var id: int = e["id"]
|
|
var view: Node3D = _views.get(id)
|
|
if view == null:
|
|
continue
|
|
var top := max_hp(e["type"])
|
|
var frac := float(e["hp"]) / float(top)
|
|
var bar: MeshInstance3D = _bars.get(id)
|
|
if bar != null:
|
|
bar.visible = frac < 1.0
|
|
(bar.material_override as ShaderMaterial).set_shader_parameter("fill", frac)
|
|
var tint: StandardMaterial3D = _tints.get(id)
|
|
if tint != null:
|
|
tint.albedo_color.a = (1.0 - frac) * 0.45 if e["type"] != "slowing_trap" else 0.0
|
|
var w := maxf(float(_wobble.get(id, 0.0)) - delta, 0.0)
|
|
_wobble[id] = w
|
|
view.rotation.z = sin(w * 60.0) * 0.08 * (w / WOBBLE_TIME)
|
|
if e["type"] == "slowing_trap":
|
|
view.get_node("Tar").visible = int(e["hp"]) > 0
|
|
elif e["type"] == "gate":
|
|
var dist := minf(Vector2(near.x - float(e["x"]), near.z - float(e["z"])).length(),
|
|
Vector2(near2.x - float(e["x"]), near2.z - float(e["z"])).length())
|
|
var target := 1.0 if dist < 2.2 else 0.0
|
|
var o := move_toward(float(_gate_open.get(id, 0.0)), target, delta * 3.0)
|
|
_gate_open[id] = o
|
|
var panel := view.get_node("Panel") as Node3D
|
|
panel.rotation.y = deg_to_rad(32.5 + 100.0 * o)
|
|
|
|
|
|
func _remove(id: int) -> void:
|
|
var s := campaign.state
|
|
for i in s.structures.size():
|
|
if int(s.structures[i]["id"]) == id:
|
|
s.structures.remove_at(i)
|
|
break
|
|
var view: Node3D = _views.get(id)
|
|
if view != null and view != _workbench_node: # the scene's own node is hidden, never freed
|
|
view.queue_free()
|
|
for d in [_views, _bars, _bodies, _tints, _wobble, _heads, _turret_cd, _gate_open]:
|
|
(d as Dictionary).erase(id)
|
|
_update_nav()
|
|
|
|
|
|
## Rebuilds a structure's view after a level change (its size or its gun may have changed), keeping
|
|
## its cooldown (a turret doesn't reset its reload on leveling up).
|
|
func _rebuild_view(id: int) -> void:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty():
|
|
return
|
|
var view: Node3D = _views.get(id)
|
|
if view != null:
|
|
view.queue_free()
|
|
for d in [_views, _bars, _tints, _wobble, _heads]:
|
|
(d as Dictionary).erase(id)
|
|
_add_view(e)
|
|
|
|
|
|
func _update_nav() -> void:
|
|
var entries: Array = []
|
|
for e in campaign.state.structures:
|
|
if blocks(e["type"]):
|
|
entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1))))})
|
|
nav.set_structures(entries)
|
|
layout_changed.emit()
|
|
|
|
|
|
## The Workbench reuses the scene's own node (shown, not built) instead of a fresh _build_view(),
|
|
## so there's only ever the one mesh; every other type is built and parented here as usual.
|
|
func _add_view(e: Dictionary) -> void:
|
|
var id: int = e["id"]
|
|
var view: Node3D
|
|
if e["type"] == "workbench" and _workbench_node != null:
|
|
view = _workbench_node
|
|
view.visible = true
|
|
else:
|
|
view = _build_view(e["type"], e["rot"], int(e.get("level", 1)))
|
|
view.name = "%s_%d" % [e["type"], id]
|
|
add_child(view)
|
|
view.global_position = Vector3(e["x"], _ground_y(Vector2(e["x"], e["z"])), e["z"])
|
|
_views[id] = view
|
|
var rids: Array[RID] = []
|
|
for body in view.find_children("*", "StaticBody3D", true, false):
|
|
rids.append((body as StaticBody3D).get_rid())
|
|
_bodies[id] = rids
|
|
var tint := StandardMaterial3D.new()
|
|
tint.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
|
|
tint.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
|
|
tint.albedo_color = Color(0.9, 0.1, 0.05, 0.0)
|
|
for mi in view.find_children("*", "MeshInstance3D", true, false):
|
|
(mi as MeshInstance3D).material_overlay = tint
|
|
_tints[id] = tint
|
|
var quad := QuadMesh.new()
|
|
quad.size = Vector2(1.1, 0.14)
|
|
var mat := ShaderMaterial.new()
|
|
mat.shader = _bar_shader
|
|
var bar := MeshInstance3D.new()
|
|
bar.mesh = quad
|
|
bar.material_override = mat
|
|
bar.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
|
bar.top_level = true
|
|
bar.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
|
|
bar.visible = false
|
|
view.add_child(bar)
|
|
bar.global_position = view.global_position + Vector3(0.0, 2.3, 0.0)
|
|
_bars[id] = bar
|
|
if e["type"] == "automated_defense":
|
|
_heads[id] = view.get_node("Head")
|
|
|
|
|
|
## The visual (and, for barriers other than gates, collision) of a structure, centered on its
|
|
## footprint and rotated to it. level only changes a slowing_trap's size (trap_size_mult).
|
|
func _build_view(type: String, rot: int, level: int = 1) -> Node3D:
|
|
var root := Node3D.new()
|
|
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
|
|
var fp := footprint(type, 0.0, 0.0, rot, level)
|
|
root.rotation.y = -float(fp["angle"])
|
|
match type:
|
|
"fence":
|
|
var fence := _instance("prop/fence_026.tscn")
|
|
fence.scale.x = float(fp["half"].x) * 2.0 / 2.08
|
|
fence.position.x = -0.05 * fence.scale.x
|
|
root.add_child(fence)
|
|
"gate":
|
|
var panel := _instance("prop/fence_018.tscn")
|
|
panel.name = "Panel"
|
|
panel.position = Vector3(-0.865, 0.0, 0.0)
|
|
panel.rotation.y = deg_to_rad(32.5)
|
|
_strip_collision(panel) # the scarecrow walks through; enemies are kept out by navigation
|
|
root.add_child(panel)
|
|
for end in [-1.0, 1.0]:
|
|
var post := _instance("prop/fence_027.tscn")
|
|
post.position = Vector3(end * 0.95, 0.0, 0.0)
|
|
root.add_child(post)
|
|
"slowing_trap":
|
|
var mult := trap_size_mult(level)
|
|
var tar := MeshInstance3D.new()
|
|
tar.name = "Tar"
|
|
var box := BoxMesh.new()
|
|
box.size = Vector3(1.4, 0.06, 1.4) * mult
|
|
var mat := StandardMaterial3D.new()
|
|
mat.albedo_color = Color(0.1, 0.07, 0.05)
|
|
mat.roughness = 0.2
|
|
mat.metallic_specular = 0.8
|
|
box.material = mat
|
|
tar.mesh = box
|
|
tar.position.y = 0.04
|
|
root.add_child(tar)
|
|
var bucket := _instance("prop/bucket_001.tscn")
|
|
bucket.position = Vector3(0.55 * mult, 0.0, 0.55 * mult)
|
|
_strip_collision(bucket)
|
|
root.add_child(bucket)
|
|
"automated_defense":
|
|
var base := _instance("prop/barrel_001.tscn")
|
|
root.add_child(base)
|
|
var metal := StandardMaterial3D.new()
|
|
metal.albedo_color = Color(0.25, 0.27, 0.3)
|
|
metal.metallic = 0.6
|
|
var accent := StandardMaterial3D.new()
|
|
accent.albedo_color = Color(0.95, 0.55, 0.15)
|
|
var post := MeshInstance3D.new()
|
|
var cyl := CylinderMesh.new()
|
|
cyl.top_radius = 0.06
|
|
cyl.bottom_radius = 0.06
|
|
cyl.height = 0.55
|
|
cyl.material = metal
|
|
post.mesh = cyl
|
|
post.position.y = 1.2
|
|
root.add_child(post)
|
|
var head := Node3D.new()
|
|
head.name = "Head"
|
|
head.position.y = 1.5
|
|
root.add_child(head)
|
|
var body := MeshInstance3D.new()
|
|
var bm := BoxMesh.new()
|
|
bm.size = Vector3(0.3, 0.22, 0.4)
|
|
bm.material = accent
|
|
body.mesh = bm
|
|
head.add_child(body)
|
|
var gun := MeshInstance3D.new()
|
|
var gm := CylinderMesh.new()
|
|
gm.top_radius = 0.05
|
|
gm.bottom_radius = 0.05
|
|
gm.height = 0.6
|
|
gm.material = metal
|
|
gun.mesh = gm
|
|
gun.rotation.x = PI * 0.5
|
|
gun.position.z = -0.4
|
|
head.add_child(gun)
|
|
return root
|
|
|
|
|
|
func _instance(path: String) -> Node3D:
|
|
return (load(PREF + path) as PackedScene).instantiate() as Node3D
|
|
|
|
|
|
static func _strip_collision(node: Node) -> void:
|
|
for body in node.find_children("*", "CollisionObject3D", true, false):
|
|
(body as CollisionObject3D).collision_layer = 0
|
|
(body as CollisionObject3D).collision_mask = 0
|
|
|
|
|
|
## Height of the ground under p (walkable terrain), for placing views.
|
|
func _ground_y(p: Vector2) -> float:
|
|
if not is_inside_tree():
|
|
return 0.0
|
|
var ray := PhysicsRayQueryParameters3D.create(Vector3(p.x, 5.0, p.y), Vector3(p.x, -2.0, p.y), 1)
|
|
ray.exclude = body_rids()
|
|
var hit := get_world_3d().direct_space_state.intersect_ray(ray)
|
|
return maxf((hit["position"] as Vector3).y, 0.0) if not hit.is_empty() and (hit["position"] as Vector3).y < 1.0 else 0.0
|
|
|
|
|
|
## Anything solid (not walkable terrain, not another structure) under the footprint, with its
|
|
## ends trimmed so a fence may touch a wall or a post.
|
|
func _world_blocked(fp: Dictionary) -> bool:
|
|
var h: Vector2 = fp["half"]
|
|
_query_box.size = Vector3(maxf(h.x * 2.0 - 0.3, 0.1), 1.4, maxf(h.y * 2.0, 0.1))
|
|
var c: Vector2 = fp["center"]
|
|
_query.transform = Transform3D(Basis(Vector3.UP, -float(fp["angle"])), Vector3(c.x, 1.05, c.y))
|
|
_query.exclude = body_rids()
|
|
for hit in get_world_3d().direct_space_state.intersect_shape(_query, 16):
|
|
var body := hit["collider"] as CollisionObject3D
|
|
if body == null:
|
|
continue
|
|
var owner_id := body.shape_find_owner(int(hit["shape"]))
|
|
var cs := body.shape_owner_get_owner(owner_id) as CollisionShape3D
|
|
if cs != null and cs.shape is ConcavePolygonShape3D:
|
|
continue # ground and road tiles
|
|
return true
|
|
return false
|
|
|
|
|
|
func _debris(at: Vector3) -> void:
|
|
var p := CPUParticles3D.new()
|
|
var box := BoxMesh.new()
|
|
box.size = Vector3(0.14, 0.06, 0.3)
|
|
var mat := StandardMaterial3D.new()
|
|
mat.albedo_color = Color(0.45, 0.3, 0.18)
|
|
box.material = mat
|
|
p.mesh = box
|
|
p.amount = 18
|
|
p.lifetime = 1.0
|
|
p.one_shot = true
|
|
p.explosiveness = 1.0
|
|
p.direction = Vector3.UP
|
|
p.spread = 70.0
|
|
p.initial_velocity_min = 2.5
|
|
p.initial_velocity_max = 5.0
|
|
p.angular_velocity_min = -360.0
|
|
p.angular_velocity_max = 360.0
|
|
p.gravity = Vector3(0.0, -12.0, 0.0)
|
|
add_child(p)
|
|
p.global_position = at + Vector3(0.0, 0.8, 0.0)
|
|
p.emitting = true
|
|
get_tree().create_timer(1.5).timeout.connect(p.queue_free)
|
|
|
|
|
|
static func _distance_to_outline(p: Vector2, outline: PackedVector2Array) -> float:
|
|
if Geometry2D.is_point_in_polygon(p, outline):
|
|
return 0.0
|
|
var best := INF
|
|
for k in outline.size() - 1:
|
|
best = minf(best, p.distance_to(Geometry2D.get_closest_point_to_segment(p, outline[k], outline[k + 1])))
|
|
return best
|
|
|
|
|
|
static func _overlaps_rect(outline: PackedVector2Array, r: Rect2) -> bool:
|
|
var box := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position])
|
|
return _overlap(outline, box)
|
|
|
|
|
|
## Separating-axis test for two closed convex outlines.
|
|
static func _overlap(a: PackedVector2Array, b: PackedVector2Array) -> bool:
|
|
for poly in [a, b]:
|
|
for k in poly.size() - 1:
|
|
var edge: Vector2 = poly[k + 1] - poly[k]
|
|
var axis := Vector2(-edge.y, edge.x)
|
|
var a_lo := INF
|
|
var a_hi := -INF
|
|
var b_lo := INF
|
|
var b_hi := -INF
|
|
for i in a.size() - 1:
|
|
var d := a[i].dot(axis)
|
|
a_lo = minf(a_lo, d)
|
|
a_hi = maxf(a_hi, d)
|
|
for i in b.size() - 1:
|
|
var d := b[i].dot(axis)
|
|
b_lo = minf(b_lo, d)
|
|
b_hi = maxf(b_hi, d)
|
|
if a_hi <= b_lo or b_hi <= a_lo:
|
|
return false
|
|
return true
|