This commit is contained in:
Forrest 2026-10-04 12:07:36 -04:00
parent 276d43613d
commit 4298caf5cb
552 changed files with 42990 additions and 776 deletions

View file

@ -0,0 +1,23 @@
class_name ActionEdges
extends RefCounted
## Per-tick "just pressed" for input actions. A press counts once, either from its input event
## (note(), so a tap between two ticks still registers) or from the action turning pressed since
## the previous poll (which also covers simulated input). Poll every action once per tick.
var _held := {}
var _requested := {}
func note(event: InputEvent, actions: Array) -> void:
for a in actions:
if event.is_action_pressed(a, false):
_requested[a] = true
func pressed(action: StringName) -> bool:
var held := Input.is_action_pressed(action)
var was: bool = _held.get(action, false)
_held[action] = held
var requested: bool = _requested.get(action, false)
_requested.erase(action)
return requested or (held and not was)

View file

@ -0,0 +1 @@
uid://cx3ym8d1fbxy1

View file

@ -0,0 +1,289 @@
class_name AlertManager
extends Control
## What's going wrong on the farm, as labeled arrows at the screen edge for whatever is off
## screen (on-screen threats already have their world markers). Every frame it collects alerts:
## ESCAPE a carrier making off with loot. It escalates as the carrier nears its exit (the
## farm's nearest edge, on foot or flying): the arrow grows, pulses faster, and
## turns from orange to red, and the label ends in "!".
## BREACH a barrier being smashed, or one just broken (for BREACH_TIME)
## THEFT loot being taken, or an enemy on its way to it
## LOOSE an animal loose on the farm, or loot lying dropped
## Alerts of the same kind, enemy type, and loot category in the same zone are grouped into one
## ("3 crows — Crop Field"). They're ordered by priority (kind, then escalation, then distance to
## the scarecrow), and at most MAX_SHOWN arrows are drawn at once.
enum Kind { ESCAPE, BREACH, THEFT, LOOSE }
const PRIORITY := {Kind.ESCAPE: 100.0, Kind.BREACH: 70.0, Kind.THEFT: 60.0, Kind.LOOSE: 45.0}
const FILL := {
Kind.ESCAPE: Color(1.0, 0.22, 0.15),
Kind.BREACH: Color(1.0, 0.45, 0.2),
Kind.THEFT: Color(1.0, 0.6, 0.1),
Kind.LOOSE: Color(1.0, 0.9, 0.25),
}
const MAX_SHOWN := 5
const MARGIN := 46.0
const BREACH_TIME := 6.0
## Escape alerts start escalating this far from the exit.
const ESCALATE_FROM := 20.0
var loot: LootSystem
var waves: WaveDirector
var enemies: EnemySystem
var structures: StructureSystem
var zones: FarmZones
var player: Node3D
## Set by FarmSim: the field to the farm's edge (how far a carrier on foot has left to go).
var sim: FarmSim
## Alerts drawn last frame (tests and debugging).
var last_shown: Array[Dictionary] = []
var _breaches: Array = [] # [seconds left, position, type name]
var _time: float = 0.0
var _font: Font
func setup(p_sim: FarmSim) -> void:
sim = p_sim
loot = sim.loot
waves = sim.waves
enemies = sim.enemies
structures = sim.structures
zones = sim.zones
player = sim.player
structures.destroyed.connect(func(_id: int, t: String, at: Vector3) -> void: _breaches.append([BREACH_TIME, at, t]))
sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, _p: CampaignController.Phase) -> void:
if phase == CampaignController.Phase.MORNING:
_breaches.clear())
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_font = ThemeDB.fallback_font
func _process(delta: float) -> void:
_time += delta
for b in _breaches:
b[0] = float(b[0]) - delta
_breaches = _breaches.filter(func(b: Array) -> bool: return float(b[0]) > 0.0)
queue_redraw()
## Every alert right now, grouped and sorted by priority (highest first). Each is a dictionary:
## kind, type (EnemySystem type or -1), category (LootSystem.Category or -1), zone (name or ""),
## position (Vector3, the group's center), count, escalation (0..1), priority, label.
func collect() -> Array[Dictionary]:
var raw: Array[Dictionary] = []
if loot != null:
for id in range(1, loot.item_count + 1):
match loot.status[id]:
LootSystem.Status.CARRIED:
var d := enemies.resolve_handle(loot.holder[id])
if d < 0:
continue
var p := Vector2(enemies.pos_x[d], enemies.pos_z[d])
raw.append(_alert(Kind.ESCAPE, enemies.type[d], loot.category[id], p, _escalation(d, p)))
LootSystem.Status.HOME:
var d := enemies.resolve_handle(loot.holder[id]) if loot.holder[id] >= 0 else -1
if d >= 0:
raw.append(_alert(Kind.THEFT, enemies.type[d], loot.category[id], loot.position_of(id), 0.0))
LootSystem.Status.DROPPED:
raw.append(_alert(Kind.LOOSE, -1, loot.category[id], loot.position_of(id), 0.0))
if enemies != null and structures != null:
for d in enemies.active_count:
if enemies.alive[d] == 1 and enemies.state[d] == ThiefBehavior.State.BREAK:
var e := structures.campaign.state.structure(enemies.barrier[d])
if not e.is_empty():
raw.append(_alert(Kind.BREACH, enemies.type[d], -1, Vector2(e["x"], e["z"]), 0.0))
for b in _breaches:
var at: Vector3 = b[1]
raw.append(_alert(Kind.BREACH, -1, -1, Vector2(at.x, at.z), 1.0))
return sort_alerts(group_alerts(raw))
## Merges alerts of the same kind, type, category, and zone.
static func group_alerts(raw: Array[Dictionary]) -> Array[Dictionary]:
var groups := {}
var order: Array[String] = []
for a in raw:
var key := "%d|%d|%d|%s" % [a["kind"], a["type"], a["category"], a["zone"]]
if not groups.has(key):
groups[key] = a.duplicate()
groups[key]["sum"] = a["position"]
order.append(key)
else:
var g: Dictionary = groups[key]
g["count"] = int(g["count"]) + 1
g["sum"] = (g["sum"] as Vector3) + (a["position"] as Vector3)
g["escalation"] = maxf(float(g["escalation"]), float(a["escalation"]))
var out: Array[Dictionary] = []
for key in order:
var g: Dictionary = groups[key]
g["position"] = (g["sum"] as Vector3) / float(g["count"])
g.erase("sum")
g["priority"] = float(PRIORITY[g["kind"]]) + 20.0 * float(g["escalation"]) + minf(float(g["count"]) - 1.0, 5.0)
g["label"] = label_for(g)
out.append(g)
return out
static func sort_alerts(list: Array[Dictionary]) -> Array[Dictionary]:
list.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
if not is_equal_approx(float(a["priority"]), float(b["priority"])):
return float(a["priority"]) > float(b["priority"])
return float(a.get("distance", 0.0)) < float(b.get("distance", 0.0)))
return list
## The first `cap` alerts that pass the filter (on the HUD: those off screen).
static func cap(list: Array[Dictionary], limit: int, keep: Callable = Callable()) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for a in list:
if out.size() >= limit:
break
if not keep.is_valid() or keep.call(a):
out.append(a)
return out
## "3 crows — Crop Field", "Crow escaping with a crop!", "Breach! — Animal Pen".
static func label_for(a: Dictionary) -> String:
var n := int(a["count"])
var t := int(a["type"])
var who := ""
if t >= 0:
who = "%d %s" % [n, EnemySystem.PLURALS[t]] if n > 1 else EnemySystem.NAMES[t].capitalize()
var what := ""
var c := int(a["category"])
if c >= 0:
what = ["crop", "animal", "supplies"][c]
if n > 1 and c != LootSystem.Category.SUPPLY:
what += "s"
var text := ""
match int(a["kind"]):
Kind.ESCAPE:
var article := ("an " if what.begins_with("a") else "a ") if n == 1 and c != LootSystem.Category.SUPPLY else ""
text = "%s escaping with %s%s" % [who, article, what]
if float(a["escalation"]) >= 0.7:
text += "!"
Kind.BREACH:
text = "Breach!" if t < 0 else "%s smashing a barrier" % who
Kind.THEFT:
text = who
Kind.LOOSE:
text = ("%d loose animals" % n if n > 1 else "Loose animal") if c == LootSystem.Category.ANIMAL \
else ("%d dropped %s" % [n, what] if n > 1 else "Dropped %s" % what)
return "%s — %s" % [text, a["zone"]] if String(a["zone"]) != "" else text
func _alert(kind: Kind, type: int, category: int, p: Vector2, escalation: float) -> Dictionary:
var zone := zones.zone_at(Vector3(p.x, 0.0, p.y)) if zones != null else null
var me := Vector2(player.global_position.x, player.global_position.z) if player != null else p
return {"kind": kind, "type": type, "category": category, "zone": zone.display_name if zone != null else "",
"position": Vector3(p.x, 1.0, p.y), "count": 1, "escalation": escalation, "distance": p.distance_to(me)}
## How close a carrier is to getting away (0 far .. 1 at the exit): on foot by the escape field,
## a flyer by its distance to the fence.
func _escalation(d: int, p: Vector2) -> float:
var left := ESCALATE_FROM
if enemies.t_flying[enemies.type[d]] == 1:
var r := zones.playable
left = maxf(minf(minf(p.x - r.position.x, r.end.x - p.x), minf(p.y - r.position.y, r.end.y - p.y)), 0.0)
elif sim != null and not sim.escape_field.is_empty():
left = sim.nav.meters(sim.escape_field[sim.nav.cell_of(p.x, p.y)])
return clampf(1.0 - left / ESCALATE_FROM, 0.0, 1.0)
func _draw() -> void:
var cam := get_viewport().get_camera_3d()
if cam == null or loot == null:
return
var view := get_viewport_rect()
var inner := view.grow(-MARGIN)
var center := inner.get_center()
var to_canvas := get_viewport().get_screen_transform().affine_inverse()
var offscreen := func(a: Dictionary) -> bool:
var world: Vector3 = a["position"]
return cam.is_position_behind(world) or not view.has_point(to_canvas * cam.unproject_position(world))
last_shown = cap(collect(), MAX_SHOWN, offscreen)
var labels: Array[Rect2] = []
for a in last_shown:
var world: Vector3 = a["position"]
var behind := cam.is_position_behind(world)
var p := to_canvas * cam.unproject_position(world)
var dir := (p - center) * (-1.0 if behind else 1.0)
dir = dir.normalized() if dir.length_squared() > 1.0 else Vector2.DOWN
var t := INF
if absf(dir.x) > 1e-4:
t = minf(t, inner.size.x * 0.5 / absf(dir.x))
if absf(dir.y) > 1e-4:
t = minf(t, inner.size.y * 0.5 / absf(dir.y))
_arrow(_clear_of_hud(center + dir * t, inner), dir, a, labels)
## The HUD's corner panels (phase, materials, scarecrow), which arrows and labels keep out of.
func _hud_rects() -> Array[Rect2]:
var v := size_px()
return [Rect2(0.0, 0.0, 600.0, 140.0), Rect2(v.x - 540.0, 0.0, 540.0, 130.0), Rect2(0.0, v.y - 180.0, 370.0, 180.0)]
## Slides a point on the arrow border along that border, out of any HUD panel.
func _clear_of_hud(p: Vector2, inner: Rect2) -> Vector2:
for r in _hud_rects():
var g := r.grow(24.0)
if not g.has_point(p):
continue
var on_side := absf(p.x - inner.position.x) < 1.0 or absf(p.x - inner.end.x) < 1.0
if on_side:
p.y = g.end.y if g.position.y <= 0.0 else g.position.y
else:
p.x = g.end.x if g.position.x <= 0.0 else g.position.x
return p
func _arrow(at: Vector2, dir: Vector2, a: Dictionary, labels: Array[Rect2]) -> void:
var e := float(a["escalation"])
var color: Color = FILL[a["kind"]]
if int(a["kind"]) == Kind.ESCAPE:
color = Color(1.0, 0.6, 0.15).lerp(Color(1.0, 0.1, 0.08), e)
var pulse := 0.5 + 0.5 * sin(_time * (5.0 + 10.0 * e))
var size := 1.0 + 0.45 * e * pulse
var side := Vector2(-dir.y, dir.x)
var tip := at + dir * 28.0 * size
var back := at - dir * 16.0 * size
var points := PackedVector2Array([tip, back + side * 22.0 * size, back - side * 22.0 * size])
draw_colored_polygon(points, color)
points.append(tip)
var rim: Color = LootSystem.CATEGORY_COLORS[a["category"]] if int(a["category"]) >= 0 else Color(0.05, 0.03, 0.0)
draw_polyline(points, rim, 5.0, true)
draw_polyline(points, Color(0.05, 0.03, 0.0), 1.5, true)
var text := String(a["label"])
var fs := 20
var w := _font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var anchor := at - dir * 44.0 - Vector2(w * 0.5, -fs * 0.35)
anchor.x = clampf(anchor.x, 8.0, size_px().x - w - 8.0)
anchor.y = clampf(anchor.y, fs + 4.0, size_px().y - 8.0)
# Stack labels instead of overlapping them (moving toward the middle of the screen).
var step := Vector2(0.0, -26.0 if anchor.y > size_px().y * 0.5 else 26.0)
var box := Rect2(anchor + Vector2(-6.0, -fs - 2.0), Vector2(w + 12.0, fs + 10.0))
for k in 6:
var hit := false
for other in labels:
if other.intersects(box):
hit = true
break
if not hit:
break
anchor += step
box.position += step
labels.append(box)
draw_rect(box, Color(0.0, 0.0, 0.0, 0.45))
draw_string_outline(_font, anchor, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, 6, Color.BLACK)
draw_string(_font, anchor, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, color.lerp(Color.WHITE, 0.35))
func size_px() -> Vector2:
return get_viewport_rect().size

View file

@ -0,0 +1 @@
uid://clqvqr3bnsp5k

View file

@ -0,0 +1,469 @@
class_name AnimalSystem
extends Node3D
## The pen's animals as moving entities. Their theft state lives in LootSystem; this moves and
## shows them:
## in the pen (HOME) wander between random spots in the pen, pausing to graze; one a thief is
## catching stands still. At night (night and dawn), while the pen is open (a
## way out that crosses no structure: its gate broken or taken down), one calm
## animal wanders out every animal_wander_interval and is loose.
## loose (DROPPED) dropped by its thief, or wandered out: walks toward the farm's nearest edge
## along the escape field at stray_speed, stopping to graze now and then, and
## can't pass structures. At the edge it is lost; inside the pen it is home
## again.
## following walks the scarecrow's trail (so it goes wherever the scarecrow went, gates
## included), in line behind it. Inside the pen it is home (returned) and calm
## for animal_calm_time.
## carried held under its thief, wriggling.
## The farm pack's animals are static meshes, so walking is procedural: chickens hop, pigs and
## sheep waddle. Each scene animal (a farm-pack prefab under the pen zone) is reparented under a
## pivot at the middle of its body.
const WANDER_SPEED := {"chicken": 0.9, "pig": 0.6, "sheep": 0.7}
const TRAIL_STEP := 0.25
const TRAIL_POINTS := 160
const FOLLOW_GAP := 1.0
const FOLLOW_FIRST := 1.5
## A follower whose scarecrow got this far away (a retry, a fall) is loose again.
const FOLLOW_LEASH := 20.0
## The pen opened (its gate broken or taken down) or was shut again.
signal pen_changed(open: bool)
var config: GameConfig
var campaign: CampaignController
var nav: FarmNavigation
var loot: LootSystem
var enemies: EnemySystem
var player: Node3D
var pen: Rect2
## Set by FarmSim: the field loose animals walk along, toward the farm's nearest edge.
var escape_field := PackedInt32Array()
var count: int = 0
## There's a way out of the pen that crosses no structure.
var pen_open := false
# Per animal, indexed 1..count.
var pos := PackedVector2Array()
var prev := PackedVector2Array()
var yaw := PackedFloat32Array()
var speed := PackedFloat32Array()
var goal := PackedVector2Array()
var timer := PackedFloat32Array()
var calm := PackedFloat32Array()
var phase := PackedFloat32Array()
## Order in the line behind the scarecrow (0 = first), -1 when not following.
var slot := PackedInt32Array()
## Wandering out of the open pen and not out yet (so being inside doesn't count as home).
var leaving := PackedByteArray()
var kinds: Array[String] = []
var _start := PackedVector2Array()
var _start_yaw := PackedFloat32Array()
var _pivots: Array[Node3D] = []
var _meshes: Array = [] # per animal: Array[MeshInstance3D]
## Co-op: the scarecrows animals can follow (player 1's, player 2's), each with its trail, and
## which one each following animal follows.
var leaders: Array[Node3D] = []
var leader := PackedInt32Array()
var _trails: Array[PackedVector2Array] = [PackedVector2Array(), PackedVector2Array()]
var _wander_wait: float = 0.0
var _rng := RandomNumberGenerator.new()
var _dir := PackedFloat32Array([0.0, 0.0])
## Takes over the farm-pack animals under the pen zone (in name order: animal ids 1..count).
static func find_animals(pen_zone: Node3D) -> Array[Node3D]:
var out: Array[Node3D] = []
for child in pen_zone.get_children():
if child is Node3D and String(child.scene_file_path).contains("/animal/"):
out.append(child)
out.sort_custom(func(a: Node3D, b: Node3D) -> bool: return String(a.name) < String(b.name))
return out
func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNavigation, p_loot: LootSystem,
p_enemies: EnemySystem, p_player: Node3D) -> void:
campaign = p_campaign
config = p_campaign.config
nav = p_nav
loot = p_loot
enemies = p_enemies
player = p_player
leaders = [p_player]
pen = pen_zone.rect()
_rng.seed = 8061
var found := find_animals(pen_zone)
count = found.size()
var n := count + 1
for a: PackedVector2Array in [pos, prev, goal, _start]:
a.resize(n)
for a: PackedFloat32Array in [yaw, speed, timer, calm, phase, _start_yaw]:
a.resize(n)
slot.resize(n)
leader.resize(n)
leaving.resize(n)
kinds.resize(n)
_pivots.resize(n)
_meshes.resize(n)
for i in count:
var node := found[i]
var id := i + 1
kinds[id] = String(node.scene_file_path.get_file().get_basename()).get_slice("_", 0)
var center := _local_center(node)
var world := node.global_transform * center
var forward := node.global_transform.basis.z
var pivot := Node3D.new()
pivot.name = "Animal%d_%s" % [id, kinds[id]]
pivot.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(pivot)
node.reparent(pivot, false)
node.transform = Transform3D(Basis(), Vector3(-center.x, 0.0, -center.z))
_pivots[id] = pivot
var meshes: Array[MeshInstance3D] = []
for mi in node.find_children("*", "MeshInstance3D", true, false):
meshes.append(mi)
_meshes[id] = meshes
_start[id] = Vector2(world.x, world.z)
_start_yaw[id] = atan2(forward.x, forward.z)
phase[id] = _rng.randf() * TAU
sync_from_state()
## Every animal back at its spot in the pen (or hidden if lost), nobody following (new morning,
## retry).
func sync_from_state() -> void:
for k in _trails.size():
_trails[k] = PackedVector2Array()
_wander_wait = config.animal_wander_interval * 0.3
for id in range(1, count + 1):
pos[id] = _start[id]
prev[id] = _start[id]
yaw[id] = _start_yaw[id]
speed[id] = 0.0
goal[id] = _start[id]
timer[id] = _rng.randf_range(0.5, 3.0)
calm[id] = 0.0
slot[id] = -1
leaving[id] = 0
_apply_visuals(1.0)
## Co-op host: every animal's [x, z, yaw, speed].
func replica_record() -> PackedFloat32Array:
var out := PackedFloat32Array()
for id in range(1, count + 1):
out.append_array([pos[id].x, pos[id].y, yaw[id], speed[id]])
return out
## Co-op partner: the host's animals (drawn between this and the last, like a physics tick).
func apply_replica(rec: PackedFloat32Array) -> void:
if rec.size() != count * 4:
return
for id in range(1, count + 1):
var k := (id - 1) * 4
prev[id] = pos[id]
pos[id] = Vector2(rec[k], rec[k + 1])
yaw[id] = rec[k + 2]
speed[id] = rec[k + 3]
func kind(id: int) -> String:
return kinds[id] if id >= 1 and id <= count else "animal"
func position(id: int) -> Vector2:
return pos[id] if id >= 1 and id <= count else Vector2.ZERO
func in_pen(p: Vector2) -> bool:
return pen.grow(-0.6).has_point(p)
## Puts a loose animal where its carrier was stopped.
func place(id: int, p: Vector2) -> void:
pos[id] = p
prev[id] = p
speed[id] = 0.0
timer[id] = _rng.randf_range(0.6, 1.2) # a moment's shock before it bolts
func start_following(id: int) -> void:
var who := clampi(loot.recoverer if loot != null else 0, 0, maxi(leaders.size() - 1, 0))
var taken := 0
for other in range(1, count + 1):
if slot[other] >= 0 and leader[other] == who:
taken = maxi(taken, slot[other] + 1)
slot[id] = taken
leader[id] = who
## Whether there's a way out of the pen that crosses no structure (flood fill from inside the pen
## over walkable cells, reaching past the pen fence). Run whenever the structures change.
func update_pen_open() -> void:
var limit := pen.grow(2.0)
var outside := pen.grow(0.75)
var start := nav.cell_of(pen.get_center().x, pen.get_center().y)
var seen := {}
var queue: Array[int] = []
for c in nav.free_cells_in(pen.grow(-1.2)):
if nav.is_walkable(c):
queue.append(c)
seen[c] = true
if queue.is_empty():
queue.append(start)
var head := 0
var was := pen_open
pen_open = false
while head < queue.size():
var c := queue[head]
head += 1
var p := nav.cell_center(c)
if not outside.has_point(p):
pen_open = true
break
for k in 4:
var nb: int = c + nav._offsets[k]
if seen.has(nb) or not nav.is_walkable(nb) or not limit.has_point(nav.cell_center(nb)):
continue
seen[nb] = true
queue.append(nb)
if pen_open and not was:
_wander_wait = config.animal_wander_interval * 0.3
if pen_open != was:
pen_changed.emit(pen_open)
## Physics tick, after the loot system (recoveries) and before the night's arrivals.
func step(dt: float) -> void:
var at: Array[Vector2] = []
for k in leaders.size():
var body := leaders[k]
at.append(Vector2(body.global_position.x, body.global_position.z) if body != null else Vector2(INF, INF))
if body != null:
_record_trail(k, at[k])
_wander_out(dt)
for id in range(1, count + 1):
prev[id] = pos[id]
calm[id] = maxf(calm[id] - dt, 0.0)
var item := loot.animal_item(id)
match loot.status[item]:
LootSystem.Status.HOME:
slot[id] = -1
_wander(id, item, dt)
LootSystem.Status.DROPPED:
slot[id] = -1
if not in_pen(pos[id]):
leaving[id] = 0
if in_pen(pos[id]) and leaving[id] == 0:
loot.animal_home(item)
_rest(id)
else:
_stray(id, item, dt)
LootSystem.Status.FOLLOWING:
var k := clampi(leader[id], 0, at.size() - 1)
_follow(id, item, at[k], dt)
LootSystem.Status.CARRIED:
slot[id] = -1
var d := enemies.resolve_handle(loot.holder[item])
if d >= 0:
pos[id] = Vector2(enemies.pos_x[d], enemies.pos_z[d])
speed[id] = 0.0
_:
slot[id] = -1
speed[id] = 0.0
func _process(_delta: float) -> void:
_apply_visuals(Engine.get_physics_interpolation_fraction())
func _wander(id: int, item: int, dt: float) -> void:
# Stand still while a thief is catching it.
var d := enemies.resolve_handle(loot.holder[item]) if loot.holder[item] >= 0 else -1
if d >= 0 and Vector2(enemies.pos_x[d], enemies.pos_z[d]).distance_to(pos[id]) < 2.0:
speed[id] = 0.0
var to := Vector2(enemies.pos_x[d], enemies.pos_z[d]) - pos[id]
if to.length_squared() > 1e-4:
yaw[id] = lerp_angle(yaw[id], atan2(-to.x, -to.y), 0.1) # facing away, cowering
return
timer[id] -= dt
if speed[id] == 0.0:
if timer[id] <= 0.0:
goal[id] = _wander_goal()
speed[id] = float(WANDER_SPEED.get(kinds[id], 0.7))
timer[id] = 8.0 # give up on a goal it can't reach
return
var to := goal[id] - pos[id]
if to.length() < 0.2 or timer[id] <= 0.0:
_rest(id)
return
_move(id, to.normalized(), speed[id], dt)
func _stray(id: int, item: int, dt: float) -> void:
if escape_field.size() > 0 and escape_field[nav.cell_of(pos[id].x, pos[id].y)] == 0:
loot.animal_escaped(item)
speed[id] = 0.0
return
timer[id] -= dt
if timer[id] <= 0.0:
if speed[id] > 0.0:
speed[id] = 0.0 # graze a moment
timer[id] = _rng.randf_range(0.8, 1.8)
else:
speed[id] = config.stray_speed
timer[id] = _rng.randf_range(3.0, 5.0)
if speed[id] > 0.0 and escape_field.size() > 0 and nav.flow_direction(escape_field, pos[id].x, pos[id].y, _dir):
_move(id, Vector2(_dir[0], _dir[1]), speed[id], dt)
func _follow(id: int, item: int, sc: Vector2, dt: float) -> void:
if in_pen(pos[id]):
loot.animal_home(item)
calm[id] = config.animal_calm_time
slot[id] = -1
_rest(id)
return
if pos[id].distance_to(sc) > FOLLOW_LEASH:
loot.status[item] = LootSystem.Status.DROPPED
loot.ground[item] = pos[id]
slot[id] = -1
_rest(id)
return
var target := _trail_point(clampi(leader[id], 0, _trails.size() - 1), sc, FOLLOW_FIRST + FOLLOW_GAP * maxi(slot[id], 0))
var to := target - pos[id]
var dist := to.length()
speed[id] = clampf(dist * 3.0, 0.0, config.follow_speed)
if dist < 0.05:
speed[id] = 0.0
return
var step_len := minf(speed[id] * dt, dist)
pos[id] += to / dist * step_len
yaw[id] = lerp_angle(yaw[id], atan2(to.x, to.y), 0.2)
## Moves with the grid's collision (static obstacles and structures), sliding along an axis
## when blocked.
func _move(id: int, dir: Vector2, v: float, dt: float) -> void:
var p := pos[id]
var n := p + dir * v * dt
if not nav.is_walkable(nav.cell_of(n.x, n.y)):
if nav.is_walkable(nav.cell_of(n.x, p.y)):
n.y = p.y
elif nav.is_walkable(nav.cell_of(p.x, n.y)):
n.x = p.x
else:
n = p
pos[id] = n
if n.distance_squared_to(p) > 1e-8:
var moved := n - p
yaw[id] = lerp_angle(yaw[id], atan2(moved.x, moved.y), 0.15)
func _rest(id: int) -> void:
speed[id] = 0.0
timer[id] = _rng.randf_range(1.5, 4.0)
func _wander_goal() -> Vector2:
var area := pen.grow(-1.2)
for attempt in 12:
var p := Vector2(_rng.randf_range(area.position.x, area.end.x), _rng.randf_range(area.position.y, area.end.y))
if nav.is_walkable(nav.cell_of(p.x, p.y)):
return p
return area.get_center()
## At night, while the pen is open, a calm animal walks out now and then.
func _wander_out(dt: float) -> void:
var ph := campaign.state.phase
if not pen_open or (ph != CampaignController.Phase.NIGHT and ph != CampaignController.Phase.DAWN):
return
_wander_wait -= dt
if _wander_wait > 0.0:
return
_wander_wait = config.animal_wander_interval
var calm_ones: Array[int] = []
for id in range(1, count + 1):
var item := loot.animal_item(id)
if loot.status[item] == LootSystem.Status.HOME and loot.holder[item] == -1 and calm[id] == 0.0:
calm_ones.append(id)
if not calm_ones.is_empty():
var id := calm_ones[_rng.randi() % calm_ones.size()]
loot.animal_strays(loot.animal_item(id))
leaving[id] = 1
speed[id] = config.stray_speed
timer[id] = 4.0
func _record_trail(k: int, sc: Vector2) -> void:
var trail := _trails[k]
if trail.is_empty() or trail[trail.size() - 1].distance_to(sc) >= TRAIL_STEP:
trail.append(sc)
if trail.size() > TRAIL_POINTS:
trail.remove_at(0)
_trails[k] = trail # packed arrays are values: store the changed one back
## The point `back` meters behind a scarecrow along the path it walked.
func _trail_point(k: int, sc: Vector2, back: float) -> Vector2:
var trail := _trails[k]
var at := sc
var left := back
for i in range(trail.size() - 1, -1, -1):
var p := trail[i]
var seg := at.distance_to(p)
if seg >= left:
return at.lerp(p, left / seg) if seg > 1e-5 else p
left -= seg
at = p
return at
func _apply_visuals(f: float) -> void:
for id in range(1, count + 1):
var pivot := _pivots[id]
var item := loot.animal_item(id)
var st := loot.status[item]
pivot.visible = st != LootSystem.Status.LOST
if not pivot.visible:
continue
var outline: Material = loot.outline_for(LootSystem.Category.ANIMAL) \
if st == LootSystem.Status.CARRIED or st == LootSystem.Status.DROPPED else null
for mi: MeshInstance3D in _meshes[id]:
if mi.material_overlay != outline:
mi.material_overlay = outline
if st == LootSystem.Status.CARRIED:
var d := enemies.resolve_handle(loot.holder[item])
var p := enemies.visual_position(d) if d >= 0 else pos[id]
var t := Time.get_ticks_msec() / 1000.0
pivot.position = Vector3(p.x, config.combat_height - 1.05, p.y)
pivot.rotation = Vector3(sin(t * 9.0) * 0.25, yaw[id] + sin(t * 4.0) * 0.4, sin(t * 11.0) * 0.2)
continue
var p := prev[id].lerp(pos[id], f)
var moving := speed[id] > 0.05
phase[id] += (get_process_delta_time() if is_inside_tree() else 0.0) * (6.0 + speed[id] * 6.0) * (1.0 if moving else 0.0)
var y := 0.0
var roll := 0.0
if moving:
if kinds[id] == "chicken":
y = absf(sin(phase[id])) * 0.12
else:
y = absf(sin(phase[id])) * 0.03
roll = sin(phase[id]) * 0.07
pivot.position = Vector3(p.x, y, p.y)
pivot.rotation = Vector3(0.0, yaw[id], roll)
## The middle of a model's body, in its own coordinates (from its meshes' bounds).
static func _local_center(node: Node3D) -> Vector3:
var box := AABB()
var first := true
for mi in node.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var local := node.global_transform.affine_inverse() * m.global_transform
var a: AABB = local * m.get_aabb()
box = a if first else box.merge(a)
first = false
return box.get_center() if not first else Vector3.ZERO

View file

@ -0,0 +1 @@
uid://cip8klystkp4v

View file

@ -0,0 +1,59 @@
class_name Assessment
extends RefCounted
## The final assessment once the farmers are back: the share of each category kept, a weighted
## score, its rating tier (GameConfig.assessment_weights, rating_tiers), and the vacation's totals.
## * Crops and animals: what's still on the farm of what was there at the start.
## * Supplies are also spent on building, so they count by theft instead: of everything that
## passed through the farm (the shed's starting stock plus everything gathered), the share
## thieves didn't carry off.
## Categories not in play are left out and the weights renormalized.
## {"parts": category -> share kept (0..1), "score": 0..100, "tier", "text" (the tier's
## line), "totals": FarmState.totals(), "supplies_handled", "supplies_lost"}.
static func of(s: FarmState, cfg: GameConfig) -> Dictionary:
var t := s.totals()
var parts := {}
if s.crops_total > 0:
parts["crops"] = float(s.crops) / s.crops_total
if s.animals_total > 0:
parts["animals"] = float(s.animals) / s.animals_total
var handled: int = s.supplies_total + int(t["gathered_wood"]) + int(t["gathered_scrap"]) + int(t["gathered_straw"])
if handled > 0:
parts["supplies"] = 1.0 - minf(float(t["supplies_lost"]) / handled, 1.0)
var weight := 0.0
var sum := 0.0
for k: String in parts:
var w := float(cfg.assessment_weights.get(k, 0.0))
weight += w
sum += w * float(parts[k])
var score := roundi(100.0 * sum / weight) if weight > 0.0 else 0
var tier := {}
for row in cfg.rating_tiers:
if score >= int(row.get("min", 0)):
tier = row
break
return {"parts": parts, "score": score, "tier": String(tier.get("name", "")), "text": String(tier.get("text", "")),
"totals": t, "supplies_handled": handled, "supplies_lost": int(t["supplies_lost"])}
## "50 crows, 20 thieves and 6 fence breakers" (or "none").
static func enemies_line(t: Dictionary) -> String:
var parts := PackedStringArray()
for type in [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER]:
var n := int(t.get("killed_" + EnemySystem.TYPE_NAMES[type], 0))
if n == 1:
parts.append("1 " + EnemySystem.NAMES[type])
elif n > 1:
parts.append("%d %s" % [n, EnemySystem.PLURALS[type]])
return PhaseHud.join_words(parts) if not parts.is_empty() else "none"
## "18 wood, 6 scrap, 12 straw" from the gathered_ or spent_ counts (or "nothing").
static func materials_line(t: Dictionary, prefix: String) -> String:
var amounts := {}
for m in ResourceStore.MATERIALS:
if int(t.get(prefix + m, 0)) > 0:
amounts[m] = int(t[prefix + m])
var text := ResourceStore.describe(amounts)
return text if text != "" else "nothing"

View file

@ -0,0 +1 @@
uid://cnn7o882bgewn

89
game/scripts/asset_hud.gd Normal file
View file

@ -0,0 +1,89 @@
class_name AssetHud
extends Control
## Top-center readout of what's left to protect: "Crops 28/30 · Animals 7/8 · Supplies 23" (the
## shed's stock plus any sacks still on the farm), each in its category's color. A count flashes
## red when it drops and green when it rises. Categories not in play are left out.
const FLASH_TIME := 1.2
const LOSS := Color(1.0, 0.3, 0.25)
const GAIN := Color(0.5, 1.0, 0.45)
var campaign: CampaignController
var _box: HBoxContainer
var _panel: PanelContainer
var _labels: Array[Label] = []
var _last := PackedInt32Array([-1, -1, -1])
var _flash := PackedFloat32Array([0.0, 0.0, 0.0])
var _flash_color: Array[Color] = [Color.WHITE, Color.WHITE, Color.WHITE]
func setup(p_campaign: CampaignController) -> void:
campaign = p_campaign
_last = _counts()
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_panel = PanelContainer.new()
var bg := StyleBoxFlat.new()
bg.bg_color = Color(0.0, 0.0, 0.0, 0.42)
bg.content_margin_left = 18.0
bg.content_margin_right = 18.0
bg.content_margin_top = 4.0
bg.content_margin_bottom = 4.0
_panel.add_theme_stylebox_override("panel", bg)
_panel.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(_panel)
_box = HBoxContainer.new()
_box.add_theme_constant_override("separation", 28)
_box.mouse_filter = Control.MOUSE_FILTER_IGNORE
_panel.add_child(_box)
for c in 3:
var l := Label.new()
l.add_theme_font_size_override("font_size", 24)
l.add_theme_color_override("font_color", LootSystem.CATEGORY_COLORS[c])
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
_box.add_child(l)
_labels.append(l)
## "Crops 28/30 · Animals 7/8 · Supplies 23", as the HUD shows it (also used by tests).
func describe() -> String:
var parts: Array[String] = []
for l in _labels:
if l.visible:
parts.append(l.text)
return " · ".join(parts)
func _process(delta: float) -> void:
if campaign == null:
return
var s := campaign.state
var now := _counts()
var texts := ["Crops %d/%d" % [s.crops, s.crops_total], "Animals %d/%d" % [s.animals, s.animals_total],
"Supplies %d" % s.supplies]
var in_play := [s.crops_total > 0, s.animals_total > 0, s.supplies_total > 0]
for c in 3:
var l := _labels[c]
l.visible = in_play[c]
l.text = texts[c]
if _last[c] >= 0 and now[c] != _last[c]:
_flash[c] = FLASH_TIME
_flash_color[c] = LOSS if now[c] < _last[c] else GAIN
_last[c] = now[c]
_flash[c] = maxf(_flash[c] - delta, 0.0)
var k := _flash[c] / FLASH_TIME
var pulse := (0.5 + 0.5 * sin(_flash[c] * 18.0)) * k
l.modulate = Color.WHITE.lerp(_flash_color[c] * 1.4, pulse)
_panel.reset_size()
_panel.position = Vector2((size.x - _panel.size.x) * 0.5, 14.0)
func _counts() -> PackedInt32Array:
var s := campaign.state
return PackedInt32Array([s.crops, s.animals, s.supplies])

View file

@ -0,0 +1 @@
uid://cdhho7exq5x3s

32
game/scripts/avatar.gd Normal file
View file

@ -0,0 +1,32 @@
class_name Avatar
extends RefCounted
## One scarecrow in play and everything that acts for it: its body, its kit (health, fear,
## patching), its gun, and its hands (Interactions). Solo there is one (player 1). In co-op
## FarmSim holds two: slot 0 is player 1 (the host's), slot 1 player 2 (the partner's). The one
## this machine plays is local; on the host the partner's reads RemoteControls (remote), and on
## the partner's machine player 1's is moved by the network.
const NAMES: Array[String] = ["P1", "P2"]
const COLORS: Array[Color] = [Color(1.0, 0.85, 0.35), Color(0.45, 0.8, 1.0)]
var slot: int = 0
var body: PlayerCharacter
var kit: Scarecrow
var combat: ScarecrowCombat
var interactions: Interactions
var remote: RemoteControls
var is_local := true
## The player's name (co-op), shown on the tag over the head and the partner HUD.
var player_name := ""
func position() -> Vector2:
return Vector2(body.global_position.x, body.global_position.z)
func label() -> String:
return "%s %s" % [NAMES[slot], player_name] if player_name != "" else NAMES[slot]
func color() -> Color:
return COLORS[slot]

View file

@ -0,0 +1 @@
uid://r1m82ruktoay

76
game/scripts/build_hud.gd Normal file
View file

@ -0,0 +1,76 @@
class_name BuildHud
extends Control
## The build hotbar, shown in build mode: one slot per buildable with its key, name, and cost
## (red when it can't be afforded), the selected one highlighted, the controls, and how many
## structures stand on the farm.
const SLOT := Vector2(230.0, 76.0)
const GAP := 12.0
var build: BuildMode
var campaign: CampaignController
var _names: Array[Label] = []
var _costs: Array[Label] = []
var _help: Label
func setup(p_build: BuildMode, p_campaign: CampaignController) -> void:
build = p_build
campaign = p_campaign
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
for i in StructureSystem.ORDER.size():
_names.append(_label(22))
_costs.append(_label(18))
_help = _label(19)
func _process(_delta: float) -> void:
visible = build != null and build.active
if not visible:
return
var r := campaign.state.resources
var origin := _origin()
for i in StructureSystem.ORDER.size():
var t: String = StructureSystem.ORDER[i]
var cost: Dictionary = campaign.config.costs.get(t, {})
var pos := origin + Vector2(i * (SLOT.x + GAP), 0.0)
_names[i].text = "%d %s" % [i + 1, StructureSystem.NAMES[t]]
_names[i].position = pos + Vector2(12.0, 8.0)
_costs[i].text = ResourceStore.describe(cost)
_costs[i].position = pos + Vector2(12.0, 42.0)
_costs[i].add_theme_color_override("font_color", Color(0.9, 0.95, 0.9) if r.can_afford(cost) else Color(1.0, 0.45, 0.4))
_help.text = "Build mode · LMB / RT build · Z C / d-pad rotate · 1-4 / Tab pick · RMB / B dismantle or leave · %d built" % \
build.structures.count()
_help.position = origin + Vector2(0.0, -34.0)
queue_redraw()
func _draw() -> void:
if build == null or not build.active:
return
var origin := _origin()
for i in StructureSystem.ORDER.size():
var rect := Rect2(origin + Vector2(i * (SLOT.x + GAP), 0.0), SLOT)
draw_rect(rect, Color(0.0, 0.0, 0.0, 0.55))
draw_rect(rect, Color(1.0, 0.9, 0.4) if i == build.selected else Color(1.0, 1.0, 1.0, 0.25), false, 3.0 if i == build.selected else 1.5)
func _origin() -> Vector2:
var n := StructureSystem.ORDER.size()
var width := n * SLOT.x + (n - 1) * GAP
return Vector2((size.x - width) * 0.5, size.y - SLOT.y - 28.0)
func _label(font_size: int) -> Label:
var l := Label.new()
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(l)
return l

View file

@ -0,0 +1 @@
uid://kmuyj86rfjj2

208
game/scripts/build_mode.gd Normal file
View file

@ -0,0 +1,208 @@
class_name BuildMode
extends Node3D
## The scarecrow's build mode (build_mode: B / d-pad up toggles it):
## * Pick what to build with 1-4, or cycle with build_next (Tab / d-pad down).
## * A ghost follows the cursor, snapped to the 0.5 m grid: the ground point under the mouse,
## or GAMEPAD_REACH ahead along the right stick. rotate_left / rotate_right (Z / C, d-pad)
## turn it by 45 degrees.
## * The ghost is green where it can go and red where it can't, with the reason above it.
## * fire (LMB / RT) builds it (StructureSystem.validate, then place).
## * Over a built structure, cancel (RMB / B) dismantles it for its refund; anywhere else
## cancel leaves build mode.
## The scarecrow doesn't shoot, gather, or repair while building (FarmSim, Interactions).
## Co-op, on the partner's machine: placing and dismantling are sent to the host (place_request,
## dismantle_request), which checks them again and does them; the result comes back as a message.
signal message(text: String, color: Color)
signal toggled(on: bool)
## A placement was refused (the reason); a structure was taken down.
signal refused(reason: String)
signal dismantled(type: String)
const ACTIONS: Array[StringName] = [&"build_mode", &"build_next", &"build_1", &"build_2", &"build_3",
&"build_4", &"rotate_left", &"rotate_right", &"fire", &"cancel"]
const GAMEPAD_REACH := 3.0
var active := false
var selected: int = 0
var rot: int = 0
var cursor := Vector2.ZERO
## Built structure under the cursor (-1 = none) and why the ghost can't be placed ("" = it can).
var hover: int = -1
var reason := ""
var config: GameConfig
var campaign: CampaignController
var player: PlayerCharacter
var camera: Camera3D
var structures: StructureSystem
var combat: ScarecrowCombat
var kit: Scarecrow
## Co-op partner: ask the host instead (type, x, z, rot) / (structure id).
var place_request: Callable
var dismantle_request: Callable
var _edges := ActionEdges.new()
var _ghost: Node3D
var _ghost_key := ""
var _ok_mat: StandardMaterial3D
var _bad_mat: StandardMaterial3D
var _label: Label3D
var _stick_dir := Vector2(0.0, -1.0)
func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter, p_camera: Camera3D,
p_structures: StructureSystem, p_combat: ScarecrowCombat, p_kit: Scarecrow) -> void:
config = cfg
campaign = p_campaign
player = p_player
camera = p_camera
structures = p_structures
combat = p_combat
kit = p_kit
_ok_mat = _ghost_material(Color(0.3, 1.0, 0.4, 0.45))
_bad_mat = _ghost_material(Color(1.0, 0.25, 0.2, 0.45))
_label = Label3D.new()
_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_label.no_depth_test = true
_label.shaded = false
_label.font_size = 40
_label.outline_size = 10
_label.pixel_size = 0.0075
_label.top_level = true
_label.visible = false
_label.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(_label)
func type() -> String:
return StructureSystem.ORDER[selected]
func set_active(on: bool) -> void:
if on == active:
return
active = on
if _ghost != null:
_ghost.visible = on
_label.visible = on
toggled.emit(on)
## One physics tick. Every action is polled each tick so presses are seen exactly once.
func step(_dt: float) -> void:
var p := {}
for a in ACTIONS:
p[a] = _edges.pressed(a)
if not kit.alive:
set_active(false)
return
if p[&"build_mode"]:
set_active(not active)
if not active:
return
for k in 4:
if p[StringName("build_%d" % (k + 1))]:
selected = k
if p[&"build_next"]:
selected = (selected + 1) % StructureSystem.ORDER.size()
if p[&"rotate_left"]:
rot = (rot + 7) % 8
if p[&"rotate_right"]:
rot = (rot + 1) % 8
_update_cursor()
var me := Vector2(player.global_position.x, player.global_position.z)
hover = structures.structure_near(cursor, 0.3)
if hover >= 0:
reason = ""
if p[&"cancel"]:
if dismantle_request.is_valid():
dismantle_request.call(hover)
hover = -1
return
var e := campaign.state.structure(hover)
var back := structures.dismantle(hover)
dismantled.emit(String(e["type"]))
message.emit("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))
hover = -1
return
reason = structures.validate(type(), cursor.x, cursor.y, rot, me)
if p[&"fire"]:
if reason == "" and place_request.is_valid():
place_request.call(type(), cursor.x, cursor.y, rot)
elif reason == "":
structures.place(type(), cursor.x, cursor.y, rot)
message.emit("Built a %s" % StructureSystem.NAMES[type()].to_lower(), Color(0.6, 1.0, 0.55))
else:
message.emit(reason, Color(1.0, 0.8, 0.5))
refused.emit(reason)
elif p[&"cancel"]:
set_active(false)
func _unhandled_input(event: InputEvent) -> void:
_edges.note(event, ACTIONS)
func _update_cursor() -> void:
var at: Vector2
if combat.device == ScarecrowCombat.Device.GAMEPAD:
var b := camera.global_transform.basis
var fwd := Vector2(-b.z.x, -b.z.z).normalized()
var right := Vector2(b.x.x, b.x.z).normalized()
var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", config.aim_dead_zone)
if stick != Vector2.ZERO:
_stick_dir = (right * stick.x + fwd * stick.y).normalized()
at = Vector2(player.global_position.x, player.global_position.z) + _stick_dir * GAMEPAD_REACH
else:
var screen := camera.get_viewport().get_mouse_position()
var o := camera.project_ray_origin(screen)
var d := camera.project_ray_normal(screen)
var t := -o.y / d.y if absf(d.y) > 1e-5 else 0.0
at = Vector2(o.x + d.x * t, o.z + d.z * t)
cursor = StructureSystem.snap(at)
func _process(_delta: float) -> void:
if not active:
return
var key := "%s/%d" % [type(), rot]
if key != _ghost_key:
_ghost_key = key
if _ghost != null:
_ghost.queue_free()
_ghost = structures.make_ghost(type(), rot)
_ghost.top_level = true
add_child(_ghost)
var ok := reason == "" and hover < 0
for mi in _ghost.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_override = _ok_mat if ok else _bad_mat
_ghost.visible = hover < 0
_ghost.global_position = Vector3(cursor.x, structures._ground_y(cursor), cursor.y)
_label.global_position = Vector3(cursor.x, 2.4, cursor.y)
if hover >= 0:
var e := campaign.state.structure(hover)
var refund := {}
var cost: Dictionary = config.costs.get(e.get("type", ""), {})
for m in cost:
if floori(int(cost[m]) * config.dismantle_refund) > 0:
refund[m] = floori(int(cost[m]) * config.dismantle_refund)
_label.text = "%s %d/%d\n[RMB / B] Dismantle%s" % [StructureSystem.NAMES.get(e.get("type", ""), ""), int(e.get("hp", 0)),
structures.max_hp(e.get("type", "fence")), (" (+%s)" % ResourceStore.describe(refund)) if not refund.is_empty() else ""]
_label.modulate = Color(0.85, 0.95, 1.0)
elif ok:
_label.text = "%s %s\n[LMB / RT] Build" % [StructureSystem.NAMES[type()], ResourceStore.describe(config.costs.get(type(), {}))]
_label.modulate = Color(0.7, 1.0, 0.7)
else:
_label.text = "%s\n%s" % [StructureSystem.NAMES[type()], reason]
_label.modulate = Color(1.0, 0.7, 0.6)
func _ghost_material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
m.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
m.albedo_color = color
m.no_depth_test = false
return m

View file

@ -0,0 +1 @@
uid://btsyw0fbbdpeh

View file

@ -1,7 +1,9 @@
class_name CampaignController
extends Node
## Owns the five-night vacation: the phase state machine, phase timers, the outcome rules, and
## the morning snapshot used to retry a failed night (rules: game/RULES.md).
## Owns the vacation (GameConfig.campaign_nights nights): the phase state machine, phase timers,
## the outcome rules, and the morning snapshot used to retry a failed night (rules:
## game/RULES.md). With save_path set, every morning is also saved to disk (SaveGame), and
## finishing the vacation deletes the save.
##
## MORNING -> DAY -> DUSK -> NIGHT -> DAWN -> MORNING of the next night; after the final dawn,
## FARMERS_RETURN. GAME_OVER can follow any phase. Both are terminal. The morning review is
@ -17,11 +19,24 @@ enum Outcome { CONTINUE, GAME_OVER_SCARECROW, GAME_OVER_STRIPPED, VACATION_COMPL
signal phase_changed(phase: Phase, previous: Phase)
signal campaign_ended(outcome: Outcome)
## The dawn grace is over: listeners settle the night (enemies leave, loot on the ground returns)
## before its losses are recorded and the outcome is checked.
signal night_ending
@export var config: GameConfig
var state: FarmState
var outcome: Outcome = Outcome.CONTINUE
## Set by FarmSim: night -> its plan's length, when the plan overrides GameConfig.night_length
## (returns 0 or less for "no override").
var night_length_for: Callable
## Co-op, on the partner's machine (a replica of the host's farm): what the player asks for
## (begin_day, retry_night, start_night_early) goes to the host instead ("begin_day" etc.).
var remote_request: Callable
## Where every morning is autosaved ("" = not saved; Main sets SaveGame.PATH).
var save_path := ""
## The last autosave's result.
var last_save_error: Error = OK
var _morning_snapshot: Dictionary = {}
var _night_start := PackedInt32Array()
@ -59,6 +74,9 @@ func tick(delta: float) -> void:
func begin_day() -> bool:
if state.phase != Phase.MORNING:
return false
if remote_request.is_valid():
remote_request.call("begin_day")
return true
_resolve(true)
return true
@ -67,6 +85,9 @@ func begin_day() -> bool:
func start_night_early() -> bool:
if not can_start_night_early():
return false
if remote_request.is_valid():
remote_request.call("start_night_early")
return true
_enter(Phase.NIGHT)
return true
@ -81,8 +102,23 @@ func advance_phase() -> void:
_resolve(true)
## D9: restarts the current night from its morning (the autosave point once saving exists).
## Continues a saved vacation (SaveGame.read): its morning becomes the current one.
func load_state(saved: FarmState) -> void:
state = saved
outcome = Outcome.CONTINUE
_enter(Phase.MORNING)
## The latest morning's state (what retry_night() restores and what was saved).
func morning_snapshot() -> Dictionary:
return _morning_snapshot.duplicate(true)
## D9: restarts the current night from its morning (the autosave point).
func retry_night() -> bool:
if remote_request.is_valid():
remote_request.call("retry_night")
return true
var restored := FarmState.from_dict(_morning_snapshot)
if restored == null:
return false
@ -92,18 +128,33 @@ func retry_night() -> bool:
return true
## D8: gathering, building, and upgrades happen by day (day and dusk), not at night or during
## the morning review.
func is_daytime() -> bool:
return state.phase == Phase.DAY or state.phase == Phase.DUSK
func is_over() -> bool:
return state.phase == Phase.GAME_OVER or state.phase == Phase.FARMERS_RETURN
func is_timed(phase: Phase) -> bool:
return is_finite(config.phase_length(phase))
return is_finite(phase_length(phase))
## Seconds a phase lasts tonight (the night can be longer or shorter than usual), or INF.
func phase_length(phase: Phase) -> float:
if phase == Phase.NIGHT and night_length_for.is_valid():
var override: float = night_length_for.call(state.night)
if override > 0.0:
return override
return config.phase_length(phase)
## The outcome rules as a pure function of the farm state. Scarecrow destruction is checked
## first, then a stripped farm, and only then completing the vacation.
static func check_outcome(s: FarmState, campaign_nights: int) -> Outcome:
if s.scarecrow_hp <= 0:
if s.scarecrow_hp <= 0 and (not s.coop or s.partner_hp <= 0): # in co-op, both down
return Outcome.GAME_OVER_SCARECROW
if s.is_stripped():
return Outcome.GAME_OVER_STRIPPED
@ -115,11 +166,15 @@ static func check_outcome(s: FarmState, campaign_nights: int) -> Outcome:
func _resolve(phase_finished: bool) -> void:
var finished_phase := state.phase
if phase_finished and finished_phase == Phase.DAWN:
night_ending.emit()
state.nights_survived = state.night
state.log_night(_night_start)
state.settle_supplies()
var result := check_outcome(state, config.campaign_nights)
if result != Outcome.CONTINUE:
outcome = result
if result == Outcome.VACATION_COMPLETE and save_path != "":
SaveGame.delete(save_path)
_enter(Phase.FARMERS_RETURN if result == Outcome.VACATION_COMPLETE else Phase.GAME_OVER)
campaign_ended.emit(result)
return
@ -133,11 +188,21 @@ func _resolve(phase_finished: bool) -> void:
func _enter(phase: Phase) -> void:
var previous := state.phase
state.phase = phase
var length := config.phase_length(phase)
var length := phase_length(phase)
state.phase_time_left = length if is_finite(length) else 0.0
match phase:
Phase.MORNING:
state.night_events.clear() # the day's and night's counts start now
if state.coop: # a scarecrow that fell in the night is back, at half health
if state.scarecrow_hp <= 0:
state.scarecrow_hp = ceili(state.scarecrow_max_hp / 2.0)
if state.partner_hp <= 0:
state.partner_hp = ceili(state.partner_max_hp / 2.0)
_morning_snapshot = state.to_dict()
if save_path != "":
last_save_error = SaveGame.write(_morning_snapshot, save_path)
if last_save_error != OK:
push_warning("Autosave to %s failed: %s" % [save_path, error_string(last_save_error)])
Phase.NIGHT:
_night_start = state.asset_counts()
phase_changed.emit(phase, previous)

View file

@ -1,16 +1,19 @@
class_name CampaignDebug
extends CanvasLayer
## Temporary campaign readout and debug keys, until the phase HUD (Step 7) and menus (Step 11)
## replace it.
## Enter / Space / A begin the day (ends the untimed morning review)
## Debug readout and keys (debug builds). The readout is hidden until F1; the keys always work.
## F1 show / hide this readout
## F2 cycle tonight's plan through the debug scenarios (one enemy type, then
## pairs, then all three; game/resources/scenarios/) and back to the real one
## N start the night early (only when GameConfig.allow_early_night is on)
## R / Start after Game Over: retry the night; after the farmers return: new vacation
## R after Game Over: retry the night; after the farmers return: new vacation
## F6 end the current phase now
## F7 cycle game speed 1x / 5x / 20x
## F9 debug: scarecrow to 0 HP
## F10 debug: strip every farm asset
## T / G / H debug: send in a thief / a crow / a fence breaker (FarmSim)
const SPEEDS: Array[float] = [1.0, 5.0, 20.0]
const SCENARIOS: Array[String] = ["crows", "thieves", "breakers", "crows_thieves", "thieves_breakers", "all_three"]
const ENDINGS := {
CampaignController.Outcome.GAME_OVER_SCARECROW: "GAME OVER: the scarecrow was destroyed",
CampaignController.Outcome.GAME_OVER_STRIPPED: "GAME OVER: the farm was stripped bare",
@ -18,17 +21,21 @@ const ENDINGS := {
}
@export var campaign: CampaignController
## Optional: shows thieves and crops in flight.
@export var sim: FarmSim
var _label: Label
var _speed_index: int = 0
var _scenario: int = -1
func _ready() -> void:
_label = Label.new()
_label.position = Vector2(24.0, 20.0)
_label.position = Vector2(24.0, 140.0)
_label.add_theme_font_size_override("font_size", 22)
_label.add_theme_color_override("font_outline_color", Color.BLACK)
_label.add_theme_constant_override("outline_size", 6)
_label.visible = false
add_child(_label)
@ -42,9 +49,7 @@ func _process(_delta: float) -> void:
func _unhandled_input(event: InputEvent) -> void:
var s := campaign.state
if event.is_action_pressed("ui_accept") and s.phase == CampaignController.Phase.MORNING:
campaign.begin_day()
elif event.is_action_pressed("restart"):
if event.is_action_pressed("restart") and event is InputEventKey:
if s.phase == CampaignController.Phase.GAME_OVER:
campaign.retry_night()
elif s.phase == CampaignController.Phase.FARMERS_RETURN:
@ -53,6 +58,10 @@ func _unhandled_input(event: InputEvent) -> void:
if key == null or not key.pressed or key.echo:
return
match key.physical_keycode:
KEY_F1:
_label.visible = not _label.visible
KEY_F2:
cycle_scenario()
KEY_N:
campaign.start_night_early()
KEY_F6:
@ -63,9 +72,20 @@ func _unhandled_input(event: InputEvent) -> void:
KEY_F9:
s.scarecrow_hp = 0
KEY_F10:
s.crops = 0
s.animals = 0
s.supplies = 0
s.strip()
## Next debug scenario as tonight's plan (after the last, the real plan again).
func cycle_scenario() -> void:
if sim == null:
return
_scenario = _scenario + 1 if _scenario + 1 < SCENARIOS.size() else -1
var plan: NightPlan = null
if _scenario >= 0:
plan = load("res://game/resources/scenarios/%s.tres" % SCENARIOS[_scenario]) as NightPlan
sim.waves.debug_plan = plan
if sim.toasts != null:
sim.toasts.push("Tonight (debug): %s" % (plan.title if plan != null else "the night's own plan"), Color(0.8, 0.9, 1.0))
func _describe() -> String:
@ -81,11 +101,13 @@ func _describe() -> String:
if s.animals_total > 0:
farm += " · Animals %d/%d" % [s.animals, s.animals_total]
if s.supplies_total > 0:
farm += " · Supplies %d" % s.supplies
farm += " · Supplies %d%s" % [s.supplies, " (raided)" if s.shed_raided else ""]
lines.append(farm)
if sim != null and sim.loot != null:
lines.append("Thieves %d · carried %d, dropped %d, following %d · pen %s" % [sim.enemies.alive_count(),
sim.loot.count(LootSystem.Status.CARRIED), sim.loot.count(LootSystem.Status.DROPPED),
sim.loot.followers(), "open" if sim.animals.pen_open else "closed"])
match s.phase:
CampaignController.Phase.MORNING:
lines.append("[Enter] begin the day")
CampaignController.Phase.GAME_OVER:
lines.append(ENDINGS[campaign.outcome] + " · [R] retry the night")
CampaignController.Phase.FARMERS_RETURN:
@ -93,5 +115,7 @@ func _describe() -> String:
_:
if campaign.can_start_night_early():
lines.append("[N] start the night early")
lines.append("F6 next phase · F7 speed · F9 scarecrow to 0 HP · F10 strip farm")
if sim != null and sim.waves.debug_plan != null:
lines.append("Scenario: %s (F2 next)" % sim.waves.debug_plan.title)
lines.append("F1 hide · F2 scenario · F6 next phase · F7 speed · F9 scarecrow to 0 HP · F10 strip farm · T/G/H thief/crow/breaker")
return "\n".join(lines)

View file

@ -0,0 +1,80 @@
class_name ConfirmBox
extends CenterContainer
## A yes / no question over the menus (Main): the message, the confirming button, and Cancel
## (focused, so a stray Enter / A never throws progress away). Escape / B cancels.
var message: Label
var yes_button: Button
var no_button: Button
var is_open := false
var _on_yes: Callable
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 30)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 22)
margin.add_child(box)
message = Label.new()
message.custom_minimum_size = Vector2(560.0, 0.0)
message.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
message.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
message.add_theme_font_size_override("font_size", 24)
box.add_child(message)
var row := HBoxContainer.new()
row.alignment = BoxContainer.ALIGNMENT_CENTER
row.add_theme_constant_override("separation", 24)
box.add_child(row)
yes_button = Button.new()
yes_button.custom_minimum_size = Vector2(240.0, 54.0)
yes_button.pressed.connect(_yes)
row.add_child(yes_button)
no_button = Button.new()
no_button.text = "Cancel"
no_button.custom_minimum_size = Vector2(200.0, 54.0)
no_button.pressed.connect(close)
row.add_child(no_button)
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func ask(text: String, confirm_text: String, on_yes: Callable) -> void:
message.text = text
yes_button.text = confirm_text
_on_yes = on_yes
is_open = true
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
no_button.grab_focus.call_deferred()
func close() -> void:
if not is_open:
return
is_open = false
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.45)) # dims what's behind
func _yes() -> void:
var then := _on_yes
close()
if then.is_valid():
then.call()
func _unhandled_input(event: InputEvent) -> void:
if is_open and event.is_action_pressed("ui_cancel"):
close()
get_viewport().set_input_as_handled()

View file

@ -0,0 +1 @@
uid://rusd2ksjv11

171
game/scripts/coop_hud.gd Normal file
View file

@ -0,0 +1,171 @@
class_name CoopHud
extends Control
## The co-op part of the HUD (Main adds it to the farm's HUD layer):
## * the partner panel, above your own health: their name in their color (P1 gold, P2 blue),
## their health pips, what they're doing (down until morning, patching, gathering, fear
## ready), a speaker mark while their voice comes through, and the ping; plus your
## microphone (on / muted, [M])
## * an arrow at the screen edge toward the partner when they're off screen, with the distance
## * the lobby's status while hosting with nobody in yet ("Waiting for a friend to join ...")
## Both scarecrows also wear name tags (PlayerCharacter.set_tag).
const PANEL := Rect2(22.0, -318.0, 336.0, 104.0) # from the bottom left
const PIP := Vector2(14.0, 9.0)
const ARROW_MARGIN := 60.0
var sim: FarmSim
var session: CoopSession
var lobby: CoopLobby
var _name: Label
var _state: Label
var _mic: Label
var _status: Label
var _arrow_label: Label
var _arrow_at := Vector2.ZERO
var _arrow_dir := Vector2.ZERO
var _arrow_on := false
var _ping: float = -1.0
var _ping_wait: float = 0.0
var _pinging := false
func setup(p_sim: FarmSim, p_session: CoopSession, p_lobby: CoopLobby) -> void:
sim = p_sim
session = p_session
lobby = p_lobby
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_name = _label(22)
_state = _label(18)
_mic = _label(16)
_status = _label(20)
_status.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_status.add_theme_color_override("font_color", Avatar.COLORS[1])
_arrow_label = _label(17)
func _process(delta: float) -> void:
queue_redraw()
_ping_wait -= delta
if _ping_wait <= 0.0 and not _pinging and lobby != null and lobby.gdsync != null and lobby.other_id >= 0 and lobby.gdsync.is_active():
_ping_wait = 2.0
_measure_ping()
var active := session != null and session.is_active() and sim != null and sim.partner != null
var other: Avatar = null
if active:
other = sim.avatars[0] if session.is_client() else sim.partner
for l: Label in [_name, _state, _mic]:
l.visible = other != null
var waiting := lobby != null and lobby.stage == CoopLobby.Stage.HOSTING and not active
_status.visible = waiting and lobby.status != ""
_status.text = "Co-op: " + lobby.status if lobby != null else ""
_status.position = Vector2((size.x - 900.0) * 0.5, 64.0)
_status.size = Vector2(900.0, 30.0)
_arrow_on = false
_arrow_label.visible = false
if other == null:
return
var base := Vector2(PANEL.position.x, size.y + PANEL.position.y)
_name.text = other.label()
_name.add_theme_color_override("font_color", other.color())
_name.position = base + Vector2(14.0, 6.0)
var k := other.kit
var what := ""
if not k.alive:
what = "Down until morning"
elif k.patching:
what = "Patching up"
elif other.interactions.gathering != null:
what = "Gathering"
elif k.fear_left == 0.0:
what = "Fear ready"
if session.partner_speaking():
what = ("%s · talking" % what) if what != "" else "Talking"
if _ping >= 0.0:
what += " %d ms" % roundi(_ping * 1000.0 if _ping < 10.0 else _ping)
_state.text = what
_state.add_theme_color_override("font_color", Color(1.0, 0.5, 0.42) if not k.alive else Color(0.85, 0.88, 0.82))
_state.position = base + Vector2(14.0, 58.0)
_mic.visible = not session.voices.is_empty()
_mic.text = "Your mic: %s [M]" % ("on" if session.microphone else "muted")
_mic.position = base + Vector2(14.0, PANEL.size.y + 2.0)
# The arrow toward the partner when they're off screen.
var cam := get_viewport().get_camera_3d()
if cam == null:
return
var world := other.body.global_position + Vector3(0.0, 1.2, 0.0)
var on_screen := cam.unproject_position(world)
var view := Rect2(Vector2.ZERO, size).grow(-ARROW_MARGIN)
if not cam.is_position_behind(world) and view.has_point(on_screen):
return
var center := size * 0.5
var dir := (on_screen - center)
if cam.is_position_behind(world):
dir = -dir
if dir.length_squared() < 1.0:
return
dir = dir.normalized()
var t := INF
var half := view.size * 0.5
if absf(dir.x) > 1e-4:
t = minf(t, half.x / absf(dir.x))
if absf(dir.y) > 1e-4:
t = minf(t, half.y / absf(dir.y))
_arrow_at = center + dir * t
_arrow_dir = dir
_arrow_on = true
var meters := sim.local_avatar.position().distance_to(other.position())
_arrow_label.visible = true
_arrow_label.text = "%s %d m" % [other.label(), roundi(meters)]
_arrow_label.add_theme_color_override("font_color", other.color())
_arrow_label.position = _arrow_at - dir * 46.0 - Vector2(60.0, 10.0)
func _draw() -> void:
if session == null or not session.is_active() or sim == null or sim.partner == null:
return
var other := sim.avatars[0] if session.is_client() else sim.partner
var base := Vector2(PANEL.position.x, size.y + PANEL.position.y)
draw_rect(Rect2(base, PANEL.size), Color(0.0, 0.0, 0.0, 0.45))
draw_rect(Rect2(base, Vector2(5.0, PANEL.size.y)), other.color())
var hp := other.kit.hp()
var top := other.kit.max_hp()
for i in top:
var r := Rect2(base + Vector2(14.0 + i * (PIP.x + 4.0), 40.0), PIP)
draw_rect(r, other.color() if i < hp else Color(0.15, 0.15, 0.15, 0.8))
if session.partner_speaking():
var c := base + Vector2(PANEL.size.x - 34.0, 22.0)
draw_rect(Rect2(c + Vector2(-8.0, -5.0), Vector2(6.0, 10.0)), other.color())
draw_colored_polygon(PackedVector2Array([c + Vector2(-2.0, -5.0), c + Vector2(6.0, -11.0), c + Vector2(6.0, 11.0),
c + Vector2(-2.0, 5.0)]), other.color())
draw_arc(c + Vector2(6.0, 0.0), 8.0, -0.9, 0.9, 8, other.color(), 2.0)
draw_arc(c + Vector2(6.0, 0.0), 13.0, -0.9, 0.9, 8, other.color(), 2.0)
if _arrow_on:
var tip := _arrow_at + _arrow_dir * 18.0
var side := Vector2(-_arrow_dir.y, _arrow_dir.x) * 13.0
var back := _arrow_at - _arrow_dir * 14.0
draw_colored_polygon(PackedVector2Array([tip, back + side, back - side]), other.color())
draw_polyline(PackedVector2Array([tip, back + side, back - side, tip]), Color.BLACK, 2.0)
## GD-Sync's ping (it sends a message and waits for the answer).
func _measure_ping() -> void:
_pinging = true
var p: float = await lobby.gdsync.get_client_ping(lobby.other_id)
_ping = p
_pinging = false
func _label(font_size: int) -> Label:
var l := Label.new()
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
l.visible = false
add_child(l)
return l

View file

@ -0,0 +1 @@
uid://dn5wrd05u30o3

85
game/scripts/coop_link.gd Normal file
View file

@ -0,0 +1,85 @@
class_name CoopLink
extends RefCounted
## The wire between the two machines of a co-op game (CoopSession talks only to this). send()
## delivers one message (a kind and a Variant) to the other side, reliably (in order, never
## lost) or not (may be dropped; for the 20 Hz snapshots and the partner's input, which the next
## one replaces). received is emitted on the other side.
## GDSyncLink is the real one (GD-Sync, LAN or online). CoopLink.pair() makes two loopback links
## for tests: messages go through var_to_bytes / bytes_to_var like on the wire, and are delivered
## when the receiving side polls. Every link counts what it sends; unreliable messages over
## UNRELIABLE_LIMIT bytes are counted as too big (GD-Sync splits datagrams at 1200 bytes).
signal received(kind: String, data: Variant)
const UNRELIABLE_LIMIT := 1100
var sent_messages: int = 0
var sent_bytes: int = 0
## The largest unreliable message so far (bytes) and how many were over the limit.
var largest_unreliable: int = 0
var oversized: int = 0
## Set when the other side went away.
var closed := false
func send(kind: String, data: Variant, reliable: bool) -> void:
var size := var_to_bytes([kind, data]).size()
sent_messages += 1
sent_bytes += size
if not reliable:
largest_unreliable = maxi(largest_unreliable, size)
if size > UNRELIABLE_LIMIT:
oversized += 1
_deliver(kind, data, reliable)
## Delivers what has arrived (loopback links; GD-Sync delivers on its own).
func poll() -> void:
pass
func close() -> void:
closed = true
func _deliver(_kind: String, _data: Variant, _reliable: bool) -> void:
pass
## Two loopback links, each the other's far end.
static func pair() -> Array[CoopLink]:
var a := Loopback.new()
var b := Loopback.new()
a.other = b
b.other = a
return [a, b]
class Loopback extends CoopLink:
var other: Loopback
## Drops every n-th unreliable message (0 = none), to test that nothing depends on them.
var drop_every: int = 0
var _inbox: Array = []
var _count: int = 0
func _deliver(kind: String, data: Variant, reliable: bool) -> void:
if other == null or other.closed:
return
_count += 1
if not reliable and drop_every > 0 and _count % drop_every == 0:
return
other._inbox.append(var_to_bytes([kind, data])) # as on the wire
func poll() -> void:
var batch := _inbox
_inbox = []
for bytes: PackedByteArray in batch:
var m: Array = bytes_to_var(bytes)
received.emit(String(m[0]), m[1])
func close() -> void:
closed = true
if other != null:
other.closed = true
other.other = null # the pair refers to each other: break the cycle
other = null

View file

@ -0,0 +1 @@
uid://cguqgjquppxln

304
game/scripts/coop_lobby.gd Normal file
View file

@ -0,0 +1,304 @@
class_name CoopLobby
extends Node
## Finding each other over GD-Sync (the GDSync autoload), for co-op:
## LAN GD-Sync's local mode: peer to peer on the same network, no account or keys. Games
## announce themselves on the network; Join lists them.
## ONLINE GD-Sync's servers, across the internet: needs the project's GD-Sync API keys
## (Project > Tools > GD-Sync in the editor, saved to addons/GD-Sync/keys.cfg, or the
## GDSYNC_PUBLIC_KEY / GDSYNC_PRIVATE_KEY environment variables).
## The host opens a lobby named after its player ("Ana's farm") for two; the partner lists the
## open lobbies (or types one's name, online) and joins. On a LAN that doesn't pass GD-Sync's
## announcements (some firewalls; VPNs like Tailscale or ZeroTier) the partner can join by the
## host's address instead (join_address; the host's waiting status shows its addresses). Once both are in, partner_arrived (on the
## host) and joined (on the partner) give the other side's GD-Sync client id, and CoopSession
## takes over over a GDSyncLink. If the other side leaves, other_left. GD-Sync keeps running
## while the game is paused (the menus).
enum Mode { LAN, ONLINE }
enum Stage { IDLE, CONNECTING, HOSTING, SEARCHING, JOINING, IN_LOBBY }
signal status_changed(text: String)
## Join's list: [{"name", "players"}] of open lobbies with room.
signal lobbies_found(lobbies: Array)
signal partner_arrived(client_id: int)
signal joined(host_id: int)
signal other_left(client_id: int)
signal failed(text: String)
const SEARCH_EVERY := 2.0
const GAME_PORT := 42400
const GAME_TAG := "harvest-season"
var gdsync: Node
var mode: Mode = Mode.LAN
var stage: Stage = Stage.IDLE
var lobby_name := ""
var my_name := ""
var other_id: int = -1
var status := ""
var _after_connect := "" # "host" or "search"
var _join_target := ""
var _search_left: float = 0.0
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
gdsync = get_node_or_null("/root/GDSync")
if gdsync == null:
return
gdsync.process_mode = Node.PROCESS_MODE_ALWAYS # the lobby works behind the paused menus
gdsync.connected.connect(_on_connected)
gdsync.connection_failed.connect(_on_connection_failed)
gdsync.disconnected.connect(_on_disconnected)
gdsync.lobby_created.connect(_on_lobby_created)
gdsync.lobby_creation_failed.connect(_on_lobby_creation_failed)
gdsync.lobby_joined.connect(_on_lobby_joined)
gdsync.lobby_join_failed.connect(_on_lobby_join_failed)
gdsync.lobbies_received.connect(_on_lobbies_received)
gdsync.client_joined.connect(_on_client_joined)
gdsync.client_left.connect(_on_client_left)
func available() -> bool:
return gdsync != null
## Whether online play can be tried (the API keys are there).
static func has_online_keys() -> bool:
var ks: Variant = load("res://addons/GD-Sync/Scripts/KeyStore.gd")
return ks != null and bool(ks.has_keys())
func my_id() -> int:
return int(gdsync.get_client_id()) if gdsync != null else -1
## Opens a lobby for a partner to join.
func host(p_mode: Mode, p_name: String) -> void:
if not _begin(p_mode, p_name):
return
lobby_name = ("%s's farm" % my_name).left(32)
_after_connect = "host"
_start()
## Looks for open lobbies (LAN: on the network, every SEARCH_EVERY seconds; online: on the server).
func search(p_mode: Mode, p_name: String) -> void:
if not _begin(p_mode, p_name):
return
_after_connect = "search"
_start()
func join(lobby: String) -> void:
if gdsync == null or not gdsync.is_active():
return
_join_target = lobby
stage = Stage.JOINING
_say("Joining %s..." % lobby)
gdsync.lobby_join(lobby)
## LAN: joins the game at a host's address ("192.168.1.20", or with ":port" when it isn't the
## first game port). Starts GD-Sync's local mode first if needed.
func join_address(address: String, p_name: String = "") -> void:
if gdsync == null:
failed.emit("GD-Sync isn't installed")
return
var a := address.strip_edges()
if a == "":
return
if not gdsync.is_active() or mode != Mode.LAN:
if not _begin(Mode.LAN, p_name if p_name != "" else my_name):
return
_after_connect = "address"
_join_target = a
_start()
return
var ip := a
var port := GAME_PORT
if a.count(":") == 1:
ip = a.get_slice(":", 0)
port = int(a.get_slice(":", 1))
var local_server: Node = gdsync.get("_local_server")
if local_server == null:
failed.emit("This GD-Sync version can't join by address")
return
var key := "%s:%d" % [ip, port]
# GD-Sync joins a LAN game it has heard announced; this one is "announced" by hand (and
# never expires).
(local_server.get("found_lobbies") as Dictionary)[key] = {"Name": key, "IP": ip, "Port": port, "Public": false,
"Open": true, "PlayerCount": 1, "PlayerLimit": 2, "Tags": {}, "DetectionTime": Time.get_unix_time_from_system() + 1e9}
_after_connect = "join"
join(key)
## This machine's addresses on the local network (and VPNs), for joining by address.
static func host_addresses() -> PackedStringArray:
var out := PackedStringArray()
for ip in IP.get_local_addresses():
if ip.contains(":"):
continue # IPv6
var parts := ip.split(".")
var a := int(parts[0])
var b := int(parts[1])
if a == 10 or (a == 192 and b == 168) or (a == 172 and b >= 16 and b <= 31) or (a == 100 and b >= 64 and b <= 127):
out.append(ip)
return out
## Leaves the lobby and stops GD-Sync.
func leave() -> void:
if gdsync == null:
return
var was := stage
stage = Stage.IDLE # first: stopping emits disconnected, which isn't a failure now
other_id = -1
_after_connect = ""
if was == Stage.HOSTING or was == Stage.IN_LOBBY or was == Stage.JOINING:
gdsync.lobby_leave()
if gdsync.is_active():
gdsync.stop_multiplayer()
_say("")
func _process(delta: float) -> void:
if stage == Stage.SEARCHING and gdsync != null and gdsync.is_active():
_search_left -= delta
if _search_left <= 0.0:
_search_left = SEARCH_EVERY
gdsync.get_public_lobbies()
func _begin(p_mode: Mode, p_name: String) -> bool:
if gdsync == null:
failed.emit("GD-Sync isn't installed")
return false
if p_mode == Mode.ONLINE and not has_online_keys():
failed.emit("Online play needs the GD-Sync API keys: in the editor, Project > Tools > GD-Sync (see game/COOP.md). LAN works without them.")
return false
leave()
mode = p_mode
my_name = p_name.strip_edges() if p_name.strip_edges() != "" else "Player %d" % (randi() % 900 + 100)
return true
func _start() -> void:
stage = Stage.CONNECTING
_say("Connecting%s..." % (" on the local network" if mode == Mode.LAN else " to GD-Sync"))
if mode == Mode.LAN:
gdsync.start_local_multiplayer()
else:
gdsync.start_multiplayer()
func _on_connected() -> void:
gdsync.player_set_username(my_name)
match _after_connect:
"host":
_say("Opening the lobby...")
gdsync.lobby_create(lobby_name, "", true, 2, {"game": GAME_TAG})
"search":
stage = Stage.SEARCHING
_search_left = 0.0
_say("Looking for games%s..." % (" on the local network" if mode == Mode.LAN else ""))
"address":
join_address(_join_target)
func _on_connection_failed(error: int) -> void:
stage = Stage.IDLE
var why := "the connection failed"
match error:
0:
why = "the GD-Sync API keys were refused"
1:
why = "it timed out"
2:
why = "no network port was free"
failed.emit("Couldn't connect: %s." % why)
_say("")
func _on_disconnected() -> void:
if stage != Stage.IDLE:
var was := other_id
stage = Stage.IDLE
other_id = -1
if was >= 0:
other_left.emit(was)
failed.emit("Disconnected from GD-Sync.")
func _on_lobby_created(created: String) -> void:
gdsync.lobby_join(created)
func _on_lobby_creation_failed(_n: String, error: int) -> void:
stage = Stage.IDLE
var why := ["a lobby with that name exists", "the name is too short", "the name is too long", "", "", "",
"wait a few seconds and try again", "no network port was free"]
failed.emit("Couldn't open the lobby: %s." % (why[error] if error < why.size() and why[error] != "" else "error %d" % error))
func _on_lobby_joined(n: String) -> void:
if _after_connect == "host":
stage = Stage.HOSTING
if mode == Mode.LAN:
var at := host_addresses()
_say("Waiting for a friend to join \"%s\" (same network%s)" % [n,
(", or by address: " + ", ".join(at)) if not at.is_empty() else ""])
else:
_say("Waiting for a friend to join \"%s\" (online)" % n)
else:
stage = Stage.IN_LOBBY
_say("Joined \"%s\": waiting for the farm..." % n)
func _on_lobby_join_failed(n: String, error: int) -> void:
stage = Stage.SEARCHING
var why := ["it doesn't exist any more", "it's closed", "it's full", "the password is wrong", "your name is the same as the host's"]
failed.emit("Couldn't join %s: %s." % [n, why[error] if error < why.size() else "error %d" % error])
func _on_lobbies_received(lobbies: Array) -> void:
var out: Array = []
for l: Variant in lobbies:
if not l is Dictionary:
continue
var d := l as Dictionary
var tags: Variant = d.get("Tags", {})
if tags is Dictionary and (tags as Dictionary).has("game") and String(tags["game"]) != GAME_TAG:
continue
var players := int(d.get("PlayerCount", 0))
var limit := int(d.get("PlayerLimit", 2))
if limit > 0 and players >= limit:
continue
out.append({"name": String(d.get("Name", "")), "players": players})
lobbies_found.emit(out)
func _on_client_joined(id: int) -> void:
if id == my_id() or other_id >= 0:
return
if stage == Stage.HOSTING:
other_id = id
partner_arrived.emit(id)
elif stage == Stage.IN_LOBBY or stage == Stage.JOINING:
other_id = id
joined.emit(id)
func _on_client_left(id: int) -> void:
if id != other_id:
return
other_id = -1
other_left.emit(id)
if stage == Stage.HOSTING:
_say("Your friend left. Waiting for someone to join \"%s\"" % lobby_name)
func _say(text: String) -> void:
status = text
status_changed.emit(text)

View file

@ -0,0 +1 @@
uid://yhd32jflx2xj

234
game/scripts/coop_menu.gd Normal file
View file

@ -0,0 +1,234 @@
class_name CoopMenu
extends CenterContainer
## "Play with a friend" from the main menu (Main does the rest):
## * your name, and how to connect: on the same network (LAN, no account) or online (GD-Sync's
## servers; needs the project's API keys, see game/COOP.md)
## * Host: continue your saved vacation or start a new one; the farm opens to your friend
## * Join: the games found (LAN: announced on the network; online: open lobbies), or a lobby's
## name typed in (online)
## The status line says what's happening and why something failed.
signal host_requested(mode: CoopLobby.Mode, player_name: String, resume: bool)
signal search_requested(mode: CoopLobby.Mode, player_name: String)
signal join_requested(lobby: String)
signal join_address_requested(address: String)
signal back_requested
var is_open := false
var mode: CoopLobby.Mode = CoopLobby.Mode.LAN
var name_edit: LineEdit
var lan_button: Button
var online_button: Button
var host_button: Button
var join_button: Button
var continue_button: Button
var new_button: Button
var back_button: Button
var lobby_edit: LineEdit
var lobby_join_button: Button
var status: Label
var list: VBoxContainer
## "home", "host" (which vacation), "join" (the list)
var view := "home"
var _host_box: VBoxContainer
var _join_box: VBoxContainer
var _online_row: HBoxContainer
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 30)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 14)
box.custom_minimum_size = Vector2(760.0, 0.0)
margin.add_child(box)
var title := Label.new()
title.text = "Play with a friend"
title.add_theme_font_size_override("font_size", 44)
title.add_theme_color_override("font_color", UiTheme.GOLD)
box.add_child(title)
var name_row := HBoxContainer.new()
name_row.add_theme_constant_override("separation", 16)
box.add_child(name_row)
var nl := Label.new()
nl.text = "Your name"
nl.custom_minimum_size = Vector2(170.0, 0.0)
name_row.add_child(nl)
name_edit = LineEdit.new()
name_edit.max_length = 20
name_edit.custom_minimum_size = Vector2(420.0, 44.0)
name_edit.placeholder_text = "Shown over your scarecrow"
name_row.add_child(name_edit)
var mode_row := HBoxContainer.new()
mode_row.add_theme_constant_override("separation", 16)
box.add_child(mode_row)
var ml := Label.new()
ml.text = "Connect"
ml.custom_minimum_size = Vector2(170.0, 0.0)
mode_row.add_child(ml)
var group := ButtonGroup.new()
lan_button = _toggle(mode_row, "Same network (LAN)", group)
lan_button.button_pressed = true
lan_button.pressed.connect(func() -> void: _set_mode(CoopLobby.Mode.LAN))
online_button = _toggle(mode_row, "Online", group)
online_button.pressed.connect(func() -> void: _set_mode(CoopLobby.Mode.ONLINE))
var actions := HBoxContainer.new()
actions.add_theme_constant_override("separation", 16)
box.add_child(actions)
host_button = _button(actions, "Host a game")
host_button.pressed.connect(func() -> void: _show("host"))
join_button = _button(actions, "Join a game")
join_button.pressed.connect(func() -> void:
_show("join")
search_requested.emit(mode, player_name()))
_host_box = VBoxContainer.new()
_host_box.add_theme_constant_override("separation", 10)
box.add_child(_host_box)
var hl := Label.new()
hl.text = "Which vacation? Your friend joins your farm."
_host_box.add_child(hl)
var host_row := HBoxContainer.new()
host_row.add_theme_constant_override("separation", 16)
_host_box.add_child(host_row)
continue_button = _button(host_row, "Continue")
continue_button.pressed.connect(func() -> void: host_requested.emit(mode, player_name(), true))
new_button = _button(host_row, "New vacation")
new_button.pressed.connect(func() -> void: host_requested.emit(mode, player_name(), false))
_join_box = VBoxContainer.new()
_join_box.add_theme_constant_override("separation", 8)
box.add_child(_join_box)
var jl := Label.new()
jl.text = "Games found:"
_join_box.add_child(jl)
list = VBoxContainer.new()
list.add_theme_constant_override("separation", 6)
_join_box.add_child(list)
_online_row = HBoxContainer.new()
_online_row.add_theme_constant_override("separation", 12)
_join_box.add_child(_online_row)
lobby_edit = LineEdit.new()
lobby_edit.custom_minimum_size = Vector2(440.0, 44.0)
_online_row.add_child(lobby_edit)
lobby_join_button = _button(_online_row, "Join")
lobby_join_button.pressed.connect(func() -> void:
var t := lobby_edit.text.strip_edges()
if t == "":
return
if mode == CoopLobby.Mode.LAN:
join_address_requested.emit(t)
else:
join_requested.emit(t))
status = Label.new()
status.custom_minimum_size = Vector2(740.0, 0.0)
status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
status.add_theme_font_size_override("font_size", 19)
status.add_theme_color_override("font_color", Color(0.78, 0.8, 0.72))
box.add_child(status)
back_button = _button(box, "Back")
back_button.pressed.connect(func() -> void: back_requested.emit())
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func open(saved: SaveGame.Loaded, nights: int, p_name: String) -> void:
is_open = true
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
if name_edit.text == "":
name_edit.text = p_name
var ok := saved != null and saved.status == SaveGame.Status.OK
continue_button.disabled = not ok
continue_button.text = "Continue (morning of day %d of %d)" % [saved.state.night, nights] if ok else "Continue"
status.text = ""
_show("home")
host_button.grab_focus.call_deferred()
func close() -> void:
is_open = false
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func player_name() -> String:
return name_edit.text.strip_edges()
func set_status(text: String) -> void:
status.text = text
func show_lobbies(lobbies: Array) -> void:
for c in list.get_children():
c.queue_free()
if lobbies.is_empty():
var l := Label.new()
l.text = "None yet. (Ask your friend to host; on a LAN you need to be on the same network.)"
l.add_theme_font_size_override("font_size", 18)
l.add_theme_color_override("font_color", Color(0.7, 0.72, 0.66))
list.add_child(l)
return
for lob: Dictionary in lobbies:
var b := _button(list, "%s (%d/2)" % [lob["name"], int(lob["players"])])
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
var n := String(lob["name"])
b.pressed.connect(func() -> void: join_requested.emit(n))
func _show(v: String) -> void:
view = v
_host_box.visible = v == "host"
_join_box.visible = v == "join"
_online_row.visible = v == "join"
_placeholder()
if v == "host":
(continue_button if not continue_button.disabled else new_button).grab_focus.call_deferred()
if v == "join":
show_lobbies([])
func _set_mode(m: CoopLobby.Mode) -> void:
mode = m
if m == CoopLobby.Mode.ONLINE and not CoopLobby.has_online_keys():
status.text = "Online play needs the GD-Sync API keys (free at gd-sync.com): in the editor, Project > Tools > GD-Sync. Until then, play on the same network (LAN)."
else:
status.text = ""
_placeholder()
if view == "join":
search_requested.emit(mode, player_name())
func _placeholder() -> void:
lobby_edit.placeholder_text = "Or the host's address, e.g. 192.168.1.20" if mode == CoopLobby.Mode.LAN \
else "Or type the game's name, e.g. Ana's farm"
func _button(parent: Control, text: String) -> Button:
var b := Button.new()
b.text = text
b.custom_minimum_size = Vector2(240.0, 50.0)
parent.add_child(b)
return b
func _toggle(parent: Control, text: String, group: ButtonGroup) -> Button:
var b := _button(parent, text)
b.toggle_mode = true
b.button_group = group
return b
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.4))
func _unhandled_input(event: InputEvent) -> void:
if is_open and event.is_action_pressed("ui_cancel"):
back_requested.emit()
get_viewport().set_input_as_handled()

View file

@ -0,0 +1 @@
uid://bwf7mnsom2ekv

View file

@ -0,0 +1,756 @@
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

View file

@ -0,0 +1 @@
uid://yyjmd3opd2bd

View file

@ -0,0 +1,31 @@
class_name CoopVoice
extends VoiceChat
## Voice chat in co-op: GD-Sync's VoiceChat, one per player at the same path on both machines
## (CoopSession/Voice1 for player 1, Voice2 for player 2). Each is owned by its player's GD-Sync
## client: the owner's microphone is recorded (above GD-Sync's volume threshold) and sent, and
## the other machine plays it on the Voice bus. This adds when the voice was last heard, for the
## "speaking" mark on the partner HUD and the name tag.
## Seconds of the game clock when audio last arrived (-1000 = never).
var last_heard: float = -1000.0
static func make(slot: int) -> CoopVoice:
var v := CoopVoice.new()
v.name = "Voice%d" % (slot + 1)
v.input_volume_threshold = 0.025 # above room noise (GD-Sync's default is 0.01)
var out := AudioStreamPlayer.new()
out.name = "Out"
out.bus = &"Voice"
v.add_child(out)
v.set_output_player(out)
return v
func speaking() -> bool:
return Time.get_ticks_msec() / 1000.0 - last_heard < 0.35
func _process_audio(audio: PackedFloat32Array, mixrate: float) -> void:
last_heard = Time.get_ticks_msec() / 1000.0
super(audio, mixrate)

View file

@ -0,0 +1 @@
uid://bbj7krc3xfv1h

127
game/scripts/day_night.gd Normal file
View file

@ -0,0 +1,127 @@
class_name DayNight
extends Node
## Lighting through the vacation's phases. Four keyed looks (day, sunset, night, sunrise) set
## the sun's angle, color, and strength, the ambient and sky light, and a whole-picture
## brightness and saturation (Environment adjustments, which leave the HUD alone):
## morning review -> mostly day; day -> day; dusk -> day turning to sunset over the dusk;
## night -> sunset to night in the first NIGHTFALL seconds (the sun becomes the moon);
## dawn -> night to sunrise over the dawn grace (brightening early: by the square root).
## The scarecrow carries a lantern that lights up as it gets dark, and enemies glow faintly at
## night (thief.gdshader night_glow) so they stay readable. The current look eases toward the
## target, so phase changes never pop.
const NIGHTFALL := 8.0
const EASE := 2.5
const DAY := {"elev": 55.0, "yaw": -35.0, "color": Color(1.0, 0.96, 0.88), "energy": 1.1, "ambient": 1.0,
"sky": 1.0, "bright": 1.0, "sat": 1.0, "lantern": 0.0, "glow": 0.0}
const SUNSET := {"elev": 9.0, "yaw": -70.0, "color": Color(1.0, 0.55, 0.3), "energy": 0.8, "ambient": 0.6,
"sky": 0.55, "bright": 0.92, "sat": 1.05, "lantern": 0.6, "glow": 0.3}
const NIGHT := {"elev": 48.0, "yaw": 25.0, "color": Color(0.55, 0.66, 1.0), "energy": 0.38, "ambient": 0.35,
"sky": 0.12, "bright": 0.78, "sat": 0.62, "lantern": 1.9, "glow": 1.0}
const SUNRISE := {"elev": 10.0, "yaw": 150.0, "color": Color(1.0, 0.72, 0.58), "energy": 0.75, "ambient": 0.6,
"sky": 0.6, "bright": 0.94, "sat": 1.0, "lantern": 0.5, "glow": 0.2}
var campaign: CampaignController
var sun: DirectionalLight3D
var env: Environment
var enemy_material: ShaderMaterial
## Set by FarmSim: the ground enemies' characters glow too.
var characters: EnemyCharacters
var lantern: OmniLight3D
## Co-op: player 2's lantern (add_lantern), lit the same.
var lanterns: Array[OmniLight3D] = []
var current := DAY.duplicate()
func setup(p_campaign: CampaignController, p_sun: DirectionalLight3D, p_env: Environment, player: Node3D,
p_enemy_material: ShaderMaterial) -> void:
campaign = p_campaign
sun = p_sun
env = p_env
enemy_material = p_enemy_material
env.adjustment_enabled = true
lantern = add_lantern(player)
snap()
## A lantern carried by a scarecrow (the first is player 1's).
func add_lantern(body: Node3D) -> OmniLight3D:
var l := OmniLight3D.new()
l.name = "Lantern"
l.light_color = Color(1.0, 0.8, 0.5)
l.omni_range = 9.0
l.omni_attenuation = 1.4
l.shadow_enabled = false
l.position = Vector3(0.0, 2.6, 0.0)
body.add_child(l)
lanterns.append(l)
return l
## 0 in daylight .. 1 at full night.
func darkness() -> float:
return clampf(float(current["glow"]), 0.0, 1.0)
## Jumps straight to the current phase's look (new vacation, retry, tests).
func snap() -> void:
current = target()
_apply()
func target() -> Dictionary:
var s := campaign.state
var cfg := campaign.config
var length := campaign.phase_length(s.phase)
var elapsed := length - s.phase_time_left if is_finite(length) else 0.0
var p := clampf(elapsed / length, 0.0, 1.0) if is_finite(length) and length > 0.0 else 0.0
match s.phase:
CampaignController.Phase.MORNING:
return _mix(SUNRISE, DAY, 0.7)
CampaignController.Phase.DUSK:
return _mix(DAY, SUNSET, p)
CampaignController.Phase.NIGHT:
return _mix(SUNSET, NIGHT, clampf(elapsed / NIGHTFALL, 0.0, 1.0))
CampaignController.Phase.DAWN:
return _mix(NIGHT, SUNRISE, sqrt(p))
CampaignController.Phase.GAME_OVER:
return current
return DAY
func _process(delta: float) -> void:
if campaign == null:
return
current = _mix(current, target(), 1.0 - exp(-EASE * delta))
_apply()
func _apply() -> void:
sun.rotation = Vector3(deg_to_rad(-float(current["elev"])), deg_to_rad(float(current["yaw"])), 0.0)
sun.light_color = current["color"]
sun.light_energy = current["energy"]
env.ambient_light_energy = current["ambient"]
env.background_energy_multiplier = current["sky"]
env.adjustment_brightness = current["bright"]
env.adjustment_saturation = current["sat"]
for l in lanterns:
if is_instance_valid(l):
l.light_energy = current["lantern"]
if enemy_material != null:
enemy_material.set_shader_parameter("night_glow", current["glow"])
if characters != null:
characters.set_night_glow(current["glow"])
static func _mix(a: Dictionary, b: Dictionary, t: float) -> Dictionary:
var out := {}
for k in a:
var va: Variant = a[k]
if va is Color:
out[k] = (va as Color).lerp(b[k], t)
elif k == "yaw":
out[k] = rad_to_deg(lerp_angle(deg_to_rad(va), deg_to_rad(b[k]), t))
else:
out[k] = lerpf(va, b[k], t)
return out

View file

@ -0,0 +1 @@
uid://c7fee6n0qdqwn

251
game/scripts/end_panel.gd Normal file
View file

@ -0,0 +1,251 @@
class_name EndPanel
extends CenterContainer
## The two end screens. Works with mouse, keyboard (arrows + Enter), and gamepad (d-pad + A)
## through focus.
## * Failure, a moment after a Game Over (so the fall can play): the cause (the scarecrow
## destroyed, or the farm stripped bare), the night reached and its plan, what's left and
## what the night cost so far, the vacation's totals, and Retry the night (D9, focused: back
## to that morning) and Main menu (New vacation when there's no menu, e.g. the farm scene on
## its own).
## * The final assessment, once the farmers' return (FarmersReturn) has played or been
## skipped: the rating and score (Assessment), the share kept per category with a bar, and
## the vacation's totals, with Main menu (or New vacation).
signal menu_requested
const DELAY := 1.4
const GOLD := Color(0.95, 0.82, 0.45)
const GREY := Color(0.75, 0.77, 0.72)
var campaign: CampaignController
## Set by Main: the Main menu button shows instead of New vacation.
var has_menu := false
## Set by FarmSim: the final assessment waits for the farmers' return to finish.
var ending: FarmersReturn
var waves: WaveDirector
## Set when the screen is up: "failure" or "assessment".
var mode := ""
var _title: Label
var _rating: Label
var _detail: Label
var _bars: GridContainer
var _bar_rows := {} # category -> [ProgressBar, Label]
var _stats: Label
var _retry: Button
var _menu: Button
var _new: Button
var _wait: float = -1.0
var _pending_mode := ""
func setup(p_campaign: CampaignController) -> void:
campaign = p_campaign
campaign.campaign_ended.connect(_on_ended)
campaign.phase_changed.connect(func(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
if phase == CampaignController.Phase.MORNING:
hide_panel())
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", ReviewPanel.backing())
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 34)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 16)
margin.add_child(box)
_title = _label(box, 46)
_rating = _label(box, 30, GOLD)
_detail = _label(box, 22)
_bars = GridContainer.new()
_bars.columns = 3
_bars.add_theme_constant_override("h_separation", 18)
_bars.add_theme_constant_override("v_separation", 8)
_bars.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
box.add_child(_bars)
for cat in ["crops", "animals", "supplies"]:
var name_label := _label(_bars, 22)
name_label.text = cat.capitalize()
name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
var bar := ProgressBar.new()
bar.custom_minimum_size = Vector2(320.0, 26.0)
bar.show_percentage = false
bar.max_value = 1.0
var fill := StyleBoxFlat.new()
fill.bg_color = Color(0.55, 0.78, 0.4)
fill.set_corner_radius_all(4)
var back := StyleBoxFlat.new()
back.bg_color = Color(0.22, 0.24, 0.2)
back.set_corner_radius_all(4)
bar.add_theme_stylebox_override("fill", fill)
bar.add_theme_stylebox_override("background", back)
_bars.add_child(bar)
var text := _label(_bars, 20, GREY)
text.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
_bar_rows[cat] = [bar, text, name_label]
_stats = _label(box, 20, GREY)
var buttons := HBoxContainer.new()
buttons.alignment = BoxContainer.ALIGNMENT_CENTER
buttons.add_theme_constant_override("separation", 24)
box.add_child(buttons)
_retry = _button(buttons, "Retry the night")
_retry.pressed.connect(func() -> void: campaign.retry_night())
_menu = _button(buttons, "Main menu")
_menu.pressed.connect(func() -> void: menu_requested.emit())
_new = _button(buttons, "New vacation")
_new.pressed.connect(func() -> void: campaign.new_campaign())
hide_panel()
func hide_panel() -> void:
visible = false
mode = ""
_wait = -1.0
_pending_mode = ""
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _on_ended(outcome: CampaignController.Outcome) -> void:
if outcome == CampaignController.Outcome.VACATION_COMPLETE:
if ending != null:
if not ending.finished.is_connected(_on_ending_finished):
ending.finished.connect(_on_ending_finished)
return
_pending_mode = "assessment"
else:
_pending_mode = "failure"
_wait = DELAY
func _on_ending_finished() -> void:
_pending_mode = "assessment"
_wait = 0.01
func _process(delta: float) -> void:
if _wait < 0.0:
return
_wait -= delta
if _wait <= 0.0:
_wait = -1.0
if _pending_mode == "assessment":
show_assessment()
else:
show_failure()
func show_failure() -> void:
var s := campaign.state
var cfg := campaign.config
mode = "failure"
var plan := waves.plan_for(s.night) if waves != null else null
var night := "Night %d of %d%s" % [s.night, cfg.campaign_nights, (": " + plan.title) if plan != null and plan.title != "" else ""]
if campaign.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW:
_title.text = "The scarecrow has fallen"
_rating.text = "%s. Its straw gave out." % night
else:
_title.text = "The farm was stripped bare"
_rating.text = "%s. Every crop, animal, and supply is gone." % night
var e := s.night_events
var lines: Array[String] = []
lines.append("You kept the farm for %d %s." % [s.nights_survived, "night" if s.nights_survived == 1 else "nights"])
lines.append("Left: %d of %d crops, %d of %d animals, %d supplies." % [s.crops, s.crops_total, s.animals, s.animals_total, s.supplies])
lines.append("Tonight: %s defeated; %d crops, %d animals, and %d supplies snatched." % [Assessment.enemies_line(e),
int(e.get("crops_stolen", 0)), int(e.get("animals_stolen", 0)), int(e.get("supplies_stolen", 0))])
_detail.text = "\n".join(lines)
_bars.visible = false
_stats.text = _totals_text(s.totals(), false)
_stats.visible = not s.night_log.is_empty()
_retry.visible = true
_retry.text = "Retry the night (from the morning of day %d)" % s.night
_show_buttons()
_open(_retry)
func show_assessment() -> void:
var s := campaign.state
var cfg := campaign.config
mode = "assessment"
var a := Assessment.of(s, cfg)
_title.text = "The farmers are home!"
_rating.text = "%s · %d points" % [a["tier"], a["score"]]
_detail.text = "%s\nYou kept the farm for all %d nights." % [a["text"], s.nights_survived]
_bars.visible = true
var parts: Dictionary = a["parts"]
for cat: String in _bar_rows:
var row: Array = _bar_rows[cat]
var shown := parts.has(cat)
for c: Control in row:
c.visible = shown
if not shown:
continue
(row[0] as ProgressBar).value = float(parts[cat])
var pct := roundi(100.0 * float(parts[cat]))
match cat:
"crops":
(row[1] as Label).text = "%d%% (%d of %d)" % [pct, s.crops, s.crops_total]
"animals":
(row[1] as Label).text = "%d%% (%d of %d)" % [pct, s.animals, s.animals_total]
_:
(row[1] as Label).text = "%d%% kept from thieves (%d of %d carried off)" % [pct, a["supplies_lost"], a["supplies_handled"]]
_stats.text = _totals_text(a["totals"], true)
_stats.visible = true
_retry.visible = false
_show_buttons()
_open(_menu if has_menu else _new)
## The vacation's totals, a few lines.
func _totals_text(t: Dictionary, finished: bool) -> String:
var s := campaign.state
var lines: Array[String] = []
if not finished:
lines.append("Over the vacation so far:")
lines.append("Enemies defeated: %s. Got away with loot: %d." % [Assessment.enemies_line(t), int(t["escaped"])])
lines.append("Recovered: %s, %s, %d supplies. Carried off: %s, %s, %d supplies." % [
_count(t["crops_recovered"], "crop"), _count(t["animals_recovered"], "animal"), int(t["supplies_recovered"]),
_count(t["crops_lost"], "crop"), _count(t["animals_lost"], "animal"), int(t["supplies_lost"])])
lines.append("Built %d, repaired %d, broken %d. Upgrades: %d of %d. Patched up %s, %d damage taken." % [
int(t["structures_built"]), int(t["repairs"]), int(t["structures_destroyed"]), s.upgrades.size(),
Upgrades.ORDER.size(), _count(t["patches"], "time"), int(t["scarecrow_damage"])])
lines.append("Gathered %s. Spent %s." % [Assessment.materials_line(t, "gathered_"), Assessment.materials_line(t, "spent_")])
return "\n".join(lines)
## "1 crop", "3 crops".
static func _count(n: Variant, word: String) -> String:
return "%d %s%s" % [int(n), word, "" if int(n) == 1 else "s"]
func _show_buttons() -> void:
_menu.visible = has_menu
_new.visible = not has_menu
func _open(focus: Button) -> void:
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
focus.grab_focus()
func _label(parent: Node, font_size: int, color: Color = Color(0.92, 0.92, 0.88)) -> Label:
var l := Label.new()
l.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_color", color)
parent.add_child(l)
return l
func _button(parent: Control, text: String) -> Button:
var b := Button.new()
b.text = text
b.custom_minimum_size = Vector2(230.0, 56.0)
b.add_theme_font_size_override("font_size", 24)
parent.add_child(b)
return b

View file

@ -0,0 +1 @@
uid://b6pkgit825mrl

View file

@ -0,0 +1,259 @@
class_name EnemyCharacters
extends Node3D
## The KayKit characters that draw ground enemies (EnemySystem keeps the simulation; flyers stay
## in its MultiMesh). A fixed pool per type is created at load and never grows: a ground enemy
## only spawns while its type has a free character.
## thief Mannequin_Medium, tinted dark, Rig_Medium clips (player_animations.res)
## breaker Mannequin_Large, rust red, scaled down, a club in its right hand, Rig_Large clips
## (breaker_animations.res)
## Each frame a character takes its enemy's interpolated position and heading and a clip for what
## it's doing (walking or running by speed, taking loot, breaking, fighting), flashes white on a
## hit, and glows faintly at night. A killed enemy's character plays its death clip where it fell
## for CORPSE_TIME; a corpse is only for show, so a new enemy can take it over at once when no
## other character is free.
const POOL := {EnemySystem.TYPE_THIEF: 48, EnemySystem.TYPE_BREAKER: 20}
const CORPSE_TIME := 1.6
const HIT_TIME := 0.35
const KIT := "res://assets/kaykit_characters/characters/"
const SCENES := {EnemySystem.TYPE_THIEF: KIT + "Mannequin_Medium.glb", EnemySystem.TYPE_BREAKER: KIT + "Mannequin_Large.glb"}
const LIBRARIES := {
EnemySystem.TYPE_THIEF: "res://game/resources/player_animations.res",
EnemySystem.TYPE_BREAKER: "res://game/resources/breaker_animations.res",
}
const SCALES := {EnemySystem.TYPE_THIEF: 0.86, EnemySystem.TYPE_BREAKER: 0.62}
const TINTS := {EnemySystem.TYPE_THIEF: Color(0.3, 0.27, 0.36), EnemySystem.TYPE_BREAKER: Color(0.72, 0.32, 0.2)}
## Clips by what the character is doing: idle, walk, run, steal (crops and animals), steal
## (supplies), break, fight, hit, death.
const CLIPS := {
EnemySystem.TYPE_THIEF: {"idle": &"Idle_A", "walk": &"Walking_A", "run": &"Running_A", "steal": &"PickUp",
"steal_supply": &"Lockpicking", "break": &"Melee_Unarmed_Attack_Punch_A", "fight": &"Melee_Unarmed_Attack_Punch_A",
"hit": &"Hit_A", "death": &"Death_A"},
EnemySystem.TYPE_BREAKER: {"idle": &"Melee_2H_Idle", "walk": &"Walking_A", "run": &"Running_A", "steal": &"Melee_2H_Idle",
"steal_supply": &"Melee_2H_Idle", "break": &"Melee_2H_Slam", "fight": &"Melee_2H_Attack",
"hit": &"Hit_A", "death": &"Death_A"},
}
var enemies: EnemySystem
var config: GameConfig
## Per character (index into the arrays below): its type, the enemy id it draws (-1 when free),
## and timers.
var type := PackedByteArray()
var enemy_id := PackedInt32Array()
var corpse := PackedFloat32Array()
var hit_left := PackedFloat32Array()
var _roots: Array[Node3D] = []
var _anims: Array[AnimationPlayer] = []
var _overlays: Array[ShaderMaterial] = []
var _clip: Array[StringName] = []
var _by_id := {} # enemy id -> character index
var _night_glow: float = 0.0
func setup(p_enemies: EnemySystem, p_config: GameConfig) -> void:
enemies = p_enemies
config = p_config
var shader := load("res://game/resources/enemy_overlay.gdshader") as Shader
for t: int in POOL:
var scene := load(SCENES[t]) as PackedScene
var library := load(LIBRARIES[t]) as AnimationLibrary
for k in POOL[t]:
var root := Node3D.new()
root.name = "%s_%d" % [EnemySystem.TYPE_NAMES[t], k]
root.visible = false
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(root)
var model := scene.instantiate() as Node3D
model.scale = Vector3.ONE * float(SCALES[t])
root.add_child(model)
var overlay := ShaderMaterial.new()
overlay.shader = shader
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = TINTS[t]
m.material_override = tinted
m.material_overlay = overlay
if t == EnemySystem.TYPE_BREAKER:
_add_club(model)
var anim := AnimationPlayer.new()
root.add_child(anim)
anim.root_node = anim.get_path_to(model)
anim.add_animation_library(&"", library)
_roots.append(root)
_anims.append(anim)
_overlays.append(overlay)
_clip.append(&"")
type.append(t)
enemy_id.append(-1)
corpse.append(0.0)
hit_left.append(0.0)
## Characters of the type not drawing a live enemy (corpses included: they can be taken over).
func free_count(t: int) -> int:
var n := 0
for c in type.size():
if type[c] == t and enemy_id[c] < 0:
n += 1
return n
func corpses() -> int:
var n := 0
for c in type.size():
if enemy_id[c] < 0 and corpse[c] > 0.0:
n += 1
return n
## Takes a character of the type for enemy id: a free one, else the corpse closest to fading.
## Returns false if every one is drawing a live enemy.
func acquire(t: int, id: int) -> bool:
var pick := -1
for c in type.size():
if type[c] != t or enemy_id[c] >= 0:
continue
if corpse[c] <= 0.0:
pick = c
break
if pick < 0 or corpse[c] < corpse[pick]:
pick = c
if pick < 0:
return false
enemy_id[pick] = id
corpse[pick] = 0.0
_by_id[id] = pick
hit_left[pick] = 0.0
_clip[pick] = &""
_roots[pick].visible = true
_overlays[pick].set_shader_parameter("flash", 0.0)
return true
## The enemy is gone: a killed one's character plays its death clip where it fell for a moment.
func release(id: int, killed: bool) -> void:
if not _by_id.has(id):
return
var c: int = _by_id[id]
_by_id.erase(id)
enemy_id[c] = -1
if killed:
corpse[c] = CORPSE_TIME
_play(c, CLIPS[type[c]]["death"], 0.1)
else:
_roots[c].visible = false
func hit(id: int) -> void:
if _by_id.has(id):
hit_left[_by_id[id]] = HIT_TIME
## Every character back to the pool, hidden (new morning, retry).
func clear() -> void:
_by_id.clear()
for c in type.size():
enemy_id[c] = -1
corpse[c] = 0.0
_roots[c].visible = false
## How many characters are drawing an enemy right now (tests).
func in_use() -> int:
return _by_id.size()
func set_night_glow(glow: float) -> void:
_night_glow = glow
func _process(delta: float) -> void:
if enemies == null:
return
for c in type.size():
var root := _roots[c]
if corpse[c] > 0.0:
corpse[c] = maxf(corpse[c] - delta, 0.0)
if corpse[c] == 0.0:
root.visible = false
continue
if enemy_id[c] < 0:
continue
var d: int = enemies.id_dense[enemy_id[c]]
if d < 0:
continue
var p := enemies.visual_position(d)
root.position = Vector3(p.x, 0.0, p.y)
root.rotation.y = lerp_angle(root.rotation.y, atan2(enemies.head_x[d], enemies.head_z[d]), 1.0 - exp(-14.0 * delta))
hit_left[c] = maxf(hit_left[c] - delta, 0.0)
_overlays[c].set_shader_parameter("flash", enemies.hurt[d])
_overlays[c].set_shader_parameter("night_glow", _night_glow)
_animate(c, d)
func _animate(c: int, d: int) -> void:
var clips: Dictionary = CLIPS[type[c]]
var speed := Vector2(enemies.vel_x[d], enemies.vel_z[d]).length()
var clip: StringName = clips["idle"]
var scale := 1.0
match enemies.state[d]:
ThiefBehavior.State.STEAL:
var tg := enemies.target[d]
var supply := tg > 0 and enemies.behavior != null and enemies.behavior.loot.category[tg] == LootSystem.Category.SUPPLY
clip = clips["steal_supply"] if supply else clips["steal"]
ThiefBehavior.State.BREAK:
clip = clips["break"]
ThiefBehavior.State.FIGHT:
clip = clips["fight"] if speed < 0.3 else clips["walk"]
_:
if speed > 2.2:
clip = clips["run"]
scale = clampf(speed / 4.5, 0.6, 1.3)
elif speed > 0.25:
clip = clips["walk"]
scale = clampf(speed / 1.6, 0.6, 1.4)
if hit_left[c] > 0.0:
clip = clips["hit"]
_anims[c].speed_scale = scale
if clip != _clip[c] or not _anims[c].is_playing():
_play(c, clip, 0.15)
func _play(c: int, clip: StringName, blend: float) -> void:
_clip[c] = clip
if _anims[c].has_animation(clip):
_anims[c].play(clip, blend)
## A club built from primitives in the large mannequin's right hand.
func _add_club(model: Node3D) -> void:
var skel := model.find_children("*", "Skeleton3D", true, false)
if skel.is_empty():
return
var attach := BoneAttachment3D.new()
attach.bone_name = "handslot.r"
(skel[0] as Skeleton3D).add_child(attach)
var wood := StandardMaterial3D.new()
wood.albedo_color = Color(0.42, 0.27, 0.15)
var handle := MeshInstance3D.new()
var cyl := CylinderMesh.new()
cyl.top_radius = 0.07
cyl.bottom_radius = 0.06
cyl.height = 1.1
cyl.material = wood
handle.mesh = cyl
handle.position = Vector3(0.0, 0.45, 0.0)
attach.add_child(handle)
var head := MeshInstance3D.new()
var knob := CylinderMesh.new()
knob.top_radius = 0.2
knob.bottom_radius = 0.16
knob.height = 0.45
knob.material = wood
head.mesh = knob
head.position = Vector3(0.0, 1.05, 0.0)
attach.add_child(head)

View file

@ -0,0 +1 @@
uid://bq245wu5ed25i

View file

@ -0,0 +1,620 @@
class_name EnemySystem
extends Node3D
## Pooled enemy simulation for the farm, forked from the prototype's HordeSystem: dense slots
## with stable ids and generation counters (handles that go stale when a slot is reused),
## swap-removal, removals deferred to the end of the tick, and one shared MultiMesh batch
## (HordeRenderer) for the flyers. Adds per-slot type, behavior state, target and carried loot,
## and a state timer. Each type's stats come from GameConfig.enemy_types (cached per type here).
## Ground enemies collide with the farm through the FarmNavigation grid: an enemy's center stays
## in walkable cells (free of static obstacles and of player-built structures, both already
## inflated by its radius), so it keeps clear of every shape the scarecrow collides with and
## can't pass a fence or gate without breaking it; slowing traps (StructureSystem.try_trap) slow
## it down; it is drawn by a pooled KayKit character (EnemyCharacters). Flyers ignore all of
## that, keep apart only from each other, and fly at a visual altitude (alt) in the MultiMesh;
## their hit proxy stays at combat height. What each enemy wants is decided by the behavior
## policy (ThiefBehavior); motion, damage, removal, and rendering live here.
enum Removal { KILLED, ESCAPED, LEFT }
enum Aggression { NONE, CONTACT, FIGHT }
const ID_BITS := 16
const ID_MASK := (1 << ID_BITS) - 1
const TYPE_THIEF := 0
const TYPE_CROW := 1
const TYPE_BREAKER := 2
## GameConfig.enemy_types keys, by type id.
const TYPE_NAMES: Array[String] = ["thief", "crow", "breaker"]
## Display names, singular and plural.
const NAMES: Array[String] = ["thief", "crow", "fence breaker"]
const PLURALS: Array[String] = ["thieves", "crows", "fence breakers"]
const NB_DX: Array[int] = [0, -1, 0, 1, -1, 1, -1, 0, 1]
const NB_DZ: Array[int] = [0, -1, -1, -1, 0, 0, 1, 1, 1]
## Emitted for every removal at the end of the tick, while the handle is still valid, with the
## loot item the enemy carried and the one it targeted (-1 for none).
signal enemy_removed(handle: int, reason: Removal, x: float, z: float, carry: int, target: int)
var config: GameConfig
var nav: FarmNavigation
var behavior: ThiefBehavior
## Set by FarmSim: slowing traps, and the characters that draw ground enemies.
var structures: StructureSystem
var characters: EnemyCharacters
var grid := SpatialGrid.new()
var renderer: HordeRenderer
# Per type (index = type id), from GameConfig.enemy_types.
var t_speed := PackedFloat32Array()
var t_accel := PackedFloat32Array()
var t_hp := PackedInt32Array()
var t_flying := PackedByteArray()
## Loot categories it takes (bit per LootSystem.Category); t_breaks for "structures".
var t_targets := PackedInt32Array()
var t_breaks := PackedByteArray()
var t_steal := PackedFloat32Array()
var t_carry := PackedFloat32Array()
var t_structure_damage := PackedInt32Array()
var t_damage := PackedInt32Array()
var t_hit_interval := PackedFloat32Array()
var t_aggression := PackedByteArray()
var t_aggro_range := PackedFloat32Array()
var t_hit_radius := PackedFloat32Array()
var capacity: int = 0
var active_count: int = 0
# Dense per-slot state (index = slot in [0, active_count)).
var pos_x := PackedFloat32Array()
var pos_z := PackedFloat32Array()
var prev_x := PackedFloat32Array()
var prev_z := PackedFloat32Array()
var vel_x := PackedFloat32Array()
var vel_z := PackedFloat32Array()
## Desired unit direction and pace (share of full speed) written by the behavior each tick.
var desire_x := PackedFloat32Array()
var desire_z := PackedFloat32Array()
var pace := PackedFloat32Array()
var head_x := PackedFloat32Array()
var head_z := PackedFloat32Array()
var flap_phase := PackedFloat32Array()
## Hit flash (1 on a hit, fading), shown by the shader.
var hurt := PackedFloat32Array()
var timer := PackedFloat32Array()
## Flyers: visual altitude.
var alt := PackedFloat32Array()
## Seconds until the enemy can attack again.
var attack_cd := PackedFloat32Array()
## Seconds of slowing-trap slowdown left.
var slow_left := PackedFloat32Array()
## Structure being broken (BREAK) and the state to resume after it (-1 / 0 when none).
var barrier := PackedInt32Array()
var resume := PackedByteArray()
var health := PackedInt32Array()
## Loot item the enemy is after and the one it carries (-1 for none).
var target := PackedInt32Array()
var carry := PackedInt32Array()
## The loot category it goes for (LootSystem.Category, or LootSystem.ANY).
var want := PackedByteArray()
var type := PackedByteArray()
var state := PackedByteArray()
var alive := PackedByteArray()
var removal := PackedByteArray()
var dense_id := PackedInt32Array()
# Stable ids: slot of each id (-1 when free) and its generation.
var id_dense := PackedInt32Array()
var id_generation := PackedInt32Array()
var _free_ids := PackedInt32Array()
var _free_top: int = 0
var _pending := PackedInt32Array()
var _pending_count: int = 0
# Diagnostics.
var spawn_skipped: int = 0
var kills: int = 0
var escapes: int = 0
var attacks_attempted: int = 0
var attacks_blocked_by_cover: int = 0
## Fraction along the last sweep_hit() segment where the nearest hit happened.
var hit_t: float = 0.0
func setup(cfg: GameConfig, p_nav: FarmNavigation, p_behavior: ThiefBehavior, mesh: Mesh,
material: Material, area: Rect2) -> void:
config = cfg
nav = p_nav
behavior = p_behavior
capacity = cfg.enemy_capacity
_load_types(cfg)
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, desire_x, desire_z,
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a.resize(capacity)
a.fill(0.0)
for a: PackedInt32Array in [health, target, carry, barrier, dense_id, id_dense, id_generation, _free_ids, _pending]:
a.resize(capacity)
a.fill(0)
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
a.resize(capacity)
a.fill(0)
id_dense.fill(-1)
grid.setup(area, 1.0, capacity)
renderer = HordeRenderer.new()
renderer.name = "EnemyRenderer"
add_child(renderer)
var aabb := AABB(Vector3(area.position.x, 0.0, area.position.y), Vector3(area.size.x, 4.0, area.size.y))
renderer.setup(mesh, material, capacity, cfg.combat_height, aabb)
clear()
func _load_types(cfg: GameConfig) -> void:
var n := TYPE_NAMES.size()
for a: PackedFloat32Array in [t_speed, t_accel, t_steal, t_carry, t_hit_interval, t_aggro_range, t_hit_radius]:
a.resize(n)
for a: PackedInt32Array in [t_hp, t_targets, t_structure_damage, t_damage]:
a.resize(n)
for a: PackedByteArray in [t_flying, t_breaks, t_aggression]:
a.resize(n)
for t in n:
var row := cfg.enemy(TYPE_NAMES[t])
t_speed[t] = float(row.get("speed", 3.0))
t_accel[t] = float(row.get("acceleration", 14.0))
t_hp[t] = int(row.get("hp", 1))
t_flying[t] = 1 if bool(row.get("flying", false)) else 0
var mask := 0
for target in row.get("targets", []):
var c := LootSystem.CATEGORY_KEYS.find(String(target))
if c >= 0:
mask |= 1 << c
t_targets[t] = mask
t_breaks[t] = 1 if (row.get("targets", []) as Array).has("structures") else 0
t_steal[t] = float(row.get("steal_time", 1.0))
t_carry[t] = float(row.get("carry_speed", 0.7))
t_structure_damage[t] = int(row.get("structure_damage", 0))
t_damage[t] = int(row.get("damage", 0))
t_hit_interval[t] = float(row.get("hit_interval", 1.2))
t_aggression[t] = maxi(["none", "contact", "fight"].find(String(row.get("aggression", "none"))), 0)
t_aggro_range[t] = float(row.get("aggro_range", 0.0))
t_hit_radius[t] = float(row.get("hit_radius", 0.4))
func is_flying(d: int) -> bool:
return t_flying[type[d]] == 1
func max_speed() -> float:
var best := 0.0
for v in t_speed:
best = maxf(best, v)
return best
## Releases every enemy at once, without removal events (used when the farm state is replaced,
## e.g. on retry: the loot system resyncs from the new state).
func clear() -> void:
active_count = 0
_pending_count = 0
_free_top = capacity
for id in capacity:
_free_ids[id] = capacity - 1 - id # pop order 0, 1, 2, ...
if id_dense[id] >= 0:
id_generation[id] += 1
id_dense[id] = -1
if renderer:
renderer.clear()
renderer.commit(0)
if characters:
characters.clear()
## Acquires a slot and initializes every state field. Returns a handle, or -1 if the pool is
## exhausted, or for a ground enemy there's no free character to draw it (the spawn is skipped
## and counted; nothing grows).
func spawn(enemy_type: int, x: float, z: float, heading: Vector2, p_want: int = LootSystem.ANY) -> int:
if active_count >= capacity or _free_top <= 0:
spawn_skipped += 1
return -1
var id := _free_ids[_free_top - 1]
if characters != null and t_flying[enemy_type] == 0 and not characters.acquire(enemy_type, id):
spawn_skipped += 1
return -1
_free_top -= 1
var d := active_count
active_count += 1
var h := heading.normalized() if heading.length_squared() > 1e-6 else Vector2(0.0, -1.0)
pos_x[d] = x
pos_z[d] = z
prev_x[d] = x
prev_z[d] = z
vel_x[d] = 0.0
vel_z[d] = 0.0
desire_x[d] = 0.0
desire_z[d] = 0.0
pace[d] = 0.0
head_x[d] = h.x
head_z[d] = h.y
flap_phase[d] = randf()
hurt[d] = 0.0
timer[d] = 0.0
attack_cd[d] = 0.0
slow_left[d] = 0.0
alt[d] = config.cruise_altitude
health[d] = t_hp[enemy_type]
target[d] = -1
carry[d] = -1
barrier[d] = -1
resume[d] = 0
type[d] = enemy_type
want[d] = p_want
state[d] = 0
alive[d] = 1
removal[d] = 0
dense_id[d] = id
id_dense[id] = d
renderer.write_new(d, x, z, h.x, h.y, flap_phase[d])
return handle_of(d)
func handle_of(d: int) -> int:
var id := dense_id[d]
return id | (id_generation[id] << ID_BITS)
## Returns the dense slot for a handle, or -1 if the handle is stale or released.
func resolve_handle(handle: int) -> int:
if handle < 0:
return -1
var id := handle & ID_MASK
if id >= capacity or id_generation[id] != (handle >> ID_BITS):
return -1
return id_dense[id]
func is_alive_slot(d: int) -> bool:
return d >= 0 and d < active_count and alive[d] == 1
func alive_count() -> int:
return active_count - _pending_count
## Interpolated render-time position of a slot (between the last two ticks).
func visual_position(d: int) -> Vector2:
var f := Engine.get_physics_interpolation_fraction()
return Vector2(lerpf(prev_x[d], pos_x[d], f), lerpf(prev_z[d], pos_z[d], f))
## Applies one hit. Returns false for dead or pending slots (no double kills).
func apply_hit(d: int, damage: int = 1) -> bool:
if not is_alive_slot(d):
return false
health[d] -= damage
hurt[d] = 1.0
if characters != null and t_flying[type[d]] == 0:
characters.hit(dense_id[d])
if health[d] <= 0:
kills += 1
queue_removal(d, Removal.KILLED)
elif behavior != null:
behavior.on_hit(self, d)
return true
func apply_hit_handle(handle: int, damage: int = 1) -> bool:
return apply_hit(resolve_handle(handle), damage)
## Takes a living enemy out of the simulation now; its slot is released (and enemy_removed
## emitted) at the end of the tick by commit_removals().
func queue_removal(d: int, reason: Removal) -> void:
if not is_alive_slot(d):
return
alive[d] = 0
removal[d] = reason
if reason == Removal.ESCAPED:
escapes += 1
_pending[_pending_count] = dense_id[d]
_pending_count += 1
## Every living enemy leaves now (end of the night): removal reason LEFT.
func remove_all() -> void:
for d in active_count:
queue_removal(d, Removal.LEFT)
commit_removals()
## One tick: behavior decides desired directions, then steering (desire plus separation from
## nearby enemies of the same kind, ground or air) and motion. Ground enemies collide with the
## grid and yield to the scarecrow; flyers do neither and ease toward their altitude.
## Co-op: player 2's scarecrow, which ground enemies yield to as well (INF when there's none).
var scarecrow2 := Vector2(INF, INF)
func step(dt: float, scarecrow: Vector2, scarecrow_radius: float) -> void:
var scarecrows: Array[Vector2] = [scarecrow, scarecrow2]
if behavior != null:
behavior.update(self, dt)
var cfg := config
var sep_r := cfg.separation_radius
var contact := cfg.enemy_radius + scarecrow_radius
var max_corr := cfg.max_correction_per_tick
var g := grid
for i in active_count:
hurt[i] = maxf(hurt[i] - dt * 4.0, 0.0)
attack_cd[i] = maxf(attack_cd[i] - dt, 0.0)
slow_left[i] = maxf(slow_left[i] - dt, 0.0)
var x := pos_x[i]
var z := pos_z[i]
prev_x[i] = x
prev_z[i] = z
if alive[i] == 0:
continue
var t := type[i]
var flying := t_flying[t] == 1
var speed := t_speed[t]
var accel := t_accel[t] * dt
if flying:
var want_alt := behavior.altitude_for(self, i) if behavior != null else cfg.cruise_altitude
alt[i] = move_toward(alt[i], want_alt, dt * 2.5)
elif structures != null and slow_left[i] == 0.0 and structures.try_trap(x, z):
slow_left[i] = structures.trap_slow_time()
# Separation from neighbors (previous tick's buckets).
var sx := 0.0
var sz := 0.0
var gx := g.cell_x(x)
var gz := g.cell_z(z)
for n in 9:
var ncx := gx + NB_DX[n]
var ncz := gz + NB_DZ[n]
if ncx < 0 or ncz < 0 or ncx >= g.width or ncz >= g.height:
continue
var c := ncz * g.width + ncx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var o := g.items[k]
if o == i or o >= active_count or alive[o] == 0 or t_flying[type[o]] != t_flying[t]:
continue
var dx := x - pos_x[o]
var dz := z - pos_z[o]
var d2 := dx * dx + dz * dz
if d2 >= sep_r * sep_r or d2 < 1e-8:
continue
var d := sqrt(d2)
sx += dx / d * (sep_r - d) / sep_r
sz += dz / d * (sep_r - d) / sep_r
var top := speed * pace[i] * (cfg.trap_slow_factor if slow_left[i] > 0.0 else 1.0)
var tx := desire_x[i] * top + sx * cfg.separation_weight * speed * 0.5
var tz := desire_z[i] * top + sz * cfg.separation_weight * speed * 0.5
var vx := vel_x[i]
var vz := vel_z[i]
var dvx := tx - vx
var dvz := tz - vz
var dl2 := dvx * dvx + dvz * dvz
if dl2 > accel * accel:
var kk := accel / sqrt(dl2)
dvx *= kk
dvz *= kk
vx += dvx
vz += dvz
var nx := x + vx * dt
var nz := z + vz * dt
if flying:
pos_x[i] = nx
pos_z[i] = nz
vel_x[i] = vx
vel_z[i] = vz
_turn(i, vx, vz)
continue
# Yield to the scarecrow (bounded push), and stop pressing into it.
for sc: Vector2 in scarecrows:
if not sc.is_finite():
continue
var ox := nx - sc.x
var oz := nz - sc.y
var od2 := ox * ox + oz * oz
if od2 < contact * contact and od2 > 1e-8:
var od := sqrt(od2)
var push := minf(contact - od, max_corr)
nx += ox / od * push
nz += oz / od * push
var vn := (vx * ox + vz * oz) / od
if vn < 0.0:
vx -= vn * ox / od
vz -= vn * oz / od
# Grid collision: keep the center in walkable cells, sliding along an axis when blocked.
if not nav.is_walkable(nav.cell_of(nx, nz)):
if nav.is_walkable(nav.cell_of(nx, z)):
nz = z
vz = 0.0
elif nav.is_walkable(nav.cell_of(x, nz)):
nx = x
vx = 0.0
else:
nx = x
nz = z
vx = 0.0
vz = 0.0
pos_x[i] = nx
pos_z[i] = nz
vel_x[i] = vx
vel_z[i] = vz
_turn(i, vx, vz)
grid.rebuild(pos_x, pos_z, active_count)
## Turns the heading toward the velocity (or the desire, when nearly still).
func _turn(i: int, vx: float, vz: float) -> void:
var sp2 := vx * vx + vz * vz
var fx := vx if sp2 > 0.04 else desire_x[i]
var fz := vz if sp2 > 0.04 else desire_z[i]
var fl := sqrt(fx * fx + fz * fz)
if fl > 1e-4:
var hx := head_x[i] + (fx / fl - head_x[i]) * 0.25
var hz := head_z[i] + (fz / fl - head_z[i]) * 0.25
var hl := sqrt(hx * hx + hz * hz)
if hl > 1e-4:
head_x[i] = hx / hl
head_z[i] = hz / hl
## Melee: enemies the behavior allows to attack, touching the scarecrow (within
## enemy_attack_reach of contact), off cooldown, and with a clear line to it, attack for their
## type's damage. The scarecrow's invulnerability decides whether a hit lands, so several attacks
## on one tick cost at most one hit. The cooldown (the type's hit_interval) starts on every
## attempt.
func evaluate_attacks(scarecrow_pos: Vector2, scarecrow_radius: float, target_kit: Scarecrow) -> void:
var cfg := config
var reach := cfg.enemy_radius + scarecrow_radius + cfg.enemy_attack_reach
var g := grid
var cx0 := g.cell_x(scarecrow_pos.x - reach)
var cx1 := g.cell_x(scarecrow_pos.x + reach)
var cz0 := g.cell_z(scarecrow_pos.y - reach)
var cz1 := g.cell_z(scarecrow_pos.y + reach)
for cz in range(cz0, cz1 + 1):
for cx in range(cx0, cx1 + 1):
var c := cz * g.width + cx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var i := g.items[k]
if i >= active_count or alive[i] == 0 or attack_cd[i] > 0.0:
continue
if behavior != null and not behavior.can_attack(self, i):
continue
var dx := pos_x[i] - scarecrow_pos.x
var dz := pos_z[i] - scarecrow_pos.y
if dx * dx + dz * dz > reach * reach:
continue
attack_cd[i] = t_hit_interval[type[i]]
attacks_attempted += 1
if not nav.line_clear(pos_x[i], pos_z[i], scarecrow_pos.x, scarecrow_pos.y):
attacks_blocked_by_cover += 1
continue
target_kit.try_damage(t_damage[type[i]])
## Swept projectile test against enemy hit proxies (vertical cylinders of the type's hit_radius;
## shots fly horizontally at combat height, so it is a 2D circle test, flyers included), using
## each enemy's motion across the tick relative to the shot's (the prototype's exact
## relative-motion test). Returns the dense slot of the nearest hit (fraction in hit_t) or -1.
func sweep_hit(x0: float, z0: float, x1: float, z1: float, use_motion: bool) -> int:
var widest := 0.0
for v in t_hit_radius:
widest = maxf(widest, v)
var margin := widest + max_speed() / float(Engine.physics_ticks_per_second) + config.max_correction_per_tick * 2.0
var g := grid
var cx0 := g.cell_x(minf(x0, x1) - margin)
var cx1 := g.cell_x(maxf(x0, x1) + margin)
var cz0 := g.cell_z(minf(z0, z1) - margin)
var cz1 := g.cell_z(maxf(z0, z1) + margin)
var best := -1
var best_t := 2.0
var mbx := x1 - x0
var mbz := z1 - z0
for cz in range(cz0, cz1 + 1):
for cx in range(cx0, cx1 + 1):
var c := cz * g.width + cx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var i := g.items[k]
if i >= active_count or alive[i] == 0:
continue
var rr := t_hit_radius[type[i]]
var ex0 := prev_x[i] if use_motion else pos_x[i]
var ez0 := prev_z[i] if use_motion else pos_z[i]
var sx := x0 - ex0
var sz := z0 - ez0
var mx := mbx - (pos_x[i] - ex0)
var mz := mbz - (pos_z[i] - ez0)
var cc := sx * sx + sz * sz - rr * rr
var t := 2.0
if cc <= 0.0:
t = 0.0
else:
var a := mx * mx + mz * mz
var bb := sx * mx + sz * mz
if a > 1e-12 and bb < 0.0:
var disc := bb * bb - a * cc
if disc >= 0.0:
t = (-bb - sqrt(disc)) / a
if t <= 1.0 and t < best_t:
best_t = t
best = i
hit_t = best_t
return best
## Releases this tick's removals: emits enemy_removed (handle still valid), then swaps the last
## active enemy into each freed slot and updates every mapping.
func commit_removals() -> void:
var n := _pending_count
_pending_count = 0
for k in n:
var id := _pending[k]
var d := id_dense[id]
if d < 0:
continue
enemy_removed.emit(handle_of(d), removal[d] as Removal, pos_x[d], pos_z[d], carry[d], target[d])
if characters != null and t_flying[type[d]] == 0:
characters.release(id, removal[d] == Removal.KILLED)
_release_slot(d)
## Uploads the flyers' poses (with their altitude) to the MultiMesh; ground enemies are drawn by
## their characters, so their instances are scaled to nothing.
func commit_render() -> void:
var b := renderer.buffer
var o := 0
for i in active_count:
var on := 1.0 if t_flying[type[i]] == 1 else 0.0
var c := -head_z[i] * on
var s := -head_x[i] * on
b[o] = c
b[o + 2] = s
b[o + 3] = pos_x[i]
b[o + 5] = on
b[o + 7] = alt[i]
b[o + 8] = -s
b[o + 10] = c
b[o + 11] = pos_z[i]
b[o + 13] = hurt[i]
o += HordeRenderer.STRIDE
renderer.commit(active_count)
func _release_slot(d: int) -> void:
var id := dense_id[d]
var last := active_count - 1
if d != last:
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, desire_x, desire_z,
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a[d] = a[last]
for a: PackedInt32Array in [health, target, carry, barrier]:
a[d] = a[last]
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
a[d] = a[last]
var moved := dense_id[last]
dense_id[d] = moved
id_dense[moved] = d
renderer.move_slot(last, d)
alive[last] = 0
id_dense[id] = -1
id_generation[id] += 1
_free_ids[_free_top] = id
_free_top += 1
active_count -= 1
## The prototype's bird, re-centered on the torso and scaled to meters, beak along -Z.
static func build_bird_mesh(scale: float) -> ArrayMesh:
var src := load(AssetCatalog.BIRD_PATH) as Mesh
var basis := Basis(Vector3(0, 0, -1), Vector3(-1, 0, 0), Vector3(0, 1, 0))
var mesh := ArrayMesh.new()
for surface in src.get_surface_count():
var arrays := src.surface_get_arrays(surface)
var verts: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var normals: PackedVector3Array = arrays[Mesh.ARRAY_NORMAL]
for i in verts.size():
verts[i] = basis * ((verts[i] - AssetCatalog.BIRD_SOURCE_PIVOT) * scale)
for i in normals.size():
normals[i] = basis * normals[i]
arrays[Mesh.ARRAY_VERTEX] = verts
arrays[Mesh.ARRAY_NORMAL] = normals
arrays[Mesh.ARRAY_TANGENT] = null
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
return mesh

View file

@ -0,0 +1 @@
uid://qpvv6poddjes

504
game/scripts/farm_audio.gd Normal file
View file

@ -0,0 +1,504 @@
class_name FarmAudio
extends Node3D
## Every sound in the game, by cue name (CUES), routed through the audio buses (Music: phase
## stingers and outcomes; SFX: everything else; Ambience: the day and night loops). FarmSim
## creates it and setup() connects it to the farm's systems:
## * scarecrow: footsteps, its weapons (a pitchfork's whoosh and what it strikes, corn shots,
## a pumpkin bomb's toss and burst), hurt, fall, fear and fear ready, patching and patched
## * enemies: crow caws and thieves' / fence breakers' arrivals (from where they come in), hits
## and deaths by type
## * theft: grabbed, dropped, recovered, carried off (with an alarm tone), animals following
## * building: placed, refused, dismantled, hit, broken (with a breach alarm), repaired,
## automated defenses firing, traps springing, the repair hammering
## * gathering: chopping, rustling straw, clanking scrap; stored at the shed; upgrades bought
## * phases: the dusk bell, stingers at dusk, nightfall, sunrise, and morning; game over;
## the day and night ambience (crossfading through dusk and dawn)
## * UI: hover, click, back, open, close, error (ui(), also from the menus)
## * Music (the Music bus), by phase: "On the Farm" on the title screen (the farm's morning
## behind it), the morning, and by day, and when the farmers are back; "Purgatory" at night;
## none at dusk, at dawn, or after a Game Over (only the ambience). Tracks crossfade.
## Positional cues play where they happen and are heard from an AudioListener3D at the
## scarecrow (or the cutscene's focus) facing the way the camera does, so left and right on
## screen are left and right in the ears. Each cue has a volume, a random pitch spread, a
## minimum gap between plays, and a voice limit, so twenty crows don't make twenty caws.
## UI, stinger, and ambience players keep playing while the game is paused; the rest pause.
## Co-op: every world sound the host plays is also sent to the partner (forward), whose game
## plays only those (remote_cues) plus what it makes itself: its footsteps and channels, the UI,
## the phase stingers, and the music (LOCAL_CUES).
## Sources: Kenney's CC0 packs (assets/audio/kenney/, with their licenses) and sounds made by
## game/tools/synth_audio.gd (assets/audio/synth/). A '*' in a file name stands for 0..9.
const ROOT := "res://assets/audio/"
const CUES := {
# UI
"ui_hover": {"files": ["kenney/ui/rollover2.ogg"], "db": -16.0, "gap": 0.03, "ui": true},
"ui_click": {"files": ["kenney/interface/click_002.ogg"], "db": -8.0, "ui": true},
"ui_back": {"files": ["kenney/interface/back_001.ogg"], "db": -8.0, "ui": true},
"ui_open": {"files": ["kenney/interface/open_001.ogg"], "db": -10.0, "ui": true},
"ui_close": {"files": ["kenney/interface/close_001.ogg"], "db": -10.0, "ui": true},
"error": {"files": ["kenney/interface/error_004.ogg"], "db": -8.0, "gap": 0.25, "ui": true},
# Scarecrow
"step": {"files": ["kenney/impact/footstep_grass_00*.ogg"], "db": -15.0, "pitch": 0.08},
"shot": {"files": ["kenney/interface/pluck_00*.ogg"], "db": -9.0, "pitch": 0.12, "max": 3},
"stab": {"files": ["synth/pitchfork_whoosh.wav"], "db": -6.0, "pitch": 0.12, "max": 3},
"throw": {"files": ["kenney/rpg/cloth*.ogg"], "db": -4.0, "pitch": 0.1},
"boom": {"files": ["synth/pumpkin_boom.wav"], "db": 0.0, "pitch": 0.08, "gap": 0.05, "max": 4},
"hurt": {"files": ["kenney/impact/impactSoft_heavy_00*.ogg"], "db": -1.0, "pitch": 0.1, "gap": 0.1},
"fall": {"files": ["kenney/impact/impactSoft_heavy_004.ogg"], "db": 0.0, "pitch": 0.0},
"fear": {"files": ["kenney/digital/phaserDown2.ogg"], "db": -5.0, "pitch": 0.05},
"fear_ready": {"files": ["kenney/interface/maximize_003.ogg"], "db": -12.0},
"patching": {"files": ["kenney/rpg/cloth*.ogg"], "db": -10.0, "pitch": 0.1},
"patched": {"files": ["kenney/rpg/clothBelt.ogg"], "db": -4.0},
# Weapon and enemies
"hit": {"files": ["kenney/impact/impactPunch_medium_00*.ogg"], "db": -8.0, "pitch": 0.1, "gap": 0.03, "max": 4},
"hit_crow": {"files": ["kenney/impact/impactSoft_medium_00*.ogg"], "db": -6.0, "pitch": 0.15, "gap": 0.03, "max": 4},
"hit_world": {"files": ["kenney/impact/impactGeneric_light_00*.ogg"], "db": -14.0, "pitch": 0.15, "gap": 0.05, "max": 3},
"crow_arrive": {"files": ["synth/crow_caw_1.wav", "synth/crow_caw_2.wav"], "db": 2.0, "pitch": 0.08, "gap": 0.7, "max": 2},
"crow_die": {"files": ["synth/crow_squawk.wav"], "db": -2.0, "pitch": 0.1, "gap": 0.05, "max": 3},
"thief_arrive": {"files": ["kenney/rpg/creak*.ogg"], "db": 0.0, "pitch": 0.1, "gap": 0.8},
"breaker_arrive": {"files": ["kenney/impact/impactWood_heavy_000.ogg"], "db": 4.0, "pitch": 0.0, "gap": 0.8},
"enemy_die": {"files": ["kenney/impact/impactPunch_heavy_00*.ogg"], "db": -3.0, "pitch": 0.1, "gap": 0.05, "max": 3},
# Theft and alerts
"grab": {"files": ["kenney/rpg/handleSmallLeather.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.1},
"theft_alert": {"files": ["kenney/digital/lowThreeTone.ogg"], "db": -10.0, "gap": 2.5, "ui": true},
"drop": {"files": ["kenney/rpg/dropLeather.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.05},
"recover": {"files": ["kenney/interface/confirmation_002.ogg"], "db": -6.0, "pitch": 0.05, "gap": 0.08},
"follow": {"files": ["kenney/interface/confirmation_001.ogg"], "db": -8.0, "pitch": 0.1, "gap": 0.08},
"lost": {"files": ["kenney/digital/lowDown.ogg"], "db": -6.0, "gap": 1.0, "ui": true},
"breach": {"files": ["kenney/digital/twoTone1.ogg"], "db": -8.0, "gap": 2.0, "ui": true},
# Building
"build": {"files": ["kenney/impact/impactPlank_medium_00*.ogg"], "db": -3.0, "pitch": 0.08},
"dismantle": {"files": ["kenney/impact/impactWood_light_00*.ogg"], "db": -4.0, "pitch": 0.1},
"structure_hit": {"files": ["kenney/impact/impactWood_medium_00*.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.12, "max": 3},
"smash": {"files": ["kenney/impact/impactWood_heavy_00*.ogg"], "db": 2.0, "pitch": 0.08},
"hammer": {"files": ["kenney/impact/impactWood_light_00*.ogg"], "db": -7.0, "pitch": 0.12},
"repaired": {"files": ["kenney/interface/confirmation_001.ogg"], "db": -6.0},
"turret": {"files": ["kenney/interface/drop_00*.ogg"], "db": -11.0, "pitch": 0.1, "gap": 0.05, "max": 3},
"trap": {"files": ["kenney/impact/impactSoft_medium_00*.ogg"], "db": -4.0, "pitch": 0.2, "gap": 0.1},
# Gathering and upgrades
"chop": {"files": ["kenney/rpg/chop.ogg"], "db": -4.0, "pitch": 0.1},
"rustle": {"files": ["kenney/rpg/cloth*.ogg"], "db": -6.0, "pitch": 0.15},
"clank": {"files": ["kenney/impact/impactMetal_light_00*.ogg"], "db": -8.0, "pitch": 0.1},
"gathered": {"files": ["kenney/rpg/handleSmallLeather2.ogg"], "db": -8.0, "pitch": 0.05},
"deposit": {"files": ["kenney/rpg/bookPlace*.ogg"], "db": -4.0, "pitch": 0.08, "gap": 0.3},
"upgrade": {"files": ["kenney/jingles/jingles_PIZZI16.ogg"], "db": -6.0, "ui": true},
# Phases and outcomes (stingers on the Music bus)
"bell": {"files": ["kenney/impact/impactBell_heavy_00*.ogg"], "db": -4.0, "pitch": 0.0, "ui": true},
"dusk": {"files": ["kenney/jingles/jingles_PIZZI07.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"night": {"files": ["kenney/jingles/jingles_PIZZI14.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"dawn": {"files": ["kenney/jingles/jingles_PIZZI10.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"morning": {"files": ["kenney/jingles/jingles_PIZZI12.ogg"], "db": -9.0, "bus": "Music", "ui": true},
"game_over": {"files": ["kenney/jingles/jingles_PIZZI01.ogg"], "db": -4.0, "bus": "Music", "ui": true},
"victory": {"files": ["kenney/jingles/jingles_PIZZI02.ogg"], "db": -4.0, "bus": "Music", "ui": true},
"assessment": {"files": ["kenney/jingles/jingles_PIZZI15.ogg"], "db": -5.0, "bus": "Music", "ui": true},
"horn": {"files": ["synth/truck_horn.wav"], "db": -4.0},
"truck_engine": {"files": ["synth/truck_engine.wav"], "db": -6.0},
"day_ambience": {"files": ["synth/day_ambience.wav"], "bus": "Ambience"},
"night_ambience": {"files": ["synth/night_ambience.wav"], "bus": "Ambience"},
}
## Cues each machine plays for itself in co-op (never sent, never skipped).
const LOCAL_CUES: Array[String] = ["ui_hover", "ui_click", "ui_back", "ui_open", "ui_close", "error", "step", "chop",
"rustle", "clank", "hammer", "patching", "bell", "dusk", "night", "dawn", "morning", "game_over", "victory",
"assessment", "horn", "truck_engine", "day_ambience", "night_ambience", "upgrade", "fear_ready"]
const VOICES_3D := 20
const VOICES_UI := 10
## Seconds of channel between repeats of the gather / repair / patch sounds, and meters per
## footstep.
const CHANNEL_REPEAT := 0.5
const STRIDE := 1.55
## Ambience levels (day, night) per phase, and the crossfade speed (share per second).
const AMBIENCE := {
CampaignController.Phase.MORNING: Vector2(1.0, 0.0), CampaignController.Phase.DAY: Vector2(1.0, 0.0),
CampaignController.Phase.DUSK: Vector2(0.55, 0.45), CampaignController.Phase.NIGHT: Vector2(0.0, 1.0),
CampaignController.Phase.DAWN: Vector2(0.6, 0.4), CampaignController.Phase.FARMERS_RETURN: Vector2(1.0, 0.0),
CampaignController.Phase.GAME_OVER: Vector2(0.0, 0.6),
}
const FADE_RATE := 0.25
const MUSIC := {"farm": "music/on_the_farm.wav", "night": "music/purgatory.ogg"}
const MUSIC_FOR := {
CampaignController.Phase.MORNING: "farm", CampaignController.Phase.DAY: "farm", CampaignController.Phase.DUSK: "",
CampaignController.Phase.NIGHT: "night", CampaignController.Phase.DAWN: "", CampaignController.Phase.FARMERS_RETURN: "farm",
CampaignController.Phase.GAME_OVER: "",
}
const MUSIC_DB := -5.0
const MUSIC_FADE := 2.5
var sim: FarmSim
## Where the listener sits (the scarecrow; the cutscene moves it).
var focus: Node3D
## Cue name -> streams, and cue name -> how many times it played (tests read this).
var streams := {}
var played := {}
## Co-op host: called with (cue, at) for every world sound, to send it to the partner.
var forward: Callable
## Co-op partner: world sounds come only from the host (play_remote).
var remote_cues := false
var _voices_3d: Array[AudioStreamPlayer3D] = []
var _voices_ui: Array[AudioStreamPlayer] = []
var _voices_game: Array[AudioStreamPlayer] = []
var _last := {} # cue -> msec of the last play
var _listener: AudioListener3D
var _day: AudioStreamPlayer
var _night: AudioStreamPlayer
var _ambience := Vector2.ZERO
var _ambience_target := Vector2(1.0, 0.0)
var _channel_left: float = 0.0
var _stride_left: float = STRIDE
var _bell_left: float = -1.0
## The track playing or fading in ("" = none), and each track's player and level (0..1).
var music_track := ""
var _music := {}
var _music_level := {}
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS # music and ambience fade on the paused title screen
for track: String in MUSIC:
var m := AudioStreamPlayer.new()
m.bus = &"Music"
m.stream = load(ROOT + MUSIC[track]) as AudioStream
m.volume_db = -80.0
add_child(m)
_music[track] = m
_music_level[track] = 0.0
for cue: String in CUES:
var list: Array[AudioStream] = []
for f: String in CUES[cue]["files"]:
for path in _expand(ROOT + f):
var s := load(path) as AudioStream
if s != null:
list.append(s)
if list.is_empty():
push_warning("FarmAudio: no sound for cue '%s'" % cue)
streams[cue] = list
for i in VOICES_3D:
var p := AudioStreamPlayer3D.new()
p.bus = &"SFX"
p.unit_size = 9.0
p.max_distance = 90.0
p.panning_strength = 0.7
p.attenuation_filter_cutoff_hz = 20500.0 # no muffling with distance
p.process_mode = Node.PROCESS_MODE_PAUSABLE # game sounds stop while paused
add_child(p)
_voices_3d.append(p)
for i in VOICES_UI:
var p := AudioStreamPlayer.new()
p.process_mode = Node.PROCESS_MODE_ALWAYS
add_child(p)
_voices_ui.append(p)
var g := AudioStreamPlayer.new()
g.process_mode = Node.PROCESS_MODE_PAUSABLE
add_child(g)
_voices_game.append(g)
_day = _loop_player("day_ambience")
_night = _loop_player("night_ambience")
_listener = AudioListener3D.new()
_listener.top_level = true
add_child(_listener)
_listener.make_current()
func setup(p_sim: FarmSim) -> void:
sim = p_sim
focus = sim.player
var c := sim.campaign
c.phase_changed.connect(_on_phase)
c.campaign_ended.connect(func(outcome: CampaignController.Outcome) -> void:
if outcome != CampaignController.Outcome.VACATION_COMPLETE:
play("game_over"))
_ambience_target = AMBIENCE.get(c.state.phase, Vector2(1.0, 0.0))
_ambience = _ambience_target
music_track = MUSIC_FOR.get(c.state.phase, "")
_wire_weapons(sim.combat, Callable())
sim.bombs.burst.connect(func(at: Vector3, _n: int) -> void: play("boom", at))
sim.projectiles.hit.connect(func(at: Vector3, type: int) -> void:
play("hit_world" if type < 0 else "hit_crow" if type == EnemySystem.TYPE_CROW else "hit", at))
sim.enemies.enemy_removed.connect(_on_removed)
sim.waves.arrived.connect(func(h: int, at: Vector2) -> void:
var d := sim.enemies.resolve_handle(h)
var type := sim.enemies.type[d] if d >= 0 else EnemySystem.TYPE_THIEF
play(["thief_arrive", "crow_arrive", "breaker_arrive"][type], Vector3(at.x, 0.0, at.y)))
var kit := sim.scarecrow
kit.damaged.connect(func(hp: int) -> void: play("fall" if hp <= 0 else "hurt"))
kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: play("fear"))
kit.fear_ready.connect(func() -> void: play("fear_ready"))
kit.patched.connect(func(_hp: int) -> void: play("patched"))
kit.patch_denied.connect(func(_m: Dictionary) -> void: play("error"))
sim.interactions.gathered.connect(func(_m: String, _a: int, n: GatherNode) -> void: play("gathered", n.global_position))
sim.interactions.deposited.connect(func(_moved: Dictionary) -> void: play("deposit", sim.player.global_position))
var st := sim.structures
st.built.connect(func(id: int, _type: String) -> void: play("build", _structure_at(id)))
st.destroyed.connect(func(_id: int, _type: String, at: Vector3) -> void:
play("smash", at)
play("breach"))
st.hurt.connect(func(_id: int, at: Vector3) -> void: play("structure_hit", at))
st.repaired.connect(func(id: int) -> void: play("repaired", _structure_at(id)))
st.turret_fired.connect(func(at: Vector3) -> void: play("turret", at))
st.trap_sprung.connect(func(at: Vector3) -> void: play("trap", at))
sim.build.refused.connect(func(_why: String) -> void: play("error"))
sim.build.dismantled.connect(func(_type: String) -> void: play("dismantle", Vector3(sim.build.cursor.x, 0.5, sim.build.cursor.y)))
sim.build.toggled.connect(func(on: bool) -> void: play("ui_open" if on else "ui_close"))
sim.loot.loot_event.connect(_on_loot)
if sim.upgrade_panel != null:
sim.upgrade_panel.bought.connect(func(_id: String) -> void: play("upgrade"))
wire_buttons(sim.upgrade_panel)
if sim.review_panel != null:
wire_buttons(sim.review_panel)
if sim.end_panel != null:
wire_buttons(sim.end_panel)
## Stops every voice, so no playback outlives the farm (the audio server holds on to playing
## ones until its next mix; Main.quit_game() gives it that moment).
func silence() -> void:
for p in get_children():
if p is AudioStreamPlayer or p is AudioStreamPlayer3D:
p.stop()
p.stream = null
func _exit_tree() -> void:
silence()
## Plays a cue: where it happens (positional) when at is given, else straight to the ears.
## Returns false when the cue is resting (its gap) or has no sound.
func play(cue: String, at: Vector3 = Vector3.INF) -> bool:
var local := LOCAL_CUES.has(cue)
if remote_cues and not local:
return false
if forward.is_valid() and not local:
forward.call(cue, at)
return _play(cue, at)
## A world sound the host played (co-op partner).
func play_remote(cue: String, at: Vector3 = Vector3.INF) -> bool:
return _play(cue, at)
## Sounds for a scarecrow other than the first (co-op): its gun, hurt, fall, fear, and patch,
## where it is.
func wire_avatar(a: Avatar) -> void:
_wire_weapons(a.combat, func() -> Vector3: return a.body.global_position)
a.kit.damaged.connect(func(hp: int) -> void: play("fall" if hp <= 0 else "hurt", a.body.global_position))
a.kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: play("fear", a.body.global_position))
a.kit.patched.connect(func(_hp: int) -> void: play("patched", a.body.global_position))
## A scarecrow's weapons: where (at) for another scarecrow than this machine's, which is heard
## from right here.
func _wire_weapons(combat: ScarecrowCombat, at: Callable) -> void:
var where := func() -> Vector3: return at.call() if at.is_valid() else Vector3.INF
combat.fired.connect(func() -> void: play("shot", where.call()))
combat.stabbed.connect(func(_n: int) -> void: play("stab", where.call()))
combat.struck.connect(func(p: Vector3, type: int) -> void: play("hit_crow" if type == EnemySystem.TYPE_CROW else "hit", p))
combat.threw.connect(func(_to: Vector3) -> void: play("throw", where.call()))
func _play(cue: String, at: Vector3) -> bool:
var def: Dictionary = CUES.get(cue, {})
var list: Array = streams.get(cue, [])
if def.is_empty() or list.is_empty():
return false
var now := Time.get_ticks_msec()
if now - int(_last.get(cue, -1000000000)) < int(float(def.get("gap", 0.0)) * 1000.0):
return false
_last[cue] = now
played[cue] = int(played.get(cue, 0)) + 1
var stream: AudioStream = list[randi() % list.size()]
var pitch := 1.0 + randf_range(-1.0, 1.0) * float(def.get("pitch", 0.0))
var db := float(def.get("db", 0.0))
var bus := StringName(def.get("bus", "SFX"))
var limit := int(def.get("max", 4))
if is_finite(at.x) and not bool(def.get("ui", false)):
var p := _free_voice(_voices_3d, cue, limit) as AudioStreamPlayer3D
p.global_position = at
p.bus = bus
_start(p, stream, db, pitch, cue)
else:
var pool := _voices_ui if bool(def.get("ui", false)) else _voices_game
var p := _free_voice(pool, cue, limit) as AudioStreamPlayer
p.bus = bus
_start(p, stream, db, pitch, cue)
return true
## UI sounds (they play while paused).
func ui(cue: String) -> void:
play(cue)
## Gives every Button under node a hover and a click sound (call again after adding buttons).
func wire_buttons(node: Node) -> void:
for b in node.find_children("*", "BaseButton", true, false):
if b.has_meta(&"sounds"):
continue
b.set_meta(&"sounds", true)
var button := b as BaseButton
button.mouse_entered.connect(func() -> void:
if not button.disabled:
ui("ui_hover"))
button.focus_entered.connect(func() -> void: ui("ui_hover"))
button.pressed.connect(func() -> void: ui("ui_click"))
## The first stream of a cue (for looping players the cutscene owns).
func stream_of(cue: String) -> AudioStream:
var list: Array = streams.get(cue, [])
return list[0] if not list.is_empty() else null
func _physics_process(dt: float) -> void:
if sim == null or sim.campaign.is_over() or get_tree().paused:
return
var p := sim.player
if sim.scarecrow.alive and p.is_on_floor():
var v := Vector2(p.velocity.x, p.velocity.z).length()
if v > 1.0:
_stride_left -= v * dt
if _stride_left <= 0.0:
_stride_left = STRIDE
play("step", p.global_position)
else:
_stride_left = minf(_stride_left, STRIDE * 0.3)
var it := sim.interactions
var channel := ""
var at := p.global_position
if it.gathering != null:
channel = {"wood": "chop", "straw": "rustle", "scrap": "clank"}.get(it.gathering.material, "rustle")
at = it.gathering.global_position
elif it.repairing >= 0:
channel = "hammer"
at = _structure_at(it.repairing)
elif sim.scarecrow.patching:
channel = "patching"
if channel == "":
_channel_left = 0.15
return
_channel_left -= dt
if _channel_left <= 0.0:
_channel_left = CHANNEL_REPEAT
play(channel, at)
func _process(delta: float) -> void:
var cam := get_viewport().get_camera_3d()
if cam != null and focus != null and is_instance_valid(focus):
_listener.global_transform = Transform3D(cam.global_transform.basis, focus.global_position + Vector3(0.0, 1.5, 0.0))
for track: String in _music:
var m := _music[track] as AudioStreamPlayer
var level := move_toward(float(_music_level[track]), 1.0 if track == music_track else 0.0, delta / MUSIC_FADE)
_music_level[track] = level
m.volume_db = MUSIC_DB + linear_to_db(maxf(level, 0.0001))
if level > 0.0 and not m.playing and m.stream != null:
m.play()
elif level <= 0.0 and m.playing:
m.stop()
_ambience = _ambience.move_toward(_ambience_target, FADE_RATE * delta)
_day.volume_db = linear_to_db(maxf(_ambience.x, 0.0001))
_night.volume_db = linear_to_db(maxf(_ambience.y, 0.0001))
if _bell_left >= 0.0:
_bell_left -= delta
if _bell_left < 0.0:
_last.erase("bell")
play("bell")
func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
_ambience_target = AMBIENCE.get(phase, Vector2(1.0, 0.0))
music_track = MUSIC_FOR.get(phase, "")
match phase:
CampaignController.Phase.MORNING:
_ambience = _ambience_target # a retry or a load jumps straight to morning
play("morning")
CampaignController.Phase.DUSK:
play("bell")
_bell_left = 1.3 # and a second strike
play("dusk")
CampaignController.Phase.NIGHT:
play("night")
CampaignController.Phase.DAWN:
play("dawn")
func _on_removed(handle: int, reason: EnemySystem.Removal, x: float, z: float, _carry: int, _target: int) -> void:
if reason != EnemySystem.Removal.KILLED:
return
var d := sim.enemies.resolve_handle(handle)
var crow := d >= 0 and sim.enemies.type[d] == EnemySystem.TYPE_CROW
play("crow_die" if crow else "enemy_die", Vector3(x, 1.0, z))
func _on_loot(kind: StringName, _id: int, at: Vector3) -> void:
match kind:
&"stolen":
play("grab", at)
play("theft_alert")
&"dropped":
play("drop", at)
&"recovered":
play("recover", at)
&"following":
play("follow", at)
&"lost":
play("lost")
&"follow_full":
play("error")
func _structure_at(id: int) -> Vector3:
var e := sim.campaign.state.structure(id)
return Vector3(e["x"], 0.5, e["z"]) if not e.is_empty() else sim.player.global_position
func _loop_player(cue: String) -> AudioStreamPlayer:
var p := AudioStreamPlayer.new()
p.process_mode = Node.PROCESS_MODE_ALWAYS
p.bus = &"Ambience"
p.stream = stream_of(cue)
p.volume_db = -80.0
add_child(p)
if p.stream != null:
p.play()
return p
## Prefers an idle voice; else the oldest of this cue's once it's at its limit; else the oldest.
func _free_voice(pool: Array, cue: String, limit: int) -> Node:
var oldest: Node = pool[0]
var oldest_same: Node = null
var same := 0
for v: Node in pool:
var playing: bool = v.playing
if not playing:
return v
if v.get_meta(&"cue", "") == cue:
same += 1
if oldest_same == null or int(v.get_meta(&"t")) < int(oldest_same.get_meta(&"t")):
oldest_same = v
if int(v.get_meta(&"t")) < int(oldest.get_meta(&"t")):
oldest = v
return oldest_same if same >= limit and oldest_same != null else oldest
func _start(p: Node, stream: AudioStream, db: float, pitch: float, cue: String) -> void:
p.set(&"stream", stream)
p.set(&"volume_db", db)
p.set(&"pitch_scale", pitch)
p.set_meta(&"cue", cue)
p.set_meta(&"t", Time.get_ticks_usec())
p.call(&"play")
static func _expand(path: String) -> Array[String]:
var out: Array[String] = []
if not path.contains("*"):
out.append(path)
return out
for i in 10:
var p := path.replace("*", str(i))
if ResourceLoader.exists(p):
out.append(p)
return out

View file

@ -0,0 +1 @@
uid://bod5ytvc2vhfs

View file

@ -1,10 +1,7 @@
@tool
class_name FarmMarker
extends Marker3D
## A point on the farm perimeter. A GAP marker sits just outside a gap in the perimeter fence:
## ground enemies arrive and escape there. A CROW marker is a direction that flyers arrive from
## and leave toward.
enum Kind { GAP, CROW }
@export var kind: Kind = Kind.GAP
## A gap in what's left of the perimeter fence (the north and east sides), just outside it. The
## scarecrow walks out through the gaps to the gathering areas, so nothing can be built in them
## (StructureSystem). Enemies don't use them as entrances: they arrive anywhere along the farm's
## edge (WaveDirector), and route through a gap only when the fence is in their way.

View file

@ -8,15 +8,21 @@ extends RefCounted
## like the flat concrete pads). Every other shape that reaches into BAND_LOW..BAND_HIGH blocks
## the cells its XZ outline covers, inflated by the mover's radius. Bodies on other layers
## (the scarecrow-only PlayerBounds) are ignored. The grid has a 1-cell blocked border.
## * A structure layer on top (set_structures): the cells of player-built barriers (fences, gates,
## defenses), inflated like the static obstacles. Movers can't walk into them, but distance
## fields cross them at barrier_cost extra per cell, so a walled-in goal still has a route: it
## ends at the cheapest barrier, which barrier_ahead() reports so the mover can break it.
## * Distance fields toward a set of goal cells: Dijkstra over 8 neighbors with octile integer
## costs (orthogonal 5, diagonal 7 ~ 5 * sqrt(2)) and a circular bucket queue with lazy
## deletion, the scheme of the prototype's ArenaNavigation. Diagonal steps never cut a blocked
## corner. Unreachable cells keep UNREACHABLE.
## costs (orthogonal 5, diagonal 7 ~ 5 * sqrt(2)) plus barrier costs, with a circular bucket
## queue (Dial's algorithm, lazy deletion), run as a FieldJob that can be sliced over ticks.
## Diagonal steps never cut a blocked corner or slip between structure cells. Unreachable cells
## keep UNREACHABLE.
const UNREACHABLE := 1 << 29
const COST_ORTH := 5
const COST_DIAG := 7
const BUCKETS := 8 # > max edge cost, so each pending distance maps to a unique bucket
## Largest barrier_cost: every edge must cost less than FieldJob.BUCKET_COUNT.
const MAX_BARRIER_COST := 240
## Height band (meters above the farm floor at y = 0) in which a shape obstructs ground movement.
const BAND_LOW := 0.35
const BAND_HIGH := 2.0
@ -28,14 +34,17 @@ var origin_z: float
var width: int
var height: int
var blocked: PackedByteArray
## Structure id per cell (-1 = none), from set_structures().
var structure_at: PackedInt32Array
## Extra path cost of entering one structure cell (5 = half a meter).
var barrier_cost: int = 180
var shapes_rasterized: int = 0
var build_usec: int = 0
var _inflate: float = 0.0
var _offsets := PackedInt32Array()
var _side_a := PackedInt32Array()
var _side_b := PackedInt32Array()
var _bucket_buf := PackedInt32Array() # BUCKETS stacks of capacity cell_count()
var _bucket_cnt := PackedInt32Array()
func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer_mask: int = 1) -> void:
@ -46,9 +55,13 @@ func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer
height = ceili(bounds.size.y * inv_cell) + 2
origin_x = bounds.position.x - cell_size
origin_z = bounds.position.y - cell_size
_inflate = inflate
var n := width * height
blocked = PackedByteArray()
blocked.resize(n)
structure_at = PackedInt32Array()
structure_at.resize(n)
structure_at.fill(-1)
for cx in width:
blocked[cx] = 1
blocked[(height - 1) * width + cx] = 1
@ -72,13 +85,26 @@ func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer
_offsets = PackedInt32Array([1, -1, w, -w, w + 1, w - 1, -w + 1, -w - 1])
_side_a = PackedInt32Array([0, 0, 0, 0, 1, -1, 1, -1])
_side_b = PackedInt32Array([0, 0, 0, 0, w, w, -w, -w])
_bucket_buf = PackedInt32Array()
_bucket_buf.resize(n * BUCKETS)
_bucket_cnt = PackedInt32Array()
_bucket_cnt.resize(BUCKETS)
build_usec = Time.get_ticks_usec() - t0
## Replaces the structure layer: entries are {"id": int, "outline": PackedVector2Array (world
## XZ convex outline)}; each covers the cells within the build inflation of its outline.
func set_structures(entries: Array) -> void:
structure_at.fill(-1)
for e: Dictionary in entries:
_rasterize_into(e["outline"], _inflate, int(e["id"]))
func set_barrier_cost(cost: int) -> void:
barrier_cost = clampi(cost, 0, MAX_BARRIER_COST)
## Free of static obstacles and structures: a mover may stand here.
func is_walkable(i: int) -> bool:
return blocked[i] == 0 and structure_at[i] < 0
func cell_count() -> int:
return width * height
@ -135,56 +161,107 @@ func free_cells_in(rect: Rect2) -> PackedInt32Array:
return out
## Free cells within radius of any of the points (goal sets such as the shed's piles).
func free_cells_near(points: PackedVector2Array, radius: float) -> PackedInt32Array:
var out := PackedInt32Array()
for p in points:
for i in free_cells_in(Rect2(p - Vector2(radius, radius), Vector2(radius, radius) * 2.0)):
if cell_center(i).distance_to(p) <= radius and not out.has(i):
out.append(i)
return out
## Free cells whose centers lie within band of a rectangle's outline (the farm's edge, where
## enemies arrive and escape).
func free_cells_on_outline(rect: Rect2, band: float) -> PackedInt32Array:
var out := PackedInt32Array()
var inner := rect.grow(-band)
for i in free_cells_in(rect.grow(band)):
if not inner.has_point(cell_center(i)):
out.append(i)
return out
## True when a straight segment crosses no blocked cell (sampled every half cell); structure
## cells count as blocked too unless through_structures.
func line_clear(x0: float, z0: float, x1: float, z1: float, through_structures: bool = false) -> bool:
var dx := x1 - x0
var dz := z1 - z0
var steps := ceili(sqrt(dx * dx + dz * dz) * inv_cell * 2.0)
for k in steps + 1:
var t := k / float(maxi(steps, 1))
var c := cell_of(x0 + dx * t, z0 + dz * t)
if blocked[c] == 1 or (not through_structures and structure_at[c] >= 0):
return false
return true
## The structure a mover at (x, z) runs into next when going downhill in a field (its steepest-
## descent neighbor is a structure cell), or -1.
func barrier_ahead(field: PackedInt32Array, x: float, z: float) -> int:
var nb := _downhill(field, cell_of(x, z))
return structure_at[nb] if nb >= 0 else -1
## Unit direction (written to out[0], out[1]) for a mover at (x, z) heading downhill in a
## distance field: toward the center of the cell reached by up to `lookahead` legal steepest-
## descent steps, which smooths the 8-way grid moves. Returns false at a goal cell, or where the
## mover's cell (and every free cell near it) has no route.
func flow_direction(field: PackedInt32Array, x: float, z: float, out: PackedFloat32Array, lookahead: int = 3) -> bool:
var c := cell_of(x, z)
if blocked[c] == 1 or field[c] >= UNREACHABLE:
c = nearest_free(c, 64)
if c < 0 or field[c] >= UNREACHABLE:
return false
var cur := c
for step in lookahead:
var nxt := _downhill(field, cur)
if nxt < 0:
break
cur = nxt
if cur == c and field[c] == 0:
return false
var p := cell_center(cur)
var dx := p.x - x
var dz := p.y - z
var l := sqrt(dx * dx + dz * dz)
if l < 1e-4:
return false
out[0] = dx / l
out[1] = dz / l
return true
func _downhill(field: PackedInt32Array, c: int) -> int:
var best := -1
var best_d := field[c]
for k in 8:
var nb := c + _offsets[k]
if blocked[nb] == 1:
continue
if k >= 4:
var sa := c + _side_a[k]
var sb := c + _side_b[k]
if blocked[sa] == 1 or blocked[sb] == 1 or structure_at[sa] >= 0 or structure_at[sb] >= 0:
continue
if field[nb] < best_d:
best_d = field[nb]
best = nb
return best
## Path cost from distance_field() in meters.
func meters(cost: int) -> float:
return cost * cell_size / COST_ORTH
## Octile path cost from every cell to the nearest goal cell (blocked goals are ignored).
## Octile path cost from every cell to the nearest goal cell, computed at once (load, tests).
## Goals that aren't walkable are ignored.
func distance_field(goals: PackedInt32Array) -> PackedInt32Array:
var n := cell_count()
var dist := PackedInt32Array()
dist.resize(n)
dist.fill(UNREACHABLE)
var buf := _bucket_buf
var cnt := _bucket_cnt
cnt.fill(0)
var pending := 0
for g in goals:
if blocked[g] == 1 or dist[g] == 0:
continue
dist[g] = 0
buf[cnt[0]] = g
cnt[0] += 1
pending += 1
var cur := 0
while pending > 0:
var b := cur % BUCKETS
var base := b * n
while cnt[b] > 0:
cnt[b] -= 1
var c := buf[base + cnt[b]]
pending -= 1
if dist[c] != cur:
continue # superseded by a shorter path (lazy deletion)
for k in 8:
var nb := c + _offsets[k]
if blocked[nb] == 1:
continue
var cost := COST_ORTH
if k >= 4:
if blocked[c + _side_a[k]] == 1 or blocked[c + _side_b[k]] == 1:
continue
cost = COST_DIAG
var nd := cur + cost
if nd < dist[nb]:
dist[nb] = nd
var nk := nd % BUCKETS
buf[nk * n + cnt[nk]] = nb
cnt[nk] += 1
pending += 1
cur += 1
return dist
var job := FieldJob.new(self)
job.start(goals)
job.step(1 << 30)
return job.dist
## XZ convex outline of a shape (from its debug mesh in world space), or empty when the shape
@ -208,6 +285,12 @@ func _outline(cs: CollisionShape3D) -> PackedVector2Array:
func _rasterize(hull: PackedVector2Array, inflate: float) -> void:
_rasterize_into(hull, inflate, -1)
## Marks the cells within inflate of a convex outline: as blocked (id < 0) or, for free cells,
## as belonging to structure id.
func _rasterize_into(hull: PackedVector2Array, inflate: float, id: int) -> void:
var lo := hull[0]
var hi := hull[0]
for p in hull:
@ -225,7 +308,10 @@ func _rasterize(hull: PackedVector2Array, inflate: float) -> void:
continue
var p := cell_center(i)
if (solid and Geometry2D.is_point_in_polygon(p, hull)) or _dist2_to_outline(p, hull) <= r2:
blocked[i] = 1
if id < 0:
blocked[i] = 1
else:
structure_at[i] = id
static func _dist2_to_outline(p: Vector2, hull: PackedVector2Array) -> float:
@ -236,3 +322,99 @@ static func _dist2_to_outline(p: Vector2, hull: PackedVector2Array) -> float:
if hull.size() == 1:
best = p.distance_squared_to(hull[0])
return best
## A distance field computation that can run in slices (step) so a rebuild after a structure
## change spreads over several ticks; the old field stays in use until it finishes. Dial's
## algorithm: BUCKET_COUNT circular buckets as linked lists over an entry pool, valid because no
## edge costs BUCKET_COUNT or more.
class FieldJob:
extends RefCounted
const BUCKET_COUNT := 256
const BUCKET_MASK := BUCKET_COUNT - 1
var nav: FarmNavigation
var dist := PackedInt32Array()
var done := true
## Queue entries processed so far (the slice budget counts these).
var processed: int = 0
var _head := PackedInt32Array()
var _cell := PackedInt32Array()
var _next := PackedInt32Array()
var _top: int = 0
var _pending: int = 0
var _cur: int = 0
func _init(p_nav: FarmNavigation) -> void:
nav = p_nav
var n := nav.cell_count()
dist.resize(n)
_head.resize(BUCKET_COUNT)
_cell.resize(n * 9) # at most 8 relaxations per cell, plus the goals
_next.resize(n * 9)
func start(goals: PackedInt32Array) -> void:
dist.fill(UNREACHABLE)
_head.fill(-1)
_top = 0
_pending = 0
_cur = 0
processed = 0
for g in goals:
if nav.is_walkable(g) and dist[g] != 0:
dist[g] = 0
_push(g, 0)
done = _pending == 0
## Processes up to budget queue entries. Returns true once the field is complete.
func step(budget: int) -> bool:
var blk := nav.blocked
var st := nav.structure_at
var off := nav._offsets
var sa_off := nav._side_a
var sb_off := nav._side_b
var barrier := nav.barrier_cost
var d := dist
var popped := 0
while _pending > 0 and popped < budget:
var b := _cur & BUCKET_MASK
var e := _head[b]
if e == -1:
_cur += 1
continue
_head[b] = _next[e]
_pending -= 1
popped += 1
var c := _cell[e]
if d[c] != _cur:
continue # superseded by a shorter path (lazy deletion)
for k in 8:
var nb := c + off[k]
if blk[nb] == 1:
continue
var cost := COST_ORTH
if k >= 4:
var sa := c + sa_off[k]
var sb := c + sb_off[k]
if blk[sa] == 1 or blk[sb] == 1 or st[sa] >= 0 or st[sb] >= 0:
continue
cost = COST_DIAG
if st[nb] >= 0:
cost += barrier
var nd := _cur + cost
if nd < d[nb]:
d[nb] = nd
_push(nb, nd)
processed += popped
done = _pending == 0
return done
func _push(cell: int, distance: int) -> void:
var b := distance & BUCKET_MASK
_cell[_top] = cell
_next[_top] = _head[b]
_head[b] = _top
_top += 1
_pending += 1

View file

@ -0,0 +1,183 @@
class_name FarmProjectiles
extends Node3D
## Fixed-capacity pooled shots with shared instanced visuals, forked from the prototype's
## ProjectileSystem for the farm (GameConfig, EnemySystem): the corn shooter's kernels and the
## automated defenses' shots. Shots are zero-width rays drawn as a corn kernel streaking
## horizontally at combat height. Each physics tick a shot's whole
## segment is tested against the farm's collision (one physics ray on the world layer) and
## against enemy hit proxies (EnemySystem.sweep_hit); the nearest hit wins, so a building
## shields a thief behind it. No piercing: a hit damages once and frees the shot. Shots also
## expire, and leave when they fly out of the farm. Exhaustion skips the shot and is counted;
## the pool never grows.
const WORLD_LAYER := 1
## A shot struck an enemy (its type) or the farm (enemy_type -1), for sound and effects.
signal hit(at: Vector3, enemy_type: int)
var capacity: int = 0
var active_count: int = 0
# Diagnostics.
var exhausted: int = 0
var fired: int = 0
var hits_enemy: int = 0
var hits_world: int = 0
var blocked_at_muzzle: int = 0
var _px := PackedFloat32Array()
var _pz := PackedFloat32Array()
var _dx := PackedFloat32Array()
var _dz := PackedFloat32Array()
var _life := PackedFloat32Array()
var _damage := PackedInt32Array()
var _cfg: GameConfig
var _enemies: EnemySystem
var _bounds: Rect2
var _renderer: HordeRenderer
var _ray := PhysicsRayQueryParameters3D.new()
func setup(cfg: GameConfig, enemies: EnemySystem, bounds: Rect2, shooter: RID) -> void:
_cfg = cfg
_enemies = enemies
_bounds = bounds
capacity = cfg.projectile_capacity
for a: PackedFloat32Array in [_px, _pz, _dx, _dz, _life]:
a.resize(capacity)
a.fill(0.0)
_damage.resize(capacity)
_ray.collision_mask = WORLD_LAYER
_ray.collide_with_areas = false
_ray.collide_with_bodies = true
_ray.hit_from_inside = true
_ray.exclude = [shooter]
var mesh := BoxMesh.new()
mesh.size = Vector3(0.13, 0.11, 0.34)
var mat := StandardMaterial3D.new()
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.albedo_color = Color(1.0, 0.82, 0.18)
_renderer = HordeRenderer.new()
_renderer.name = "ShotRenderer"
add_child(_renderer)
var aabb := AABB(Vector3(bounds.position.x, 0.0, bounds.position.y), Vector3(bounds.size.x, 4.0, bounds.size.y))
_renderer.setup(mesh, mat, capacity, cfg.combat_height, aabb)
func clear() -> void:
active_count = 0
_renderer.clear()
_renderer.commit(0)
## Fires from the weapon origin (scarecrow center at combat height) through the muzzle. The
## origin -> muzzle segment is tested first, so a barrel poking through a wall resolves there
## instead of spawning the shot on the far side. Returns false if the shot was skipped.
func fire(origin: Vector3, muzzle: Vector3, dir: Vector3, damage: int = 1) -> bool:
if active_count >= capacity:
exhausted += 1
return false
fired += 1
if _resolve_segment(origin.x, origin.z, muzzle.x, muzzle.z, false, damage):
blocked_at_muzzle += 1
return false
var d := active_count
active_count += 1
_px[d] = muzzle.x
_pz[d] = muzzle.z
_dx[d] = dir.x
_dz[d] = dir.z
_life[d] = _cfg.projectile_lifetime
_damage[d] = damage
_renderer.write_new(d, muzzle.x, muzzle.z, dir.x, dir.z, 0.0)
return true
func step(dt: float) -> void:
var step_len := _cfg.projectile_speed * dt
var i := 0
while i < active_count:
var x0 := _px[i]
var z0 := _pz[i]
var x1 := x0 + _dx[i] * step_len
var z1 := z0 + _dz[i] * step_len
if _resolve_segment(x0, z0, x1, z1, true, _damage[i]):
_release(i)
continue
_px[i] = x1
_pz[i] = z1
_life[i] -= dt
if _life[i] <= 0.0 or not _bounds.has_point(Vector2(x1, z1)):
_release(i)
continue
i += 1
## Co-op host: every shot in flight as [x, z, dx, dz] (at most max_shots).
func replica_record(max_shots: int) -> PackedFloat32Array:
var out := PackedFloat32Array()
for i in mini(active_count, max_shots):
out.append_array([_px[i], _pz[i], _dx[i], _dz[i]])
return out
## Co-op partner: the host's shots, which then fly on here until the next update.
func apply_replica(rec: PackedFloat32Array) -> void:
active_count = mini(rec.size() / 4, capacity)
for i in active_count:
_px[i] = rec[i * 4]
_pz[i] = rec[i * 4 + 1]
_dx[i] = rec[i * 4 + 2]
_dz[i] = rec[i * 4 + 3]
_life[i] = _cfg.projectile_lifetime
func advance_replica(dt: float) -> void:
var step_len := _cfg.projectile_speed * dt
for i in active_count:
_px[i] += _dx[i] * step_len
_pz[i] += _dz[i] * step_len
func commit_render() -> void:
_renderer.write_poses(active_count, _px, _pz, _dx, _dz)
_renderer.commit(active_count)
## Resolves the nearest world/enemy hit along a segment. Returns true if something was hit
## (damage is applied for enemy hits). use_motion selects the relative-motion enemy test.
func _resolve_segment(x0: float, z0: float, x1: float, z1: float, use_motion: bool, damage: int) -> bool:
var h := _cfg.combat_height
var world_t := 2.0
_ray.from = Vector3(x0, h, z0)
_ray.to = Vector3(x1, h, z1)
var res := get_world_3d().direct_space_state.intersect_ray(_ray)
if not res.is_empty():
var seg := Vector2(x1 - x0, z1 - z0).length()
var p: Vector3 = res["position"]
world_t = Vector2(p.x - x0, p.z - z0).length() / maxf(seg, 1e-6)
var e := _enemies.sweep_hit(x0, z0, x1, z1, use_motion)
if e >= 0 and _enemies.hit_t <= world_t:
var t := _enemies.type[e]
_enemies.apply_hit(e, damage)
hits_enemy += 1
hit.emit(Vector3(lerpf(x0, x1, _enemies.hit_t), h, lerpf(z0, z1, _enemies.hit_t)), t)
return true
if world_t <= 1.0:
hits_world += 1
hit.emit(Vector3(lerpf(x0, x1, world_t), h, lerpf(z0, z1, world_t)), -1)
return true
return false
func _release(i: int) -> void:
var last := active_count - 1
if i != last:
_px[i] = _px[last]
_pz[i] = _pz[last]
_dx[i] = _dx[last]
_dz[i] = _dz[last]
_life[i] = _life[last]
_damage[i] = _damage[last]
_renderer.move_slot(last, i)
active_count -= 1

View file

@ -0,0 +1 @@
uid://bjfvqmqtt45ww

735
game/scripts/farm_sim.gd Normal file
View file

@ -0,0 +1,735 @@
class_name FarmSim
extends Node
## Drives the farm's simulation in a fixed order each physics tick, after the scarecrow has
## moved (PlayerCharacter runs earlier in the tree):
## scarecrow kit (fear, patch, timers) -> build mode -> interactions (gather, workbench,
## repair, shed drop-off) -> weapons (recharge, switching) -> aim and attack (pitchfork, corn
## shooter, pumpkin bombs) -> enemies (behavior, steering, motion, collision, traps) -> enemy
## melee -> automated defenses -> shots -> pumpkin bombs -> recovery by touch -> animals
## (wander, stray, follow) -> night arrivals (WaveDirector) -> deferred enemy removals ->
## flow-field rebuild slice -> render upload -> campaign phase timers and outcome.
## Whenever the structures change (built, broken, dismantled), the flow fields are rebuilt as
## FieldJobs in slices of flow_slice_cells per tick; thieves keep using the old fields until the
## new ones are complete.
## It builds the farm navigation and the theft flow fields at load (toward the crop rows, the
## inside of the pen, each of the shed's piles, and the farm's edge, where enemies arrive and
## escape: WaveDirector.ground_spawns are the edge cells with a route in), owns the combat and theft systems,
## and applies the phase rules: thieves arrive only at night (the night's NightPlan, run by
## WaveDirector), sunrise makes them retreat (carriers keep running), the end of the dawn grace
## sends the rest off the farm with whatever they carry, returns dropped loot (and loose animals)
## home, and regrows the gather points, and every new morning (also after a retry) resets the
## theft state from the farm state. DayNight lights the phases; PhaseHud, AssetHud, ReviewPanel,
## and the other HUD parts show them. Co-op (CoopSession): a second scarecrow (add_partner) is
## simulated alongside the first, and on the partner's machine the farm is a replica: nothing is
## simulated there, the host's state is applied instead (replica = true), and player, scarecrow,
## combat, and interactions are that machine's own scarecrow's (player 2's).
## FarmAudio plays every sound, Tutorial shows the first
## day's and night's tips, and FarmersReturn plays the ending. Debug: T / G / H send in a
## thief / a crow / a fence breaker at any time.
const SCARECROW_RADIUS := 0.4
const HUNT_INTERVAL := 0.4
const NIGHT_PLANS: Array[String] = [
"res://game/resources/nights/night_1.tres", "res://game/resources/nights/night_2.tres",
"res://game/resources/nights/night_3.tres", "res://game/resources/nights/night_4.tres",
"res://game/resources/nights/night_5.tres",
]
@export var campaign: CampaignController
@export var zones: FarmZones
@export var player: PlayerCharacter
@export var camera: Camera3D
@export var toasts: ToastFeed
@export var alerts: AlertManager
@export var hud: ScarecrowHud
@export var end_panel: EndPanel
@export var resource_hud: ResourceHud
@export var build_hud: BuildHud
@export var phase_hud: PhaseHud
@export var asset_hud: AssetHud
@export var review_panel: ReviewPanel
@export var upgrade_panel: UpgradePanel
@export var sun: DirectionalLight3D
@export var world_environment: WorldEnvironment
var config: GameConfig
var nav := FarmNavigation.new()
var crop_field := PackedInt32Array()
var escape_field := PackedInt32Array()
var animal_field := PackedInt32Array()
## Material -> the field toward that material's pile at the shed.
var supply_fields := {}
var enemies: EnemySystem
var behavior := ThiefBehavior.new()
var loot: LootSystem
var animals: AnimalSystem
var shed_stock: ShedStock
var projectiles: FarmProjectiles
var bombs: PumpkinBombs
var combat: ScarecrowCombat
var scarecrow: Scarecrow
var interactions: Interactions
var structures: StructureSystem
var build: BuildMode
var waves: WaveDirector
var day_night: DayNight
## Every scarecrow in play (player 1's first), the one this machine plays, and the other one
## (co-op; null solo). On the partner's machine the farm is a replica of the host's.
var avatars: Array[Avatar] = []
var local_avatar: Avatar
var partner: Avatar
var replica := false
## Co-op menus don't pause the farm: this machine's scarecrow ignores the input meanwhile.
var local_frozen := false
## Set by CoopSession on the partner's machine: applies the host's state each tick.
var replica_step: Callable
## Co-op: the session with the other machine (idle solo).
var coop: CoopSession
var audio: FarmAudio
var tutorial: Tutorial
var ending: FarmersReturn
## Flow-field rebuild after a structure change: running, and stats of the last one.
var rebuilding := false
var rebuilds: int = 0
var last_rebuild_usec: int = 0
var last_rebuild_ticks: int = 0
var max_rebuild_slice_usec: int = 0
var load_msec: int = 0
## Flow-field jobs by name: "escape" (the farm's edge), "pen" (inside the pen), one per shed pile (by
## material), "breaker" (barriers guarding valuables), and "crops" (the crop rows) only when a
## ground enemy type goes for crops.
var _jobs := {}
var _goals := {} # name -> goal cells (the breaker's are worked out at every rebuild)
var breaker_field := PackedInt32Array()
## Toward the scarecrow, for enemies hunting it: rebuilt in slices (HUNT_INTERVAL apart at most)
## while any enemy fights and the scarecrow has moved to another cell.
var hunt_field := PackedInt32Array()
var characters: EnemyCharacters
var _hunt_job: FarmNavigation.FieldJob
var _hunt_cell: int = -1
var _hunt_wait: float = 0.0
var _rebuild_usec: int = 0
var _rebuild_ticks: int = 0
func _ready() -> void:
var t0 := Time.get_ticks_msec()
config = campaign.config
campaign.set_physics_process(false) # ticked from step(), after the simulation
player.config = config # the sprint
player.campaign = campaign
var shed_zone := zones.zone(FarmZone.Kind.SUPPLY_SHED)
var pen_zone := zones.zone(FarmZone.Kind.ANIMAL_PEN)
shed_stock = ShedStock.new()
shed_stock.name = "ShedStock"
add_child(shed_stock)
shed_stock.setup(campaign, shed_zone, player) # every pile prop in place for the navigation
nav.build(get_parent(), zones.playable.grow(5.0), config.nav_cell_size, config.enemy_radius + config.nav_inflate_margin)
shed_stock.refresh()
var field := zones.zone(FarmZone.Kind.CROP_FIELD)
# Goals are the crop rows themselves (not the whole zone), so a fence around the crops
# encloses every goal and thieves have to break in. Likewise the inside of the pen.
var crop_goals := PackedInt32Array()
for u in zones.crop_units():
var lo := Vector2(INF, INF)
var hi := Vector2(-INF, -INF)
for plant in u.get_children():
var at := Vector2((plant as Node3D).global_position.x, (plant as Node3D).global_position.z)
lo = lo.min(at)
hi = hi.max(at)
crop_goals.append_array(nav.free_cells_in(Rect2(lo, hi - lo).grow(0.3)))
_goals = {"escape": nav.free_cells_on_outline(zones.edge(config.spawn_margin), nav.cell_size * 0.75),
"pen": nav.free_cells_in(pen_zone.rect().grow(-1.0)), "breaker": PackedInt32Array()}
for m in ResourceStore.MATERIALS:
_goals[m] = nav.free_cells_near(PackedVector2Array([shed_stock.spot(m)]), 0.8)
if _ground_takes_crops():
_goals["crops"] = crop_goals
for job_name in _goals:
_jobs[job_name] = FarmNavigation.FieldJob.new(nav)
_hunt_job = FarmNavigation.FieldJob.new(nav)
enemies = EnemySystem.new()
enemies.name = "Enemies"
add_child(enemies)
loot = LootSystem.new()
loot.name = "Loot"
add_child(loot)
animals = AnimalSystem.new()
animals.name = "Animals"
add_child(animals)
behavior.setup(config, nav, loot, crop_field, escape_field, field.rect())
behavior.pen_rect = pen_zone.rect()
behavior.shed_rect = shed_zone.rect()
behavior.farm_rect = zones.playable
characters = EnemyCharacters.new()
characters.name = "EnemyCharacters"
add_child(characters)
var mat := ShaderMaterial.new()
mat.shader = load("res://game/resources/thief.gdshader") as Shader
enemies.setup(config, nav, behavior, EnemySystem.build_bird_mesh(0.0055), mat, zones.playable.grow(12.0))
characters.setup(enemies, config)
enemies.characters = characters
loot.animals = animals
loot.shed_stock = shed_stock
loot.setup(campaign, zones.crop_units(), enemies, AnimalSystem.find_animals(pen_zone).size())
animals.setup(campaign, pen_zone, nav, loot, enemies, player)
if animals.count != config.start_animals:
push_warning("The pen holds %d animals but GameConfig.start_animals is %d" % [animals.count, config.start_animals])
enemies.enemy_removed.connect(loot.on_enemy_removed)
enemies.enemy_removed.connect(_count_removal)
projectiles = FarmProjectiles.new()
projectiles.name = "Shots"
add_child(projectiles)
projectiles.setup(config, enemies, zones.playable.grow(8.0), player.get_rid())
bombs = PumpkinBombs.new()
bombs.name = "Bombs"
add_child(bombs)
bombs.setup(config, enemies)
structures = StructureSystem.new()
structures.name = "Structures"
add_child(structures)
structures.setup(campaign, nav, zones, enemies, projectiles, player)
enemies.structures = structures
behavior.structures = structures
_start_field_rebuild()
_finish_field_rebuild(1 << 30) # at load, all at once
max_rebuild_slice_usec = 0
structures.layout_changed.connect(_start_field_rebuild)
structures.layout_changed.connect(animals.update_pen_open)
animals.update_pen_open()
combat = ScarecrowCombat.new()
combat.name = "Combat"
add_child(combat)
combat.setup(config, player, camera, projectiles)
combat.campaign = campaign
combat.enemies = enemies
combat.bombs = bombs
scarecrow = Scarecrow.new()
scarecrow.name = "Scarecrow"
add_child(scarecrow)
scarecrow.setup(config, campaign, player, enemies, behavior)
interactions = Interactions.new()
interactions.name = "Interactions"
add_child(interactions)
interactions.setup(config, campaign, player, scarecrow, zones)
scarecrow.interactions = interactions
interactions.gathered.connect(func(material: String, amount: int, _n: GatherNode) -> void:
campaign.state.record_event("gathered_" + material, amount))
var first := Avatar.new()
first.slot = 0
first.body = player
first.kit = scarecrow
first.combat = combat
first.interactions = interactions
avatars = [first]
local_avatar = first
waves = WaveDirector.new()
waves.name = "Waves"
add_child(waves)
var plans: Array[NightPlan] = []
for path in NIGHT_PLANS:
plans.append(load(path) as NightPlan)
waves.setup(campaign, enemies, zones, plans)
for c in _goals["escape"]:
if animal_field[c] < FarmNavigation.UNREACHABLE: # not shut in by the props around it
waves.ground_spawns.append(nav.cell_center(c))
campaign.night_length_for = waves.night_length
if sun != null and world_environment != null:
day_night = DayNight.new()
day_night.name = "DayNight"
add_child(day_night)
day_night.characters = characters
day_night.setup(campaign, sun, world_environment.environment, player, mat)
build = BuildMode.new()
build.name = "Build"
add_child(build)
build.setup(config, campaign, player, camera, structures, combat, scarecrow)
build.toggled.connect(func(_on: bool) -> void: combat.reset())
interactions.structures = structures
interactions.build = build
if upgrade_panel != null:
upgrade_panel.setup(campaign, structures, player)
interactions.upgrade_panel = upgrade_panel
upgrade_panel.bought.connect(func(id: String) -> void: # a new weapon goes into the hand
var w := ScarecrowCombat.WEAPON_IDS.find(id)
if w > 0:
combat.equip(w))
if resource_hud != null:
resource_hud.setup(campaign)
resource_hud.structures = structures
if build_hud != null:
build_hud.setup(build, campaign)
if phase_hud != null:
phase_hud.setup(campaign, waves, enemies)
if asset_hud != null:
asset_hud.setup(campaign)
if review_panel != null:
review_panel.setup(campaign, structures)
review_panel.animals = animals
review_panel.waves = waves
review_panel.refresh()
if hud != null:
hud.setup(scarecrow, campaign, combat)
ending = FarmersReturn.new()
ending.name = "FarmersReturn"
add_child(ending)
ending.setup(self)
if end_panel != null:
end_panel.setup(campaign)
end_panel.ending = ending
end_panel.waves = waves
if hud != null and hud.get_parent() != null:
tutorial = Tutorial.new()
tutorial.name = "Tutorial"
hud.get_parent().add_child(tutorial)
tutorial.setup(self)
if end_panel != null:
end_panel.get_parent().move_child(end_panel, -1) # over the banners and the tips
audio = FarmAudio.new()
audio.name = "Audio"
add_child(audio)
audio.setup(self)
coop = CoopSession.new()
coop.name = "Coop" # the same path on both machines (GD-Sync calls it by path)
add_child(coop)
campaign.phase_changed.connect(_on_phase_changed)
campaign.night_ending.connect(_on_night_ending)
if toasts != null:
toasts.loot = loot
loot.loot_event.connect(toasts.on_loot_event)
interactions.message.connect(toasts.push)
if upgrade_panel != null:
upgrade_panel.message.connect(toasts.push)
build.message.connect(toasts.push)
waves.arrived.connect(func(h: int, at: Vector2) -> void:
toasts.push(arrival_message(enemies.type[enemies.resolve_handle(h)], zones.side_of(at)), Color(1.0, 0.75, 0.55)))
structures.destroyed.connect(func(_id: int, type: String, _at: Vector3) -> void:
toasts.push("Breach! A %s was broken" % StructureSystem.NAMES[type].to_lower(), Color(1.0, 0.35, 0.3)))
animals.pen_changed.connect(func(open: bool) -> void:
if open and campaign.state.phase != CampaignController.Phase.MORNING:
toasts.push("The pen is open: animals will wander out at night", Color(1.0, 0.55, 0.35)))
scarecrow.patch_denied.connect(func(missing: Dictionary) -> void:
toasts.push("Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5)))
if alerts != null:
alerts.setup(self)
load_msec = Time.get_ticks_msec() - t0
func _physics_process(dt: float) -> void:
step(dt)
func step(dt: float) -> void:
if replica:
_step_replica(dt)
return
if not campaign.is_over():
var first := avatars[0]
var p := first.position()
behavior.scarecrow = p if first.kit.alive else Vector2(INF, INF)
var second := avatars[1] if avatars.size() > 1 else null
behavior.scarecrow2 = second.position() if second != null and second.kit.alive else Vector2(INF, INF)
enemies.scarecrow2 = behavior.scarecrow2
for a in avatars:
a.kit.step(dt)
if not local_frozen:
build.step(dt)
for a in avatars:
a.interactions.step(dt)
for a in avatars:
a.combat.tick(dt, a.is_local and not build.active and not local_frozen and not _menu_open())
for a in avatars:
var building := build.active if a.is_local else (a.remote != null and a.remote.build_active)
if a.kit.can_shoot() and a.interactions.can_shoot() and not building:
a.combat.step(dt)
enemies.step(dt, p, SCARECROW_RADIUS)
for a in avatars:
if a.kit.alive:
enemies.evaluate_attacks(a.position(), SCARECROW_RADIUS, a.kit)
structures.step(dt)
projectiles.step(dt)
bombs.step(dt)
for a in avatars:
if a.kit.alive:
loot.step(a.position(), a.slot)
animals.step(dt)
waves.step(dt)
enemies.commit_removals()
if rebuilding:
_finish_field_rebuild(config.flow_slice_cells)
_update_hunt(dt)
enemies.commit_render()
projectiles.commit_render()
campaign.tick(dt)
## The partner's machine: only its own scarecrow acts locally (aiming, build mode as a UI); the
## host's state is applied (replica_step), then drawn.
func _step_replica(dt: float) -> void:
if replica_step.is_valid():
replica_step.call(dt)
combat.tick(dt, not build.active and not local_frozen and not _menu_open())
bombs.step(dt) # the host's throws, drawn
if not campaign.is_over() and scarecrow.alive and not local_frozen:
build.step(dt)
if interactions.can_shoot() and not build.active and not _menu_open():
combat.step(dt)
enemies.commit_render()
projectiles.commit_render()
func _menu_open() -> bool:
return upgrade_panel != null and upgrade_panel.is_open
## Co-op: while this machine's scarecrow is down, the camera watches the partner's.
func _process(_delta: float) -> void:
if partner == null or not (camera is FollowCamera):
return
var other := avatars[0] if local_avatar == partner else partner
var want := local_avatar.body if local_avatar.kit.alive or not other.kit.alive else other.body
if (camera as FollowCamera).target != want:
(camera as FollowCamera).target = want
## Co-op: while a menu is up, this machine's scarecrow takes no input (its kit, hands, and gun
## read an empty RemoteControls; its body doesn't move).
func freeze_local(on: bool) -> void:
local_frozen = on
var a := local_avatar
var none := RemoteControls.new() if on else null
a.kit.remote = none
a.interactions.remote = none
a.combat.remote = none
a.body.input_enabled = not on
if on:
build.set_active(false)
## Co-op: brings player 2's scarecrow onto the farm (next to player 1's): a second body with its
## own kit, gun, and hands. local: whether this machine plays it (the partner's machine) or the
## partner's game does (the host: then it reads remote). Returns it.
func add_partner(local: bool, name_text: String = "") -> Avatar:
if partner != null:
return partner
var a := Avatar.new()
a.slot = 1
a.is_local = local
a.player_name = name_text
var body := (load("res://game/scenes/player.tscn") as PackedScene).instantiate() as PlayerCharacter
body.name = "Player2"
get_parent().add_child(body)
body.global_position = player.global_position + Vector3(1.8, 0.0, 0.6)
body.set_tint(Color(0.55, 0.75, 1.0))
body.config = config
body.campaign = campaign
a.body = body
a.kit = Scarecrow.new()
a.kit.name = "Scarecrow2"
a.kit.slot = 1
add_child(a.kit)
a.kit.setup(config, campaign, body, enemies, behavior)
a.combat = ScarecrowCombat.new()
a.combat.name = "Combat2"
add_child(a.combat)
a.combat.setup(config, body, camera, projectiles)
a.combat.campaign = campaign
a.combat.enemies = enemies
a.combat.bombs = bombs
a.combat.show_marker = local
a.interactions = Interactions.new()
a.interactions.name = "Interactions2"
add_child(a.interactions)
a.interactions.setup(config, campaign, body, a.kit, zones)
a.interactions.structures = structures
a.interactions.show_labels = local
a.kit.interactions = a.interactions
a.interactions.gathered.connect(func(material: String, amount: int, _n: GatherNode) -> void:
if not replica:
campaign.state.record_event("gathered_" + material, amount))
if not local:
a.remote = RemoteControls.new()
a.kit.remote = a.remote
a.combat.remote = a.remote
a.interactions.remote = a.remote
avatars.append(a)
partner = a
animals.leaders.append(body)
structures.partner = body
if day_night != null:
day_night.add_lantern(body)
if audio != null:
audio.wire_avatar(a)
if not replica:
var s := campaign.state
if not s.coop:
s.coop = true
s.partner_max_hp = s.scarecrow_max_hp
s.partner_hp = s.scarecrow_max_hp
return a
## Co-op: player 2 left. Their scarecrow goes; if player 1's is down, that's the end of the night.
func remove_partner() -> void:
if partner == null:
return
var a := partner
partner = null
avatars.erase(a)
if camera is FollowCamera and (camera as FollowCamera).target == a.body:
(camera as FollowCamera).target = local_avatar.body
animals.leaders.erase(a.body)
if structures.partner == a.body:
structures.partner = null
for n: Node in [a.kit, a.combat, a.interactions, a.body]:
if is_instance_valid(n):
n.queue_free()
if not replica:
campaign.state.coop = false
behavior.scarecrow2 = Vector2(INF, INF)
enemies.scarecrow2 = Vector2(INF, INF)
## Makes another scarecrow this machine's own (the partner's machine plays player 2): the HUD,
## the camera, build mode, the upgrade menu, sounds, and tips follow it.
func set_local(a: Avatar) -> void:
for other in avatars:
other.is_local = other == a
other.combat.show_marker = other == a
other.interactions.show_labels = other == a
local_avatar = a
player = a.body
scarecrow = a.kit
combat = a.combat
interactions = a.interactions
interactions.structures = structures
interactions.build = build
interactions.upgrade_panel = upgrade_panel
build.player = a.body
build.combat = a.combat
build.kit = a.kit
if upgrade_panel != null:
upgrade_panel.player = a.body
if camera is FollowCamera:
(camera as FollowCamera).target = a.body
(camera as FollowCamera).snap_to_target()
if hud != null:
hud.retarget(a.kit, a.combat)
if audio != null:
audio.focus = a.body
if alerts != null:
alerts.player = a.body
shed_stock.player = a.body
## Restarts every flow-field job for the current structure layout.
func _start_field_rebuild() -> void:
_goals["breaker"] = _breaker_goals()
for job_name in _jobs:
(_jobs[job_name] as FarmNavigation.FieldJob).start(_goals[job_name])
rebuilding = true
_rebuild_usec = 0
_rebuild_ticks = 0
## Runs up to budget cells of the rebuild, one job after another; swaps the new fields in once
## all are complete.
func _finish_field_rebuild(budget: int) -> void:
var t0 := Time.get_ticks_usec()
var left := budget
for job: FarmNavigation.FieldJob in _jobs.values():
if left <= 0:
break
if not job.done:
var before := job.processed
job.step(left)
left -= job.processed - before
var slice := Time.get_ticks_usec() - t0
_rebuild_usec += slice
_rebuild_ticks += 1
max_rebuild_slice_usec = maxi(max_rebuild_slice_usec, slice)
if _jobs.values().all(func(j: FarmNavigation.FieldJob) -> bool: return j.done):
if _jobs.has("crops"):
crop_field = _jobs["crops"].dist.duplicate()
escape_field = _jobs["escape"].dist.duplicate()
animal_field = _jobs["pen"].dist.duplicate()
breaker_field = _jobs["breaker"].dist.duplicate()
for m in ResourceStore.MATERIALS:
supply_fields[m] = _jobs[m].dist.duplicate()
behavior.crop_field = crop_field
behavior.escape_field = escape_field
behavior.animal_field = animal_field
behavior.supply_fields = supply_fields
behavior.breaker_field = breaker_field
animals.escape_field = escape_field
rebuilding = false
rebuilds += 1
last_rebuild_usec = _rebuild_usec
last_rebuild_ticks = _rebuild_ticks
## Sends a ground thief in at a random point along the farm's edge (or at the given point), going
## for the given target (a LootSystem.Category, or LootSystem.ANY: its type's targets by weight).
## Returns its handle.
func spawn_thief(want: int = LootSystem.ANY, at: Vector2 = WaveDirector.ANYWHERE) -> int:
return spawn_enemy(EnemySystem.TYPE_THIEF, want, at)
## Sends an enemy of any type in at a random point along the farm's edge (or at the given
## point). Returns its handle.
func spawn_enemy(type: int, want: int = LootSystem.ANY, at: Vector2 = WaveDirector.ANYWHERE) -> int:
return waves.spawn(type, want, at)
## Counts the night's kills by type, and the enemies that got away with loot.
func _count_removal(handle: int, reason: EnemySystem.Removal, _x: float, _z: float, _carry: int, _target: int) -> void:
match reason:
EnemySystem.Removal.KILLED:
var d := enemies.resolve_handle(handle)
if d >= 0:
campaign.state.record_event("killed_" + EnemySystem.TYPE_NAMES[enemies.type[d]])
EnemySystem.Removal.ESCAPED:
campaign.state.record_event("escaped")
## Keeps the field toward the scarecrow fresh while anything is fighting it.
func _update_hunt(dt: float) -> void:
_hunt_wait = maxf(_hunt_wait - dt, 0.0)
if not _hunt_job.done:
if _hunt_job.step(config.flow_slice_cells):
hunt_field = _hunt_job.dist.duplicate()
behavior.hunt_field = hunt_field
return
var hunting := false
for d in enemies.active_count:
if enemies.alive[d] == 1 and enemies.state[d] == ThiefBehavior.State.FIGHT:
hunting = true
break
if not hunting:
return
# Toward every scarecrow standing (each enemy follows it to the nearer one).
var goals := PackedInt32Array()
var key := 0
for a in avatars:
if not a.kit.alive:
continue
var p := a.position()
var c := nav.nearest_free(nav.cell_of(p.x, p.y), 64)
if c >= 0:
goals.append(c)
key = key * 100003 + c + 1
if goals.is_empty() or (key == _hunt_cell and not hunt_field.is_empty()) or _hunt_wait > 0.0:
return
_hunt_cell = key
_hunt_wait = HUNT_INTERVAL
_hunt_job.start(goals)
## Whether any ground enemy type goes for crops (then the crop rows get a flow field).
func _ground_takes_crops() -> bool:
for type_name: String in config.enemy_types:
var row := config.enemy(type_name)
if not bool(row.get("flying", false)) and (row.get("targets", []) as Array).has("crops"):
return true
return false
## Where fence breakers head: the walkable cells next to every barrier within guard_range of the
## crop rows, the pen, or the shed (or next to any barrier, when none guards anything).
func _breaker_goals() -> PackedInt32Array:
if structures == null:
return PackedInt32Array()
var areas: Array[Rect2] = [zones.zone(FarmZone.Kind.CROP_FIELD).rect(), zones.zone(FarmZone.Kind.ANIMAL_PEN).rect(),
zones.zone(FarmZone.Kind.SUPPLY_SHED).rect()]
var guarding: Array[Dictionary] = []
var barriers: Array[Dictionary] = []
for e in campaign.state.structures:
if not structures.blocks(e["type"]):
continue
barriers.append(e)
var at := Vector2(e["x"], e["z"])
for a in areas:
if a.grow(config.guard_range).has_point(at):
guarding.append(e)
break
var out := PackedInt32Array()
for e in (guarding if not guarding.is_empty() else barriers):
var outline := StructureSystem.corners(structures.footprint(e["type"], e["x"], e["z"], e["rot"]))
var lo := outline[0]
var hi := outline[0]
for q in outline:
lo = lo.min(q)
hi = hi.max(q)
for c in nav.free_cells_in(Rect2(lo, hi - lo).grow(1.2)):
if nav.is_walkable(c) and StructureSystem._distance_to_outline(nav.cell_center(c), outline) <= 1.1:
out.append(c)
return out
## "A crow flew in from the east", "A fence breaker came in from the south-west" (side:
## FarmZones.side_of the arrival point).
static func arrival_message(type: int, side: String) -> String:
var from := " from the %s" % side if side != "" else ""
match type:
EnemySystem.TYPE_CROW:
return "A crow flew in" + from
EnemySystem.TYPE_BREAKER:
return "A fence breaker came in" + from
return "A thief slipped in" + from
func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
match phase:
CampaignController.Phase.DUSK, CampaignController.Phase.NIGHT:
if toasts != null and scarecrow.alive and not zones.is_inside_fence(player.global_position):
toasts.push("You're outside the fence: get back in before nightfall!" if phase == CampaignController.Phase.DUSK
else "Night has fallen and you're outside the fence!", Color(1.0, 0.55, 0.35))
CampaignController.Phase.DAWN:
behavior.retreat_all(enemies)
if enemies.alive_count() > 0 and toasts != null:
toasts.push("Sunrise! The thieves are running for it", Color(1.0, 0.85, 0.6))
CampaignController.Phase.MORNING:
if partner == null and not replica:
campaign.state.coop = false # a co-op save continued alone: solo rules
enemies.clear()
projectiles.clear()
bombs.clear()
loot.sync_from_state()
animals.sync_from_state()
structures.sync_from_state()
shed_stock.refresh()
build.set_active(false)
for a in avatars:
a.combat.ready_for_morning()
a.kit.reset_for_morning()
a.interactions.cancel()
if a.remote != null:
a.remote.release()
if upgrade_panel != null:
upgrade_panel.close()
if review_panel != null:
review_panel.refresh() # after the farm is back in sync (the pen's gate)
## End of the dawn grace: whoever is still on the farm leaves (carrying their loot off), and
## loot still lying on the ground goes home (crops to their plots, sacks to the shed, loose
## animals to the pen).
func _on_night_ending() -> void:
enemies.remove_all()
loot.return_dropped()
interactions.regen_overnight()
func _unhandled_input(event: InputEvent) -> void:
var key := event as InputEventKey
if key == null or not key.pressed or key.echo or not OS.is_debug_build():
return
match key.physical_keycode:
KEY_T:
spawn_enemy(EnemySystem.TYPE_THIEF)
KEY_G:
spawn_enemy(EnemySystem.TYPE_CROW)
KEY_H:
spawn_enemy(EnemySystem.TYPE_BREAKER)

View file

@ -0,0 +1 @@
uid://c6auf64ahke4k

View file

@ -1,16 +1,44 @@
class_name FarmState
extends RefCounted
## The single source of truth for everything that persists through the vacation: farm assets,
## scarecrow health, campaign progress, and the nightly loss records. Scene nodes only display
## it. to_dict() / from_dict() round-trip every field, also through JSON (the morning retry
## snapshot now, save games later). Plain asset counts become per-unit records in Step 3.
## scarecrow health, campaign progress, and the nightly records. Scene nodes only display it.
## to_dict() / from_dict() round-trip every field, also through JSON (the morning retry
## snapshot and the save game, SaveGame). Crops and animals are per-unit records (lost ids, 1..total);
## supplies are the supply shed's stock of construction materials (the shed and the scarecrow's
## pouch live in resources). Gather points below full, bought upgrades, and the built structures
## are kept too.
const VERSION := 1
const VERSION := 4
const KEYS: Array[String] = [
"night", "nights_survived", "phase", "phase_time_left", "scarecrow_max_hp", "scarecrow_hp",
"crops_total", "crops", "animals_total", "animals", "supplies_total", "supplies", "night_log",
"crops_total", "lost_crops", "animals_total", "lost_animals", "supplies_total", "shed_raided",
"resources", "gather_charges", "upgrades", "structures", "next_structure_id", "night_events",
"night_log", "coop", "partner_max_hp", "partner_hp",
]
const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp"]
## Events counted from the morning to the end of the dawn grace, copied into the night's log
## entry when it closes. Theft: supply events count material units, the others crop units or
## animals. Then enemies killed by type and those that escaped with loot; the scarecrow's damage
## taken (HP) and patches; structures built, damaged (HP lost), destroyed, and repaired;
## upgrades bought; and materials gathered (into the pouch) and spent, per material.
const EVENTS: Array[String] = [
"crops_stolen", "crops_recovered", "animals_stolen", "animals_strayed", "animals_recovered",
"supplies_stolen", "supplies_recovered", "supplies_lost",
"killed_crow", "killed_thief", "killed_breaker", "escaped",
"scarecrow_damage", "patches",
"structures_built", "structures_damaged", "structures_destroyed", "repairs", "upgrades_bought",
"gathered_wood", "gathered_scrap", "gathered_straw", "spent_wood", "spent_scrap", "spent_straw",
]
## The keys of a night_log entry: the night, crops and animals lost, then every EVENTS key.
const LOG_KEYS: Array[String] = [
"night", "crops_lost", "animals_lost",
"crops_stolen", "crops_recovered", "animals_stolen", "animals_strayed", "animals_recovered",
"supplies_stolen", "supplies_recovered", "supplies_lost",
"killed_crow", "killed_thief", "killed_breaker", "escaped",
"scarecrow_damage", "patches",
"structures_built", "structures_damaged", "structures_destroyed", "repairs", "upgrades_bought",
"gathered_wood", "gathered_scrap", "gathered_straw", "spent_wood", "spent_scrap", "spent_straw",
]
const LOG_KEYS: Array[String] = ["night", "crops_lost", "animals_lost", "supplies_lost"]
## Current night (1-based). The morning, day, dusk, night, and dawn of a cycle all belong to it.
var night: int = 1
@ -21,17 +49,64 @@ var phase_time_left: float = 0.0
var scarecrow_max_hp: int = 10
var scarecrow_hp: int = 10
## Co-op (a second scarecrow, player 2, is on the farm) and that scarecrow's health. Upgrades to
## max health apply to both. In co-op a scarecrow at 0 HP is out until the morning, and only both
## down at once is a Game Over.
var coop := false
var partner_max_hp: int = 10
var partner_hp: int = 10
## Per category: the starting count (0 = not in play yet) and what remains on the farm.
## Per category: the starting count (0 = not in play) and what remains on the farm.
var crops_total: int = 0
var crops: int = 0
## Ids of the crop units that are gone for good (carried off the farm), sorted.
var lost_crops := PackedInt32Array()
var animals_total: int = 0
var animals: int = 0
## Ids of the animals that are gone for good (carried or wandered off the farm), sorted.
var lost_animals := PackedInt32Array()
## The shed's stock when the vacation started (0 = supplies not in play).
var supplies_total: int = 0
var supplies: int = 0
## The shed was last emptied by thieves (not by spending). Only then do empty supplies count
## toward a stripped farm (D2); storing anything clears it (settle_supplies).
var shed_raided := false
## Material units carried off by thieves or lying dropped, still on the farm. Not saved: the dawn
## grace ends with none (LootSystem keeps it).
var supplies_in_transit: int = 0
## One entry per completed night, closed when its dawn ends:
## {"night", "crops_lost", "animals_lost", "supplies_lost"}.
## Crop units still on the farm (home, targeted, carried, or dropped). Derived from lost_crops;
## change it through lose_crop().
var crops: int:
get:
return crops_total - lost_crops.size()
set(_value):
push_error("FarmState.crops is derived from lost_crops; use lose_crop()")
## Animals still on the farm (in the pen, loose, following, or carried). Derived from lost_animals.
var animals: int:
get:
return animals_total - lost_animals.size()
set(_value):
push_error("FarmState.animals is derived from lost_animals; use lose_animal()")
## Supplies still on the farm: the shed's stock plus what thieves carry or dropped.
var supplies: int:
get:
return resources.shed_total() + supplies_in_transit
set(_value):
push_error("FarmState.supplies is derived from the shed's stock")
## Wood, scrap, and straw in the supply shed and in the scarecrow's pouch.
var resources := ResourceStore.new()
## Charges of the gather points that are below full (GatherNode name -> charges left); a point
## missing here is full.
var gather_charges: Dictionary = {}
## Bought upgrades (id -> level).
var upgrades: Dictionary = {}
## Built structures: {"id", "type", "x", "z" (world position, on the 0.5 m build grid), "rot"
## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow)}.
var structures: Array[Dictionary] = []
var next_structure_id: int = 1
## Event counts of the day and night in progress (EVENTS keys), since this morning.
var night_events: Dictionary = {}
## One entry per completed night, closed when its dawn ends (LOG_KEYS).
var night_log: Array[Dictionary] = []
@ -39,24 +114,117 @@ static func create(cfg: GameConfig) -> FarmState:
var s := FarmState.new()
s.scarecrow_max_hp = cfg.scarecrow_max_hp
s.scarecrow_hp = cfg.scarecrow_max_hp
s.partner_max_hp = cfg.scarecrow_max_hp
s.partner_hp = cfg.scarecrow_max_hp
s.crops_total = cfg.start_crops
s.crops = cfg.start_crops
s.animals_total = cfg.start_animals
s.animals = cfg.start_animals
s.supplies_total = cfg.start_supplies
s.supplies = cfg.start_supplies
s.resources.pouch_capacity = cfg.pouch_capacity
s.resources.shed = {"wood": cfg.start_wood, "scrap": cfg.start_scrap, "straw": cfg.start_straw}
s.supplies_total = s.resources.shed_total()
for e in cfg.start_structures:
var t := String(e["type"])
s.structures.append({"id": s.next_structure_id, "type": t, "x": float(e["x"]), "z": float(e["z"]),
"rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t)})
s.next_structure_id += 1
return s
## D2: every category in play is gone. Categories not in play (starting count 0) are ignored.
func is_crop_lost(unit_id: int) -> bool:
return lost_crops.has(unit_id)
## Marks a crop unit as gone for good. Returns false for unknown or already-lost units.
func lose_crop(unit_id: int) -> bool:
if unit_id < 1 or unit_id > crops_total or lost_crops.has(unit_id):
return false
lost_crops.append(unit_id)
lost_crops.sort()
return true
func lose_all_crops() -> void:
for id in range(1, crops_total + 1):
lose_crop(id)
func is_animal_lost(id: int) -> bool:
return lost_animals.has(id)
## Marks an animal as gone for good. Returns false for unknown or already-lost animals.
func lose_animal(id: int) -> bool:
if id < 1 or id > animals_total or lost_animals.has(id):
return false
lost_animals.append(id)
lost_animals.sort()
return true
func lose_all_animals() -> void:
for id in range(1, animals_total + 1):
lose_animal(id)
## Debug and tests: every asset gone, the shed emptied by thieves.
func strip() -> void:
lose_all_crops()
lose_all_animals()
for m in ResourceStore.MATERIALS:
resources.shed[m] = 0
supplies_in_transit = 0
shed_raided = true
func record_event(key: String, amount: int = 1) -> void:
night_events[key] = int(night_events.get(key, 0)) + amount
## Pays a cost from the pouch and shed (ResourceStore.pay) and counts what was spent. Every
## purchase (building, repairs, patching, upgrades) goes through here.
func pay(cost: Dictionary) -> bool:
if not resources.pay(cost):
return false
for m in cost:
if int(cost[m]) > 0:
record_event("spent_" + String(m), int(cost[m]))
return true
## Every night_log entry's EVENTS key added up (plus crops_lost and animals_lost).
func totals() -> Dictionary:
var out := {}
for key in LOG_KEYS:
if key != "night":
out[key] = 0
for entry in night_log:
for key in out:
out[key] += int(entry.get(key, 0))
return out
## Called every tick before the outcome check: once the shed holds anything again, it no longer
## counts as raided.
func settle_supplies() -> void:
if shed_raided and resources.shed_total() > 0:
shed_raided = false
## D2: every category in play is gone. Categories not in play are ignored. Supplies only count
## as gone when thieves emptied the shed: spending the last materials doesn't strip the farm.
func is_stripped() -> bool:
var in_play := false
for pair: Vector2i in [Vector2i(crops_total, crops), Vector2i(animals_total, animals),
Vector2i(supplies_total, supplies)]:
if pair.x > 0:
in_play = true
if pair.y > 0:
return false
if crops_total > 0:
in_play = true
if crops > 0:
return false
if animals_total > 0:
in_play = true
if animals > 0:
return false
if supplies_total > 0:
in_play = true
if supplies > 0 or not shed_raided:
return false
return in_play
@ -64,23 +232,34 @@ func asset_counts() -> PackedInt32Array:
return PackedInt32Array([crops, animals, supplies])
## Records the night that just ended, given the asset counts when it started.
## Records the night that just ended, given the asset counts when it started, and clears the
## night's event counts. Crops and animals lost are what's gone since then; supplies lost are the
## units carried off (the shed's stock also changes by storing and spending).
func log_night(start: PackedInt32Array) -> void:
var now := asset_counts()
if start.size() != now.size():
start = now
night_log.append({
var entry := {
"night": night,
"crops_lost": maxi(start[0] - now[0], 0),
"animals_lost": maxi(start[1] - now[1], 0),
"supplies_lost": maxi(start[2] - now[2], 0),
})
}
for key in EVENTS:
entry[key] = int(night_events.get(key, 0))
night_log.append(entry)
night_events.clear()
func to_dict() -> Dictionary:
var entries: Array = []
for entry in night_log:
entries.append(entry.duplicate())
var lost: Array = []
for id in lost_crops:
lost.append(id)
var lost_a: Array = []
for id in lost_animals:
lost_a.append(id)
return {
"version": VERSION,
"night": night,
@ -90,12 +269,21 @@ func to_dict() -> Dictionary:
"scarecrow_max_hp": scarecrow_max_hp,
"scarecrow_hp": scarecrow_hp,
"crops_total": crops_total,
"crops": crops,
"lost_crops": lost,
"animals_total": animals_total,
"animals": animals,
"lost_animals": lost_a,
"supplies_total": supplies_total,
"supplies": supplies,
"shed_raided": shed_raided,
"resources": resources.to_dict(),
"gather_charges": gather_charges.duplicate(),
"upgrades": upgrades.duplicate(),
"structures": _structures_copy(),
"next_structure_id": next_structure_id,
"night_events": night_events.duplicate(),
"night_log": entries,
"coop": coop,
"partner_max_hp": partner_max_hp,
"partner_hp": partner_hp,
}
@ -110,7 +298,11 @@ static func from_dict(d: Dictionary) -> FarmState:
var phase_value := int(d["phase"])
if not CampaignController.Phase.values().has(phase_value):
return null
if not d["night_log"] is Array:
if not (d["night_log"] is Array and d["lost_crops"] is Array and d["lost_animals"] is Array and d["night_events"] is Dictionary
and d["gather_charges"] is Dictionary and d["upgrades"] is Dictionary and d["structures"] is Array):
return null
var store := ResourceStore.from_dict(d["resources"])
if store == null:
return null
var s := FarmState.new()
s.night = int(d["night"])
@ -119,12 +311,52 @@ static func from_dict(d: Dictionary) -> FarmState:
s.phase_time_left = float(d["phase_time_left"])
s.scarecrow_max_hp = int(d["scarecrow_max_hp"])
s.scarecrow_hp = int(d["scarecrow_hp"])
s.coop = bool(d["coop"])
s.partner_max_hp = int(d["partner_max_hp"])
s.partner_hp = int(d["partner_hp"])
s.crops_total = int(d["crops_total"])
s.crops = int(d["crops"])
for id in d["lost_crops"]:
if not s.lose_crop(int(id)):
return null # unknown or duplicate unit id
s.animals_total = int(d["animals_total"])
s.animals = int(d["animals"])
for id in d["lost_animals"]:
if not s.lose_animal(int(id)):
return null
s.supplies_total = int(d["supplies_total"])
s.supplies = int(d["supplies"])
s.shed_raided = bool(d["shed_raided"])
s.resources = store
for key in d["gather_charges"]:
if int(d["gather_charges"][key]) < 0:
return null
s.gather_charges[String(key)] = int(d["gather_charges"][key])
for key in d["upgrades"]:
if int(d["upgrades"][key]) < 0:
return null
s.upgrades[String(key)] = int(d["upgrades"][key])
s.next_structure_id = int(d["next_structure_id"])
var ids := {}
for raw in d["structures"]:
if not raw is Dictionary:
return null
var e := {}
for key in STRUCTURE_KEYS:
if not (raw as Dictionary).has(key):
return null
e["id"] = int(raw["id"])
e["type"] = String(raw["type"])
e["x"] = float(raw["x"])
e["z"] = float(raw["z"])
e["rot"] = int(raw["rot"])
e["hp"] = int(raw["hp"])
if e["id"] < 1 or e["id"] >= s.next_structure_id or ids.has(e["id"]) or e["type"] == "" \
or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0:
return null
ids[e["id"]] = true
s.structures.append(e)
for key in d["night_events"]:
if not EVENTS.has(String(key)):
return null
s.night_events[String(key)] = int(d["night_events"][key])
for raw in d["night_log"]:
if not raw is Dictionary:
return null
@ -137,10 +369,26 @@ static func from_dict(d: Dictionary) -> FarmState:
return s if s.is_valid() else null
## The structure record with this id, or an empty dictionary.
func structure(id: int) -> Dictionary:
for e in structures:
if int(e["id"]) == id:
return e
return {}
func _structures_copy() -> Array:
var out: Array = []
for e in structures:
out.append(e.duplicate())
return out
func is_valid() -> bool:
return night >= 1 and nights_survived >= 0 and nights_survived <= night \
and phase_time_left >= 0.0 \
and scarecrow_max_hp >= 1 and scarecrow_hp >= 0 and scarecrow_hp <= scarecrow_max_hp \
and crops >= 0 and crops <= crops_total \
and animals >= 0 and animals <= animals_total \
and supplies >= 0 and supplies <= supplies_total
and partner_max_hp >= 1 and partner_hp >= 0 and partner_hp <= partner_max_hp \
and crops_total >= 0 and lost_crops.size() <= crops_total \
and animals_total >= 0 and lost_animals.size() <= animals_total \
and supplies_total >= 0 and supplies_in_transit >= 0

View file

@ -4,6 +4,9 @@ extends Node3D
## One purposeful area of the farm: an axis-aligned rectangle on the ground, centered on this
## node (rotation is ignored). Zones live under Zones/ in farm.tscn, and FarmZones looks them
## up by position. In the editor each zone draws a translucent box so the layout is visible.
## Outside zones are gathering areas beyond the farm's edge (north and east of it through the
## fence's gaps, south of it across open ground): there can be several of a kind, and
## FarmZones.zone(kind) only returns the farm's own.
enum Kind { CROP_FIELD, ANIMAL_PEN, SUPPLY_SHED, WORK_AREA, WOOD, SCRAP, STRAW }
@ -19,6 +22,8 @@ enum Kind { CROP_FIELD, ANIMAL_PEN, SUPPLY_SHED, WORK_AREA, WOOD, SCRAP, STRAW }
set(value):
tint = value
_update_preview()
## Beyond the farm's fence (a gathering area outside).
@export var outside := false
var _preview: MeshInstance3D

View file

@ -1,28 +1,37 @@
class_name FarmZones
extends Node3D
## The Zones/ node of farm.tscn: every FarmZone (with the props that belong to it), the
## perimeter and its markers, and the crop units, plus lookups by position. The playable map is
## the rectangle inside the perimeter fence; the rest of the farm is out-of-bounds scenery.
## perimeter (what's left of its fence, on the north and east sides, and that fence's gaps), and
## the crop units, plus lookups by position. The playable map is the farm's rectangle (where
## building, navigation, and the night happen). Its edge is where enemies come from and go:
## edge(margin) is the rectangle that far outside it, and enemies arrive at random points along it
## (WaveDirector). Beyond the map the scarecrow can roam out to the old farm's outer fences
## (Perimeter/PlayerBounds), where outside zones hold more to gather.
@export var playable := Rect2(-13.0, -45.0, 60.0, 60.0)
## Where the scarecrow can go: out to the old farm's outer fences.
@export var roam := Rect2(-27.6, -59.6, 82.4, 106.6)
## The farm's own zones (inside the fence).
func zones() -> Array[FarmZone]:
var out: Array[FarmZone] = []
for child in get_children():
if child is FarmZone:
if child is FarmZone and not (child as FarmZone).outside:
out.append(child)
return out
## The zone containing a world position (zones don't overlap), or null between zones.
## The zone containing a world position, inside the fence or out (zones don't overlap), or null
## between zones.
func zone_at(point: Vector3) -> FarmZone:
for zone in zones():
for zone in zones() + outside_zones():
if zone.contains(point):
return zone
return null
## The farm's own zone of a kind (never an outside one).
func zone(kind: FarmZone.Kind) -> FarmZone:
for z in zones():
if z.kind == kind:
@ -30,14 +39,76 @@ func zone(kind: FarmZone.Kind) -> FarmZone:
return null
func markers(kind: FarmMarker.Kind) -> Array[FarmMarker]:
## The gathering areas beyond the fence.
func outside_zones() -> Array[FarmZone]:
var out: Array[FarmZone] = []
for child in get_children():
if child is FarmZone and (child as FarmZone).outside:
out.append(child)
return out
func is_inside_fence(point: Vector3) -> bool:
return playable.has_point(Vector2(point.x, point.z))
## The gaps in what's left of the perimeter fence.
func gaps() -> Array[FarmMarker]:
var out: Array[FarmMarker] = []
for node in find_children("*", "Marker3D", true, false):
if node is FarmMarker and (node as FarmMarker).kind == kind:
if node is FarmMarker:
out.append(node)
return out
## The rectangle margin meters outside the playable map's edge.
func edge(margin: float) -> Rect2:
return playable.grow(margin)
## The point a share t (0..1, wrapping) of the way around edge(margin), clockwise from its
## north-west corner.
func edge_point(t: float, margin: float) -> Vector2:
var r := edge(margin)
var d := fposmod(t, 1.0) * 2.0 * (r.size.x + r.size.y)
if d < r.size.x:
return r.position + Vector2(d, 0.0)
d -= r.size.x
if d < r.size.y:
return Vector2(r.end.x, r.position.y + d)
d -= r.size.y
if d < r.size.x:
return Vector2(r.end.x - d, r.end.y)
return Vector2(r.position.x, r.end.y - (d - r.size.x))
## The nearest point on a rectangle's outline to p (from inside: straight out the nearest side).
static func nearest_on_outline(r: Rect2, p: Vector2) -> Vector2:
var q := p.clamp(r.position, r.end)
var to_side := [q.x - r.position.x, r.end.x - q.x, q.y - r.position.y, r.end.y - q.y]
match to_side.find(to_side.min()):
0:
q.x = r.position.x
1:
q.x = r.end.x
2:
q.y = r.position.y
_:
q.y = r.end.y
return q
## Which side of the farm p is on, as the HUD says it: "north", "south-east", ... (the map split
## in thirds each way; "" in the middle).
func side_of(p: Vector2) -> String:
var c := playable.get_center()
var u := (p.x - c.x) / (playable.size.x * 0.5)
var v := (p.y - c.y) / (playable.size.y * 0.5)
var ns := "north" if v < -1.0 / 3.0 else ("south" if v > 1.0 / 3.0 else "")
var we := "west" if u < -1.0 / 3.0 else ("east" if u > 1.0 / 3.0 else "")
return ns + "-" + we if ns != "" and we != "" else ns + we
func crop_units() -> Array[CropUnit]:
var out: Array[CropUnit] = []
var field := zone(FarmZone.Kind.CROP_FIELD)

View file

@ -0,0 +1,350 @@
class_name FarmersReturn
extends Node3D
## The ending once the last night's dawn is over (FARMERS_RETURN): the farmers' station wagon
## (car_002, roof rack and all) comes up the road east of the farm, turns in at the driveway gap,
## and parks in the farmyard by the house with a honk; the two farmers (tinted mannequins) get
## out, walk to the house door, wave to the scarecrow waiting by the yard, and cheer. A cutscene
## camera follows the car, then frames the yard; the HUD hides behind letterbox bars. Fire,
## interact, or Space / Enter / A skips to the end. finished is emitted once it's
## over (or skipped), and EndPanel shows the final assessment over the scene.
## Built when it starts, after the game is over, so nothing is created during play.
signal finished
const CAR_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/transport/car_002.tscn"
const FARMER_SCENE := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
const ANIMATIONS := "res://game/resources/player_animations.res"
## The road from the south along the east side, in at GapDriveway, through the farmyard to the
## parking spot east of the house (game/LAYOUT.md); the car faces the way it drives.
const ROUTE: Array[Vector3] = [
Vector3(52.0, 0.0, 6.0), Vector3(52.0, 0.0, -30.0), Vector3(51.0, 0.0, -38.0), Vector3(46.0, 0.0, -39.6),
Vector3(38.0, 0.0, -39.4), Vector3(34.5, 0.0, -36.5), Vector3(33.0, 0.0, -32.5), Vector3(32.8, 0.0, -29.5),
]
const DRIVE_SPEED := 11.0
## Where the farmers walk (from the car's left and right doors to the porch steps on the house's
## north side) and where the scarecrow waits, beside their way. The yard shot looks south at the
## porch.
const DOOR := Vector3(19.6, 0.0, -29.8)
const FARMER_SPOTS: Array[Vector3] = [Vector3(18.9, 0.0, -31.4), Vector3(20.5, 0.0, -31.5)]
const SCARECROW_SPOT := Vector3(24.6, 0.0, -34.0)
const YARD_CAMERA := Vector3(28.0, 10.0, -45.5)
const YARD_LOOK := Vector3(24.8, 0.8, -30.8)
const WALK_SPEED := 2.0
const TINTS: Array[Color] = [Color(0.35, 0.5, 0.85), Color(0.85, 0.45, 0.4)]
## Seconds: honk after parking, farmers out, then waving, cheering, and the end.
const OUT_AT := 0.9
const WAVE_TIME := 2.2
const CHEER_TIME := 2.6
var sim: FarmSim
var running := false
var done := false
## Seconds since the start, and the stage: "drive", "walk", "wave", "cheer", "end".
var elapsed: float = 0.0
var stage := ""
var _car: Node3D
var _engine: AudioStreamPlayer3D
var _curve := Curve3D.new()
var _driven: float = 0.0
var _parked_for: float = 0.0
var _farmers: Array[Node3D] = []
var _anims: Array[AnimationPlayer] = []
var _camera: Camera3D
var _previous_camera: Camera3D
var _stage_left: float = 0.0
var _overlay: CanvasLayer
var _caption: Label
func setup(p_sim: FarmSim) -> void:
sim = p_sim
sim.campaign.campaign_ended.connect(func(outcome: CampaignController.Outcome) -> void:
if outcome == CampaignController.Outcome.VACATION_COMPLETE:
start())
sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, _p: CampaignController.Phase) -> void:
if phase == CampaignController.Phase.MORNING:
clear())
func start() -> void:
if running:
return
clear()
running = true
done = false
elapsed = 0.0
stage = "drive"
_driven = 0.0
_parked_for = 0.0
for p in ROUTE:
_curve.add_point(p)
for i in range(1, ROUTE.size() - 1): # round the corners
var t := (ROUTE[i + 1] - ROUTE[i - 1]) * 0.25
_curve.set_point_in(i, -t)
_curve.set_point_out(i, t)
_car = (load(CAR_SCENE) as PackedScene).instantiate() as Node3D
add_child(_car)
for body in _car.find_children("*", "CollisionObject3D", true, false):
(body as CollisionObject3D).collision_layer = 0
_engine = AudioStreamPlayer3D.new()
_engine.bus = &"SFX"
_engine.unit_size = 10.0
_engine.volume_db = -6.0
if sim.audio != null:
_engine.stream = sim.audio.stream_of("truck_engine")
_car.add_child(_engine)
if _engine.stream != null:
_engine.play()
_place_car(0.0)
var library := load(ANIMATIONS) as AnimationLibrary
for i in 2:
var root := Node3D.new()
root.visible = false
add_child(root)
var model := (load(FARMER_SCENE) as PackedScene).instantiate() as Node3D
root.add_child(model)
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = TINTS[i]
m.material_override = tinted
var straw := StandardMaterial3D.new() # a straw sun hat for the trip
straw.albedo_color = Color(0.92, 0.8, 0.45)
for part in [[0.62, 0.05, 2.12], [0.34, 0.26, 2.26]]: # brim, crown: radius, height, y
var mesh := CylinderMesh.new()
mesh.top_radius = part[0]
mesh.bottom_radius = part[0]
mesh.height = part[1]
var hat := MeshInstance3D.new()
hat.mesh = mesh
hat.position = Vector3(0.0, part[2], 0.0)
hat.material_override = straw
model.add_child(hat)
var anim := AnimationPlayer.new()
root.add_child(anim)
anim.root_node = anim.get_path_to(model)
anim.add_animation_library(&"", library)
_farmers.append(root)
_anims.append(anim)
# The scarecrow waits by the yard (in co-op, both, side by side).
for a in sim.avatars:
var at := SCARECROW_SPOT + Vector3(1.6, 0.0, 0.6) * a.slot
var yaw := atan2(-(DOOR.x - at.x), -(DOOR.z - at.z))
a.body.global_position = at
a.body.velocity = Vector3.ZERO
a.body.model.rotation.y = yaw
a.body.net_position = at
a.body.net_yaw = yaw
a.body.start_channel(&"Idle_A")
_previous_camera = get_viewport().get_camera_3d()
_camera = Camera3D.new()
_camera.fov = 45.0
add_child(_camera)
_camera.make_current()
_follow_camera(1.0)
if sim.audio != null:
sim.audio.focus = _car
_build_overlay()
_set_hud(false)
## Jumps to the end: parked, the farmers at the door cheering.
func skip() -> void:
if not running or done:
return
_driven = _curve.get_baked_length()
_place_car(_driven)
_stop_engine()
for i in 2:
_farmers[i].visible = true
_farmers[i].global_position = FARMER_SPOTS[i]
_face(_farmers[i], SCARECROW_SPOT)
_anims[i].play(&"Cheering")
_frame_yard(1.0)
_finish()
## Removes everything (a new vacation or a retry after the ending).
func clear() -> void:
running = false
stage = ""
for n in get_children():
n.queue_free()
_farmers.clear()
_anims.clear()
_car = null
_engine = null
_camera = null
_overlay = null
_curve = Curve3D.new()
if sim != null:
_set_hud(true)
if sim.audio != null:
sim.audio.focus = sim.player
if _previous_camera != null and is_instance_valid(_previous_camera):
_previous_camera.make_current()
for a in sim.avatars:
a.body.stop_channel()
func _process(delta: float) -> void:
if running and not done:
step(delta)
func step(delta: float) -> void:
elapsed += delta
match stage:
"drive":
var length := _curve.get_baked_length()
var left := length - _driven
var speed := DRIVE_SPEED * clampf(left / 9.0, 0.18, 1.0) # ease into the spot
_driven = minf(_driven + speed * delta, length)
_place_car(_driven)
_follow_camera(delta)
if _driven >= length:
_parked_for += delta
if _parked_for >= 0.15 and _engine != null and _engine.playing:
_stop_engine()
if sim.audio != null:
sim.audio.play("horn", _car.global_position)
if _parked_for >= OUT_AT:
stage = "walk"
var right := _car.global_basis.x
for i in 2:
_farmers[i].visible = true
_farmers[i].global_position = _car.global_position + right * (1.4 if i == 0 else -1.4)
_anims[i].play(&"Walking_A", 0.1)
"walk":
_frame_yard(delta)
var arrived := 0
for i in 2:
var f := _farmers[i]
var to := FARMER_SPOTS[i] - f.global_position
to.y = 0.0
if to.length() <= 0.05:
arrived += 1
continue
f.global_position += to.limit_length(WALK_SPEED * delta)
_face(f, f.global_position + to)
if arrived == 2:
stage = "wave"
_stage_left = WAVE_TIME
for i in 2:
_face(_farmers[i], SCARECROW_SPOT)
_anims[i].play(&"Waving", 0.15)
if sim.audio != null:
sim.audio.play("victory")
if _caption != null:
_caption.text = "The farmers are home!"
"wave", "cheer":
_frame_yard(delta)
_stage_left -= delta
if _stage_left <= 0.0:
if stage == "wave":
stage = "cheer"
_stage_left = CHEER_TIME
for a in _anims:
a.play(&"Cheering", 0.2)
else:
_finish()
func _finish() -> void:
done = true
stage = "end"
if _overlay != null:
_overlay.visible = false
_set_hud(true) # the final assessment is on it
finished.emit()
func _set_hud(on: bool) -> void:
if sim.hud != null and sim.hud.get_parent() is CanvasLayer:
(sim.hud.get_parent() as CanvasLayer).visible = on
func _place_car(distance: float) -> void:
var length := _curve.get_baked_length()
var at := _curve.sample_baked(distance, true)
var ahead := _curve.sample_baked(minf(distance + 1.0, length), true)
var behind := _curve.sample_baked(maxf(distance - 1.0, 0.0), true)
var dir := ahead - behind
dir.y = 0.0
if dir.length_squared() > 1e-6:
_car.rotation = Vector3(0.0, atan2(dir.x, dir.z), 0.0)
_car.global_position = Vector3(at.x, 0.0, at.z)
## Behind and above the car, looking a little ahead of it.
func _follow_camera(delta: float) -> void:
var fwd := _car.global_basis.z
var want := _car.global_position - fwd * 11.0 + Vector3(0.0, 8.0, 0.0) + _car.global_basis.x * 3.0
var look := _car.global_position + fwd * 4.0 + Vector3(0.0, 1.0, 0.0)
_move_camera(want, look, delta, 2.5)
## A wide shot of the yard from the north-east: the car, the porch, and the scarecrow.
func _frame_yard(delta: float) -> void:
_move_camera(YARD_CAMERA, YARD_LOOK, delta, 1.2)
func _move_camera(want: Vector3, look: Vector3, delta: float, rate: float) -> void:
var k := 1.0 - exp(-rate * delta) if delta < 1.0 else 1.0
_camera.global_position = _camera.global_position.lerp(want, k) if _camera.global_position != Vector3.ZERO else want
var target := _camera.global_transform.looking_at(look, Vector3.UP)
_camera.global_basis = _camera.global_basis.slerp(target.basis, k).orthonormalized() if k < 1.0 else target.basis
func _face(node: Node3D, at: Vector3) -> void:
var d := at - node.global_position
if Vector2(d.x, d.z).length_squared() > 1e-6:
node.rotation.y = atan2(d.x, d.z)
func _stop_engine() -> void:
if _engine != null:
_engine.stop()
func _build_overlay() -> void:
_overlay = CanvasLayer.new()
_overlay.layer = 5
add_child(_overlay)
for top in [true, false]:
var bar := ColorRect.new()
bar.color = Color.BLACK
bar.mouse_filter = Control.MOUSE_FILTER_IGNORE
_overlay.add_child(bar)
bar.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE if top else Control.PRESET_BOTTOM_WIDE)
if top:
bar.offset_bottom = 96.0
else:
bar.offset_top = -96.0
_caption = Label.new()
_caption.text = "The farmers are on their way home"
_caption.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_caption.add_theme_font_size_override("font_size", 38)
_caption.add_theme_color_override("font_color", Color(0.95, 0.85, 0.55))
_overlay.add_child(_caption)
_caption.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE)
_caption.offset_top = 22.0
var hint := Label.new()
hint.text = "[Space / Enter / A] skip"
hint.add_theme_font_size_override("font_size", 22)
hint.add_theme_color_override("font_color", Color(0.8, 0.8, 0.75))
_overlay.add_child(hint)
hint.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_RIGHT)
hint.offset_left = -360.0
hint.offset_top = -70.0
func _unhandled_input(event: InputEvent) -> void:
if not running or done:
return
if event.is_action_pressed("ui_accept") or event.is_action_pressed("interact") or event.is_action_pressed("fire"):
skip()
get_viewport().set_input_as_handled()

View file

@ -0,0 +1 @@
uid://00yqn4v1vtyl

View file

@ -6,7 +6,20 @@ extends Resource
@export_group("Campaign")
## Nights the scarecrow must survive before the farmers return.
@export_range(1, 20) var campaign_nights: int = 5
@export_range(1, 60) var campaign_nights: int = 5
@export_group("Waves")
## Every night plan's groups are scaled when played: this many times the enemies, arriving this
## many times the plan's spacing apart (NightPlan.scaled_count / scaled_every). 5 and 0.4: five
## times the enemies, two and a half times as often. A plan can set its own instead
## (NightPlan.count_scale / spacing_scale; night 1 plays unscaled).
@export_range(0.1, 20.0) var wave_count_scale: float = 7.0
@export_range(0.05, 4.0) var wave_spacing_scale: float = 0.3
## Every enemy arrives at its own random point along the farm's edge (FarmZones.edge), on foot this
## many meters outside the playable map (also where carriers escape to), flyers this far out.
## Ground arrivals stay inside the navigation grid (5 m beyond the map).
@export_range(0.5, 4.5) var spawn_margin: float = 3.0
@export var flyer_spawn_margin: float = 8.0
@export_group("Phases")
## Seconds of game time per phase. The morning review is untimed: it waits for the player.
@ -20,14 +33,32 @@ extends Resource
@export_group("Scarecrow")
## HP carries over between nights (D7); 0 HP is an immediate Game Over.
@export_range(1, 100) var scarecrow_max_hp: int = 10
@export_range(1, 100) var scarecrow_max_hp: int = 3
## After an accepted hit the scarecrow ignores further hits for this long.
@export var invulnerability_time: float = 1.0
## Fear: enemies within fear_radius flee for fear_duration; usable every fear_cooldown seconds.
@export var fear_radius: float = 6.0
@export var fear_cooldown: float = 12.0
@export var fear_duration: float = 2.0
## Patch up: hold for patch_time (rooted, no shooting) to restore patch_heal HP.
@export var patch_time: float = 2.0
@export_range(1, 100) var patch_heal: int = 3
## Sprint (the workbench's Sprint upgrade): hold sprint while moving to run sprint_speed_mult
## times as fast for up to sprint_time seconds; once it ends, sprint_cooldown seconds until the
## next one.
@export var sprint_speed_mult: float = 1.6
@export var sprint_time: float = 3.0
@export var sprint_cooldown: float = 10.0
@export_group("Farm assets")
## Starting count per target category. A category with a count of 0 is not in play and is
## ignored by the "farm stripped" check (D2). Animals and supplies arrive in Step 8.
## Crop units and animals on the farm when the vacation starts; they must match the farm scene
## (the crop field's CropUnits, the animals in the pen). Supplies are the shed's stock (the start
## materials below). A category with nothing in it at the start is not in play and is ignored by
## the "farm stripped" check (D2).
@export_range(0, 500) var start_crops: int = 30
@export_range(0, 100) var start_animals: int = 0
@export_range(0, 5000) var start_supplies: int = 0
@export_range(0, 100) var start_animals: int = 8
## Structures standing when the vacation starts ({"type", "x", "z", "rot"}): the animal pen's gate.
@export var start_structures: Array[Dictionary] = [{"type": "gate", "x": 4.0, "z": -6.0, "rot": 2}]
@export_group("Theft rules")
## D5: fear makes carriers drop their loot, not only killing them.
@ -35,7 +66,228 @@ extends Resource
## D6: dropped loot still on the ground when the dawn grace ends returns home automatically.
@export var loot_returns_at_dawn: bool = true
## D6: animals that can follow the scarecrow back to the pen at once.
@export_range(1, 10) var max_following_animals: int = 3
@export_range(1, 10) var max_following_animals: int = 5
## Seconds an enemy needs to take a crop unit, catch an animal, or fill a sack at the shed (times
## its type's steal_time); damage during that time resets it.
@export var crop_steal_time: float = 2.5
@export var animal_capture_time: float = 2.0
@export var supply_steal_time: float = 1.0
## A supply thief takes this many units of the material the shed holds most of (never more than
## there is).
@export_range(1, 100) var supply_bundle: int = 5
## Loose animals (dropped, or wandered out of an open pen) walk toward the farm's nearest edge at
## this speed, stopping to graze now and then; one that gets off the farm is lost.
@export var stray_speed: float = 1.1
## At night, while the pen is open (its gate broken or removed), one animal wanders out every
## this many seconds. An animal brought back stays calm (won't wander out) for animal_calm_time.
@export var animal_wander_interval: float = 10.0
@export var animal_calm_time: float = 30.0
## Animals following the scarecrow walk its trail at up to this speed.
@export var follow_speed: float = 6.0
## What a thief with no set target goes for ("any" in a night plan), and where a thief whose target
## is gone goes next: relative weights per category.
@export var target_weights: Dictionary = {"crops": 2.0, "animals": 1.0, "supplies": 1.0}
## The scarecrow recovers dropped loot by walking within this distance of it.
@export var pickup_radius: float = 1.3
@export_group("Resources")
## Wood, scrap, and straw in the supply shed when the vacation starts.
@export_range(0, 999) var start_wood: int = 4
@export_range(0, 999) var start_scrap: int = 2
@export_range(0, 999) var start_straw: int = 4
## The scarecrow's pouch holds this many units in total; it empties into the shed on entry.
@export_range(1, 200) var pouch_capacity: int = 16
## Seconds of holding interact per gather (each takes one charge of the gather point).
@export var gather_time: float = 1.5
## What things cost: name -> {material: amount}: patching up, the buildables, and the upgrades.
@export var costs: Dictionary = {
"patch": {"straw": 2},
"straw_stuffing": {"straw": 12, "wood": 4},
"sprint": {"wood": 8, "straw": 6},
"corn_shooter": {"scrap": 10, "wood": 4},
"pumpkin_bomb": {"straw": 12, "scrap": 6},
"rapid_fire": {"scrap": 12, "wood": 8},
"heavy_seeds": {"scrap": 14, "straw": 10},
"wide_fear": {"straw": 20, "wood": 4},
"quick_fear": {"straw": 16, "scrap": 6},
"reinforced_fences": {"wood": 20, "scrap": 6},
"long_range": {"scrap": 14, "wood": 10},
"sticky_tar": {"straw": 14, "scrap": 6},
"fence": {"wood": 2},
"gate": {"wood": 4, "scrap": 1},
"slowing_trap": {"scrap": 3, "wood": 1},
"automated_defense": {"scrap": 6, "wood": 2, "straw": 2},
}
@export_group("Upgrades")
## Bought once each by day at the work area's workbench, for costs[id] (Upgrades). Each changes
## one stat: "mult" multiplies it, "add" adds to it. Stats are GameConfig settings, plus
## scarecrow_max_hp (the scarecrow's, in FarmState) and barrier_hp (fences' and gates' health).
## One without a stat unlocks something instead (sprint: PlayerCharacter; the corn shooter and
## pumpkin bombs: ScarecrowCombat). "requires": another upgrade that must be bought first.
@export var upgrades: Dictionary = {
"corn_shooter": {"name": "Corn shooter", "text": "A gun that fires corn kernels, from afar", "track": "Weapon"},
"rapid_fire": {"name": "Rapid fire", "text": "The corn shooter fires a third faster", "track": "Weapon", "stat": "fire_rate", "mult": 1.333, "requires": "corn_shooter"},
"heavy_seeds": {"name": "Heavy seeds", "text": "Each kernel does 2 damage", "track": "Weapon", "stat": "shot_damage", "add": 1, "requires": "corn_shooter"},
"pumpkin_bomb": {"name": "Pumpkin bombs", "text": "Throw a pumpkin that bursts, hurting everything within 3 m (one every 4 s)", "track": "Weapon"},
"wide_fear": {"name": "Wide fear", "text": "Fear reaches 30% farther", "track": "Fear", "stat": "fear_radius", "mult": 1.3},
"quick_fear": {"name": "Quick fear", "text": "Fear recharges 20% faster", "track": "Fear", "stat": "fear_cooldown", "mult": 0.8},
"straw_stuffing": {"name": "Straw stuffing", "text": "+2 max health", "track": "Scarecrow", "stat": "scarecrow_max_hp", "add": 2},
"sprint": {"name": "Sprint", "text": "Sprint 60% faster for 3 s at a time, every 10 s", "track": "Scarecrow"},
"reinforced_fences": {"name": "Reinforced fences", "text": "Fences and gates +50% health", "track": "Defenses", "stat": "barrier_hp", "mult": 1.5},
"long_range": {"name": "Long-range defenses", "text": "Automated defenses reach 30% farther", "track": "Defenses", "stat": "turret_range", "mult": 1.3},
"sticky_tar": {"name": "Sticky tar", "text": "Slowing traps hold 50% longer", "track": "Defenses", "stat": "trap_slow_time", "mult": 1.5},
}
@export_group("Assessment")
## The final assessment's weight per category (Assessment): the score is the weighted share of
## each category kept, renormalized over the categories in play, as 0..100 points.
@export var assessment_weights: Dictionary = {"crops": 0.5, "animals": 0.3, "supplies": 0.2}
## Rating tiers, best first: the first one whose min the score reaches.
@export var rating_tiers: Array[Dictionary] = [
{"min": 95, "name": "Blue-ribbon harvest", "text": "The farmers can hardly tell they were gone."},
{"min": 80, "name": "Bumper crop", "text": "A few gaps in the rows, nothing a good week won't fix."},
{"min": 60, "name": "Fair season", "text": "The farm made it, a little thinner than they left it."},
{"min": 40, "name": "Lean season", "text": "The farmers will be counting what's missing for a while."},
{"min": 0, "name": "Hanging by a thread", "text": "There's a farm left, but only just."},
]
@export_group("Structures")
## Hit points of the built defenses; a slowing trap's "HP" is the enemies it can still slow.
@export_range(1, 500) var fence_hp: int = 20
@export_range(1, 500) var gate_hp: int = 30
@export_range(1, 500) var trap_triggers: int = 10
@export_range(1, 500) var turret_hp: int = 25
## A ground enemy crossing a slowing trap moves at this share of its speed for this long.
@export_range(0.05, 1.0) var trap_slow_factor: float = 0.5
@export var trap_slow_time: float = 2.0
## The automated defense shoots the nearest enemy in range with a clear line, every interval.
@export var turret_range: float = 7.0
@export var turret_fire_interval: float = 1.0
## The scarecrow builds within this distance of itself.
@export var build_range: float = 9.0
## Enemies treat each cell of a barrier as this many meters of extra path, so they walk around
## a short wall but break through a long one.
@export var barrier_detour: float = 18.0
## Holding interact for repair_time repairs a structure fully, for its build cost scaled by the
## share of HP (or triggers) it is missing, rounded up.
@export var repair_time: float = 1.5
## Dismantling gives back this share of the build cost (rounded down), into the shed.
@export_range(0.0, 1.0) var dismantle_refund: float = 0.5
## Cells finalized per tick while flow fields rebuild after a structure change.
@export_range(100, 100000) var flow_slice_cells: int = 2000
@export_group("Combat")
## Height of the gun muzzle, the bullets, and enemy hit proxies (shots fly horizontally). It
## clears the sunflowers (1.67 m) and the pen fence (1.69 m), so thieves in the field stay
## visible and shootable.
@export var combat_height: float = 1.8
## The pitchfork, every scarecrow's from the start (ScarecrowCombat): a stab every
## pitchfork_interval s hits the nearest pitchfork_targets enemies within pitchfork_reach m of the
## scarecrow's center (plus their hit radius) and pitchfork_arc degrees of the aim, with a clear
## line, for pitchfork_damage each.
@export var pitchfork_reach: float = 2.2
@export var pitchfork_arc: float = 100.0
@export_range(1, 20) var pitchfork_damage: int = 2
@export_range(1, 20) var pitchfork_targets: int = 3
@export var pitchfork_interval: float = 0.5
## Pumpkin bombs (the Pumpkin bombs upgrade): thrown at the aim point, bomb_min_range ..
## bomb_range m away, flying at bomb_speed m/s; on landing every enemy within bomb_radius m takes
## bomb_damage. One every bomb_cooldown s.
@export var bomb_range: float = 10.0
@export var bomb_min_range: float = 2.0
@export var bomb_speed: float = 12.0
@export var bomb_radius: float = 3.0
@export_range(1, 50) var bomb_damage: int = 3
@export var bomb_cooldown: float = 4.0
## The corn shooter (the Corn shooter upgrade) is the gun: kernels per second and their damage
## (rapid fire and heavy seeds raise them), and the projectiles below.
@export var fire_rate: float = 6.0
## Damage of one of the scarecrow's shots (automated defenses always do 1).
@export_range(1, 10) var shot_damage: int = 1
@export var projectile_speed: float = 24.0
@export var projectile_lifetime: float = 2.0
@export_range(1, 1024) var projectile_capacity: int = 64
## Horizontal distance from the scarecrow's center to the muzzle along the aim direction.
@export var muzzle_distance: float = 1.05
## Right-stick radial dead zone, and mouse travel (px) that switches aiming back to the mouse.
@export var aim_dead_zone: float = 0.3
@export var mouse_switch_threshold: float = 12.0
@export_group("Enemies")
@export_range(1, 1024) var enemy_capacity: int = 800
## The enemy roster (EnemySystem.TYPE_NAMES), one row per type:
## speed, acceleration m/s, m/s^2
## hp hits it takes
## flying ignores ground occupancy, structures, and traps; altitude is only
## visual (its hit proxy stays at combat height)
## targets what it goes for: loot categories ("crops", "animals", "supplies"), or
## "structures" (barriers guarding valuables)
## steal_time times the category's steal time
## carry_speed share of its speed while carrying loot
## structure_damage per hit on a barrier, every hit_interval
## damage, hit_interval per melee hit on the scarecrow, and the cooldown between hits
## aggression "none" (never fights), "contact" (hits the scarecrow when touching it
## while busy), "fight" (turns on a scarecrow within aggro_range, and
## hunts it when nothing is left to break)
## hit_radius projectile hit proxy
@export var enemy_types: Dictionary = {
"thief": {"speed": 3.0, "acceleration": 14.0, "hp": 3, "flying": false, "targets": ["animals", "supplies"],
"steal_time": 1.0, "carry_speed": 0.7, "structure_damage": 2, "damage": 1, "hit_interval": 1.2,
"aggression": "contact", "hit_radius": 0.4, "aggro_range": 0.0},
"crow": {"speed": 5.5, "acceleration": 18.0, "hp": 1, "flying": true, "targets": ["crops"],
"steal_time": 0.8, "carry_speed": 0.75, "structure_damage": 0, "damage": 0, "hit_interval": 1.0,
"aggression": "none", "hit_radius": 0.45, "aggro_range": 0.0},
"breaker": {"speed": 1.9, "acceleration": 8.0, "hp": 6, "flying": false, "targets": ["structures"],
"steal_time": 0.0, "carry_speed": 0.0, "structure_damage": 8, "damage": 2, "hit_interval": 1.5,
"aggression": "fight", "hit_radius": 0.55, "aggro_range": 4.0},
}
## Flyers cruise at this visual altitude and come down to land_altitude to take a crop.
@export var cruise_altitude: float = 3.2
@export var land_altitude: float = 1.55
## Barriers within this distance of the crop rows, the pen, or the shed guard them: fence
## breakers go for those first.
@export var guard_range: float = 6.0
## Body radius of ground enemies (navigation clearance is this plus nav_inflate_margin).
@export var enemy_radius: float = 0.3
@export var nav_cell_size: float = 0.5
@export var nav_inflate_margin: float = 0.05
@export var separation_radius: float = 0.8
@export var separation_weight: float = 1.4
## Bounded push per tick when enemies overlap each other or the scarecrow.
@export var max_correction_per_tick: float = 0.15
## Melee: an enemy touching the scarecrow (within this much of contact) and off cooldown hits
## it for its type's damage; the cooldown (hit_interval) starts on every attempt.
@export var enemy_attack_reach: float = 0.25
## Fleeing enemies (fear) run at this share of their normal speed.
@export var flee_speed_factor: float = 1.15
## Within this distance and with a clear line, enemies steer straight at their target.
@export var direct_seek_distance: float = 12.0
## Trickle mode, for tests and soaks: when above 0, the night's plan is ignored and this many
## enemies of trickle_type are kept on the farm, the next arriving thief_spawn_interval after one
## leaves (anywhere along the farm's edge). 0 plays the night's NightPlan (WaveDirector).
@export_range(0, 32) var night_thieves: int = 0
@export var thief_spawn_interval: float = 6.0
@export var trickle_type: String = "crow"
## What trickle enemies go for: "crops", "animals", "supplies", or "any" (of their type's targets).
@export var trickle_target: String = "any"
## A row of the enemy roster.
func enemy(type_name: String) -> Dictionary:
return enemy_types.get(type_name, {})
## Full hit points of a structure type (a slowing trap's are the enemies it can still slow).
func structure_hp(type: String) -> int:
match type:
"fence":
return fence_hp
"gate":
return gate_hp
"slowing_trap":
return trap_triggers
return turret_hp
## Length of a phase in seconds, or INF for the untimed morning review and terminal phases.

View file

@ -0,0 +1,102 @@
class_name GameSettings
extends RefCounted
## The player's settings, kept in user://settings.cfg (ConfigFile) apart from the save game, and
## applied at start and on every change (SettingsMenu):
## * Audio: the volume of each audio bus (game/resources/audio_buses.tres).
## * Controls: the dead zones of the move stick (the move_* actions) and the aim stick
## (GameConfig.aim_dead_zone). Mouse aim follows the cursor directly, so it has no
## sensitivity to set.
## * Display: fullscreen, VSync, and the 3D resolution scale (the HUD stays sharp).
## * Gameplay: whether the tips show on the first day and night (Tutorial).
## * Co-op: your player name, and whether your microphone is sent in voice chat.
## Values missing from the file or out of range fall back to the defaults, so an old or
## hand-edited file never breaks the game.
const PATH := "user://settings.cfg"
const BUSES: Array[String] = ["Master", "Music", "SFX", "Ambience", "Voice"]
const BUS_NAMES := {"Master": "Master volume", "Music": "Music and stingers", "SFX": "Sound effects", "Ambience": "Ambience",
"Voice": "Voice chat (your friend)"}
const DEFAULT_VOLUME := {"Master": 0.8, "Music": 0.7, "SFX": 0.8, "Ambience": 0.6, "Voice": 1.0}
var volume := DEFAULT_VOLUME.duplicate()
var move_dead_zone := 0.2
var aim_dead_zone := 0.3
var fullscreen := false
var vsync := true
var resolution_scale := 1.0
var show_tips := true
## Co-op: your name for the lobby and the name tag, and whether your microphone is sent.
var player_name := ""
var microphone := true
static func load_from(path: String = PATH) -> GameSettings:
var g := GameSettings.new()
var f := ConfigFile.new()
if f.load(path) != OK:
return g
for bus in BUSES:
g.volume[bus] = _number(f.get_value("audio", bus.to_lower(), g.volume[bus]), 0.0, 1.0, g.volume[bus])
g.move_dead_zone = _number(f.get_value("controls", "move_dead_zone", g.move_dead_zone), 0.05, 0.9, g.move_dead_zone)
g.aim_dead_zone = _number(f.get_value("controls", "aim_dead_zone", g.aim_dead_zone), 0.05, 0.9, g.aim_dead_zone)
g.fullscreen = _flag(f.get_value("display", "fullscreen", g.fullscreen), g.fullscreen)
g.vsync = _flag(f.get_value("display", "vsync", g.vsync), g.vsync)
g.resolution_scale = _number(f.get_value("display", "resolution_scale", g.resolution_scale), 0.5, 1.0, g.resolution_scale)
g.show_tips = _flag(f.get_value("gameplay", "show_tips", g.show_tips), g.show_tips)
var n: Variant = f.get_value("coop", "player_name", "")
g.player_name = String(n).strip_edges().left(20) if n is String else ""
g.microphone = _flag(f.get_value("coop", "microphone", g.microphone), g.microphone)
return g
func save_to(path: String = PATH) -> Error:
var f := ConfigFile.new()
for bus in BUSES:
f.set_value("audio", bus.to_lower(), volume.get(bus, DEFAULT_VOLUME[bus]))
f.set_value("controls", "move_dead_zone", move_dead_zone)
f.set_value("controls", "aim_dead_zone", aim_dead_zone)
f.set_value("display", "fullscreen", fullscreen)
f.set_value("display", "vsync", vsync)
f.set_value("display", "resolution_scale", resolution_scale)
f.set_value("gameplay", "show_tips", show_tips)
f.set_value("coop", "player_name", player_name)
f.set_value("coop", "microphone", microphone)
return f.save(path)
## Applies everything: bus volumes, dead zones (into config too, when given), and the display
## (skipped without a real display, e.g. headless).
func apply(viewport: Viewport, config: GameConfig = null) -> void:
for bus in BUSES:
var i := AudioServer.get_bus_index(bus)
if i < 0:
continue
var v: float = volume.get(bus, DEFAULT_VOLUME[bus])
AudioServer.set_bus_volume_db(i, linear_to_db(maxf(v, 0.0001)))
AudioServer.set_bus_mute(i, v <= 0.001)
for action in ["move_left", "move_right", "move_forward", "move_back"]:
if InputMap.has_action(action):
InputMap.action_set_deadzone(action, move_dead_zone)
if config != null:
config.aim_dead_zone = aim_dead_zone
if viewport != null:
viewport.scaling_3d_scale = resolution_scale
if DisplayServer.get_name() == "headless":
return
var mode := DisplayServer.window_get_mode()
var want_full := fullscreen
var is_full := mode == DisplayServer.WINDOW_MODE_FULLSCREEN or mode == DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN
if want_full != is_full:
DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN if want_full else DisplayServer.WINDOW_MODE_WINDOWED)
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED if vsync else DisplayServer.VSYNC_DISABLED)
static func _number(v: Variant, lo: float, hi: float, fallback: float) -> float:
if not (v is float or v is int):
return fallback
var x := float(v)
return clampf(x, lo, hi) if is_finite(x) else fallback
static func _flag(v: Variant, fallback: bool) -> bool:
return bool(v) if v is bool else fallback

View file

@ -0,0 +1 @@
uid://bunyhk45ja6cu

View file

@ -0,0 +1,66 @@
class_name GatherNode
extends Node3D
## A spot where the scarecrow gathers one material by day: holding interact for gather_time
## puts yield_amount into the pouch and uses one of max_charges. Its children are the props it
## is made of; they fade grey once it is used up. Used charges come back overnight
## (regen_per_night each, applied by Interactions). The farm state keeps only points below
## full, keyed by this node's name, so names must be unique among gather points.
const COLORS := {
"wood": Color(0.95, 0.68, 0.4),
"scrap": Color(0.72, 0.84, 0.95),
"straw": Color(1.0, 0.9, 0.42),
}
@export_enum("wood", "scrap", "straw") var material: String = "wood"
@export_range(1, 20) var max_charges: int = 2
@export_range(1, 20) var yield_amount: int = 2
@export_range(1, 20) var regen_per_night: int = 20
## How close the scarecrow's center has to be to this node's origin to gather.
@export var reach: float = 1.8
## Clip the scarecrow loops while gathering here.
@export var clip: StringName = &"PickUp"
var _faded := false
var _fade: StandardMaterial3D
var _label: Label3D
var _top: float = 1.5
func _ready() -> void:
_fade = StandardMaterial3D.new()
_fade.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
_fade.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
_fade.albedo_color = Color(0.45, 0.45, 0.45, 0.6)
for vi in find_children("*", "VisualInstance3D", true, false):
var box := (vi as VisualInstance3D).global_transform * (vi as VisualInstance3D).get_aabb()
_top = maxf(_top, box.end.y - global_position.y)
_label = Label3D.new()
_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_label.no_depth_test = true
_label.shaded = false
_label.font_size = 40
_label.outline_size = 10
_label.pixel_size = 0.0075
_label.modulate = COLORS[material]
_label.position = Vector3(0.0, minf(_top, 4.0) + 0.5, 0.0)
_label.visible = false
add_child(_label)
## Top of the point's props (local), for popups.
func top() -> float:
return minf(_top, 4.0)
## Updates the faded look and the floating label (hidden when show is false).
func show_state(charges: int, show: bool, prompt: String) -> void:
var empty := charges <= 0
if empty != _faded:
_faded = empty
for mi in find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _fade if empty else null
_label.visible = show
if show:
var text := "%s %d/%d" % [material.capitalize(), charges, max_charges]
_label.text = text if prompt == "" else text + "\n" + prompt

View file

@ -0,0 +1 @@
uid://cj88bbt6nct61

View file

@ -0,0 +1,24 @@
class_name GDSyncLink
extends CoopLink
## The co-op wire over GD-Sync (the GDSync autoload; LAN or online): every message is a remote
## call of CoopSession.net_receive on the other machine (the same node path on both, since both
## run main.tscn), reliable or unreliable. The session exposes that function to GD-Sync.
var gdsync: Node
var peer: int = -1
var session: Node
func _init(p_gdsync: Node, p_peer: int, p_session: Node) -> void:
gdsync = p_gdsync
peer = p_peer
session = p_session
func _deliver(kind: String, data: Variant, reliable: bool) -> void:
if closed or gdsync == null or peer < 0:
return
if reliable:
gdsync.call_func_on(peer, session.net_receive, kind, data)
else:
gdsync.call_func_on_unreliable(peer, session.net_receive, kind, data)

View file

@ -0,0 +1 @@
uid://c1sifg7g5bbsn

View file

@ -0,0 +1,313 @@
class_name Interactions
extends Node3D
## The scarecrow's hands: gathering at GatherNodes, buying at the Workbench, repairing damaged
## structures, and dropping the pouch off at the supply shed. Nothing here works in build mode.
## * Focus: the nearest gather point or workbench within its reach, preferring points with
## charges left over used-up ones; nearby points show their charges, the focused one its
## prompt (or why it can't be used).
## * Gather: hold interact by day (D8) at a point with charges left and room in the pouch for
## the whole yield (so a charge is never half wasted).
## The scarecrow is rooted for gather_time looping the point's clip, then yield_amount goes
## into the pouch ("+2 wood" pops up) and one charge is used. Keep holding to gather again.
## Letting go, a hit, fear, nightfall, or a full pouch cancels it.
## * Workbench: press interact by day to open the upgrade menu (UpgradePanel); interact again,
## walking away, or nightfall closes it. Nothing else happens here while it's open.
## * Repair: a damaged structure within REPAIR_REACH comes first. Hold interact for
## repair_time (any phase) to repair it fully for StructureSystem.repair_cost (paid at the
## end); it is refused, once per press, without the materials.
## * Deposit: walking into the Supply Shed zone empties the pouch into the shed.
## * Overnight (the end of the dawn grace) every used point regains regen_per_night charges.
## In co-op each scarecrow has its own Interactions. The partner's, on the host, reads its
## RemoteControls (remote), asks the partner's game to open its own upgrade menu
## (workbench_requested), and leaves the gather labels to the local player's (show_labels).
signal gathered(material: String, amount: int, node: GatherNode)
signal deposited(moved: Dictionary)
signal message(text: String, color: Color)
## A remote kit pressed interact at the workbench by day (its game opens the upgrade menu).
signal workbench_requested
const LABEL_RANGE := 7.0
const REPAIR_REACH := 1.4
const POPUP_TIME := 1.1
const POPUPS := 6
var config: GameConfig
var campaign: CampaignController
var player: PlayerCharacter
var kit: Scarecrow
var zones: FarmZones
## Set by FarmSim.
var structures: StructureSystem
var build: BuildMode
var upgrade_panel: UpgradePanel
## The partner's input on the host (co-op), and whether this one draws the gather labels.
var remote: RemoteControls
var show_labels := true
var nodes: Array[GatherNode] = []
var workbench: Workbench
var focus: Node3D
var gathering: GatherNode
var gather_elapsed: float = 0.0
## Damaged structure in reach (-1 = none) and the one being repaired.
var repair_target: int = -1
var repairing: int = -1
var repair_elapsed: float = 0.0
var _shed: FarmZone
var _interact_requested := false
var _interact_was_held := false
var _denied := false
var _popups: Array[Label3D] = []
var _repair_label: Label3D
var _popup_left := PackedFloat32Array()
func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter, p_kit: Scarecrow,
p_zones: FarmZones) -> void:
config = cfg
campaign = p_campaign
player = p_player
kit = p_kit
zones = p_zones
_shed = zones.zone(FarmZone.Kind.SUPPLY_SHED)
for n in zones.find_children("*", "Node3D", true, false):
if n is GatherNode:
nodes.append(n)
elif n is Workbench and workbench == null:
workbench = n
kit.damaged.connect(func(_hp: int) -> void: cancel())
kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: cancel())
_repair_label = Label3D.new()
_repair_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_repair_label.no_depth_test = true
_repair_label.shaded = false
_repair_label.font_size = 40
_repair_label.outline_size = 10
_repair_label.pixel_size = 0.0075
_repair_label.modulate = Color(1.0, 0.9, 0.7)
_repair_label.top_level = true
_repair_label.visible = false
add_child(_repair_label)
_popup_left.resize(POPUPS)
for i in POPUPS:
var l := Label3D.new()
l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
l.no_depth_test = true
l.shaded = false
l.font_size = 56
l.outline_size = 12
l.pixel_size = 0.01
l.visible = false
l.top_level = true
l.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(l)
_popups.append(l)
func charges(n: GatherNode) -> int:
return int(campaign.state.gather_charges.get(String(n.name), n.max_charges))
func channeling() -> bool:
return gathering != null or repairing >= 0
func can_shoot() -> bool:
return not channeling() and not (upgrade_panel != null and upgrade_panel.is_open) and not (remote != null and remote.ui_open)
## One physics tick, after the scarecrow kit.
func step(dt: float) -> void:
var held := remote.held(&"interact") if remote != null else Input.is_action_pressed("interact")
var pressed := _interact_requested or (held and not _interact_was_held)
if remote != null:
pressed = remote.take(&"interact")
_interact_requested = false
_interact_was_held = held
if not held:
_denied = false
if not kit.alive or (build != null and build.active) or (remote != null and (remote.build_active or remote.ui_open)):
if upgrade_panel != null:
upgrade_panel.close()
cancel()
repair_target = -1
focus = null
return
var p := Vector2(player.global_position.x, player.global_position.z)
if upgrade_panel != null and upgrade_panel.is_open:
var bench := Vector2(workbench.global_position.x, workbench.global_position.z) if workbench != null else p
if pressed or not campaign.is_daytime() or bench.distance_to(p) > workbench.reach + 0.5 or (build != null and build.active):
upgrade_panel.close()
return
if _shed != null and _shed.contains(player.global_position) and campaign.state.resources.pouch_total() > 0:
var moved := campaign.state.resources.deposit()
deposited.emit(moved)
message.emit("Stored %s in the shed" % ResourceStore.describe(moved), Color(0.85, 0.95, 1.0))
if repairing >= 0:
if not held or structures.repair_cost(repairing).is_empty():
cancel()
return
repair_elapsed += dt
if repair_elapsed >= config.repair_time:
var id := repairing
var cost := structures.repair_cost(id)
cancel()
if structures.repair(id):
message.emit("Repaired (%s)" % ResourceStore.describe(cost), Color(0.6, 1.0, 0.55))
return
if gathering != null:
if not held or _blocker(gathering) != "":
cancel()
return
gather_elapsed += dt
var to := Vector2(gathering.global_position.x - p.x, gathering.global_position.z - p.y)
if to.length_squared() > 1e-4:
player.face_aim(to.normalized(), 0.3)
if gather_elapsed >= config.gather_time:
_finish_gather()
return
repair_target = structures.structure_near(p, REPAIR_REACH, true) if structures != null else -1
if repair_target >= 0:
focus = null
if held and not kit.patching:
var cost := structures.repair_cost(repair_target)
if campaign.state.resources.can_afford(cost):
repairing = repair_target
repair_elapsed = 0.0
player.start_channel(&"Hammering")
elif not _denied:
_denied = true
message.emit("Not enough to repair: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost)), Color(1.0, 0.8, 0.5))
return
focus = _nearest(p)
if focus is GatherNode and held and not kit.patching:
var why := _blocker(focus)
if why == "":
gathering = focus
gather_elapsed = 0.0
player.start_channel(gathering.clip)
elif not _denied:
_denied = true
message.emit(why, Color(1.0, 0.8, 0.5))
elif focus is Workbench and pressed:
if not campaign.is_daytime():
message.emit("The work area is for daytime", Color(1.0, 0.8, 0.5))
elif upgrade_panel != null:
upgrade_panel.open()
elif remote != null:
workbench_requested.emit()
## Why a point can't be gathered right now ("" if it can).
func _blocker(n: GatherNode) -> String:
if not campaign.is_daytime():
return "Gathering is for daytime"
if charges(n) <= 0:
return "Nothing left here; it grows back overnight"
if campaign.state.resources.pouch_room() < n.yield_amount:
return "Pouch full: drop it off at the supply shed"
return ""
func cancel() -> void:
if gathering != null or repairing >= 0:
gathering = null
gather_elapsed = 0.0
repairing = -1
repair_elapsed = 0.0
player.stop_channel()
## Overnight: every used gather point regains its regen_per_night charges.
func regen_overnight() -> void:
var used := campaign.state.gather_charges
for n in nodes:
var key := String(n.name)
if used.has(key):
var c := int(used[key]) + n.regen_per_night
if c >= n.max_charges:
used.erase(key)
else:
used[key] = c
func _finish_gather() -> void:
var n := gathering
var s := campaign.state
var added := s.resources.add_to_pouch(n.material, n.yield_amount)
var left := charges(n) - 1
s.gather_charges[String(n.name)] = left
cancel()
gathered.emit(n.material, added, n)
_popup("+%d %s" % [added, n.material], n.global_position + Vector3(0.0, n.top() + 1.4, 0.0), GatherNode.COLORS[n.material])
func _nearest(p: Vector2) -> Node3D:
var best: Node3D = null
var best_d := INF
for n in nodes:
var d := Vector2(n.global_position.x, n.global_position.z).distance_to(p)
var score := d + (100.0 if charges(n) <= 0 else 0.0) # used-up points only as a fallback
if d <= n.reach and score < best_d:
best = n
best_d = score
if workbench != null:
var d := Vector2(workbench.global_position.x, workbench.global_position.z).distance_to(p)
if d <= workbench.reach and d < best_d:
best = workbench
best_d = d
return best
func _popup(text: String, at: Vector3, color: Color) -> void:
var slot := 0
for i in POPUPS:
if _popup_left[i] < _popup_left[slot]:
slot = i
var l := _popups[slot]
l.text = text
l.modulate = color
l.global_position = at
l.visible = true
_popup_left[slot] = POPUP_TIME
func _process(delta: float) -> void:
if player == null:
return
var p := player.global_position
for n in nodes if show_labels else []:
var near := Vector2(n.global_position.x - p.x, n.global_position.z - p.z).length() < LABEL_RANGE
var prompt := ""
if n == gathering:
prompt = "Gathering..."
elif n == focus:
var why := _blocker(n)
prompt = "[E / X] Gather" if why == "" else why
n.show_state(charges(n), near and kit.alive, prompt)
if workbench != null and show_labels:
var near := Vector2(workbench.global_position.x - p.x, workbench.global_position.z - p.z).length() < LABEL_RANGE
workbench.show_state(campaign, near and kit.alive, focus == workbench)
var shown := (repairing if repairing >= 0 else repair_target) if show_labels else -1
_repair_label.visible = shown >= 0
if shown >= 0:
var e := campaign.state.structure(shown)
if not e.is_empty():
_repair_label.global_position = Vector3(e["x"], 2.7, e["z"])
var cost := structures.repair_cost(shown)
_repair_label.text = "%s %d/%d\n%s" % [StructureSystem.NAMES[e["type"]], int(e["hp"]), structures.max_hp(e["type"]),
"Repairing..." if repairing >= 0 else "[E / X] Repair (%s)" % ResourceStore.describe(cost)]
for i in POPUPS:
if _popup_left[i] <= 0.0:
continue
_popup_left[i] = maxf(_popup_left[i] - delta, 0.0)
var l := _popups[i]
l.visible = _popup_left[i] > 0.0
l.global_position.y += delta * 1.2
l.modulate.a = clampf(_popup_left[i] / 0.4, 0.0, 1.0)
func _unhandled_input(event: InputEvent) -> void:
if remote == null and event.is_action_pressed("interact", false):
_interact_requested = true

View file

@ -0,0 +1 @@
uid://clbenujyc2nyp

717
game/scripts/loot_system.gd Normal file
View file

@ -0,0 +1,717 @@
class_name LootSystem
extends Node3D
## Runtime state and feedback of everything thieves can take, on top of the persistent record in
## FarmState. Three categories share one id space (1..item_count):
## CROP ids 1..unit_count: one crop unit each (CropUnit.unit_id), at home in its plot.
## ANIMAL the next animal_count ids: one animal each (AnimalSystem moves it), at home in the pen.
## SUPPLY the last SACKS ids: sacks for bundles of the shed's stock. A sack at home is "in the
## shed": it can be claimed while the shed has stock, and the thief takes it from the pile
## of the material the shed holds most of. Picking it up fills it with up to
## supply_bundle units of that material (never more than there is).
## Each item has a status:
## HOME in its plot, the pen, or the shed. One thief at a time may claim it: it is then
## targeted ("!" marker) and, while being taken, shows a filling progress ring.
## CARRIED on a thief, outlined in its category's color, with a badge over it.
## DROPPED its carrier was stopped. A crop or a sack lies on the ground, glowing; an animal is
## loose and makes for the farm's edge (AnimalSystem). The scarecrow walks up to it to
## recover it (a loose animal then follows it, at most max_following_animals at once),
## and another thief may claim it.
## FOLLOWING animals only: following the scarecrow; back inside the pen it is home.
## LOST carried (or, for an animal, wandered) off the farm. Crops and animals are recorded
## in FarmState and gone for the rest of the run; a sack's contents are gone and the
## sack is free for the next theft.
## Supplies in a carried or dropped sack still count as on the farm (FarmState.supplies_in_transit).
## Claims and carriers are enemy handles (id + generation), so a stale handle from a reused enemy
## slot can never move an item. Every change emits loot_event (toasts now, sounds later); steals,
## recoveries, strays, and supply losses count toward the night's record.
enum Category { CROP, ANIMAL, SUPPLY }
enum Status { HOME, CARRIED, DROPPED, LOST, FOLLOWING }
enum Threat { NONE, TARGETED, CARRIED, DROPPED }
## EnemySystem.want for a thief with no set target (it goes by GameConfig.target_weights).
const ANY := 255
## Every category (a bit per Category), for claim()'s allowed mask.
const ALL := 7
const SACKS := 6
const CATEGORY_KEYS: Array[String] = ["crops", "animals", "supplies"]
const CATEGORY_COLORS := {
Category.CROP: Color(1.0, 0.8, 0.15),
Category.ANIMAL: Color(1.0, 0.45, 0.75),
Category.SUPPLY: Color(0.35, 0.8, 1.0),
}
## Badge interiors (loot_icon.gdshader): fill and center per category.
const BADGE_FILL := {
Category.CROP: [Color(1.0, 0.82, 0.18), Color(0.32, 0.18, 0.07)],
Category.ANIMAL: [Color(1.0, 0.62, 0.78), Color(1.0, 0.92, 0.95)],
Category.SUPPLY: [Color(0.78, 0.62, 0.4), Color(0.35, 0.8, 1.0)],
}
const TOKEN_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_007.tscn"
const SACK_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_002.tscn"
const THREAT_COLORS := {
Threat.TARGETED: Color(1.0, 0.6, 0.1),
Threat.CARRIED: Color(1.0, 0.22, 0.15),
Threat.DROPPED: Color(1.0, 0.9, 0.25),
}
## kind: &"targeted", &"stolen", &"dropped", &"recovered", &"returned" (back home without the
## scarecrow's help: auto at dawn, or an animal dropped inside the pen), &"lost", &"following",
## &"follow_full" (the scarecrow already leads the most animals it can), &"strayed" (an animal
## wandered out of an open pen).
signal loot_event(kind: StringName, id: int, position: Vector3)
var campaign: CampaignController
var enemies: EnemySystem
var config: GameConfig
## Set by FarmSim: animal positions and the shed's piles (where supply thieves stand).
var animals: AnimalSystem
var shed_stock: ShedStock
## Crop units (ids 1..unit_count), then animals, then sacks.
var unit_count: int = 0
var animal_count: int = 0
var item_count: int = 0
# Per item, indexed by id (index 0 unused).
var category := PackedByteArray()
var status := PackedByteArray()
var holder := PackedInt32Array()
var progress := PackedFloat32Array()
## Crops: the plot position. Sacks: the pile spot it is taken from (set when claimed).
var home := PackedVector2Array()
var ground := PackedVector2Array()
## Sacks: the material and how much of it they hold.
var sack_material: Array[String] = []
var sack_amount := PackedInt32Array()
## What the HUD should point at this frame, and where (filled in _process).
var threat := PackedByteArray()
var focus := PackedVector3Array()
var _units: Array[CropUnit] = []
var _markers: Array[Label3D] = []
var _rings: Array[MeshInstance3D] = []
var _ring_mats: Array[ShaderMaterial] = []
var _tokens: Array[Node3D] = []
var _icons: Array[MeshInstance3D] = []
var _icon_mats: Array[ShaderMaterial] = []
var _warned := PackedByteArray()
var _outline := {} # Category -> StandardMaterial3D
var _rng := RandomNumberGenerator.new()
var _time: float = 0.0
func setup(p_campaign: CampaignController, units: Array[CropUnit], p_enemies: EnemySystem, p_animal_count: int = 0) -> void:
campaign = p_campaign
config = p_campaign.config
enemies = p_enemies
unit_count = units.size()
animal_count = p_animal_count
item_count = unit_count + animal_count + SACKS
var n := item_count + 1
for a: PackedByteArray in [category, status, threat, _warned]:
a.resize(n)
for a: PackedInt32Array in [holder, sack_amount]:
a.resize(n)
progress.resize(n)
home.resize(n)
ground.resize(n)
focus.resize(n)
sack_material.resize(n)
sack_material.fill("")
_units.resize(unit_count + 1)
_markers.resize(n)
_rings.resize(n)
_ring_mats.resize(n)
_tokens.resize(n)
_icons.resize(n)
_icon_mats.resize(n)
_rng.seed = 20261003
for c: Category in CATEGORY_COLORS:
_outline[c] = outline_material(CATEGORY_COLORS[c])
var ring_shader := load("res://game/resources/steal_ring.gdshader") as Shader
var icon_shader := load("res://game/resources/loot_icon.gdshader") as Shader
var token_scene := load(TOKEN_SCENE) as PackedScene
var sack_scene := load(SACK_SCENE) as PackedScene
for id in range(1, n):
category[id] = _category_of(id)
_markers[id] = _marker()
_ring_mats[id] = ShaderMaterial.new()
_ring_mats[id].shader = ring_shader
_rings[id] = _billboard(1.1, _ring_mats[id])
_icon_mats[id] = ShaderMaterial.new()
_icon_mats[id].shader = icon_shader
var fill: Array = BADGE_FILL[category[id]]
_icon_mats[id].set_shader_parameter("fill_color", fill[0])
_icon_mats[id].set_shader_parameter("center_color", fill[1])
_icons[id] = _billboard(0.9, _icon_mats[id])
var token: Node3D = null
match category[id]:
Category.CROP:
token = token_scene.instantiate() as Node3D
token.scale = Vector3.ONE * 0.6
Category.SUPPLY:
token = sack_scene.instantiate() as Node3D
token.scale = Vector3.ONE * 0.85
StructureSystem._strip_collision(token)
if token != null:
token.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
for mi in token.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _outline[category[id]]
add_child(token)
_tokens[id] = token
for u in units:
_units[u.unit_id] = u
home[u.unit_id] = Vector2(u.global_position.x, u.global_position.z)
sync_from_state()
## Every item back home, or gone if the farm state records it as lost (new vacation, retry,
## load). Clears all claims and empties every sack.
func sync_from_state() -> void:
var s := campaign.state
for id in range(1, item_count + 1):
match category[id]:
Category.CROP:
status[id] = Status.LOST if s.is_crop_lost(id) else Status.HOME
_units[id].visible = status[id] == Status.HOME
Category.ANIMAL:
status[id] = Status.LOST if s.is_animal_lost(animal_index(id)) else Status.HOME
Category.SUPPLY:
status[id] = Status.HOME
sack_amount[id] = 0
holder[id] = -1
progress[id] = 0.0
_warned[id] = 0
s.supplies_in_transit = 0
update_visuals()
## Co-op host: every item's status, holder (enemy handle), steal progress, ground spot, and sack.
func replica_record() -> Dictionary:
var shown := PackedByteArray()
shown.resize(unit_count + 1)
for id in range(1, unit_count + 1):
shown[id] = 1 if _units[id].visible else 0
return {"status": status, "holder": holder, "progress": progress, "ground": ground, "amount": sack_amount,
"material": sack_material.duplicate(), "transit": campaign.state.supplies_in_transit, "units": shown}
## Co-op partner: shows the host's items (resolve: host enemy handle -> this machine's handle).
func apply_replica(rec: Dictionary, resolve: Callable) -> void:
var st: PackedByteArray = rec.get("status", PackedByteArray())
if st.size() != status.size():
return
status = st
var hosts: PackedInt32Array = rec["holder"]
for id in hosts.size():
holder[id] = int(resolve.call(hosts[id])) if hosts[id] >= 0 else -1
progress = rec["progress"]
ground = rec["ground"]
sack_amount = rec["amount"]
for i in mini(sack_material.size(), (rec["material"] as Array).size()):
sack_material[i] = String(rec["material"][i])
campaign.state.supplies_in_transit = int(rec.get("transit", 0))
var shown: PackedByteArray = rec.get("units", PackedByteArray())
for id in range(1, mini(unit_count + 1, shown.size())):
_units[id].visible = shown[id] == 1
func is_valid_unit(id: int) -> bool:
return id >= 1 and id <= item_count
func is_home(id: int) -> bool:
return is_valid_unit(id) and status[id] == Status.HOME
## Animal ids in FarmState (1..animal_count) <-> item ids.
func animal_index(id: int) -> int:
return id - unit_count
func animal_item(index: int) -> int:
return unit_count + index
func first_sack() -> int:
return unit_count + animal_count + 1
func is_claimed_by(id: int, handle: int) -> bool:
return is_valid_unit(id) and handle >= 0 and holder[id] == handle \
and (status[id] == Status.HOME or status[id] == Status.DROPPED)
## Where a thief has to go for this item: its plot, the animal itself, the shed pile, or where it
## was dropped.
func position_of(id: int) -> Vector2:
if category[id] == Category.ANIMAL and animals != null:
return animals.position(animal_index(id))
return ground[id] if status[id] == Status.DROPPED else home[id]
## Seconds a thief needs to take this item.
func steal_time(id: int) -> float:
match category[id]:
Category.ANIMAL:
return config.animal_capture_time
Category.SUPPLY:
return config.supply_steal_time
return config.crop_steal_time
## Claims an item for a thief, only from the allowed categories (a bit per Category: what its
## enemy type takes): the nearest unclaimed dropped item in view within range (in clear view
## unless need_line is off, for flyers), else one at home in the wanted category (a random crop or
## animal, a sack at the pile of the material the shed holds most of), else in another allowed
## category, picked by target_weights. Returns the id, or -1 if nothing is left.
func claim(handle: int, from: Vector2, nav: FarmNavigation, view_range: float, want: int = ANY,
allowed: int = ALL, need_line: bool = true) -> int:
var best := -1
var best_d := view_range
for id in range(1, item_count + 1):
if status[id] == Status.DROPPED and holder[id] == -1 and (allowed & (1 << category[id])) != 0:
var at := position_of(id)
var d := at.distance_to(from)
if d < best_d and (not need_line or nav.line_clear(from.x, from.y, at.x, at.y)):
best = id
best_d = d
if best < 0:
for c in _preference(want):
if (allowed & (1 << c)) == 0:
continue
best = _claim_home(c)
if best > 0:
break
if best < 0:
return -1
holder[best] = handle
progress[best] = 0.0
loot_event.emit(&"targeted", best, _world(position_of(best)))
return best
## Whether a thief could claim anything at home in this category right now.
func available(c: Category) -> bool:
match c:
Category.SUPPLY:
return campaign.state.resources.shed_total() > 0 and _free_sack() > 0
_:
for id in _ids(c):
if status[id] == Status.HOME and holder[id] == -1:
return true
return false
func release(id: int, handle: int) -> void:
if is_claimed_by(id, handle):
holder[id] = -1
progress[id] = 0.0
func set_progress(id: int, handle: int, value: float) -> void:
if is_claimed_by(id, handle):
progress[id] = clampf(value, 0.0, 1.0)
## The claiming thief takes the item. Returns false if it doesn't hold the claim, or (for a sack)
## the shed has nothing left; the claim is released then.
func pick_up(id: int, handle: int) -> bool:
if not is_claimed_by(id, handle):
return false
var s := campaign.state
var at := position_of(id)
match category[id]:
Category.CROP:
_units[id].visible = false
s.record_event("crops_stolen")
Category.ANIMAL:
s.record_event("animals_stolen")
Category.SUPPLY:
if status[id] == Status.HOME:
var r := s.resources
var m := sack_material[id]
if m == "" or int(r.shed[m]) <= 0:
m = r.most_stocked()
if m == "":
release(id, handle)
return false
var amount := mini(config.supply_bundle, int(r.shed[m]))
r.shed[m] = int(r.shed[m]) - amount
sack_material[id] = m
sack_amount[id] = amount
s.supplies_in_transit += amount
s.record_event("supplies_stolen", amount)
if r.shed_total() == 0:
s.shed_raided = true
status[id] = Status.CARRIED
progress[id] = 0.0
loot_event.emit(&"stolen", id, _world(at))
return true
## The carrier was stopped at (x, z).
func drop(id: int, handle: int, x: float, z: float) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return
status[id] = Status.DROPPED
holder[id] = -1
ground[id] = Vector2(x, z)
if category[id] == Category.ANIMAL and animals != null:
animals.place(animal_index(id), ground[id])
loot_event.emit(&"dropped", id, _world(ground[id]))
## The carrier left the farm with the item: it is lost for good (a sack's contents are).
func escape(id: int, handle: int) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return
_lose(id)
## The scarecrow got a dropped item back: a crop returns to its plot, a sack to the shed, and a
## loose animal starts following (if the scarecrow has room for another).
func recover(id: int) -> bool:
if not is_valid_unit(id) or status[id] != Status.DROPPED:
return false
var s := campaign.state
match category[id]:
Category.ANIMAL:
if followers() >= config.max_following_animals:
return false
status[id] = Status.FOLLOWING
holder[id] = -1
if animals != null:
animals.start_following(animal_index(id))
loot_event.emit(&"following", id, _world(position_of(id)))
return true
Category.CROP:
_return_home(id)
s.record_event("crops_recovered")
Category.SUPPLY:
s.record_event("supplies_recovered", sack_amount[id])
loot_event.emit(&"recovered", id, _world(ground[id]))
_empty_sack(id, true)
return true
loot_event.emit(&"recovered", id, _world(home[id]))
return true
## An animal (loose, or following the scarecrow) is back inside the pen.
func animal_home(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL:
return
if status[id] != Status.FOLLOWING and status[id] != Status.DROPPED:
return
var led := status[id] == Status.FOLLOWING
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
if led:
campaign.state.record_event("animals_recovered")
loot_event.emit(&"recovered" if led else &"returned", id, _world(position_of(id)))
## An animal at home walks out of the open pen: it is loose now.
func animal_strays(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.HOME or holder[id] != -1:
return
status[id] = Status.DROPPED
ground[id] = position_of(id)
campaign.state.record_event("animals_strayed")
loot_event.emit(&"strayed", id, _world(ground[id]))
## A loose animal got off the farm on its own.
func animal_escaped(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.DROPPED:
return
_lose(id)
## End of the dawn grace (D6): dropped items still on the ground go home (crops to their plots,
## sacks to the shed); loose and following animals are back in the pen.
func return_dropped() -> void:
for id in range(1, item_count + 1):
var st := status[id]
if st == Status.DROPPED or (st == Status.FOLLOWING and category[id] == Category.ANIMAL):
var at := _world(position_of(id))
if category[id] == Category.SUPPLY:
_empty_sack(id, true)
else:
_return_home(id)
loot_event.emit(&"returned", id, at)
## Settles what a removed enemy held: a killed carrier drops its loot, one that left at the end
## of the night takes it along, and any claim is released.
func on_enemy_removed(handle: int, reason: EnemySystem.Removal, x: float, z: float, carried: int, targeted: int) -> void:
if carried >= 0:
if reason == EnemySystem.Removal.KILLED:
drop(carried, handle, x, z)
elif reason == EnemySystem.Removal.LEFT:
escape(carried, handle)
if targeted >= 0:
release(targeted, handle)
## Physics tick: the scarecrow recovers dropped items it walks up to (a loose animal starts
## following it; with no room left it says so once per approach).
## Co-op: which scarecrow (0 = player 1, 1 = player 2) recovered last (a loose animal follows it).
var recoverer: int = 0
## Recovery by touch for one scarecrow (who: 0 = player 1, 1 = player 2; call once each).
func step(scarecrow: Vector2, who: int = 0) -> void:
recoverer = who
var r2 := config.pickup_radius * config.pickup_radius
for id in range(1, item_count + 1):
if status[id] != Status.DROPPED:
_warned[id] = 0
continue
var near := position_of(id).distance_squared_to(scarecrow) <= r2
if not near:
_warned[id] = 0
elif not recover(id) and _warned[id] == 0:
_warned[id] = 1
loot_event.emit(&"follow_full", id, _world(position_of(id)))
func followers() -> int:
return count(Status.FOLLOWING, Category.ANIMAL)
## Items with this status, in one category (or all, cat = -1).
func count(which: Status, cat: int = -1) -> int:
var n := 0
for id in range(1, item_count + 1):
if status[id] == which and (cat < 0 or category[id] == cat):
n += 1
return n
## "crop", "pig", "sack of wood": what an item is, for messages.
func noun(id: int) -> String:
match category[id]:
Category.ANIMAL:
return animals.kind(animal_index(id)) if animals != null else "animal"
Category.SUPPLY:
return "%d %s" % [sack_amount[id], sack_material[id]] if sack_amount[id] > 0 else "supplies"
return "crop"
func _process(delta: float) -> void:
_time += delta
update_visuals()
## Places markers, rings, tokens, and badges, and fills threat / focus for the HUD.
func update_visuals() -> void:
var bob := sin(_time * 5.0)
for id in range(1, item_count + 1):
var st := status[id]
var cat := category[id]
var h := position_of(id) if st == Status.HOME or st == Status.FOLLOWING else home[id]
var top := 2.0 if cat == Category.ANIMAL else 3.2
var targeted := st == Status.HOME and holder[id] >= 0
var marker := _markers[id]
var ring := _rings[id]
ring.visible = targeted and progress[id] > 0.0
marker.visible = targeted
if targeted:
marker.position = Vector3(h.x, (top + 0.55 if ring.visible else top) + bob * 0.12, h.y)
if ring.visible:
ring.position = Vector3(h.x, top - 0.75, h.y)
_ring_mats[id].set_shader_parameter("progress", progress[id])
var token := _tokens[id]
var icon := _icons[id]
threat[id] = Threat.TARGETED if targeted else Threat.NONE
focus[id] = Vector3(h.x, 2.0, h.y)
var shown := false
match st:
Status.CARRIED:
var d := enemies.resolve_handle(holder[id]) if enemies != null else -1
var p := enemies.visual_position(d) if d >= 0 else h
if token != null:
token.position = Vector3(p.x, config.combat_height + 0.25, p.y)
token.rotation.y = _time * 1.5
icon.position = Vector3(p.x, config.combat_height + 1.55, p.y)
_icon_mats[id].set_shader_parameter("edge_color", THREAT_COLORS[Threat.CARRIED])
_icon_mats[id].set_shader_parameter("pulse", 0.0)
threat[id] = Threat.CARRIED
focus[id] = Vector3(p.x, config.combat_height + 0.25, p.y)
shown = true
Status.DROPPED:
var g := position_of(id)
if token != null:
token.position = Vector3(g.x, 0.15 + (bob + 1.0) * 0.12, g.y)
token.rotation.y = _time * 0.8
icon.position = Vector3(g.x, 1.75 + bob * 0.12, g.y)
_icon_mats[id].set_shader_parameter("edge_color", THREAT_COLORS[Threat.DROPPED])
_icon_mats[id].set_shader_parameter("pulse", 0.5 + 0.5 * sin(_time * 7.0))
threat[id] = Threat.DROPPED
focus[id] = Vector3(g.x, 0.6, g.y)
shown = true
if token != null:
token.visible = shown
icon.visible = shown
## An unshaded, front-culled shell drawn over a mesh: a colored outline.
static func outline_material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
m.cull_mode = BaseMaterial3D.CULL_FRONT
m.grow = true
m.grow_amount = 0.05
m.albedo_color = color
return m
func outline_for(c: Category) -> StandardMaterial3D:
return _outline[c]
func _category_of(id: int) -> Category:
if id <= unit_count:
return Category.CROP
if id <= unit_count + animal_count:
return Category.ANIMAL
return Category.SUPPLY
func _ids(c: Category) -> Array:
match c:
Category.CROP:
return range(1, unit_count + 1)
Category.ANIMAL:
return range(unit_count + 1, unit_count + animal_count + 1)
return range(first_sack(), item_count + 1)
## The categories to try, in order: the wanted one first (all of them by weight for ANY), then
## the others in a weighted random order.
func _preference(want: int) -> Array[int]:
var left: Array[int] = [Category.CROP, Category.ANIMAL, Category.SUPPLY]
var out: Array[int] = []
if want != ANY and left.has(want):
out.append(want)
left.erase(want)
while not left.is_empty():
var total := 0.0
for c in left:
total += _weight(c)
var pick := left[0]
if total > 0.0:
var roll := _rng.randf() * total
for c in left:
roll -= _weight(c)
if roll <= 0.0:
pick = c
break
out.append(pick)
left.erase(pick)
return out
func _weight(c: int) -> float:
return maxf(float(config.target_weights.get(CATEGORY_KEYS[c], 1.0)), 0.0)
func _claim_home(c: int) -> int:
if c == Category.SUPPLY:
var r := campaign.state.resources
var m := r.most_stocked()
var sack := _free_sack()
if m == "" or sack < 0:
return -1
sack_material[sack] = m
home[sack] = shed_stock.spot(m) if shed_stock != null else Vector2.ZERO
return sack
var free: Array[int] = []
for id in _ids(c):
if status[id] == Status.HOME and holder[id] == -1:
free.append(id)
if free.is_empty():
return -1
return free[_rng.randi() % free.size()]
func _free_sack() -> int:
for id in range(first_sack(), item_count + 1):
if status[id] == Status.HOME and holder[id] == -1:
return id
return -1
func _lose(id: int) -> void:
var s := campaign.state
var at := _world(position_of(id))
holder[id] = -1
match category[id]:
Category.CROP:
status[id] = Status.LOST
s.lose_crop(id)
_units[id].visible = false
Category.ANIMAL:
status[id] = Status.LOST
s.lose_animal(animal_index(id))
Category.SUPPLY:
s.record_event("supplies_lost", sack_amount[id])
loot_event.emit(&"lost", id, at)
_empty_sack(id, false)
return
loot_event.emit(&"lost", id, at)
## A sack is done with: its contents go back to the shed (or are gone), and it is free again.
func _empty_sack(id: int, to_shed: bool) -> void:
var s := campaign.state
if to_shed and sack_material[id] != "":
s.resources.shed[sack_material[id]] = int(s.resources.shed[sack_material[id]]) + sack_amount[id]
s.supplies_in_transit = maxi(s.supplies_in_transit - sack_amount[id], 0)
sack_amount[id] = 0
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
func _return_home(id: int) -> void:
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
if category[id] == Category.CROP:
_units[id].visible = true
func _world(p: Vector2) -> Vector3:
return Vector3(p.x, 0.0, p.y)
func _marker() -> Label3D:
var l := Label3D.new()
l.text = "!"
l.font_size = 128
l.outline_size = 28
l.pixel_size = 0.006
l.modulate = THREAT_COLORS[Threat.TARGETED]
l.outline_modulate = Color(0.1, 0.05, 0.0)
l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
l.no_depth_test = true
l.shaded = false
l.visible = false
l.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(l)
return l
func _billboard(size: float, mat: ShaderMaterial) -> MeshInstance3D:
var quad := QuadMesh.new()
quad.size = Vector2(size, size)
var mi := MeshInstance3D.new()
mi.mesh = quad
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.visible = false
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
return mi

View file

@ -0,0 +1 @@
uid://gakx27ujp4gh

384
game/scripts/main.gd Normal file
View file

@ -0,0 +1,384 @@
class_name Main
extends Node
## The game's entry scene (game/scenes/main.tscn): the farm (farm.tscn) with the menus over it.
## * Starts at the main menu: the tree is paused (the farm stands still) and a camera slowly
## circles the farm behind the menu; the HUD is hidden.
## * New vacation (asks first when it would replace a save), Continue (the saved morning,
## SaveGame; refused with the reason when the save can't be used), Settings, Quit.
## * During play, Escape / Start pauses (PauseMenu): the tree pauses, so the simulation tick,
## timers, enemies, and game sounds all freeze. Resume, Restart the night (asks first),
## Settings, Save & quit to menu, Quit the game (asks first).
## * Every morning is autosaved (CampaignController.save_path). Back at the menu the farm is
## put back at that morning without saving again, so the menu never changes the save.
## * Settings (GameSettings) load at start and are applied and saved on every change.
## * Play with a friend (CoopMenu): host (continue or start a vacation, then the lobby opens,
## CoopLobby) or join (the games found). When both are in, the farm's CoopSession takes over
## over GD-Sync (GDSyncLink), with voice chat. In co-op the menus don't pause the farm; the
## host's leaving ends the partner's game (back to this menu, which says why), the partner's
## leaving leaves the host alone. [M] mutes the microphone.
## Main processes while paused; the farm doesn't. Tests set save_path and settings_path
## before adding it to the tree.
enum Screen { MENU, PLAYING, PAUSED }
const ORBIT_CENTER := Vector3(17.0, 0.0, -15.0)
const ORBIT_RADIUS := 44.0
const ORBIT_HEIGHT := 26.0
const ORBIT_SPEED := 0.035
var save_path := SaveGame.PATH
var settings_path := GameSettings.PATH
var screen: Screen = Screen.MENU
var settings: GameSettings
var quitting := false
## Why the last co-op game ended, for the main menu after the scene reloads.
static var notice := ""
var lobby: CoopLobby
var coop_hud: CoopHud
@onready var farm: Node3D = $Farm
@onready var sim: FarmSim = $Farm/FarmSim
@onready var main_menu: MainMenu = $Menus/MainMenu
@onready var pause_menu: PauseMenu = $Menus/PauseMenu
@onready var settings_menu: SettingsMenu = $Menus/SettingsMenu
@onready var confirm: ConfirmBox = $Menus/ConfirmBox
@onready var coop_menu: CoopMenu = $Menus/CoopMenu
var _menu_camera: Camera3D
var _orbit: float = 0.6
func _ready() -> void:
get_tree().auto_accept_quit = false # the window's close button goes through quit_game()
process_mode = Node.PROCESS_MODE_ALWAYS
farm.process_mode = Node.PROCESS_MODE_PAUSABLE
settings = GameSettings.load_from(settings_path)
settings.apply(get_viewport(), sim.config)
sim.campaign.save_path = save_path
if sim.end_panel != null:
sim.end_panel.has_menu = true
sim.end_panel.menu_requested.connect(to_menu)
if sim.tutorial != null:
sim.tutorial.enabled = settings.show_tips
main_menu.continue_requested.connect(continue_vacation)
main_menu.new_requested.connect(_ask_new_vacation)
main_menu.settings_requested.connect(_open_settings)
main_menu.quit_requested.connect(quit_game)
pause_menu.resume_requested.connect(resume)
pause_menu.restart_requested.connect(func() -> void:
confirm.ask("Restart night %d from this morning? Everything since the morning is lost." % sim.campaign.state.night,
"Restart the night", restart_night))
pause_menu.settings_requested.connect(_open_settings)
pause_menu.menu_requested.connect(to_menu)
pause_menu.quit_requested.connect(func() -> void:
confirm.ask("Quit the game? Continue picks up at the morning of day %d." % sim.campaign.state.night, "Quit", quit_game))
settings_menu.changed.connect(_on_settings_changed)
settings_menu.closed.connect(_on_settings_closed)
lobby = CoopLobby.new()
lobby.name = "Lobby"
add_child(lobby)
main_menu.coop_requested.connect(func() -> void:
main_menu.close()
coop_menu.open(SaveGame.read(save_path), sim.config.campaign_nights, settings.player_name))
coop_menu.back_requested.connect(func() -> void:
lobby.leave()
coop_menu.close()
show_main_menu())
coop_menu.host_requested.connect(_host_coop)
coop_menu.search_requested.connect(func(mode: CoopLobby.Mode, player: String) -> void:
_remember_name(player)
lobby.search(mode, player))
coop_menu.join_requested.connect(func(n: String) -> void: lobby.join(n))
coop_menu.join_address_requested.connect(func(a: String) -> void:
_remember_name(coop_menu.player_name())
lobby.join_address(a, coop_menu.player_name()))
lobby.status_changed.connect(func(text: String) -> void:
if coop_menu.is_open:
coop_menu.set_status(text))
lobby.failed.connect(func(text: String) -> void:
if coop_menu.is_open:
coop_menu.set_status(text)
elif sim.toasts != null:
sim.toasts.push(text, Color(1.0, 0.6, 0.4)))
lobby.lobbies_found.connect(func(list: Array) -> void: coop_menu.show_lobbies(list))
lobby.partner_arrived.connect(_on_partner_arrived)
lobby.joined.connect(_on_joined)
lobby.other_left.connect(_on_other_left)
var session := sim.coop
session.process_mode = Node.PROCESS_MODE_ALWAYS # a join arrives while the menus pause the farm
if lobby.gdsync != null:
lobby.gdsync.expose_func(session.net_receive) # before anyone can call it
session.welcomed.connect(_on_welcomed)
session.ended.connect(_on_session_ended)
coop_hud = CoopHud.new()
coop_hud.name = "CoopHud"
coop_hud.setup(sim, session, lobby)
var hud_layer := farm.get_node_or_null("Hud")
if hud_layer != null:
hud_layer.add_child(coop_hud)
if sim.audio != null:
sim.audio.wire_buttons($Menus)
_menu_camera = Camera3D.new()
_menu_camera.fov = 50.0
add_child(_menu_camera)
show_main_menu()
func _process(delta: float) -> void:
if screen == Screen.MENU:
_orbit += ORBIT_SPEED * delta
_place_menu_camera()
func show_main_menu() -> void:
screen = Screen.MENU
get_tree().paused = true
_set_hud(false)
pause_menu.close()
_place_menu_camera()
_menu_camera.make_current()
main_menu.open(SaveGame.read(save_path), sim.config.campaign_nights)
main_menu.notice.text = notice
notice = ""
## Continue: the saved morning, if it can be used.
func continue_vacation() -> bool:
var saved := SaveGame.read(save_path)
if saved.status != SaveGame.Status.OK:
main_menu.open(saved, sim.config.campaign_nights)
if sim.audio != null:
sim.audio.ui("error")
return false
_play()
sim.campaign.load_state(saved.state)
return true
## New vacation: a fresh farm, the morning of night 1 (saved at once, replacing any save).
func new_vacation() -> void:
_play()
sim.campaign.new_campaign()
func pause() -> void:
if screen != Screen.PLAYING:
return
screen = Screen.PAUSED
var coop := 0
if sim.coop.is_host():
coop = 1
elif sim.coop.is_client():
coop = 2
if coop == 0:
get_tree().paused = true
else:
sim.freeze_local(true) # co-op: the farm doesn't stop for one player's menu
pause_menu.open(sim.campaign, coop)
func resume() -> void:
if screen != Screen.PAUSED:
return
confirm.close()
settings_menu.close()
pause_menu.close()
screen = Screen.PLAYING
get_tree().paused = false
if sim.local_frozen:
sim.freeze_local(false)
func restart_night() -> void:
resume()
sim.campaign.retry_night()
## Back to the main menu, with the farm reset to the saved morning (nothing is saved). In co-op
## the host ends the game for both; a partner leaves (their game resets).
func to_menu() -> void:
confirm.close()
settings_menu.close()
if sim.coop.is_client():
_leave_as_partner("")
return
sim.coop.stop()
lobby.leave()
var c := sim.campaign
c.save_path = ""
if c.outcome == CampaignController.Outcome.VACATION_COMPLETE or not SaveGame.exists(save_path):
c.new_campaign()
else:
c.retry_night()
c.save_path = save_path
show_main_menu()
## Quits (the save is the morning's; nothing else to write): the farm goes first, and the audio
## server gets a moment to drop its stopped sounds.
func quit_game() -> void:
if quitting:
return
quitting = true
sim.coop.stop()
lobby.leave()
if is_instance_valid(farm):
farm.queue_free()
await get_tree().process_frame
await get_tree().create_timer(0.2, true, false, true).timeout
get_tree().quit()
func _notification(what: int) -> void:
if what == NOTIFICATION_WM_CLOSE_REQUEST:
quit_game()
func _play() -> void:
main_menu.close()
confirm.close()
settings_menu.close()
pause_menu.close()
_set_hud(true)
sim.camera.make_current()
screen = Screen.PLAYING
get_tree().paused = false
## Hosting: the vacation first (the save, or a new one), then the lobby opens; the friend can
## join any time.
func _host_coop(mode: CoopLobby.Mode, player: String, resume: bool) -> void:
_remember_name(player)
var go := func() -> void:
coop_menu.close()
if resume:
if not continue_vacation():
return
else:
new_vacation()
lobby.host(mode, player)
if not resume and SaveGame.read(save_path).status == SaveGame.Status.OK:
confirm.ask("Start a new vacation? It replaces your saved one.", "New vacation", go)
else:
go.call()
func _on_partner_arrived(client_id: int) -> void:
var gd := lobby.gdsync
gd.expose_func(sim.coop.net_receive)
var link := GDSyncLink.new(gd, client_id, sim.coop)
sim.coop.start_host(sim, link, lobby.my_name, String(gd.player_get_username(client_id, "Friend")))
sim.coop.start_voice(gd, [lobby.my_id(), client_id], settings.microphone)
func _on_joined(host_id: int) -> void:
var gd := lobby.gdsync
gd.expose_func(sim.coop.net_receive)
var link := GDSyncLink.new(gd, host_id, sim.coop)
sim.coop.start_client(sim, link, lobby.my_name)
sim.coop.start_voice(gd, [host_id, lobby.my_id()], settings.microphone)
coop_menu.set_status("Joined: waiting for the farm...")
func _on_welcomed() -> void:
coop_menu.close()
_play()
func _on_other_left(_client_id: int) -> void:
if sim.coop.is_host():
sim.coop.stop() # the host plays on alone; the lobby stays open
elif sim.coop.is_client():
sim.coop.stop("The host left the game")
func _on_session_ended(reason: String) -> void:
_leave_as_partner(reason)
## A partner's game is a replica of the host's: leaving resets it by reloading the scene.
func _leave_as_partner(reason: String) -> void:
notice = reason
sim.coop.stop()
lobby.leave()
get_tree().paused = false
get_tree().reload_current_scene.call_deferred()
func _remember_name(player: String) -> void:
if player != settings.player_name:
settings.player_name = player
settings.save_to(settings_path)
func _ask_new_vacation() -> void:
var saved := SaveGame.read(save_path)
if saved.status == SaveGame.Status.OK:
confirm.ask("Start a new vacation? It replaces your saved one (the morning of day %d of %d)." % [saved.state.night,
sim.config.campaign_nights], "New vacation", new_vacation)
else:
new_vacation()
func _open_settings() -> void:
pause_menu.visible = false # one menu at a time
settings_menu.open(settings)
func _on_settings_changed() -> void:
settings.apply(get_viewport(), sim.config)
sim.coop.set_microphone(settings.microphone)
if sim.tutorial != null:
sim.tutorial.enabled = settings.show_tips
var err := settings.save_to(settings_path)
if err != OK:
push_warning("Couldn't save settings to %s: %s" % [settings_path, error_string(err)])
func _on_settings_closed() -> void:
match screen:
Screen.MENU:
main_menu.settings_button.grab_focus.call_deferred()
Screen.PAUSED:
pause_menu.visible = true
pause_menu.settings_button.grab_focus.call_deferred()
func _set_hud(on: bool) -> void:
for layer_name in ["Hud", "ZoneBanner"]:
var layer := farm.get_node_or_null(layer_name) as CanvasLayer
if layer != null:
layer.visible = on
func _place_menu_camera() -> void:
var at := ORBIT_CENTER + Vector3(cos(_orbit) * ORBIT_RADIUS, ORBIT_HEIGHT, sin(_orbit) * ORBIT_RADIUS)
_menu_camera.global_position = at
_menu_camera.look_at(ORBIT_CENTER + Vector3(4.0, 0.0, 0.0), Vector3.UP)
func _unhandled_input(event: InputEvent) -> void:
if quitting:
return
if event.is_action_pressed("toggle_mic") and sim.coop.is_active() and not sim.coop.voices.is_empty():
settings.microphone = not settings.microphone
sim.coop.set_microphone(settings.microphone)
settings.save_to(settings_path)
if sim.toasts != null:
sim.toasts.push("Microphone %s" % ("on" if settings.microphone else "muted"), Color(0.85, 0.95, 1.0))
get_viewport().set_input_as_handled()
return
if not event.is_action_pressed("pause"):
return
match screen:
Screen.PLAYING:
pause()
get_viewport().set_input_as_handled()
Screen.PAUSED:
if confirm.is_open:
confirm.close()
elif settings_menu.is_open:
settings_menu.close()
else:
resume()
get_viewport().set_input_as_handled()

1
game/scripts/main.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cknwtl25dvosc

113
game/scripts/main_menu.gd Normal file
View file

@ -0,0 +1,113 @@
class_name MainMenu
extends Control
## The title screen over the farm (Main slowly circles a camera around it): the title, then
## Continue (with which morning it resumes at, or why the save can't be continued), New
## vacation, Play with a friend (co-op, CoopMenu), Settings, and Quit, and a notice line (e.g.
## why a co-op game ended). Mouse, keyboard, and gamepad work through focus.
signal continue_requested
signal new_requested
signal settings_requested
signal coop_requested
signal quit_requested
var continue_button: Button
var new_button: Button
var settings_button: Button
var coop_button: Button
var notice: Label
var quit_button: Button
var save_note: Label
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var shade := ColorRect.new() # darkens the left side behind the buttons
shade.color = Color(0.03, 0.04, 0.03, 0.62)
shade.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(shade)
shade.set_anchors_and_offsets_preset(Control.PRESET_LEFT_WIDE)
shade.offset_right = 700.0
var box := VBoxContainer.new()
box.position = Vector2(110.0, 150.0)
box.add_theme_constant_override("separation", 16)
add_child(box)
var title := Label.new()
title.text = "Harvest Season"
title.add_theme_font_size_override("font_size", 92)
title.add_theme_color_override("font_color", UiTheme.GOLD)
title.add_theme_color_override("font_outline_color", Color(0.15, 0.1, 0.05))
title.add_theme_constant_override("outline_size", 14)
box.add_child(title)
var sub := Label.new()
sub.text = "The farmers are away. You're the scarecrow."
sub.add_theme_font_size_override("font_size", 28)
sub.add_theme_color_override("font_color", UiTheme.TEXT)
box.add_child(sub)
var gap := Control.new()
gap.custom_minimum_size = Vector2(0.0, 50.0)
box.add_child(gap)
continue_button = _button(box, "Continue")
continue_button.pressed.connect(func() -> void: continue_requested.emit())
save_note = Label.new()
save_note.add_theme_font_size_override("font_size", 19)
save_note.add_theme_color_override("font_color", Color(0.75, 0.77, 0.7))
box.add_child(save_note)
new_button = _button(box, "New vacation")
new_button.pressed.connect(func() -> void: new_requested.emit())
coop_button = _button(box, "Play with a friend")
coop_button.pressed.connect(func() -> void: coop_requested.emit())
settings_button = _button(box, "Settings")
settings_button.pressed.connect(func() -> void: settings_requested.emit())
quit_button = _button(box, "Quit")
quit_button.pressed.connect(func() -> void: quit_requested.emit())
notice = Label.new()
notice.add_theme_font_size_override("font_size", 22)
notice.add_theme_color_override("font_color", Color(1.0, 0.75, 0.5))
box.add_child(notice)
var credits := Label.new()
credits.text = "Art: KayKit and ithappy · Sounds: Kenney (CC0) · Music: \"On the Farm\"; DavidKBD, Purgatory · Co-op: GD-Sync · Made with Godot"
credits.add_theme_font_size_override("font_size", 16)
credits.add_theme_color_override("font_color", Color(0.6, 0.62, 0.56))
add_child(credits)
credits.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_LEFT)
credits.offset_top = -60.0
credits.offset_left = 110.0
visible = false
## Shows the menu for the save as read (SaveGame.read): Continue says where it resumes, or is
## off with the reason.
func open(saved: SaveGame.Loaded, nights: int) -> void:
visible = true
var ok := saved != null and saved.status == SaveGame.Status.OK
continue_button.disabled = not ok
continue_button.focus_mode = Control.FOCUS_ALL if ok else Control.FOCUS_NONE
if ok:
save_note.text = "Morning of day %d of %d%s" % [saved.state.night, nights,
(" · saved " + saved.saved_at.replace("T", " ").left(16)) if saved.saved_at != "" else ""]
else:
save_note.text = saved.message if saved != null else "No saved vacation"
_focus_first.call_deferred()
func close() -> void:
visible = false
## Continue when it can be used, else New vacation (checked when it runs: open() may have been
## called again since).
func _focus_first() -> void:
if visible:
(new_button if continue_button.disabled else continue_button).grab_focus()
func _button(parent: Control, text: String) -> Button:
var b := Button.new()
b.text = text
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.custom_minimum_size = Vector2(380.0, 62.0)
b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
b.add_theme_font_size_override("font_size", 28)
parent.add_child(b)
return b

View file

@ -0,0 +1 @@
uid://cw4ypb8hbwkef

View file

@ -0,0 +1,86 @@
class_name NightPlan
extends Resource
## One night (the plan's NightDefinition): its title, the hint shown at dusk, an optional length,
## and groups of enemies, each arriving at a time into the night. Where is not planned: every
## enemy arrives at its own random point along the farm's edge (WaveDirector).
## game/resources/nights/night_1..5.tres are the vacation's nights; game/resources/scenarios/
## holds debug plans.
## time seconds after nightfall when the group's first enemy arrives
## count how many arrive
## every seconds between them
## type enemy type: "thief", "crow", or "breaker"
## target what they're after: "crops", "animals", "supplies", or "any" (GameConfig.target_weights)
## The plans are the nights' designs; GameConfig.wave_count_scale and wave_spacing_scale scale
## every group when the night is played (count_scale x the enemies, spacing_scale x the time
## between them), so the whole vacation's pressure is tuned in one place. A plan can set its own
## scales instead (night 1 plays as designed, at 1 and 1).
@export var title: String = ""
## What the HUD tells the player at dusk about tonight.
@export_multiline var dusk_hint: String = ""
## Seconds the night lasts; 0 uses GameConfig.night_length.
@export var night_length: float = 0.0
## This night's own scales; 0 uses GameConfig.wave_count_scale / wave_spacing_scale.
@export var count_scale: float = 0.0
@export var spacing_scale: float = 0.0
@export var groups: Array[Dictionary] = []
## The scales this night is played at: its own, or the config's.
func count_scale_in(config: GameConfig) -> float:
return count_scale if count_scale > 0.0 else config.wave_count_scale
func spacing_scale_in(config: GameConfig) -> float:
return spacing_scale if spacing_scale > 0.0 else config.wave_spacing_scale
## A group's enemies and the seconds between them, scaled.
static func scaled_count(g: Dictionary, count_scale: float = 1.0) -> int:
return maxi(roundi(int(g.get("count", 1)) * count_scale), 1)
static func scaled_every(g: Dictionary, spacing_scale: float = 1.0) -> float:
return float(g.get("every", 2.0)) * spacing_scale
func total(count_scale: float = 1.0) -> int:
var n := 0
for g in groups:
n += scaled_count(g, count_scale)
return n
## What's wrong with the plan (empty when it's fine): unknown enemy types, a target the type
## doesn't take, or arrivals outside the night (as scaled).
func problems(length: float, count_scale: float = 1.0, spacing_scale: float = 1.0) -> PackedStringArray:
var out := PackedStringArray()
if groups.is_empty():
out.append("no groups")
for k in groups.size():
var g: Dictionary = groups[k]
var where := "group %d" % (k + 1)
var type := String(g.get("type", ""))
var t := EnemySystem.TYPE_NAMES.find(type)
if t < 0:
out.append("%s: unknown enemy type '%s'" % [where, type])
continue
var target := String(g.get("target", "any"))
var allowed := {"crow": ["crops", "any"], "thief": ["animals", "supplies", "any"], "breaker": ["any"]}
if not (allowed[type] as Array).has(target):
out.append("%s: a %s doesn't go for '%s'" % [where, type, target])
if int(g.get("count", 0)) < 1 or float(g.get("every", 0.0)) <= 0.0:
out.append("%s: count and spacing must be positive" % where)
var last := float(g.get("time", 0.0)) + (scaled_count(g, count_scale) - 1) * scaled_every(g, spacing_scale)
if float(g.get("time", -1.0)) < 0.0 or last >= length:
out.append("%s: arrivals (%.0f..%.0f s) outside the %.0f s night" % [where, float(g.get("time", 0.0)), last, length])
return out
## How many of each enemy type (EnemySystem type id -> count), scaled.
func type_counts(count_scale: float = 1.0) -> Dictionary:
var out := {}
for g in groups:
var t := maxi(EnemySystem.TYPE_NAMES.find(String(g.get("type", "thief"))), 0)
out[t] = int(out.get(t, 0)) + scaled_count(g, count_scale)
return out

View file

@ -0,0 +1 @@
uid://bx3jd1naaa7iu

View file

@ -0,0 +1,98 @@
class_name PauseMenu
extends CenterContainer
## Escape / Start during play (Main pauses the tree): where you are, then Resume, Restart the
## night, Settings, Save & quit to the menu, and Quit the game, with a reminder of what Continue
## picks up (the vacation is saved every morning).
signal resume_requested
signal restart_requested
signal settings_requested
signal menu_requested
signal quit_requested
var resume_button: Button
var restart_button: Button
var settings_button: Button
var menu_button: Button
var quit_button: Button
var _where: Label
var _note: Label
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 32)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 14)
margin.add_child(box)
var title := Label.new()
title.text = "Paused"
title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
title.add_theme_font_size_override("font_size", 48)
title.add_theme_color_override("font_color", UiTheme.GOLD)
box.add_child(title)
_where = Label.new()
_where.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_where.add_theme_font_size_override("font_size", 22)
box.add_child(_where)
resume_button = _button(box, "Resume")
resume_button.pressed.connect(func() -> void: resume_requested.emit())
restart_button = _button(box, "Restart the night")
restart_button.pressed.connect(func() -> void: restart_requested.emit())
settings_button = _button(box, "Settings")
settings_button.pressed.connect(func() -> void: settings_requested.emit())
menu_button = _button(box, "Save & quit to menu")
menu_button.pressed.connect(func() -> void: menu_requested.emit())
quit_button = _button(box, "Quit the game")
quit_button.pressed.connect(func() -> void: quit_requested.emit())
_note = Label.new()
_note.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_note.custom_minimum_size = Vector2(520.0, 0.0)
_note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_note.add_theme_font_size_override("font_size", 18)
_note.add_theme_color_override("font_color", Color(0.72, 0.74, 0.68))
box.add_child(_note)
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
## coop: 0 solo, 1 hosting a co-op game, 2 a partner in one (the farm doesn't stop for menus).
func open(campaign: CampaignController, coop: int = 0) -> void:
var s := campaign.state
var phase: String = CampaignController.Phase.keys()[s.phase]
_where.text = "Night %d of %d · %s" % [s.night, campaign.config.campaign_nights, phase.replace("_", " ").capitalize()]
var over := campaign.outcome == CampaignController.Outcome.VACATION_COMPLETE
restart_button.disabled = over or coop == 2
menu_button.text = "Leave the game" if coop == 2 else "Save & quit to menu"
_note.text = "The vacation is finished." if over else \
"The vacation is saved every morning: Continue picks up at the morning of day %d." % s.night
if coop == 1:
_note.text += " Co-op: the farm keeps going while you're in this menu, and quitting ends the game for your friend."
elif coop == 2:
_note.text = "Co-op: the farm keeps going while you're in this menu. Only the host can restart the night; the host's game is saved."
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
resume_button.grab_focus.call_deferred()
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.4)) # dims what's behind
func close() -> void:
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _button(parent: Control, text: String) -> Button:
var b := Button.new()
b.text = text
b.custom_minimum_size = Vector2(420.0, 56.0)
b.add_theme_font_size_override("font_size", 24)
parent.add_child(b)
return b

View file

@ -0,0 +1 @@
uid://f0v40qt4cy1s

195
game/scripts/phase_hud.gd Normal file
View file

@ -0,0 +1,195 @@
class_name PhaseHud
extends Control
## Top-left phase indicator: a dial whose ring fills over the current phase with a sun (day), a
## setting sun (dusk), a moon (night), or a rising sun (dawn) in it; "Night N of M"; the phase
## and its time left; and a hint line (what tonight brings at dusk, thieves on the farm at night, the
## early-night key when allowed). Each phase also announces itself with a banner that fades;
## from dusk into the night, tonight's dusk hint (NightPlan.dusk_hint) shows under it.
const DIAL_CENTER := Vector2(62.0, 64.0)
const DIAL_RADIUS := 34.0
const BANNER_TIME := 3.0
var campaign: CampaignController
var waves: WaveDirector
var enemies: EnemySystem
var _title: Label
var _sub: Label
var _hint: Label
var _banner: Label
var _banner_left: float = 0.0
var _dusk_hint: Label
func setup(p_campaign: CampaignController, p_waves: WaveDirector, p_enemies: EnemySystem) -> void:
campaign = p_campaign
waves = p_waves
enemies = p_enemies
campaign.phase_changed.connect(_on_phase_changed)
_on_phase_changed(campaign.state.phase, campaign.state.phase)
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_title = _label(28, Vector2(112.0, 26.0))
_sub = _label(22, Vector2(112.0, 62.0))
_hint = _label(19, Vector2(112.0, 92.0))
_banner = Label.new()
_banner.set_anchors_preset(Control.PRESET_TOP_WIDE)
_banner.offset_top = 250.0
_banner.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_banner.add_theme_font_size_override("font_size", 52)
_banner.add_theme_color_override("font_outline_color", Color.BLACK)
_banner.add_theme_constant_override("outline_size", 12)
_banner.mouse_filter = Control.MOUSE_FILTER_IGNORE
_banner.modulate.a = 0.0
add_child(_banner)
_dusk_hint = Label.new()
_dusk_hint.set_anchors_preset(Control.PRESET_CENTER_TOP)
_dusk_hint.offset_top = 330.0
_dusk_hint.offset_left = -520.0
_dusk_hint.offset_right = 520.0
_dusk_hint.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_dusk_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_dusk_hint.add_theme_font_size_override("font_size", 26)
_dusk_hint.add_theme_color_override("font_color", Color(1.0, 0.88, 0.7))
_dusk_hint.add_theme_color_override("font_outline_color", Color.BLACK)
_dusk_hint.add_theme_constant_override("outline_size", 8)
_dusk_hint.mouse_filter = Control.MOUSE_FILTER_IGNORE
_dusk_hint.visible = false
add_child(_dusk_hint)
## "Night 1 of 5 · Day · 2:34 left", as the HUD shows it (also used by tests).
func describe() -> String:
return "%s · %s" % [_title.text, _sub.text]
func _process(delta: float) -> void:
if campaign == null:
return
var s := campaign.state
var cfg := campaign.config
_title.text = "Night %d of %d" % [s.night, cfg.campaign_nights]
var left := _clock(s.phase_time_left)
var hint := ""
match s.phase:
CampaignController.Phase.MORNING:
_sub.text = "Morning"
CampaignController.Phase.DAY:
_sub.text = "Day · %s left" % left
if campaign.can_start_night_early():
hint = "[N] start the night early"
CampaignController.Phase.DUSK:
_sub.text = "Dusk · nightfall in %s" % left
hint = "\n".join(waves.tonight_warning()) if waves != null else ""
CampaignController.Phase.NIGHT:
_sub.text = "Night · sunrise in %s" % left
hint = on_the_farm(enemies)
CampaignController.Phase.DAWN:
_sub.text = "Dawn · the thieves are fleeing (%s)" % left
CampaignController.Phase.FARMERS_RETURN:
_sub.text = "The farmers are back"
CampaignController.Phase.GAME_OVER:
_sub.text = "Game over"
_hint.text = hint
var plan := waves.tonight() if waves != null else null
_dusk_hint.visible = plan != null and plan.dusk_hint != "" and waves.warning_active()
if _dusk_hint.visible:
_dusk_hint.text = plan.dusk_hint
_banner_left = maxf(_banner_left - delta, 0.0)
_banner.modulate.a = clampf(_banner_left / 0.8, 0.0, 1.0)
queue_redraw()
func _draw() -> void:
if campaign == null:
return
var s := campaign.state
var length := campaign.phase_length(s.phase)
var frac := 1.0 - s.phase_time_left / length if is_finite(length) and length > 0.0 else 0.0
var phase := s.phase
var night := phase == CampaignController.Phase.NIGHT
var hint_size := _hint.get_minimum_size() if _hint.text != "" else Vector2.ZERO
var box := Vector2(maxf(430.0, 112.0 + hint_size.x + 18.0), maxf(104.0, 92.0 + hint_size.y - 14.0 + 22.0))
draw_rect(Rect2(Vector2(14.0, 14.0), box), Color(0.0, 0.0, 0.0, 0.42))
draw_circle(DIAL_CENTER, DIAL_RADIUS, Color(0.08, 0.1, 0.18, 0.95) if night else Color(0.25, 0.45, 0.7, 0.95))
var ring := Color(0.6, 0.7, 1.0) if night else Color(1.0, 0.85, 0.4)
draw_arc(DIAL_CENTER, DIAL_RADIUS - 4.0, -PI * 0.5, -PI * 0.5 + TAU * frac, 48, ring, 5.0)
match phase:
CampaignController.Phase.NIGHT:
draw_circle(DIAL_CENTER, 15.0, Color(0.93, 0.95, 1.0))
draw_circle(DIAL_CENTER + Vector2(7.0, -5.0), 13.0, Color(0.08, 0.1, 0.18))
CampaignController.Phase.DUSK, CampaignController.Phase.DAWN:
var c := DIAL_CENTER + Vector2(0.0, 8.0)
draw_circle(c, 15.0, Color(1.0, 0.55, 0.3) if phase == CampaignController.Phase.DUSK else Color(1.0, 0.72, 0.6))
draw_rect(Rect2(c + Vector2(-20.0, 4.0), Vector2(40.0, 16.0)), Color(0.12, 0.2, 0.12))
_:
draw_circle(DIAL_CENTER, 15.0, Color(1.0, 0.88, 0.35))
func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
var s := campaign.state
var text := ""
match phase:
CampaignController.Phase.DAY:
text = "Day %d: gather and build" % s.night
CampaignController.Phase.DUSK:
text = "Dusk: %s" % _tonight_title("the thieves come at nightfall")
CampaignController.Phase.NIGHT:
text = "Night %d: %s" % [s.night, _tonight_title("")] if _tonight_title("") != "" else "Night %d" % s.night
CampaignController.Phase.DAWN:
text = "Sunrise"
if text != "":
_banner.text = text
_banner_left = BANNER_TIME
func _tonight_title(fallback: String) -> String:
var plan := waves.tonight() if waves != null else null
return plan.title if plan != null and plan.title != "" else fallback
static func _clock(seconds: float) -> String:
var t := ceili(seconds)
return "%d:%02d" % [floori(t / 60.0), t % 60]
## "3 crows, 2 thieves, and a fence breaker on the farm" (or "" when nobody is).
static func on_the_farm(es: EnemySystem) -> String:
if es == null:
return ""
var counts := PackedInt32Array()
counts.resize(EnemySystem.TYPE_NAMES.size())
for d in es.active_count:
if es.alive[d] == 1:
counts[es.type[d]] += 1
var parts := PackedStringArray()
for t in [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER]:
if counts[t] == 1:
parts.append("a " + EnemySystem.NAMES[t])
elif counts[t] > 1:
parts.append("%d %s" % [counts[t], EnemySystem.PLURALS[t]])
if parts.is_empty():
return "Nobody on the farm"
var text := join_words(parts) + " on the farm"
return text[0].to_upper() + text.substr(1)
static func join_words(words: PackedStringArray) -> String:
if words.size() <= 1:
return "".join(words)
return ", ".join(words.slice(0, words.size() - 1)) + " and " + words[words.size() - 1]
func _label(font_size: int, at: Vector2) -> Label:
var l := Label.new()
l.position = at
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(l)
return l

View file

@ -0,0 +1 @@
uid://bp7dq566avk2v

View file

@ -1,13 +1,28 @@
class_name PlayerCharacter
extends CharacterBody3D
## The farmer: camera-relative movement on the move_* actions (WASD / arrows / left stick) with
## gravity. The model turns toward the direction of travel and crossfades idle / walk / run.
## The walk clip plays for partial stick deflection; full keyboard input runs.
## The scarecrow's body: camera-relative movement on the move_* actions (WASD / arrows / left
## stick) with gravity. The model turns toward the direction of travel and crossfades idle /
## walk / run; the walk clip plays for partial stick deflection, full keyboard input runs.
## While shooting (face_aim) the model turns toward the aim instead. During a channel
## (start_channel: patching up, gathering) it is rooted and loops the channel's clip; once fallen
## (die) it plays the death clip and takes no input until revived. set_flash() tints the model
## for hit feedback.
## Sprint (the workbench's Sprint upgrade): holding sprint (Shift / L3) while moving runs at
## GameConfig.sprint_speed_mult times run_speed, the run clip sped up to match, for up to
## sprint_time seconds; once it ends (time's up, let go, or stopped) it takes sprint_cooldown
## seconds to come back. FarmSim sets config and campaign; without them, or without the upgrade,
## there's no sprint.
## Co-op: the other machine's scarecrow is remote_driven: it eases toward the position and facing
## it was last sent (net_position, net_yaw) and animates by net_speed (like input strength: 1 at
## run speed, more while sprinting) instead of reading the input. Each scarecrow sprints on the
## machine that plays it. set_tint() and set_tag() tell the two scarecrows apart.
@export var run_speed := 5.0
@export var acceleration := 30.0
## How quickly the model turns to face the movement direction (higher = snappier).
@export var turn_speed := 12.0
## How quickly the model turns toward the aim while shooting.
@export var aim_turn_speed := 30.0
## Input strength (0..1) above which the run clip plays instead of the walk clip.
@export_range(0.0, 1.0) var run_threshold := 0.6
@ -15,29 +30,201 @@ extends CharacterBody3D
@export var idle_animation: StringName = &"Idle_A"
@export var walk_animation: StringName = &"Walking_A"
@export var run_animation: StringName = &"Running_A"
@export var channel_animation: StringName = &"Use_Item"
@export var death_animation: StringName = &"Death_A"
@export var blend_time := 0.2
@onready var model: Node3D = $Model
@onready var animation_player: AnimationPlayer = $Model/AnimationPlayer
var alive := true
## Standing still for a channel: no movement input, the channel clip loops.
var rooted := false
var channel_clip: StringName = &"Use_Item"
## Off while a co-op menu is up (the farm doesn't pause): no movement input.
var input_enabled := true
## Co-op: moved by the network (see above).
var remote_driven := false
var net_position := Vector3.ZERO
var net_yaw: float = 0.0
var net_speed: float = 0.0
## Set by FarmSim: the sprint's tuning, and the farm state that says whether it's unlocked.
var config: GameConfig
var campaign: CampaignController
## Sprinting now, seconds of it left, and seconds until the next one (0 = ready).
var sprinting := false
var sprint_left: float = 0.0
var sprint_recharge: float = 0.0
var _aim := Vector2.ZERO
var _aim_hold: float = 0.0
var _flash_mat: ShaderMaterial
var _tag: Label3D
func _ready() -> void:
_flash_mat = ShaderMaterial.new()
_flash_mat.shader = load("res://prototype/resources/hit_flash.gdshader") as Shader
for mi in model.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _flash_mat
func _physics_process(delta: float) -> void:
var move := _move_direction()
var horizontal := Vector3(velocity.x, 0.0, velocity.z).move_toward(move * run_speed, acceleration * delta)
if remote_driven:
_follow_net(delta)
return
var move := _move_direction() if alive and not rooted else Vector3.ZERO
step_sprint(delta, can_sprint() and input_enabled and Input.is_action_pressed("sprint"), move.length_squared() > 1e-4)
var horizontal := Vector3(velocity.x, 0.0, velocity.z).move_toward(move * run_speed * speed_factor(), acceleration * delta)
velocity.x = horizontal.x
velocity.z = horizontal.z
if not is_on_floor():
velocity += get_gravity() * delta
move_and_slide()
if move.length_squared() > 1e-4:
if not alive:
return
if _aim_hold > 0.0:
_aim_hold -= delta
var aim_yaw := atan2(-_aim.x, -_aim.y)
model.rotation.y = lerp_angle(model.rotation.y, aim_yaw, 1.0 - exp(-aim_turn_speed * delta))
elif move.length_squared() > 1e-4:
var yaw := atan2(-move.x, -move.z)
model.rotation.y = lerp_angle(model.rotation.y, yaw, 1.0 - exp(-turn_speed * delta))
_update_animation(move.length())
_update_animation(move.length() * speed_factor())
func _follow_net(delta: float) -> void:
velocity = Vector3.ZERO
if global_position.distance_to(net_position) > 6.0:
global_position = net_position # too far behind (a join, a respawn): jump
else:
global_position = global_position.lerp(net_position, 1.0 - exp(-14.0 * delta))
if not alive:
return
model.rotation.y = lerp_angle(model.rotation.y, net_yaw, 1.0 - exp(-20.0 * delta))
_update_animation(net_speed)
## Starts following the network from where it is (no glide in from the old spot).
func snap_to_net(at: Vector3, yaw: float) -> void:
net_position = at
net_yaw = yaw
global_position = at
model.rotation.y = yaw
## Movement strength for the network: 0 standing .. 1 at run speed (more while sprinting).
func move_strength() -> float:
return clampf(Vector2(velocity.x, velocity.z).length() / run_speed, 0.0, 2.0)
## Whether the Sprint upgrade is owned.
func can_sprint() -> bool:
return config != null and campaign != null and Upgrades.owned(campaign.state, "sprint")
## Speed relative to run_speed: sprint_speed_mult while sprinting.
func speed_factor() -> float:
return config.sprint_speed_mult if sprinting else 1.0
## One tick of the sprint: starts one while held and moving (when unlocked and recharged); ends
## it when its time is up, it's let go, or the scarecrow stops; then counts the recharge down.
func step_sprint(dt: float, held: bool, moving: bool) -> void:
if sprinting:
sprint_left -= dt
if sprint_left <= 0.0 or not held or not moving or not alive or not can_sprint():
_end_sprint()
return
sprint_recharge = maxf(sprint_recharge - dt, 0.0)
if held and moving and alive and sprint_recharge == 0.0 and can_sprint():
sprinting = true
sprint_left = config.sprint_time
## Ready to sprint again at once (a new morning).
func reset_sprint() -> void:
sprinting = false
sprint_left = 0.0
sprint_recharge = 0.0
func _end_sprint() -> void:
sprinting = false
sprint_left = 0.0
sprint_recharge = config.sprint_cooldown if config != null else 0.0
## Tints the model (co-op: player 2's scarecrow is blue).
func set_tint(color: Color) -> void:
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = color
m.material_override = tinted
## A name tag over the head ("" hides it).
func set_tag(text: String, color: Color) -> void:
if _tag == null:
_tag = Label3D.new()
_tag.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_tag.no_depth_test = true
_tag.shaded = false
_tag.font_size = 44
_tag.outline_size = 12
_tag.pixel_size = 0.009
_tag.position = Vector3(0.0, 2.75, 0.0)
add_child(_tag)
_tag.text = text
_tag.modulate = color
_tag.visible = text != ""
## Faces the (unit, XZ) aim direction instead of the travel direction for the next hold seconds.
func face_aim(aim: Vector2, hold: float) -> void:
_aim = aim
_aim_hold = maxf(_aim_hold, hold)
func start_channel(clip: StringName) -> void:
rooted = true
channel_clip = clip
func stop_channel() -> void:
rooted = false
func die() -> void:
alive = false
rooted = false
reset_sprint()
animation_player.speed_scale = 1.0
animation_player.play(death_animation, 0.15)
func revive() -> void:
alive = true
rooted = false
_aim_hold = 0.0
reset_sprint()
animation_player.play(idle_animation, 0.1)
## Hit tint over the model, 0 (none) .. 1 (solid red).
func set_flash(amount: float) -> void:
_flash_mat.set_shader_parameter("flash", amount)
## Input rotated by the active camera's yaw, so "forward" is always up the screen.
func _move_direction() -> Vector3:
if not input_enabled:
return Vector3.ZERO
var input := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
var camera := get_viewport().get_camera_3d()
var yaw := camera.global_rotation.y if camera != null else 0.0
@ -45,10 +232,18 @@ func _move_direction() -> Vector3:
func _update_animation(strength: float) -> void:
if rooted:
animation_player.speed_scale = 1.0
# Some channel clips don't loop; replay them for as long as the channel lasts.
if animation_player.current_animation != channel_clip or not animation_player.is_playing():
animation_player.play(channel_clip, blend_time)
return
var clip := idle_animation
if strength > run_threshold:
clip = run_animation
elif strength > 0.0:
clip = walk_animation
# A sprint (strength above 1) plays the run clip faster.
animation_player.speed_scale = maxf(strength, 1.0) if clip == run_animation else 1.0
if animation_player.current_animation != clip:
animation_player.play(clip, blend_time)

View file

@ -0,0 +1,141 @@
class_name PumpkinBombs
extends Node3D
## Pumpkin bombs in flight, for both scarecrows (ScarecrowCombat throws them): each flies in an
## arc from the thrower's hand to its target, spinning, at GameConfig.bomb_speed, and bursts on
## landing: every enemy within its radius (plus the enemy's hit radius) takes its damage, crows
## included. Walls don't stop the blast; structures, animals, and the scarecrows aren't hurt.
## A burst flashes an orange ring on the ground (the fear burst's shader) over the blast radius.
## Co-op: on the partner's machine (replica) bombs are only drawn, from the host's throws; the
## host's bursts do the damage.
signal thrown(from: Vector3, to: Vector3)
signal burst(at: Vector3, hits: int)
const MAX_FLYING := 12
const BURST_TIME := 0.5
## Seconds of flight at the shortest and longest.
const MIN_FLIGHT := 0.35
const MAX_FLIGHT := 1.1
var replica := false
var bursts: int = 0
var enemies_hit: int = 0
var _cfg: GameConfig
var _enemies: EnemySystem
var _flying: Array[Dictionary] = [] # {from, to, t, time, damage, radius, mesh}
var _idle: Array[MeshInstance3D] = []
var _rings: Array[Dictionary] = [] # {mesh, t}
func setup(cfg: GameConfig, enemies: EnemySystem) -> void:
_cfg = cfg
_enemies = enemies
## Throws one from from (the hand) to to (on the ground). Returns false if too many are flying.
func throw(from: Vector3, to: Vector3, damage: int, radius: float) -> bool:
if _flying.size() >= MAX_FLYING:
return false
var span := Vector2(to.x - from.x, to.z - from.z).length()
var mi: MeshInstance3D = _idle.pop_back() if not _idle.is_empty() else _new_mesh()
mi.visible = true
mi.global_position = from
mi.reset_physics_interpolation()
_flying.append({"from": from, "to": Vector3(to.x, 0.2, to.z), "t": 0.0, "damage": damage, "radius": radius,
"time": clampf(span / _cfg.bomb_speed, MIN_FLIGHT, MAX_FLIGHT), "peak": 1.0 + span * 0.22, "mesh": mi})
thrown.emit(from, to)
return true
func flying() -> int:
return _flying.size()
## Every bomb in flight lands now, without bursting (a new morning).
func clear() -> void:
for f in _flying:
_park(f["mesh"])
_flying.clear()
## Physics tick: flights move on; landed ones burst.
func step(dt: float) -> void:
var i := 0
while i < _flying.size():
var f := _flying[i]
f["t"] = float(f["t"]) + dt
var u := minf(float(f["t"]) / float(f["time"]), 1.0)
var mi := f["mesh"] as MeshInstance3D
var at := (f["from"] as Vector3).lerp(f["to"], u)
at.y += float(f["peak"]) * 4.0 * u * (1.0 - u)
mi.global_position = at
mi.rotation = Vector3(u * TAU * 1.5, 0.0, u * PI)
if u < 1.0:
i += 1
continue
_burst(f["to"], int(f["damage"]), float(f["radius"]))
_park(mi)
_flying.remove_at(i)
func _burst(at: Vector3, damage: int, radius: float) -> void:
bursts += 1
var n := 0
if not replica:
var es := _enemies
for d in es.active_count:
if es.alive[d] == 0:
continue
var reach := radius + es.t_hit_radius[es.type[d]]
if Vector2(es.pos_x[d] - at.x, es.pos_z[d] - at.z).length_squared() <= reach * reach:
es.apply_hit(d, damage)
n += 1
enemies_hit += n
_flash(at, radius)
burst.emit(at, n)
func _new_mesh() -> MeshInstance3D:
var mi := MeshInstance3D.new()
mi.mesh = WeaponModels.mesh_of(2)
mi.scale = Vector3.ONE * WeaponModels.BOMB_SCALE
mi.top_level = true
add_child(mi)
return mi
func _park(mi: MeshInstance3D) -> void:
mi.visible = false
_idle.append(mi)
func _flash(at: Vector3, radius: float) -> void:
var plane := PlaneMesh.new()
plane.size = Vector2.ONE * radius * 2.0
var mat := ShaderMaterial.new()
mat.shader = load("res://game/resources/fear_burst.gdshader") as Shader
mat.set_shader_parameter("color", Color(1.0, 0.55, 0.12))
var mi := MeshInstance3D.new()
mi.mesh = plane
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.top_level = true
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
mi.global_position = Vector3(at.x, 0.3, at.z)
_rings.append({"mesh": mi, "t": 0.0})
func _process(delta: float) -> void:
var i := 0
while i < _rings.size():
var r := _rings[i]
r["t"] = float(r["t"]) + delta / BURST_TIME
var mi := r["mesh"] as MeshInstance3D
(mi.material_override as ShaderMaterial).set_shader_parameter("t", minf(float(r["t"]), 1.0))
if float(r["t"]) >= 1.0:
mi.queue_free()
_rings.remove_at(i)
continue
i += 1

View file

@ -0,0 +1 @@
uid://bsvpn6aieq3fw

View file

@ -0,0 +1,86 @@
class_name RemoteControls
extends RefCounted
## What a scarecrow played on another machine wants this tick, as the host sees it (co-op,
## CoopSession). The partner's game sends its input every frame: which actions are held, a
## running press count per action (so a press is never lost with a dropped packet: the host
## counts the new ones), its aim (and the ground point a pumpkin bomb would land on), the weapon
## in hand, and whether it is building or has the upgrade menu open. The
## kit classes (Scarecrow, Interactions, ScarecrowCombat) read this instead of the local Input
## when their remote is set.
const ACTIONS: Array[StringName] = [&"fire", &"fear", &"patch", &"interact"]
var aim := Vector2(0.0, -1.0)
var aim_point := Vector3.ZERO
var ground_point := Vector3.ZERO
## ScarecrowCombat.Device of the partner's aim, and its ScarecrowCombat.Weapon (-1: none said).
var device: int = 0
var weapon: int = -1
var build_active := false
var ui_open := false
var _held := 0
var _presses := PackedInt32Array([0, 0, 0, 0])
var _seen := PackedInt32Array([0, 0, 0, 0])
func held(action: StringName) -> bool:
var i := ACTIONS.find(action)
return i >= 0 and (_held & (1 << i)) != 0
## Whether the action was pressed since the last time this was asked (one press each time).
func take(action: StringName) -> bool:
var i := ACTIONS.find(action)
if i < 0 or _seen[i] >= _presses[i]:
return false
_seen[i] += 1
return true
## The partner's input record (CoopSession): {"held": bits, "presses": counts, "aim": Vector2,
## "aim_point": Vector3, "ground": Vector3, "device", "weapon", "build", "ui"}.
func apply(rec: Dictionary) -> void:
_held = int(rec.get("held", 0))
var p: Variant = rec.get("presses", [])
var counts: Array = Array(p) if p is PackedInt32Array else (p if p is Array else [])
for i in mini(ACTIONS.size(), counts.size()):
_presses[i] = maxi(_presses[i], int(counts[i]))
aim = rec.get("aim", aim)
aim_point = rec.get("aim_point", aim_point)
ground_point = rec.get("ground", ground_point)
device = int(rec.get("device", device))
weapon = int(rec.get("weapon", weapon))
build_active = bool(rec.get("build", false))
ui_open = bool(rec.get("ui", false))
## Forget held actions (the partner left, or a new morning).
func release() -> void:
_held = 0
_seen = _presses.duplicate()
## The local side: an input record for the actions held now and every press so far.
class Sender:
var presses := PackedInt32Array([0, 0, 0, 0])
var _was := PackedInt32Array([0, 0, 0, 0])
## Counts presses from input events (taps between two frames still count).
func note(event: InputEvent) -> void:
for i in RemoteControls.ACTIONS.size():
if event.is_action_pressed(RemoteControls.ACTIONS[i], false):
presses[i] += 1
_was[i] = 1
func record(aim: Vector2, aim_point: Vector3, device: int, build: bool, ui: bool) -> Dictionary:
var bits := 0
for i in RemoteControls.ACTIONS.size():
var down := Input.is_action_pressed(RemoteControls.ACTIONS[i])
if down:
bits |= 1 << i
if _was[i] == 0: # pressed without an event (simulated input)
presses[i] += 1
_was[i] = 1 if down else 0
return {"held": bits, "presses": presses.duplicate(), "aim": aim, "aim_point": aim_point, "device": device,
"build": build, "ui": ui}

View file

@ -0,0 +1 @@
uid://ub7soqkr43sf

View file

@ -0,0 +1,76 @@
class_name ResourceHud
extends Control
## Top-right materials readout: what the supply shed holds, and what the scarecrow carries in
## its pouch (with its capacity). A line flashes when its numbers change.
var campaign: CampaignController
## Set by FarmSim: shows how many structures stand.
var structures: StructureSystem
var _shed: RichTextLabel
var _pouch: RichTextLabel
var _built: RichTextLabel
var _last_shed := ""
var _last_pouch := ""
var _flash_shed: float = 0.0
var _flash_pouch: float = 0.0
func setup(p_campaign: CampaignController) -> void:
campaign = p_campaign
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_shed = _line(20.0)
_pouch = _line(52.0)
_built = _line(84.0)
func _process(delta: float) -> void:
if campaign == null:
return
var r := campaign.state.resources
var shed := "Shed %s" % _amounts(r.shed)
var pouch := "Pouch %d/%d %s" % [r.pouch_total(), r.pouch_capacity, _amounts(r.pouch) if r.pouch_total() > 0 else "empty"]
if shed != _last_shed:
_last_shed = shed
_shed.text = shed
_flash_shed = 1.0
if pouch != _last_pouch:
_last_pouch = pouch
_pouch.text = pouch
_flash_pouch = 1.0
_flash_shed = maxf(_flash_shed - delta * 2.0, 0.0)
_flash_pouch = maxf(_flash_pouch - delta * 2.0, 0.0)
if structures != null:
_built.text = "Built %d structures [B] build" % structures.count()
_shed.modulate = Color.WHITE.lerp(Color(1.0, 1.0, 0.55), _flash_shed)
_pouch.modulate = Color.WHITE.lerp(Color(1.0, 1.0, 0.55), _flash_pouch)
func _amounts(d: Dictionary) -> String:
var parts: Array[String] = []
for m in ResourceStore.MATERIALS:
parts.append("[color=#%s]%s %d[/color]" % [GatherNode.COLORS[m].to_html(false), m.capitalize(), int(d[m])])
return " ".join(parts)
func _line(y: float) -> RichTextLabel:
var l := RichTextLabel.new()
l.bbcode_enabled = true
l.fit_content = true
l.scroll_active = false
l.autowrap_mode = TextServer.AUTOWRAP_OFF
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
l.add_theme_font_size_override("normal_font_size", 22)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.set_anchors_preset(Control.PRESET_TOP_RIGHT)
l.offset_left = -520.0
l.offset_right = -24.0
l.offset_top = y
add_child(l)
return l

View file

@ -0,0 +1 @@
uid://dc3i7w50plvjs

View file

@ -0,0 +1,124 @@
class_name ResourceStore
extends RefCounted
## The farm's construction materials (wood, scrap, straw): stock stored in the supply shed, and
## what the scarecrow carries in its pouch (pouch_capacity units across all materials). The
## pouch empties into the shed when the scarecrow walks in. Costs are paid all-or-nothing, from
## the pouch first and then the shed. Only shed stock can be stolen.
const MATERIALS: Array[String] = ["wood", "scrap", "straw"]
var shed := {"wood": 0, "scrap": 0, "straw": 0}
var pouch := {"wood": 0, "scrap": 0, "straw": 0}
var pouch_capacity: int = 15
func pouch_total() -> int:
var n := 0
for m in MATERIALS:
n += int(pouch[m])
return n
func shed_total() -> int:
var n := 0
for m in MATERIALS:
n += int(shed[m])
return n
## The material the shed holds most of (ties in MATERIALS order), or "" when it's empty.
func most_stocked() -> String:
var best := ""
var most := 0
for m in MATERIALS:
if int(shed[m]) > most:
most = int(shed[m])
best = m
return best
func pouch_room() -> int:
return maxi(pouch_capacity - pouch_total(), 0)
## Puts up to amount into the pouch, as much as fits. Returns how much went in.
func add_to_pouch(material: String, amount: int) -> int:
var added := mini(maxi(amount, 0), pouch_room())
pouch[material] = int(pouch[material]) + added
return added
## Moves the whole pouch into the shed. Returns what moved (material -> amount, only non-zero).
func deposit() -> Dictionary:
var moved := {}
for m in MATERIALS:
var n := int(pouch[m])
if n > 0:
shed[m] = int(shed[m]) + n
pouch[m] = 0
moved[m] = n
return moved
func available(material: String) -> int:
return int(shed[material]) + int(pouch[material])
## What a cost still lacks (material -> amount short; empty when affordable).
func missing(cost: Dictionary) -> Dictionary:
var short := {}
for m in cost:
var need := int(cost[m]) - available(String(m))
if need > 0:
short[m] = need
return short
func can_afford(cost: Dictionary) -> bool:
return missing(cost).is_empty()
## Pays a cost from the pouch first, then the shed. Pays nothing and returns false if short.
func pay(cost: Dictionary) -> bool:
if not can_afford(cost):
return false
for m in cost:
var need := int(cost[m])
var from_pouch := mini(need, int(pouch[m]))
pouch[m] = int(pouch[m]) - from_pouch
shed[m] = int(shed[m]) - (need - from_pouch)
return true
func to_dict() -> Dictionary:
return {"shed": shed.duplicate(), "pouch": pouch.duplicate(), "pouch_capacity": pouch_capacity}
## Returns null for unknown materials, missing entries, negative amounts, or an overfull pouch.
static func from_dict(d: Variant) -> ResourceStore:
if not d is Dictionary:
return null
var dd := d as Dictionary
if not (dd.get("shed") is Dictionary and dd.get("pouch") is Dictionary and dd.has("pouch_capacity")):
return null
var r := ResourceStore.new()
r.pouch_capacity = int(dd["pouch_capacity"])
for part in ["shed", "pouch"]:
var src: Dictionary = dd[part]
if src.size() != MATERIALS.size():
return null
for m in MATERIALS:
if not src.has(m) or int(src[m]) < 0:
return null
var into: Dictionary = r.shed if part == "shed" else r.pouch
into[m] = int(src[m])
return r if r.pouch_capacity >= 1 and r.pouch_total() <= r.pouch_capacity else null
## "6 wood, 2 straw" for a material -> amount dictionary (in MATERIALS order).
static func describe(amounts: Dictionary) -> String:
var parts: Array[String] = []
for m in MATERIALS:
if int(amounts.get(m, 0)) > 0:
parts.append("%d %s" % [int(amounts[m]), m])
return ", ".join(parts)

View file

@ -0,0 +1 @@
uid://cwji8ltvlipll

View file

@ -0,0 +1,223 @@
class_name ReviewPanel
extends CenterContainer
## The morning screen (the untimed MORNING phase), between one night and the next day:
## * Last night's results (from the night's log entry): per category what was taken,
## recovered, and lost; enemies defeated by type and how many got away with loot; damage
## (the scarecrow's, structures hit, broken, and repaired); materials gathered and spent
## over the day and night.
## * This morning: what's left (crops, animals, supplies, the scarecrow's health), what needs
## repair (damaged structures keep their health bars on the farm), the pen's gate, the
## materials on hand, and tonight's plan.
## "Start the day" (focused, so Enter / A work) ends it. The first morning explains the vacation
## instead of results.
const CATEGORIES := ["Crops", "Animals", "Supplies"]
const GOLD := Color(0.95, 0.82, 0.45)
const GREY := Color(0.7, 0.72, 0.68)
const RED := Color(1.0, 0.5, 0.42)
var campaign: CampaignController
var structures: StructureSystem
## Set by FarmSim: whether the pen is open, and tonight's plan.
var animals: AnimalSystem
var waves: WaveDirector
var _title: Label
var _last_head: Label
var _grid: GridContainer
var _cells := {} # "Crops/taken" -> Label
var _results: Label
var _rule: HSeparator
var _morning_head: Label
var _body: Label
var _start: Button
func setup(p_campaign: CampaignController, p_structures: StructureSystem) -> void:
campaign = p_campaign
structures = p_structures
campaign.phase_changed.connect(func(_p: CampaignController.Phase, _prev: CampaignController.Phase) -> void: refresh())
refresh()
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", backing())
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 30)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 12)
margin.add_child(box)
_title = _label(box, 38)
_last_head = _label(box, 26, GOLD)
_grid = GridContainer.new()
_grid.columns = 4
_grid.add_theme_constant_override("h_separation", 48)
_grid.add_theme_constant_override("v_separation", 2)
box.add_child(_grid)
for head in ["", "Taken", "Recovered", "Lost"]:
_label(_grid, 20, GREY).text = head
for cat: String in CATEGORIES:
_label(_grid, 22).text = cat
for col in ["taken", "recovered", "lost"]:
var l := _label(_grid, 22)
l.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
_cells["%s/%s" % [cat, col]] = l
_results = _label(box, 21)
_results.custom_minimum_size = Vector2(760.0, 0.0)
_results.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_rule = HSeparator.new()
box.add_child(_rule)
_morning_head = _label(box, 26, GOLD)
_morning_head.text = "This morning"
_body = _label(box, 21)
_body.custom_minimum_size = Vector2(760.0, 0.0)
_body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_start = Button.new()
_start.text = "Start the day"
_start.custom_minimum_size = Vector2(260.0, 56.0)
_start.add_theme_font_size_override("font_size", 24)
_start.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
_start.pressed.connect(func() -> void: campaign.begin_day())
box.add_child(_start)
visible = false
## The dark, nearly opaque panel behind the morning screen, the menus, and the end screens.
static func backing() -> StyleBoxFlat:
var bg := StyleBoxFlat.new()
bg.bg_color = Color(0.1, 0.12, 0.1)
bg.border_color = Color(0.55, 0.5, 0.35)
bg.set_border_width_all(2)
bg.set_corner_radius_all(6)
return bg
func refresh() -> void:
if campaign == null:
return
visible = campaign.state.phase == CampaignController.Phase.MORNING
mouse_filter = Control.MOUSE_FILTER_STOP if visible else Control.MOUSE_FILTER_IGNORE
if not visible:
return
var s := campaign.state
var nights := campaign.config.campaign_nights
var first := s.night_log.is_empty()
for n: Control in [_last_head, _grid, _results, _rule, _morning_head]:
n.visible = not first
var lines: Array[String] = []
if first:
_title.text = "The farmers are away"
lines.append("Keep the farm safe for %d nights until they come home: the crops, the animals in the pen, and the supplies in the shed." % nights)
lines.append("By day, gather wood, scrap, and straw (hold E), store them at the barn, and build defenses (B). There's more to gather off the farm, to the north, east, and south.")
lines.append("At night, stab thieves with your pitchfork (left mouse), scare them off (Q), and pick up anything they drop. A dropped animal runs off: walk up to it and lead it back to the pen. The workbench sells a corn shooter and pumpkin bombs (switch weapons with Tab or 1-3).")
else:
var e: Dictionary = s.night_log[s.night_log.size() - 1]
_title.text = "Morning of day %d of %d" % [s.night, nights]
var plan := waves.plan_for(int(e["night"])) if waves != null else null
_last_head.text = "Night %d: %s" % [e["night"], plan.title] if plan != null and plan.title != "" else "Night %d" % e["night"]
_fill_grid(e)
_results.text = "\n".join(result_lines(e, s))
lines.append("Left: %d of %d crops, %d of %d animals, %d supplies. Scarecrow: %d of %d HP." % [s.crops, s.crops_total,
s.animals, s.animals_total, s.supplies, s.scarecrow_hp, s.scarecrow_max_hp])
lines.append(_damage_line())
if animals != null and animals.pen_open and s.animals > 0:
lines.append("The pen is open: put a gate in its opening (B) before nightfall, or animals will wander out.")
var r := s.resources
lines.append("In the shed: %s. In the pouch: %s." % [_or_none(ResourceStore.describe(r.shed)), _or_none(ResourceStore.describe(r.pouch))])
var plan := waves.tonight() if waves != null else null
if plan != null and plan.title != "":
lines.append("Tonight: %s. Upgrades at the work area: %d of %d done." % [plan.title, _upgrades_done(), Upgrades.ORDER.size()])
_body.text = "\n".join(lines)
_start.grab_focus.call_deferred()
## The results table as text, one row per category ("Crops 4 3 1"), for tests.
func grid_text() -> String:
var rows: Array[String] = []
for cat: String in CATEGORIES:
rows.append("%s %s %s %s" % [cat, _cells[cat + "/taken"].text, _cells[cat + "/recovered"].text, _cells[cat + "/lost"].text])
return "\n".join(rows)
## Per category: (taken, recovered, lost) in a night's log entry. Animals taken include those
## that wandered out of an open pen.
static func category_counts(e: Dictionary) -> Dictionary:
return {
"Crops": [int(e["crops_stolen"]), int(e["crops_recovered"]), int(e["crops_lost"])],
"Animals": [int(e["animals_stolen"]) + int(e["animals_strayed"]), int(e["animals_recovered"]), int(e["animals_lost"])],
"Supplies": [int(e["supplies_stolen"]), int(e["supplies_recovered"]), int(e["supplies_lost"])],
}
## Enemies, damage, and materials of a night's log entry.
static func result_lines(e: Dictionary, s: FarmState) -> Array[String]:
var out: Array[String] = []
var enemies := "Enemies defeated: %s." % Assessment.enemies_line(e)
if int(e["escaped"]) > 0:
enemies = enemies.trim_suffix(".") + "; %d got away with loot." % int(e["escaped"])
out.append(enemies)
var damage := PackedStringArray()
damage.append("the scarecrow took %d" % int(e["scarecrow_damage"]) if int(e["scarecrow_damage"]) > 0 else "the scarecrow wasn't hurt")
if int(e["patches"]) > 0:
damage.append("patched up %d %s" % [int(e["patches"]), "time" if int(e["patches"]) == 1 else "times"])
if int(e["structures_damaged"]) > 0:
damage.append("structures took %d damage" % int(e["structures_damaged"]))
if int(e["structures_destroyed"]) > 0:
damage.append("%d broken" % int(e["structures_destroyed"]))
if int(e["repairs"]) > 0:
damage.append("%d repaired" % int(e["repairs"]))
out.append("Damage: %s." % ", ".join(damage))
out.append("Materials: gathered %s; spent %s." % [Assessment.materials_line(e, "gathered_"), Assessment.materials_line(e, "spent_")])
if s != null and int(e["structures_built"]) + int(e["upgrades_bought"]) > 0:
out.append("Built %d, upgrades bought %d." % [int(e["structures_built"]), int(e["upgrades_bought"])])
return out
func _fill_grid(e: Dictionary) -> void:
var counts := category_counts(e)
for cat: String in CATEGORIES:
var c: Array = counts[cat]
for k in 3:
var l: Label = _cells["%s/%s" % [cat, ["taken", "recovered", "lost"][k]]]
l.text = str(c[k])
l.add_theme_color_override("font_color", RED if k == 2 and int(c[k]) > 0 else Color(0.92, 0.92, 0.88))
func _damage_line() -> String:
if structures == null or structures.count() == 0:
return "Nothing built yet."
var damaged := {}
for e in campaign.state.structures:
if int(e["hp"]) < structures.max_hp(e["type"]):
damaged[e["type"]] = int(damaged.get(e["type"], 0)) + 1
if damaged.is_empty():
return "No repairs needed."
var parts: Array[String] = []
for t in damaged:
parts.append("%d %s%s" % [damaged[t], StructureSystem.NAMES[t].to_lower(), "s" if int(damaged[t]) > 1 else ""])
return "Needs repair (marked with health bars): %s." % ", ".join(parts)
func _upgrades_done() -> int:
var n := 0
for id in Upgrades.ORDER:
if Upgrades.owned(campaign.state, id):
n += 1
return n
func _label(parent: Node, font_size: int, color: Color = Color(0.92, 0.92, 0.88)) -> Label:
var l := Label.new()
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_color", color)
parent.add_child(l)
return l
static func _or_none(text: String) -> String:
return text if text != "" else "nothing"

View file

@ -0,0 +1 @@
uid://cwll33writ0hq

108
game/scripts/save_game.gd Normal file
View file

@ -0,0 +1,108 @@
class_name SaveGame
extends RefCounted
## The vacation's save file: the farm state of the latest morning as JSON (full float precision)
## at user://savegame.json. CampaignController writes it every MORNING when its save_path is set
## (Main sets it; tests and the farm scene on its own don't), so Continue always resumes at that
## morning, and a Game Over leaves the failed night's morning there to retry. Finishing the
## vacation deletes it.
##
## Reading it back never crashes and never loads something broken: a missing file, unreadable
## JSON, a state that FarmState.from_dict rejects or that isn't a morning, and a save from a newer
## version are reported (Loaded.status) and not loaded. A save from an older version is upgraded
## first (migrate) when there's a known way forward, and reported as OLD when there isn't.
enum Status { OK, MISSING, CORRUPT, OLD, NEWER }
const PATH := "user://savegame.json"
const GAME := "harvest-season"
class Loaded:
var status: Status = Status.MISSING
## The saved farm state (status OK only).
var state: FarmState
## For the player: why it can't be continued ("" when it can).
var message := ""
var saved_at := ""
## The version the file was written with (-1 if unknown).
var version: int = -1
## Writes a FarmState.to_dict() atomically: to path.tmp, then renamed over path.
static func write(state: Dictionary, path: String = PATH) -> Error:
var data := {"game": GAME, "version": FarmState.VERSION, "saved_at": Time.get_datetime_string_from_system(false, true),
"state": state}
var tmp := path + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error()
f.store_string(JSON.stringify(data, "\t", true, true))
f.close()
return DirAccess.rename_absolute(ProjectSettings.globalize_path(tmp), ProjectSettings.globalize_path(path))
static func read(path: String = PATH) -> Loaded:
var out := Loaded.new()
if not FileAccess.file_exists(path):
out.message = "No saved vacation"
return out
var json := JSON.new()
var parsed: Variant = json.data if json.parse(FileAccess.get_file_as_string(path)) == OK else null
if not parsed is Dictionary or String((parsed as Dictionary).get("game", "")) != GAME \
or not (parsed as Dictionary).get("state") is Dictionary:
return _fail(out, Status.CORRUPT, "The saved vacation is damaged and can't be continued")
out.saved_at = String(parsed.get("saved_at", ""))
var d: Dictionary = parsed["state"]
out.version = int(d.get("version", -1))
if out.version > FarmState.VERSION:
return _fail(out, Status.NEWER, "The saved vacation is from a newer version of the game")
if out.version < FarmState.VERSION:
d = migrate(d)
if d.is_empty():
return _fail(out, Status.OLD, "The saved vacation is from an older version and can't be continued")
var s := FarmState.from_dict(d)
if s == null or s.phase != CampaignController.Phase.MORNING:
return _fail(out, Status.CORRUPT, "The saved vacation is damaged and can't be continued")
out.status = Status.OK
out.state = s
return out
## Upgrades a FarmState dictionary from an older VERSION, one version at a time. Returns {} when
## there's no way forward (version 1 predates saving to disk).
static func migrate(d: Dictionary) -> Dictionary:
var out := d.duplicate(true)
while int(out.get("version", -1)) < FarmState.VERSION:
match int(out.get("version", -1)):
2:
# Version 3 counts more per night: kills, damage, building, and materials.
for entry: Variant in out.get("night_log", []):
if entry is Dictionary:
for key in FarmState.LOG_KEYS:
if not (entry as Dictionary).has(key):
entry[key] = 0
out["version"] = 3
3:
# Version 4 adds co-op: a second scarecrow's health.
out["coop"] = false
out["partner_max_hp"] = int(out.get("scarecrow_max_hp", 10))
out["partner_hp"] = int(out.get("scarecrow_max_hp", 10))
out["version"] = 4
_:
return {}
return out
static func exists(path: String = PATH) -> bool:
return FileAccess.file_exists(path)
static func delete(path: String = PATH) -> void:
if FileAccess.file_exists(path):
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
static func _fail(out: Loaded, status: Status, message: String) -> Loaded:
out.status = status
out.message = message
return out

View file

@ -0,0 +1 @@
uid://b85t5jrscqbpo

302
game/scripts/scarecrow.gd Normal file
View file

@ -0,0 +1,302 @@
class_name Scarecrow
extends Node3D
## The scarecrow's defensive kit apart from the gun (ScarecrowCombat):
## * Health lives in FarmState and carries over between nights (D7). try_damage() is the only
## way to hurt the scarecrow: after an accepted hit it is invulnerable for
## invulnerability_time, so several hits on one tick cost one hit's damage. Hits blink the
## model red, tint the screen (ScarecrowHud), and interrupt patching.
## * Fear (fear action): every thief within fear_radius flees for fear_duration; carriers
## drop their crop (D5) and thieves mid-steal lose their progress. Then fear_cooldown
## seconds until the next one. A ring under the scarecrow shows that fear is ready.
## * Patch up (hold patch): stand still, unable to shoot, for patch_time, then +patch_heal HP
## for costs["patch"] (straw, paid when the patch completes). Releasing early, taking a hit,
## or using fear cancels it. Not available at full health, while gathering, or without the
## straw (patch_denied says what's missing).
## * Defeat: at 0 HP the scarecrow falls (death clip) and stops acting; the campaign turns it
## into Game Over on the same tick (in co-op only once both have fallen: until then it's out
## until the morning). Every new morning, also after a retry, revives it with fear ready.
## In co-op there are two kits: slot 0 (player 1) uses FarmState.scarecrow_hp, slot 1 (player 2)
## partner_hp. A kit whose remote is set (the partner's, on the host) reads RemoteControls
## instead of the local input.
signal damaged(hp: int)
signal fear_used(position: Vector3, scared: int)
signal fear_ready
signal patched(hp: int)
signal patch_cancelled
signal patch_denied(missing: Dictionary)
const BURST_TIME := 0.45
var config: GameConfig
var campaign: CampaignController
var player: PlayerCharacter
var enemies: EnemySystem
var behavior: ThiefBehavior
## Set by FarmSim: patching doesn't start while a gather channel runs.
var interactions: Interactions
## 0 = player 1, 1 = player 2 (whose health in FarmState), and the partner's input (co-op host).
var slot: int = 0
var remote: RemoteControls
var alive := true
var invulnerable_left: float = 0.0
## Seconds until fear can be used again (0 = ready).
var fear_left: float = 0.0
var patching := false
var patch_elapsed: float = 0.0
var accepted_hits: int = 0
var rejected_hits: int = 0
var _burst: MeshInstance3D
var _burst_mat: ShaderMaterial
var _burst_t: float = -1.0
var _ready_ring: MeshInstance3D
var _ready_mat: StandardMaterial3D
var _patch_ring: MeshInstance3D
var _patch_mat: ShaderMaterial
var _time: float = 0.0
var _fear_requested := false
var _patch_denied := false
var _fear_was_held := false
func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter,
p_enemies: EnemySystem, p_behavior: ThiefBehavior) -> void:
config = cfg
campaign = p_campaign
player = p_player
enemies = p_enemies
behavior = p_behavior
campaign.campaign_ended.connect(_on_campaign_ended)
_build_effects()
func hp() -> int:
return campaign.state.scarecrow_hp if slot == 0 else campaign.state.partner_hp
func max_hp() -> int:
return campaign.state.scarecrow_max_hp if slot == 0 else campaign.state.partner_max_hp
func _set_hp(value: int) -> void:
if slot == 0:
campaign.state.scarecrow_hp = clampi(value, 0, campaign.state.scarecrow_max_hp)
else:
campaign.state.partner_hp = clampi(value, 0, campaign.state.partner_max_hp)
func can_shoot() -> bool:
return alive and not patching
## Share of the fear cooldown that has passed: 1 when fear is ready.
func fear_charge() -> float:
var cd := fear_cooldown()
return 1.0 - fear_left / cd if cd > 0.0 else 1.0
## Fear's reach and recharge time, with upgrades.
func fear_radius() -> float:
return Upgrades.value(config, campaign.state, "fear_radius")
func fear_cooldown() -> float:
return Upgrades.value(config, campaign.state, "fear_cooldown")
## One physics tick: timers, then the fear and patch inputs.
func step(dt: float) -> void:
invulnerable_left = maxf(invulnerable_left - dt, 0.0)
if fear_left > 0.0:
fear_left = maxf(fear_left - dt, 0.0)
if fear_left == 0.0:
fear_ready.emit()
# A fear press counts from its input event (so even a tap between two ticks registers) or
# from the action turning pressed since the last tick (simulated input).
var held := remote.held(&"fear") if remote != null else Input.is_action_pressed("fear")
var pressed := _fear_requested or (held and not _fear_was_held)
if remote != null:
pressed = remote.take(&"fear")
_fear_requested = false
_fear_was_held = held
if not alive:
return
if pressed:
use_fear()
step_patch(dt, remote.held(&"patch") if remote != null else Input.is_action_pressed("patch"))
func _unhandled_input(event: InputEvent) -> void:
if remote == null and event.is_action_pressed("fear", false):
_fear_requested = true
## Advances the patch channel while held (keeps channeling, one patch after another, for as
## long as it is held and the scarecrow isn't at full health); releasing cancels.
func step_patch(dt: float, held: bool) -> void:
if not held or not alive:
cancel_patch()
_patch_denied = false
return
var s := campaign.state
var cost: Dictionary = config.costs.get("patch", {})
if not patching:
if hp() >= max_hp() or (interactions != null and interactions.channeling()):
return
if not s.resources.can_afford(cost):
if not _patch_denied: # once per press
_patch_denied = true
patch_denied.emit(s.resources.missing(cost))
return
patching = true
patch_elapsed = 0.0
player.start_channel(player.channel_animation)
patch_elapsed += dt
if patch_elapsed >= config.patch_time:
_end_patch()
if s.pay(cost):
_set_hp(hp() + config.patch_heal)
s.record_event("patches")
patched.emit(hp())
func cancel_patch() -> void:
if patching:
_end_patch()
patch_cancelled.emit()
## The only way to hurt the scarecrow. Returns true if the hit was accepted.
func try_damage(amount: int = 1) -> bool:
if not alive:
return false
if invulnerable_left > 0.0:
rejected_hits += 1
return false
invulnerable_left = config.invulnerability_time
accepted_hits += 1
var s := campaign.state
s.record_event("scarecrow_damage", mini(amount, hp()))
_set_hp(hp() - amount)
cancel_patch()
damaged.emit(hp())
if hp() <= 0:
_die()
return true
## Fear burst at the scarecrow. Returns how many thieves fled, or -1 if it isn't ready.
func use_fear() -> int:
if not alive or fear_left > 0.0:
return -1
cancel_patch()
fear_left = fear_cooldown()
var p := player.global_position
var n := behavior.scare(enemies, Vector2(p.x, p.z), fear_radius())
play_burst()
fear_used.emit(p, n)
return n
## The fear ring spreading from the scarecrow (also on the co-op partner's machine).
func play_burst() -> void:
var p := player.global_position
_burst.scale = Vector3.ONE * fear_radius() / config.fear_radius
_burst_t = 0.0
_burst.global_position = Vector3(p.x, p.y + 0.3, p.z)
func reset_for_morning() -> void:
alive = true
invulnerable_left = 0.0
fear_left = 0.0
_end_patch()
player.revive()
player.set_flash(0.0)
func _die() -> void:
if not alive:
return
alive = false
_end_patch()
player.die()
func _end_patch() -> void:
patching = false
patch_elapsed = 0.0
if player != null:
player.stop_channel()
func _on_campaign_ended(outcome: CampaignController.Outcome) -> void:
if outcome == CampaignController.Outcome.GAME_OVER_SCARECROW:
_die()
func _process(delta: float) -> void:
if player == null:
return
_time += delta
var flash := 0.0
if alive and invulnerable_left > 0.0:
flash = 0.65 if fmod(invulnerable_left, 0.2) > 0.1 else 0.15
player.set_flash(flash)
var at := player.get_global_transform_interpolated().origin
if _burst_t >= 0.0:
_burst_t += delta / BURST_TIME
_burst.visible = _burst_t < 1.0
_burst_mat.set_shader_parameter("t", clampf(_burst_t, 0.0, 1.0))
if _burst_t >= 1.0:
_burst_t = -1.0
_ready_ring.visible = alive and fear_left == 0.0
if _ready_ring.visible:
_ready_ring.global_position = at + Vector3(0.0, 0.12, 0.0)
_ready_mat.albedo_color.a = 0.45 + 0.25 * sin(_time * 4.0)
_patch_ring.visible = patching
if patching:
_patch_ring.global_position = at + Vector3(0.0, 2.75, 0.0)
_patch_mat.set_shader_parameter("progress", patch_elapsed / config.patch_time)
func _build_effects() -> void:
var plane := PlaneMesh.new()
plane.size = Vector2.ONE * config.fear_radius * 2.0
_burst_mat = ShaderMaterial.new()
_burst_mat.shader = load("res://game/resources/fear_burst.gdshader") as Shader
_burst = _effect(plane, _burst_mat)
var torus := TorusMesh.new()
torus.inner_radius = 0.55
torus.outer_radius = 0.68
torus.rings = 32
torus.ring_segments = 4
_ready_mat = StandardMaterial3D.new()
_ready_mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
_ready_mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
_ready_mat.albedo_color = Color(0.6, 0.9, 1.0, 0.6)
_ready_mat.no_depth_test = true
_ready_ring = _effect(torus, _ready_mat)
_ready_ring.scale = Vector3(1.0, 0.12, 1.0)
var quad := QuadMesh.new()
quad.size = Vector2(0.9, 0.9)
_patch_mat = ShaderMaterial.new()
_patch_mat.shader = load("res://game/resources/steal_ring.gdshader") as Shader
_patch_mat.set_shader_parameter("fill_color", Color(0.45, 1.0, 0.4))
_patch_ring = _effect(quad, _patch_mat)
func _effect(mesh: Mesh, mat: Material) -> MeshInstance3D:
var mi := MeshInstance3D.new()
mi.mesh = mesh
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.top_level = true
mi.visible = false
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
return mi

View file

@ -0,0 +1 @@
uid://bskggq8mxtab3

View file

@ -0,0 +1,433 @@
class_name ScarecrowCombat
extends Node3D
## The scarecrow's weapons, ported from the prototype's PlayerInput + WeaponController (Step 4
## finished the kit; the weapons came after Step 11):
## * Three weapons (Weapon): the pitchfork, every scarecrow's from the start; the corn shooter
## and pumpkin bombs, bought at the workbench (Upgrades "corn_shooter", "pumpkin_bomb").
## weapon_next (Tab / d-pad down) cycles through the ones owned, weapon_1..3 (1-3) pick one,
## both only outside build mode (where those keys pick structures) and with no menu open.
## One no longer owned (a retry from before it was bought) goes back to the pitchfork.
## * Aim with the mouse (the cursor projected onto the combat-height plane through the follow
## camera, corrected for the gun's side offset so shots pass through the cursor; bombs land
## on the ground point under the cursor) or the right stick (camera-relative, radial dead
## zone, last aim kept). The active device switches only on deliberate input: mouse travel
## past a threshold or a click, stick deflection past the dead zone or the trigger.
## * Attack with the fire action, needing a fresh press after every reset; holding it repeats:
## pitchfork a stab every pitchfork_interval: the nearest pitchfork_targets enemies
## within pitchfork_reach and pitchfork_arc of the aim, with a clear line,
## take pitchfork_damage
## corn shooter kernels at fire_rate through FarmProjectiles, shot_damage each (rapid fire
## and heavy seeds)
## pumpkin bomb one every bomb_cooldown, thrown at the aim point (bomb_min_range ..
## bomb_range away; GAMEPAD_THROW ahead with the stick), bursting where it
## lands (PumpkinBombs)
## * The weapon in hand on the scarecrow's model (WeaponModels), and an aim marker (with bombs:
## on the ground where one would land, ringed by its blast).
## While attacking, the model faces the aim.
## Co-op: the partner's weapons on the host read its RemoteControls (aim, fire, and its pick of
## weapon come from the partner's game); on the partner's machine its own only aims and shows the
## attack motions (replica: the host attacks), and only the local player's aim marker shows.
enum Device { MOUSE, GAMEPAD }
enum Weapon { PITCHFORK, CORN_SHOOTER, PUMPKIN_BOMB }
## A corn shot left the gun (for its sound).
signal fired
## A pitchfork stab (how many it hit), and each enemy it struck (for the sounds).
signal stabbed(hits: int)
signal struck(at: Vector3, enemy_type: int)
## A pumpkin bomb thrown (where it will land).
signal threw(at: Vector3)
## Any attack (co-op: the partner's machine shows its motion), and a change of weapon.
signal attacked(weapon: Weapon)
signal switched(weapon: Weapon)
## Lateral offset of the gun from the scarecrow's center line (the prototype's value).
const SIDE_OFFSET := 0.35
## Upgrade ids that unlock the weapons (the pitchfork needs none), and what they're called.
const WEAPON_IDS: Array[String] = ["pitchfork", "corn_shooter", "pumpkin_bomb"]
const WEAPON_NAMES: Array[String] = ["Pitchfork", "Corn shooter", "Pumpkin bombs"]
const SWITCH_ACTIONS: Array[StringName] = [&"weapon_next", &"weapon_1", &"weapon_2", &"weapon_3"]
## How far ahead a bomb lands when aiming with the stick, and how high it leaves the hand.
const GAMEPAD_THROW := 7.0
const THROW_HEIGHT := 1.6
const WORLD_LAYER := 1
var device: Device = Device.MOUSE
var weapon: Weapon = Weapon.PITCHFORK
## Last valid horizontal aim direction (unit, XZ).
var aim := Vector2(0.0, -1.0)
## World point the mouse aims at (combat-height plane), and the ground point under the cursor;
## valid in MOUSE mode.
var aim_point := Vector3.ZERO
var ground_point := Vector3.ZERO
var shots_fired: int = 0
var stabs: int = 0
var bombs_thrown: int = 0
## Seconds until the next pumpkin bomb is in hand (0 = ready).
var bomb_left: float = 0.0
var remote: RemoteControls
var replica := false
var show_marker := true
## Set by FarmSim: the enemies the pitchfork stabs, and the pumpkin bombs in flight.
var enemies: EnemySystem
var bombs: PumpkinBombs
var models: WeaponModels
var _cfg: GameConfig
## Set by FarmSim: the upgrades (the weapons, fire rate, shot damage).
var campaign: CampaignController
var _player: PlayerCharacter
var _camera: Camera3D
var _shots: FarmProjectiles
var _marker: MeshInstance3D
var _blast: MeshInstance3D
## Ticks until each weapon can attack again (the pumpkin bomb's recharge is bomb_left), kept
## through switches so swapping weapons can't skip a wait.
var _cooldown := PackedInt32Array([0, 0, 0])
var _needs_release := true
var _mouse_travel: float = 0.0
var _edges := ActionEdges.new()
var _ray := PhysicsRayQueryParameters3D.new()
func setup(cfg: GameConfig, player: PlayerCharacter, camera: Camera3D, shots: FarmProjectiles) -> void:
_cfg = cfg
_player = player
_camera = camera
_shots = shots
_ray.collision_mask = WORLD_LAYER
_ray.collide_with_areas = false
_ray.exclude = [player.get_rid()]
models = WeaponModels.new()
models.setup(player.model, Vector3(SIDE_OFFSET, cfg.combat_height, -cfg.muzzle_distance))
_build_marker()
## Requires a fresh fire press, so a held button can't fire into a new morning or a retry.
func reset() -> void:
_cooldown.fill(0)
_needs_release = true
## A new morning (also after a retry): a pumpkin bomb back in hand.
func ready_for_morning() -> void:
reset()
bomb_left = 0.0
## Whether this scarecrow has the weapon: the pitchfork always, the others once bought.
func owns(w: int) -> bool:
if w == Weapon.PITCHFORK:
return true
return w > 0 and w < WEAPON_IDS.size() and campaign != null and Upgrades.owned(campaign.state, WEAPON_IDS[w])
## Takes the weapon in hand if it's owned. Returns whether it's in hand now.
func equip(w: int) -> bool:
if not owns(w):
return false
if w != weapon:
show_weapon(w)
switched.emit(weapon)
return true
## The next weapon owned after the one in hand.
func cycle() -> void:
for k in range(1, WEAPON_IDS.size()):
if equip((weapon + k) % WEAPON_IDS.size()):
return
## Shows the weapon in hand without the ownership check (co-op: the other scarecrow's, as its
## machine says).
func show_weapon(w: int) -> void:
var next := clampi(w, 0, WEAPON_IDS.size() - 1) as Weapon
if next == weapon and models.weapon == next:
return # (a snapshot saying so again mustn't cut an attack's motion short)
weapon = next
models.show_weapon(weapon)
func _input(event: InputEvent) -> void:
if remote != null:
return
_edges.note(event, SWITCH_ACTIONS)
if event is InputEventMouseMotion:
if device == Device.GAMEPAD:
_mouse_travel += (event as InputEventMouseMotion).relative.length()
if _mouse_travel >= _cfg.mouse_switch_threshold:
device = Device.MOUSE
elif event is InputEventMouseButton and (event as InputEventMouseButton).pressed:
device = Device.MOUSE
elif event is InputEventJoypadButton and (event as InputEventJoypadButton).pressed and event.is_action("fire"):
_to_gamepad()
elif event is InputEventJoypadMotion:
var jm := event as InputEventJoypadMotion
if jm.axis == JOY_AXIS_TRIGGER_RIGHT and jm.axis_value > 0.5:
_to_gamepad()
## Every tick, attacking or not (building, patching): the bomb's recharge, and the pick of
## weapon (the switch actions count only when can_switch: outside build mode, no menu open; the
## partner's pick comes from its game).
func tick(dt: float, can_switch: bool) -> void:
bomb_left = maxf(bomb_left - dt, 0.0)
models.set_bomb_charge(1.0 - bomb_left / _cfg.bomb_cooldown if _cfg.bomb_cooldown > 0.0 else 1.0)
if not owns(weapon):
equip(Weapon.PITCHFORK)
if remote != null:
if remote.weapon >= 0:
equip(remote.weapon)
return
var p := {}
for a in SWITCH_ACTIONS:
p[a] = _edges.pressed(a)
if not can_switch:
return
if p[&"weapon_next"]:
cycle()
for k in WEAPON_IDS.size():
if p[SWITCH_ACTIONS[k + 1]]:
equip(k)
## One physics tick while the scarecrow can attack: update the aim, then attack with the weapon
## in hand if fire is held and it's ready.
func step(_dt: float) -> void:
_update_aim()
var held := remote.held(&"fire") if remote != null else Input.is_action_pressed("fire")
for i in _cooldown.size():
_cooldown[i] = maxi(_cooldown[i] - 1, 0)
if replica:
if held:
_player.face_aim(aim, 0.35)
_show_attack()
return
if _needs_release:
if held:
return
_needs_release = false
if not held:
return
_player.face_aim(aim, 0.35)
attack()
## The weapon in hand attacks along the aim, if it's ready. Returns whether it did.
func attack() -> bool:
if _cooldown[weapon] > 0:
return false
match weapon:
Weapon.CORN_SHOOTER:
_cooldown[weapon] = interval_ticks()
_shoot()
Weapon.PUMPKIN_BOMB:
if bomb_left > 0.0 or not _throw():
return false
_:
_cooldown[weapon] = stab_ticks()
_stab()
attacked.emit(weapon)
return true
## A scripted attack (the soak's scarecrow, tests): aims at target and attacks if ready.
func attack_toward(target: Vector2) -> bool:
var p := Vector2(_player.global_position.x, _player.global_position.z)
var to := target - p
if to.length() > 1e-3:
aim = PlayerInput.muzzle_corrected_aim(to, to.normalized()) if weapon == Weapon.CORN_SHOOTER else to.normalized()
aim_point = Vector3(target.x, _cfg.combat_height, target.y)
ground_point = Vector3(target.x, 0.0, target.y)
device = Device.MOUSE
_player.face_aim(aim, 0.35)
return attack()
## Attacks so far, with any weapon.
func attacks() -> int:
return stabs + shots_fired + bombs_thrown
## Ticks between shots, and a shot's damage, with upgrades.
func interval_ticks() -> int:
var state := campaign.state if campaign != null else null
return maxi(1, roundi(Engine.physics_ticks_per_second / Upgrades.value(_cfg, state, "fire_rate")))
func shot_damage() -> int:
return roundi(Upgrades.value(_cfg, campaign.state if campaign != null else null, "shot_damage"))
## Ticks between pitchfork stabs.
func stab_ticks() -> int:
return maxi(1, roundi(_cfg.pitchfork_interval * Engine.physics_ticks_per_second))
## Where a bomb thrown now lands: the ground point aimed at (GAMEPAD_THROW ahead with the stick),
## bomb_min_range .. bomb_range from the scarecrow.
func throw_target() -> Vector3:
var p := Vector2(_player.global_position.x, _player.global_position.z)
var want := Vector2(ground_point.x, ground_point.z) - p if device == Device.MOUSE else aim * GAMEPAD_THROW
var dir := want.normalized() if want.length() > 1e-3 else aim
var at := p + dir * clampf(want.length(), _cfg.bomb_min_range, _cfg.bomb_range)
return Vector3(at.x, 0.0, at.y)
func _shoot() -> void:
var origin := Vector3(_player.global_position.x, _cfg.combat_height, _player.global_position.z)
var dir := Vector3(aim.x, 0.0, aim.y)
var right := Vector3(-aim.y, 0.0, aim.x)
var muzzle := origin + dir * _cfg.muzzle_distance + right * SIDE_OFFSET
shots_fired += 1
_shots.fire(origin, muzzle, dir, shot_damage())
models.attack(Weapon.CORN_SHOOTER)
fired.emit()
## The nearest few enemies in reach, in the arc, and in the clear take a stab.
func _stab() -> int:
stabs += 1
models.attack(Weapon.PITCHFORK)
var hits := 0
if enemies != null:
var es := enemies
var p := Vector2(_player.global_position.x, _player.global_position.z)
var cos_half := cos(deg_to_rad(_cfg.pitchfork_arc) * 0.5)
var found: Array = [] # [distance, slot]
for d in es.active_count:
if es.alive[d] == 0:
continue
var e := Vector2(es.pos_x[d], es.pos_z[d])
var dist := e.distance_to(p)
if dist > _cfg.pitchfork_reach + es.t_hit_radius[es.type[d]]:
continue
if dist > 0.3 and (e - p).dot(aim) < cos_half * dist:
continue
if _clear_line(p, e):
found.append([dist, d])
found.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0])
for k in mini(found.size(), _cfg.pitchfork_targets):
var d: int = found[k][1]
var at := Vector3(es.pos_x[d], _cfg.combat_height, es.pos_z[d])
var type := es.type[d]
if es.apply_hit(d, _cfg.pitchfork_damage):
hits += 1
struck.emit(at, type)
stabbed.emit(hits)
return hits
func _throw() -> bool:
if bombs == null:
return false
var p := _player.global_position
var hand := Vector3(p.x - aim.y * 0.4, THROW_HEIGHT, p.z + aim.x * 0.4)
var to := throw_target()
if not bombs.throw(hand, to, _cfg.bomb_damage, _cfg.bomb_radius):
return false
bomb_left = _cfg.bomb_cooldown
models.set_bomb_charge(0.0)
bombs_thrown += 1
threw.emit(to)
return true
## The partner's machine: the attack motion on the weapon's own cadence (the host attacks).
func _show_attack() -> void:
if weapon == Weapon.PUMPKIN_BOMB or _cooldown[weapon] > 0:
return # the host's throw shows the bomb, and empties the hand
_cooldown[weapon] = interval_ticks() if weapon == Weapon.CORN_SHOOTER else stab_ticks()
models.attack(weapon)
func _clear_line(a: Vector2, b: Vector2) -> bool:
if not is_inside_tree():
return true
_ray.from = Vector3(a.x, _cfg.combat_height, a.y)
_ray.to = Vector3(b.x, _cfg.combat_height, b.y)
return get_world_3d().direct_space_state.intersect_ray(_ray).is_empty()
func _update_aim() -> void:
if remote != null:
aim = remote.aim
aim_point = remote.aim_point
ground_point = remote.ground_point
device = remote.device as Device
return
var b := _camera.global_transform.basis
var fwd := Vector3(-b.z.x, 0.0, -b.z.z).normalized()
var right := Vector3(b.x.x, 0.0, b.x.z).normalized()
var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", _cfg.aim_dead_zone)
if stick != Vector2.ZERO:
_to_gamepad()
var w := right * stick.x + fwd * stick.y
aim = Vector2(w.x, w.z).normalized()
elif device == Device.MOUSE:
aim_point = _cursor_on_plane(_cfg.combat_height)
ground_point = _cursor_on_plane(0.0)
var p := _player.global_position
aim = PlayerInput.muzzle_corrected_aim(Vector2(aim_point.x - p.x, aim_point.z - p.z), aim)
func _cursor_on_plane(height: float) -> Vector3:
var screen := _camera.get_viewport().get_mouse_position()
var o := _camera.project_ray_origin(screen)
var d := _camera.project_ray_normal(screen)
if absf(d.y) < 1e-5:
return Vector3(o.x, height, o.z)
return o + d * ((height - o.y) / d.y)
func _to_gamepad() -> void:
device = Device.GAMEPAD
_mouse_travel = 0.0
func _process(_delta: float) -> void:
if _player == null:
return
var bomb := weapon == Weapon.PUMPKIN_BOMB
_marker.visible = show_marker
_blast.visible = show_marker and bomb
if bomb:
var at := throw_target()
_marker.global_position = Vector3(at.x, 0.12, at.z)
_blast.global_position = Vector3(at.x, 0.1, at.z)
elif device == Device.MOUSE:
_marker.global_position = Vector3(aim_point.x, _cfg.combat_height, aim_point.z)
else:
var p := _player.get_global_transform_interpolated().origin
_marker.global_position = Vector3(p.x + aim.x * 3.0, _cfg.combat_height, p.z + aim.y * 3.0)
func _build_marker() -> void:
_marker = _ring(0.2, 0.3, Color(1.0, 0.85, 0.25))
_marker.name = "AimMarker"
_blast = _ring(_cfg.bomb_radius - 0.08, _cfg.bomb_radius, Color(1.0, 0.55, 0.12, 0.8))
_blast.name = "BlastMarker"
func _ring(inner: float, outer: float, color: Color) -> MeshInstance3D:
var torus := TorusMesh.new()
torus.inner_radius = inner
torus.outer_radius = outer
torus.rings = 48
torus.ring_segments = 6
var mat := StandardMaterial3D.new()
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.albedo_color = color
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA if color.a < 1.0 else BaseMaterial3D.TRANSPARENCY_DISABLED
mat.no_depth_test = true
mat.render_priority = 1
var mi := MeshInstance3D.new()
mi.mesh = torus
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.top_level = true
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
return mi

View file

@ -0,0 +1 @@
uid://bumgf758vykhm

View file

@ -0,0 +1,205 @@
class_name ScarecrowHud
extends Control
## Bottom-left status for the scarecrow: health as pips, the fear ability as a circle that
## sweeps full while it cools down and flashes when it is ready again, the patch hint with its
## progress, and once the Sprint upgrade is bought a sprint line (ready, seconds left, or
## recharging); plus a red screen tint when the scarecrow is hit. Bottom-right, the weapons:
## the three by number, the one in hand marked, the ones not bought yet greyed out (from the
## workbench), the pumpkin bomb's recharge, and how to switch.
const PIP := Vector2(22.0, 16.0)
const PIP_GAP := 5.0
const FEAR_RADIUS := 26.0
## Extra height of the panel for the sprint line.
const SPRINT_ROW := 30.0
## The weapon panel, from the bottom-right corner, and its rows.
const WEAPONS := Rect2(-340.0, -176.0, 304.0, 150.0)
const WEAPON_ROW := 30.0
var kit: Scarecrow
## This machine's scarecrow's weapons.
var combat: ScarecrowCombat
var campaign: CampaignController
## The health line's name ("Scarecrow"; in co-op "P1 Scarecrow" / "P2 Scarecrow").
var label := "Scarecrow"
var _tint: ColorRect
var _hp_label: Label
var _fear_label: Label
var _patch_label: Label
var _sprint_label: Label
var _weapon_title: Label
var _weapon_rows: Array[Label] = []
var _weapon_hint: Label
var _hit: float = 0.0
var _ready_flash: float = 0.0
func setup(p_kit: Scarecrow, p_campaign: CampaignController, p_combat: ScarecrowCombat = null) -> void:
campaign = p_campaign
retarget(p_kit, p_combat)
## Shows another kit (co-op: the partner's game shows player 2's).
func retarget(p_kit: Scarecrow, p_combat: ScarecrowCombat = null) -> void:
combat = p_combat
if kit != null:
kit.damaged.disconnect(_on_damaged)
kit.fear_ready.disconnect(_on_fear_ready)
kit = p_kit
kit.damaged.connect(_on_damaged)
kit.fear_ready.connect(_on_fear_ready)
func _on_damaged(_hp: int) -> void:
_hit = 1.0
func _on_fear_ready() -> void:
_ready_flash = 1.0
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_tint = ColorRect.new()
_tint.set_anchors_preset(Control.PRESET_FULL_RECT)
_tint.color = Color(0.85, 0.05, 0.0, 0.0)
_tint.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(_tint)
_hp_label = _label(22)
_fear_label = _label(20)
_patch_label = _label(20)
_sprint_label = _label(20)
_weapon_title = _label(18)
_weapon_title.text = "Weapon"
for i in ScarecrowCombat.WEAPON_NAMES.size():
_weapon_rows.append(_label(20))
_weapon_hint = _label(16)
_weapon_hint.text = "Switch: Tab / 1-3 / d-pad down"
func _process(delta: float) -> void:
_hit = maxf(_hit - delta * 2.5, 0.0)
_ready_flash = maxf(_ready_flash - delta * 2.0, 0.0)
_tint.color.a = 0.22 * _hit
if kit == null:
return
var base := _base()
var s := campaign.state
_hp_label.text = "%s %d/%d" % [label, kit.hp(), kit.max_hp()]
_hp_label.position = base + Vector2(0.0, -34.0)
if not kit.alive:
_fear_label.text = "Fear"
elif kit.fear_left == 0.0:
_fear_label.text = "Fear Q / LB"
else:
_fear_label.text = "Fear %.0f s" % ceilf(kit.fear_left)
_fear_label.position = base + Vector2(FEAR_RADIUS * 2.0 + 14.0, 34.0)
if not kit.alive:
_patch_label.text = "Patch"
elif kit.patching:
_patch_label.text = "Patching up..."
elif kit.hp() >= kit.max_hp():
_patch_label.text = "Patch (full health)"
else:
_patch_label.text = "Patch hold F / Y (%s)" % ResourceStore.describe(kit.config.costs.get("patch", {}))
_patch_label.position = base + Vector2(FEAR_RADIUS * 2.0 + 14.0, 62.0)
var body := kit.player
_sprint_label.visible = _sprint_shown()
if _sprint_label.visible:
if not kit.alive:
_sprint_label.text = "Sprint"
elif body.sprinting:
_sprint_label.text = "Sprinting %.1f s" % body.sprint_left
elif body.sprint_recharge > 0.0:
_sprint_label.text = "Sprint %.0f s" % ceilf(body.sprint_recharge)
else:
_sprint_label.text = "Sprint hold Shift / L3"
_sprint_label.position = base + Vector2(0.0, 100.0)
_update_weapons()
queue_redraw()
func _update_weapons() -> void:
var shown := combat != null
_weapon_title.visible = shown
_weapon_hint.visible = shown
for l in _weapon_rows:
l.visible = shown
if not shown:
return
var at := _weapons_rect().position
_weapon_title.position = at + Vector2(12.0, 6.0)
for i in _weapon_rows.size():
var l := _weapon_rows[i]
var text := "%d %s" % [i + 1, ScarecrowCombat.WEAPON_NAMES[i]]
var color := Color(0.95, 0.95, 0.95)
if not combat.owns(i):
text += " (workbench)"
color = Color(0.55, 0.55, 0.55)
elif i == ScarecrowCombat.Weapon.PUMPKIN_BOMB and combat.bomb_left > 0.0:
text += " %.0f s" % ceilf(combat.bomb_left)
if i == combat.weapon:
color = Color(1.0, 0.85, 0.3)
l.text = text
l.add_theme_color_override("font_color", color)
l.position = at + Vector2(30.0, 30.0 + i * WEAPON_ROW)
_weapon_hint.position = at + Vector2(12.0, 30.0 + _weapon_rows.size() * WEAPON_ROW + 2.0)
func _weapons_rect() -> Rect2:
return Rect2(size + WEAPONS.position, WEAPONS.size)
func _draw() -> void:
if kit == null:
return
var base := _base()
var s := campaign.state
var height := 146.0 + (SPRINT_ROW if _sprint_shown() else 0.0)
draw_rect(Rect2(base - Vector2(14.0, 46.0), Vector2(340.0, height)), Color(0.0, 0.0, 0.0, 0.42))
var frac := float(kit.hp()) / float(maxi(kit.max_hp(), 1))
var full := Color(0.45, 0.9, 0.35) if frac > 0.5 else (Color(1.0, 0.8, 0.2) if frac > 0.25 else Color(1.0, 0.3, 0.2))
full = full.lerp(Color.WHITE, _hit * 0.6)
for i in kit.max_hp():
var r := Rect2(base + Vector2(i * (PIP.x + PIP_GAP), 0.0), PIP)
draw_rect(r, full if i < kit.hp() else Color(0.15, 0.15, 0.15, 0.8))
draw_rect(r, Color(0.0, 0.0, 0.0, 0.9), false, 2.0)
# Fear: dark disc, a sweep that fills while cooling down, bright when ready.
var c := base + Vector2(FEAR_RADIUS, 32.0 + FEAR_RADIUS)
var ready := kit.fear_left == 0.0 and kit.alive
draw_circle(c, FEAR_RADIUS, Color(0.08, 0.1, 0.14, 0.9))
if ready:
draw_circle(c, FEAR_RADIUS - 5.0, Color(0.55, 0.85, 1.0).lerp(Color.WHITE, _ready_flash))
else:
draw_arc(c, FEAR_RADIUS - 8.0, -PI * 0.5, -PI * 0.5 + TAU * kit.fear_charge(), 48, Color(0.4, 0.6, 0.75), 9.0)
draw_arc(c, FEAR_RADIUS + 3.0 + _ready_flash * 10.0, 0.0, TAU, 48, Color(1.0, 1.0, 1.0, 0.25 + 0.75 * _ready_flash), 2.5)
if combat != null:
var w := _weapons_rect()
draw_rect(w, Color(0.0, 0.0, 0.0, 0.42))
var row := Rect2(w.position + Vector2(6.0, 32.0 + combat.weapon * WEAPON_ROW), Vector2(w.size.x - 12.0, WEAPON_ROW - 2.0))
draw_rect(row, Color(1.0, 0.85, 0.3, 0.18))
draw_rect(Rect2(row.position, Vector2(4.0, row.size.y)), Color(1.0, 0.85, 0.3))
if kit.patching:
var bar := Rect2(base + Vector2(FEAR_RADIUS * 2.0 + 14.0, 92.0), Vector2(210.0, 8.0))
draw_rect(bar, Color(0.1, 0.1, 0.1, 0.9))
draw_rect(Rect2(bar.position, Vector2(bar.size.x * kit.patch_elapsed / kit.config.patch_time, bar.size.y)), Color(0.45, 1.0, 0.4))
func _base() -> Vector2:
return Vector2(36.0, size.y - 126.0 - (SPRINT_ROW if _sprint_shown() else 0.0))
func _sprint_shown() -> bool:
return kit != null and kit.player != null and kit.player.can_sprint()
func _label(font_size: int) -> Label:
var l := Label.new()
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(l)
return l

View file

@ -0,0 +1 @@
uid://e768baxfmoit

View file

@ -0,0 +1,304 @@
class_name SettingsMenu
extends CenterContainer
## Settings, from the main menu or the pause menu (Main): one scrolling column so the
## keyboard and gamepad can reach everything in order.
## Audio a volume slider per bus (GameSettings.BUSES)
## Controls move / aim stick dead zones, then every binding (read from the InputMap, so
## it always shows what the game really uses; remapping isn't offered)
## Display fullscreen, VSync, 3D resolution scale
## Gameplay tips on the first day and night
## Co-op your name (the lobby and your name tag), and your microphone for voice chat
## Every change is applied and saved at once (changed); Back or Escape / B closes it.
signal changed
signal closed
## (label, actions) shown in the bindings list.
const BINDINGS := [
["Move", []],
["Aim", []],
["Shoot", ["fire"]],
["Fear", ["fear"]],
["Patch up (hold)", ["patch"]],
["Gather / repair / workbench", ["interact"]],
["Build mode", ["build_mode"]],
["Pick a buildable", ["build_1", "build_2", "build_3", "build_4", "build_next"]],
["Rotate", ["rotate_left", "rotate_right"]],
["Dismantle / leave build mode", ["cancel"]],
["Pause", ["pause"]],
["Hide tips", ["hide_tips"]],
["Microphone on / off (co-op)", ["toggle_mic"]],
]
const PAD_BUTTONS := {
JOY_BUTTON_A: "A", JOY_BUTTON_B: "B", JOY_BUTTON_X: "X", JOY_BUTTON_Y: "Y", JOY_BUTTON_BACK: "Back",
JOY_BUTTON_START: "Start", JOY_BUTTON_LEFT_SHOULDER: "LB", JOY_BUTTON_RIGHT_SHOULDER: "RB",
JOY_BUTTON_DPAD_UP: "D-pad up", JOY_BUTTON_DPAD_DOWN: "D-pad down", JOY_BUTTON_DPAD_LEFT: "D-pad left",
JOY_BUTTON_DPAD_RIGHT: "D-pad right", JOY_BUTTON_LEFT_STICK: "L3", JOY_BUTTON_RIGHT_STICK: "R3",
}
var settings: GameSettings
var is_open := false
var back_button: Button
## Controls by setting, for tests: "volume/Master", "move_dead_zone", "aim_dead_zone",
## "fullscreen", "vsync", "resolution_scale", "show_tips".
var controls := {}
var _box: VBoxContainer
var _scroll: ScrollContainer
var _values := {} # setting -> value Label
var _loading := false
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 28)
panel.add_child(margin)
var outer := VBoxContainer.new()
outer.add_theme_constant_override("separation", 14)
margin.add_child(outer)
var title := Label.new()
title.text = "Settings"
title.add_theme_font_size_override("font_size", 44)
title.add_theme_color_override("font_color", UiTheme.GOLD)
outer.add_child(title)
_scroll = ScrollContainer.new()
_scroll.custom_minimum_size = Vector2(980.0, 640.0)
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_scroll.follow_focus = true
outer.add_child(_scroll)
_box = VBoxContainer.new()
_box.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_box.add_theme_constant_override("separation", 10)
_scroll.add_child(_box)
_head("Audio")
for bus in GameSettings.BUSES:
_slider("volume/" + bus, GameSettings.BUS_NAMES[bus], 0.0, 1.0, 0.05)
_head("Controls")
_slider("move_dead_zone", "Move stick dead zone", 0.05, 0.9, 0.05)
_slider("aim_dead_zone", "Aim stick dead zone", 0.05, 0.9, 0.05)
_note("Mouse aim follows the cursor directly, so it has no sensitivity to set.")
_bindings()
_head("Display")
_check("fullscreen", "Fullscreen")
_check("vsync", "VSync")
_slider("resolution_scale", "3D resolution scale", 0.5, 1.0, 0.05)
_head("Gameplay")
_check("show_tips", "Tips on the first day and night")
_head("Co-op")
_text("player_name", "Your name")
_check("microphone", "Send my microphone in voice chat")
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 20)
outer.add_child(row)
back_button = Button.new()
back_button.text = "Back"
back_button.custom_minimum_size = Vector2(220.0, 54.0)
back_button.pressed.connect(close)
row.add_child(back_button)
var reset := Button.new()
reset.text = "Reset to defaults"
reset.custom_minimum_size = Vector2(280.0, 54.0)
reset.pressed.connect(func() -> void:
var fresh := GameSettings.new()
for key in ["volume", "move_dead_zone", "aim_dead_zone", "fullscreen", "vsync", "resolution_scale", "show_tips"]:
settings.set(key, fresh.get(key))
_load()
changed.emit())
row.add_child(reset)
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func open(p_settings: GameSettings) -> void:
settings = p_settings
_load()
is_open = true
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
_scroll.scroll_vertical = 0
(controls["volume/Master"] as Control).grab_focus.call_deferred()
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.4)) # dims what's behind
func close() -> void:
if not is_open:
return
is_open = false
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
closed.emit()
## "W, A, S, D, Up, Left, Down, Right" and "Left stick" for an action list.
static func describe_keys(actions: Array) -> String:
var out := PackedStringArray()
for a: String in actions:
if not InputMap.has_action(a):
continue
for e in InputMap.action_get_events(a):
var text := ""
if e is InputEventKey:
var k := e as InputEventKey
text = OS.get_keycode_string(k.physical_keycode if k.physical_keycode != KEY_NONE else k.keycode)
elif e is InputEventMouseButton:
text = {MOUSE_BUTTON_LEFT: "Left mouse", MOUSE_BUTTON_RIGHT: "Right mouse", MOUSE_BUTTON_MIDDLE: "Middle mouse"}.get(
(e as InputEventMouseButton).button_index, "Mouse")
if text != "" and not out.has(text):
out.append(text)
return ", ".join(out)
static func describe_pad(actions: Array) -> String:
var out := PackedStringArray()
for a: String in actions:
if not InputMap.has_action(a):
continue
for e in InputMap.action_get_events(a):
var text := ""
if e is InputEventJoypadButton:
text = PAD_BUTTONS.get((e as InputEventJoypadButton).button_index, "Button %d" % (e as InputEventJoypadButton).button_index)
elif e is InputEventJoypadMotion:
var m := e as InputEventJoypadMotion
text = {JOY_AXIS_LEFT_X: "Left stick", JOY_AXIS_LEFT_Y: "Left stick", JOY_AXIS_RIGHT_X: "Right stick",
JOY_AXIS_RIGHT_Y: "Right stick", JOY_AXIS_TRIGGER_LEFT: "LT", JOY_AXIS_TRIGGER_RIGHT: "RT"}.get(m.axis, "Axis")
if text != "" and not out.has(text):
out.append(text)
return ", ".join(out)
func _load() -> void:
_loading = true
for key: String in controls:
var c: Control = controls[key]
var v: Variant = settings.volume[key.trim_prefix("volume/")] if key.begins_with("volume/") else settings.get(key)
if c is HSlider:
(c as HSlider).value = float(v)
_show_value(key, float(v))
elif c is CheckBox:
(c as CheckBox).button_pressed = bool(v)
elif c is LineEdit:
(c as LineEdit).text = String(v)
_loading = false
func _apply_value(key: String, v: Variant) -> void:
if _loading or settings == null:
return
if key.begins_with("volume/"):
settings.volume[key.trim_prefix("volume/")] = float(v)
else:
settings.set(key, v)
if v is float:
_show_value(key, v)
changed.emit()
func _show_value(key: String, v: float) -> void:
if _values.has(key):
(_values[key] as Label).text = "%d%%" % roundi(v * 100.0)
func _head(text: String) -> void:
var l := Label.new()
l.text = text
l.add_theme_font_size_override("font_size", 28)
l.add_theme_color_override("font_color", UiTheme.GOLD)
_box.add_child(l)
func _note(text: String) -> void:
var l := Label.new()
l.text = text
l.add_theme_font_size_override("font_size", 18)
l.add_theme_color_override("font_color", Color(0.72, 0.74, 0.68))
_box.add_child(l)
func _slider(key: String, label: String, lo: float, hi: float, step: float) -> void:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 18)
_box.add_child(row)
var l := Label.new()
l.text = label
l.custom_minimum_size = Vector2(340.0, 0.0)
row.add_child(l)
var s := HSlider.new()
s.min_value = lo
s.max_value = hi
s.step = step
s.custom_minimum_size = Vector2(440.0, 32.0)
s.size_flags_vertical = Control.SIZE_SHRINK_CENTER
s.value_changed.connect(func(v: float) -> void: _apply_value(key, v))
row.add_child(s)
var value := Label.new()
value.custom_minimum_size = Vector2(80.0, 0.0)
row.add_child(value)
controls[key] = s
_values[key] = value
func _text(key: String, label: String) -> void:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 18)
_box.add_child(row)
var l := Label.new()
l.text = label
l.custom_minimum_size = Vector2(340.0, 0.0)
row.add_child(l)
var e := LineEdit.new()
e.max_length = 20
e.custom_minimum_size = Vector2(440.0, 40.0)
e.placeholder_text = "Shown over your scarecrow in co-op"
e.text_changed.connect(func(t: String) -> void: _apply_value(key, t.strip_edges()))
row.add_child(e)
controls[key] = e
func _check(key: String, label: String) -> void:
var c := CheckBox.new()
c.text = label
c.toggled.connect(func(on: bool) -> void: _apply_value(key, on))
_box.add_child(c)
controls[key] = c
func _bindings() -> void:
var grid := GridContainer.new()
grid.columns = 3
grid.add_theme_constant_override("h_separation", 30)
grid.add_theme_constant_override("v_separation", 4)
_box.add_child(grid)
for head in ["Action", "Keyboard / mouse", "Gamepad"]:
var l := Label.new()
l.text = head
l.add_theme_font_size_override("font_size", 18)
l.add_theme_color_override("font_color", Color(0.72, 0.74, 0.68))
grid.add_child(l)
for row: Array in BINDINGS:
var keys := describe_keys(row[1])
var pad := describe_pad(row[1])
match row[0]:
"Move":
keys = "W A S D, arrow keys"
pad = describe_pad(["move_left", "move_right", "move_forward", "move_back"])
"Aim":
keys = "Mouse cursor"
pad = describe_pad(["aim_left", "aim_right", "aim_up", "aim_down"])
for text in [row[0], keys, pad]:
var l := Label.new()
l.text = text
l.add_theme_font_size_override("font_size", 19)
grid.add_child(l)
func _unhandled_input(event: InputEvent) -> void:
if is_open and event.is_action_pressed("ui_cancel"):
close()
get_viewport().set_input_as_handled()

View file

@ -0,0 +1 @@
uid://cvfknxxm526j2

145
game/scripts/shed_stock.gd Normal file
View file

@ -0,0 +1,145 @@
class_name ShedStock
extends Node3D
## The supply shed's stock piles, which grow and shrink with what the shed holds: logs for wood,
## crates for scrap, hay bales for straw. Each pile is a list of props (some already in the scene,
## the rest added here); a pile shows one prop per `per` units, up to all of them. Every prop has
## collision, and all of them are in place when the farm's navigation is built, so a pile's
## footprint never changes for enemies; a hidden prop only stops colliding for the scarecrow and
## shots. Each pile has a spot in front of it where supply thieves stand to fill their sacks, and a
## label with the amount while the scarecrow is nearby.
const PREF := "res://assets/farm/ithappy/farm/prefabs/assets/"
const LABEL_RANGE := 9.0
## material -> adopt (scene props under the shed zone, in fill order), extra ([prefab, world
## position, yaw in degrees, scale]), per (units per prop), front (thieves' spot), label (world).
const PILES := {
"wood": {
"adopt": ["firewood_010_1", "firewood_010_2"],
"extra": [
["prop/firewood_010", Vector3(4.2, 0.0, -19.0), -4.0, 1.0],
["prop/firewood_010", Vector3(4.2, 0.35, -19.0), 5.0, 1.0],
["prop/firewood_010", Vector3(4.2, 0.7, -18.45), 3.0, 1.0],
["prop/firewood_010", Vector3(4.2, 0.7, -19.0), -2.0, 1.0],
["prop/firewood_010", Vector3(4.2, 1.05, -18.7), 6.0, 1.0],
],
"per": 4,
"front": Vector2(2.6, -18.6),
"label": Vector3(4.2, 2.2, -18.7),
},
"scrap": {
"adopt": ["box_004_1", "box_004_2", "case_001_1", "box_004_3"],
"extra": [
["box/box_004", Vector3(-2.0, 0.5, -20.3), 4.0, 1.0],
["box/box_004", Vector3(-3.1, 0.5, -20.4), -6.0, 1.0],
["prop/barrel_010", Vector3(-4.3, 0.0, -20.3), 0.0, 1.0],
["box/box_004", Vector3(-2.55, 1.5, -20.35), 12.0, 1.0],
["prop/barrel_001", Vector3(-5.4, 0.0, -20.2), 0.0, 1.0],
["box/box_004", Vector3(-3.1, 2.5, -20.35), -15.0, 1.0],
],
"per": 3,
"front": Vector2(-3.0, -15.1),
"label": Vector3(-3.4, 2.8, -18.6),
},
"straw": {
"adopt": ["hay_001_1"],
"extra": [
["prop/hay_001", Vector3(7.3, 0.0, -18.9), 15.0, 0.55],
["prop/hay_001", Vector3(7.3, 0.0, -17.7), -10.0, 0.55],
["prop/hay_001", Vector3(6.3, 0.0, -20.1), 30.0, 0.55],
["prop/hay_001", Vector3(5.9, 1.9, -18.0), 0.0, 0.55],
["prop/hay_001", Vector3(5.1, 0.0, -20.1), -25.0, 0.55],
],
"per": 4,
"front": Vector2(6.75, -16.25),
"label": Vector3(6.2, 3.2, -18.4),
},
}
var campaign: CampaignController
var player: Node3D
## material -> Array[Node3D], in fill order.
var slots := {}
var shown := {}
var _labels := {}
var _bodies := {} # material -> Array (per slot: Array[CollisionObject3D])
var _last := {}
## Before the navigation is built: adopts the scene's piles and adds the extra props (every prop
## present and colliding).
func setup(p_campaign: CampaignController, shed_zone: Node3D, p_player: Node3D) -> void:
campaign = p_campaign
player = p_player
for m: String in PILES:
var pile: Dictionary = PILES[m]
var list: Array[Node3D] = []
for prop_name: String in pile["adopt"]:
var n := shed_zone.get_node_or_null(prop_name) as Node3D
if n != null:
list.append(n)
for e: Array in pile["extra"]:
var n := (load(PREF + String(e[0]) + ".tscn") as PackedScene).instantiate() as Node3D
n.name = "Stock_%s_%d" % [m, list.size()]
shed_zone.add_child(n)
n.global_transform = Transform3D(Basis(Vector3.UP, deg_to_rad(float(e[2]))).scaled(Vector3.ONE * float(e[3])), e[1])
list.append(n)
slots[m] = list
var bodies: Array = []
for n in list:
bodies.append(n.find_children("*", "CollisionObject3D", true, false))
_bodies[m] = bodies
var l := Label3D.new()
l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
l.no_depth_test = true
l.shaded = false
l.font_size = 44
l.outline_size = 10
l.pixel_size = 0.0075
l.modulate = GatherNode.COLORS[m]
l.visible = false
add_child(l)
l.global_position = pile["label"]
_labels[m] = l
## Where supply thieves stand to take this material.
func spot(material: String) -> Vector2:
return PILES[material]["front"] if PILES.has(material) else Vector2.ZERO
## Props a pile shows for an amount.
static func props_for(material: String, amount: int, slot_count: int) -> int:
return clampi(ceili(amount / float(PILES[material]["per"])), 0, slot_count)
## Shows each pile for the shed's stock (after the navigation is built; then on every change).
func refresh() -> void:
var shed := campaign.state.resources.shed
for m: String in slots:
var list: Array = slots[m]
var n := props_for(m, int(shed[m]), list.size())
shown[m] = n
_last[m] = int(shed[m])
for i in list.size():
var on := i < n
(list[i] as Node3D).visible = on
for body: CollisionObject3D in _bodies[m][i]:
body.collision_layer = 1 if on else 0
func _process(_delta: float) -> void:
if campaign == null:
return
var shed := campaign.state.resources.shed
for m: String in slots:
if int(shed[m]) != int(_last.get(m, -1)):
refresh()
break
var near := player != null
for m: String in _labels:
var l := _labels[m] as Label3D
var at: Vector3 = PILES[m]["label"]
l.visible = near and Vector2(player.global_position.x - at.x, player.global_position.z - at.z).length() < LABEL_RANGE
if l.visible:
l.text = "%s %d" % [m.capitalize(), int(shed[m])]

View file

@ -0,0 +1 @@
uid://c8v027vvws1b3

View file

@ -0,0 +1,642 @@
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: 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).
signal layout_changed
signal built(id: int, type: String)
signal destroyed(id: int, type: String, position: Vector3)
## Damaged but still standing; repaired fully; an automated defense shot; a trap slowed someone.
signal hurt(id: int, position: Vector3)
signal repaired(id: 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": "Slowing trap",
"automated_defense": "Automated defense",
}
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
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 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).
func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
var half := Vector2(0.75, 0.75) 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}
## 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.
func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) -> 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"]), 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):
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost))
return ""
## Builds after validate() passed: pays, records, shows, and updates navigation. Returns the id.
func place(type: String, x: float, z: float, rot: int) -> int:
var s := campaign.state
if not s.pay(config.costs.get(type, {})):
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)})
s.record_event("structures_built")
_add_view(s.structures[s.structures.size() - 1])
_update_nav()
built.emit(id, type)
return id
## Takes a structure down, refunding dismantle_refund of its cost into the shed. Returns the
## refund.
func dismantle(id: int) -> Dictionary:
var e := campaign.state.structure(id)
if e.is_empty():
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.
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:
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 and repairs fully. Returns false if there was nothing to repair or it couldn't be paid.
func repair(id: int) -> bool:
var cost := repair_cost(id)
if cost.is_empty() or not campaign.state.pay(cost):
return false
var e := campaign.state.structure(id)
e["hp"] = max_hp(e["type"])
campaign.state.record_event("repairs")
repaired.emit(id)
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"])))
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
if absf(x - float(e["x"])) <= 0.75 and absf(z - float(e["z"])) <= 0.75:
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)
projectiles.fire(origin, origin + dir * 0.6, dir)
turret_fired.emit(origin)
_turret_cd[id] = config.turret_fire_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).
func sync_from_state() -> void:
for id in _views.keys():
(_views[id] as Node3D).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)
_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:
view.queue_free()
for d in [_views, _bars, _bodies, _tints, _wobble, _heads, _turret_cd, _gate_open]:
(d as Dictionary).erase(id)
_update_nav()
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"]))})
nav.set_structures(entries)
layout_changed.emit()
func _add_view(e: Dictionary) -> void:
var id: int = e["id"]
var view := _build_view(e["type"], e["rot"])
view.name = "%s_%d" % [e["type"], id]
add_child(view)
_views[id] = view
view.global_position = Vector3(e["x"], _ground_y(Vector2(e["x"], e["z"])), e["z"])
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.
func _build_view(type: String, rot: int) -> Node3D:
var root := Node3D.new()
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
var fp := footprint(type, 0.0, 0.0, rot)
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 tar := MeshInstance3D.new()
tar.name = "Tar"
var box := BoxMesh.new()
box.size = Vector3(1.4, 0.06, 1.4)
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, 0.0, 0.55)
_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

View file

@ -0,0 +1 @@
uid://di5ehcmuhbqy7

View file

@ -0,0 +1,506 @@
class_name ThiefBehavior
extends RefCounted
## What each enemy wants, decided every tick (EnemySystem turns it into motion). Three types
## (stats in GameConfig.enemy_types):
## thief on foot, after its type's targets (animals and supplies): the theft lifecycle of
## game/RULES.md below. Routes around barriers when it can, breaks through when not.
## crow flies, after crops only: straight at a claimed crop (fences, gates, and traps mean
## nothing to it), lands and takes it, then flies straight off the farm out its
## nearest side. It never fights.
## breaker the fence breaker, on foot; steals nothing. It walks (breaker_field) to the nearest
## barrier guarding the crops, the pen, or the shed and smashes it, then goes for the
## next. It turns on the scarecrow when it comes close or shoots it, and hunts the
## scarecrow when nothing is left to break.
## States:
## SEEK claim something to take (LootSystem.claim, limited to the type's categories: dropped
## loot in view first, then its wanted category, EnemySystem.want, then the others),
## reserving it so it shows as targeted, and go there. On foot: along its category's
## flow field (the crop rows, the pen, the shed piles) from afar, straight at it once
## inside that area or close with a clear line. Flying: straight at it. A breaker
## follows the breaker field instead.
## STEAL stand at it for its steal time (the category's, times the type's steal_time; the
## progress ring fills); a hit restarts it. An animal that moved off is chased again; a
## sack finds the shed empty and seeks again.
## CARRY take it off the farm at the type's carry_speed: on foot along the escape field to the
## nearest point of the farm's edge (reaching the edge carries it off), flying straight
## out the nearest side. The loot is lost.
## RETREAT nothing left to take, or sunrise: leave the same way.
## FLEE scared (the scarecrow's fear): run straight away for fear_duration, giving up any
## claim; carriers drop their loot (D5) unless fear_drops_loot is off. Afterwards an
## enemy seeks again, or keeps carrying what it still holds.
## BREAK its route runs into a player-built barrier (FarmNavigation.barrier_ahead), or a
## breaker reached the one it came for: it hits the barrier (structure_damage every
## hit_interval) until it breaks, then goes back to what it was doing. Steering straight
## at loot needs a line clear of barriers too, so a fence in the way is broken or walked
## around, not ignored.
## FIGHT a breaker goes for the scarecrow, until it's more than FIGHT_LEASH away and there's
## still something to break.
## An enemy whose claim disappears (another one took it, the scarecrow recovered it, an animal
## followed the scarecrow away) claims another. Who hits the scarecrow (EnemySystem.
## evaluate_attacks) depends on the type's aggression: thieves when touching it while seeking,
## stealing, carrying, or breaking; breakers while fighting; crows never.
enum State { SEEK, STEAL, CARRY, RETREAT, FLEE, BREAK, FIGHT }
## Distance at which an enemy starts taking its loot.
const STEAL_REACH := 0.9
## Seconds a thief keeps walking toward dropped loot it can't see before choosing another.
const GIVE_UP_TIME := 10.0
## Flyers see dropped crops from above within this distance.
const AIR_VIEW := 20.0
## A flyer this far outside the farm has left it.
const AIR_EXIT_MARGIN := 2.0
const FIGHT_LEASH := 12.0
var loot: LootSystem
var nav: FarmNavigation
var crop_field: PackedInt32Array
var escape_field: PackedInt32Array
var field_rect: Rect2
## Set by FarmSim: the flow fields toward the pen, each shed pile (material -> field), and the
## barriers guarding valuables; those areas; the farm (flyers leave over its edge); and, every
## tick, where the scarecrow is.
var animal_field := PackedInt32Array()
var supply_fields := {}
var breaker_field := PackedInt32Array()
## Toward the scarecrow (FarmSim keeps it fresh while anything fights).
var hunt_field := PackedInt32Array()
var pen_rect := Rect2()
var shed_rect := Rect2()
var farm_rect := Rect2()
var scarecrow := Vector2(INF, INF)
## Co-op: where player 2's scarecrow is (INF when there's none, or it's down). Enemies go for the
## nearer of the two.
var scarecrow2 := Vector2(INF, INF)
var cfg: GameConfig
## Set by FarmSim: the barriers enemies break.
var structures: StructureSystem
var _dir := PackedFloat32Array([0.0, 0.0])
func setup(p_cfg: GameConfig, p_nav: FarmNavigation, p_loot: LootSystem, p_crop_field: PackedInt32Array,
p_escape_field: PackedInt32Array, p_field_rect: Rect2) -> void:
cfg = p_cfg
nav = p_nav
loot = p_loot
crop_field = p_crop_field
escape_field = p_escape_field
field_rect = p_field_rect
func update(es: EnemySystem, dt: float) -> void:
for i in es.active_count:
if es.alive[i] == 0:
continue
var t := es.type[i]
match es.state[i]:
State.SEEK:
if t == EnemySystem.TYPE_CROW:
_crow_seek(es, i)
elif es.t_breaks[t] == 1:
_breaker_seek(es, i)
else:
_seek(es, i, dt)
State.STEAL:
_steal(es, i, dt)
State.CARRY:
if es.t_flying[t] == 1:
_fly_off(es, i, EnemySystem.Removal.ESCAPED)
else:
_carry(es, i)
State.FLEE:
_flee(es, i, dt)
State.BREAK:
_break(es, i)
State.FIGHT:
_fight(es, i)
_:
if es.t_flying[t] == 1:
_fly_off(es, i, EnemySystem.Removal.LEFT)
else:
_leave(es, i)
## A hit while stealing restarts the theft; a hit on a fighter makes it turn on the scarecrow.
func on_hit(es: EnemySystem, d: int) -> void:
if es.state[d] == State.STEAL:
es.timer[d] = 0.0
loot.set_progress(es.target[d], es.handle_of(d), 0.0)
if es.t_aggression[es.type[d]] == EnemySystem.Aggression.FIGHT and (es.state[d] == State.SEEK or es.state[d] == State.BREAK):
_start_fight(es, d)
func can_attack(es: EnemySystem, d: int) -> bool:
var st := es.state[d]
match es.t_aggression[es.type[d]]:
EnemySystem.Aggression.CONTACT:
return st == State.SEEK or st == State.STEAL or st == State.CARRY or st == State.BREAK
EnemySystem.Aggression.FIGHT:
return st == State.FIGHT
return false
## Whether fear makes it flee: anything busy on the farm (not already fleeing or leaving).
func can_be_scared(es: EnemySystem, d: int) -> bool:
var st := es.state[d]
return st == State.SEEK or st == State.STEAL or st == State.CARRY or st == State.BREAK or st == State.FIGHT
## Fear from center: every enemy busy on the farm within radius flees straight away. Returns how
## many were scared.
func scare(es: EnemySystem, center: Vector2, radius: float) -> int:
var n := 0
for i in es.active_count:
if es.alive[i] == 0 or not can_be_scared(es, i):
continue
var away := Vector2(es.pos_x[i], es.pos_z[i]) - center
var d := away.length()
if d > radius:
continue
var h := es.handle_of(i)
if es.carry[i] >= 0 and cfg.fear_drops_loot:
loot.drop(es.carry[i], h, es.pos_x[i], es.pos_z[i])
es.carry[i] = -1
loot.release(es.target[i], h)
es.target[i] = -1
es.barrier[i] = -1
var dir := away / d if d > 1e-3 else Vector2(es.head_x[i], es.head_z[i])
es.desire_x[i] = dir.x
es.desire_z[i] = dir.y
es.timer[i] = cfg.fear_duration
es.state[i] = State.FLEE
n += 1
return n
## Sunrise: every enemy gives up what it was after and leaves; carriers keep running.
func retreat_all(es: EnemySystem) -> void:
for i in es.active_count:
if es.alive[i] == 1:
loot.release(es.target[i], es.handle_of(i))
es.target[i] = -1
es.barrier[i] = -1
es.state[i] = State.CARRY if es.carry[i] >= 0 else State.RETREAT
## A flyer's visual altitude: cruising, coming down as it nears its crop, sitting on it while it
## takes it.
func altitude_for(es: EnemySystem, i: int) -> float:
match es.state[i]:
State.STEAL:
return cfg.land_altitude
State.SEEK:
var unit := es.target[i]
if unit > 0:
var d := loot.position_of(unit).distance_to(Vector2(es.pos_x[i], es.pos_z[i]))
return lerpf(cfg.land_altitude, cfg.cruise_altitude, clampf((d - 0.5) / 4.0, 0.0, 1.0))
return cfg.cruise_altitude
func _seek(es: EnemySystem, i: int, dt: float) -> void:
var h := es.handle_of(i)
var p := Vector2(es.pos_x[i], es.pos_z[i])
var unit := es.target[i]
if unit < 0 or not loot.is_claimed_by(unit, h):
unit = loot.claim(h, p, nav, cfg.direct_seek_distance, es.want[i], es.t_targets[es.type[i]])
es.target[i] = unit
es.timer[i] = 0.0
if unit < 0:
es.state[i] = State.RETREAT
_leave(es, i)
return
var goal := loot.position_of(unit)
var to := goal - p
var d := to.length()
if d <= STEAL_REACH:
es.state[i] = State.STEAL
es.timer[i] = 0.0
_still(es, i, to / maxf(d, 1e-4))
return
es.pace[i] = 1.0
var field := field_for(unit)
if (area_for(loot.category[unit]).has_point(p) or d < cfg.direct_seek_distance) and nav.line_clear(p.x, p.y, goal.x, goal.y):
es.desire_x[i] = to.x / d
es.desire_z[i] = to.y / d
es.timer[i] = 0.0
return
if field.is_empty():
es.desire_x[i] = to.x / d
es.desire_z[i] = to.y / d
return
if loot.is_home(unit) and nav.flow_direction(field, p.x, p.y, _dir):
es.desire_x[i] = _dir[0]
es.desire_z[i] = _dir[1]
_check_barrier(es, i, field)
return
# Dropped loot out of sight: head for its home area meanwhile, and give up after a while.
es.timer[i] += dt
if es.timer[i] > GIVE_UP_TIME:
loot.release(unit, h)
es.target[i] = -1
if nav.flow_direction(field, p.x, p.y, _dir):
es.desire_x[i] = _dir[0]
es.desire_z[i] = _dir[1]
_check_barrier(es, i, field)
else:
es.desire_x[i] = to.x / d
es.desire_z[i] = to.y / d
## A crow: straight at its crop, whatever is in the way.
func _crow_seek(es: EnemySystem, i: int) -> void:
var h := es.handle_of(i)
var p := Vector2(es.pos_x[i], es.pos_z[i])
var unit := es.target[i]
if unit < 0 or not loot.is_claimed_by(unit, h):
unit = loot.claim(h, p, nav, AIR_VIEW, es.want[i], es.t_targets[es.type[i]], false)
es.target[i] = unit
es.timer[i] = 0.0
if unit < 0:
es.state[i] = State.RETREAT
return
var to := loot.position_of(unit) - p
var d := to.length()
if d <= STEAL_REACH:
es.state[i] = State.STEAL
es.timer[i] = 0.0
_still(es, i, to / maxf(d, 1e-4))
return
es.desire_x[i] = to.x / d
es.desire_z[i] = to.y / d
es.pace[i] = 1.0
## A flyer heading straight off the farm out its nearest side (carrying its loot, or not); once
## it's past the edge it's gone.
func _fly_off(es: EnemySystem, i: int, reason: EnemySystem.Removal) -> void:
var p := Vector2(es.pos_x[i], es.pos_z[i])
if not farm_rect.grow(AIR_EXIT_MARGIN).has_point(p):
if es.carry[i] >= 0:
loot.escape(es.carry[i], es.handle_of(i))
es.carry[i] = -1
es.queue_removal(i, reason)
return
var exit := _nearest_exit(p)
var to := exit - p
var d := maxf(to.length(), 1e-4)
es.desire_x[i] = to.x / d
es.desire_z[i] = to.y / d
es.pace[i] = es.t_carry[es.type[i]] if es.carry[i] >= 0 else 1.0
## Just past the nearest point of the farm's edge.
func _nearest_exit(p: Vector2) -> Vector2:
return FarmZones.nearest_on_outline(farm_rect.grow(AIR_EXIT_MARGIN + 1.0), p)
## A fence breaker: to the nearest barrier guarding something, and smash it.
func _breaker_seek(es: EnemySystem, i: int) -> void:
if _aggro(es, i):
_start_fight(es, i)
return
var p := Vector2(es.pos_x[i], es.pos_z[i])
if breaker_field.is_empty() or breaker_field[nav.cell_of(p.x, p.y)] >= FarmNavigation.UNREACHABLE:
_start_fight(es, i) # nothing left to break
return
es.pace[i] = 1.0
if nav.flow_direction(breaker_field, p.x, p.y, _dir):
es.desire_x[i] = _dir[0]
es.desire_z[i] = _dir[1]
_check_barrier(es, i, breaker_field)
return
var id := _adjacent_structure(p)
if id >= 0:
es.barrier[i] = id
es.resume[i] = State.SEEK
es.state[i] = State.BREAK
var e := structures.campaign.state.structure(id)
var at := Vector2(float(e["x"]), float(e["z"])) - p
_still(es, i, at.normalized() if at.length_squared() > 1e-4 else Vector2(es.head_x[i], es.head_z[i]))
else:
_still(es, i, Vector2(es.head_x[i], es.head_z[i])) # the field is catching up after a breach
## The structure (in the navigation's structure layer: every barrier) nearest to p within 1.5 m,
## or -1.
func _adjacent_structure(p: Vector2) -> int:
var best := -1
var best_d := INF
var r := 3
var c := nav.cell_of(p.x, p.y)
for dz in range(-r, r + 1):
for dx in range(-r, r + 1):
var cell := c + dz * nav.width + dx
if cell < 0 or cell >= nav.cell_count() or nav.structure_at[cell] < 0:
continue
var d := nav.cell_center(cell).distance_squared_to(p)
if d < best_d:
best_d = d
best = nav.structure_at[cell]
return best
## The nearer scarecrow standing (INF if none).
func nearest_scarecrow(p: Vector2) -> Vector2:
if not scarecrow2.is_finite():
return scarecrow
if not scarecrow.is_finite():
return scarecrow2
return scarecrow if p.distance_squared_to(scarecrow) <= p.distance_squared_to(scarecrow2) else scarecrow2
func _aggro(es: EnemySystem, i: int) -> bool:
var t := es.type[i]
var p := Vector2(es.pos_x[i], es.pos_z[i])
var sc := nearest_scarecrow(p)
if es.t_aggression[t] != EnemySystem.Aggression.FIGHT or not sc.is_finite():
return false
return p.distance_to(sc) <= es.t_aggro_range[t] and nav.line_clear(p.x, p.y, sc.x, sc.y)
func _start_fight(es: EnemySystem, i: int) -> void:
es.barrier[i] = -1
es.state[i] = State.FIGHT
func _fight(es: EnemySystem, i: int) -> void:
var p := Vector2(es.pos_x[i], es.pos_z[i])
var sc := nearest_scarecrow(p)
if not sc.is_finite():
es.state[i] = State.SEEK
return
var to := sc - p
var d := to.length()
var has_work := not breaker_field.is_empty() and breaker_field[nav.cell_of(p.x, p.y)] < FarmNavigation.UNREACHABLE
if d > FIGHT_LEASH and has_work:
es.state[i] = State.SEEK
return
var contact := cfg.enemy_radius + FarmSim.SCARECROW_RADIUS + cfg.enemy_attack_reach * 0.5
if d <= contact:
_still(es, i, to / maxf(d, 1e-4))
return
es.pace[i] = 1.0
if not nav.line_clear(p.x, p.y, sc.x, sc.y) and not hunt_field.is_empty() \
and nav.flow_direction(hunt_field, p.x, p.y, _dir):
es.desire_x[i] = _dir[0]
es.desire_z[i] = _dir[1]
_check_barrier(es, i, hunt_field) # smash through to it
return
es.desire_x[i] = to.x / d
es.desire_z[i] = to.y / d
## The flow field toward an item's home: the crop rows, the pen, or its sack's pile at the shed.
func field_for(id: int) -> PackedInt32Array:
match loot.category[id]:
LootSystem.Category.ANIMAL:
return animal_field if animal_field.size() > 0 else crop_field
LootSystem.Category.SUPPLY:
return supply_fields.get(loot.sack_material[id], crop_field)
return crop_field
func area_for(c: int) -> Rect2:
match c:
LootSystem.Category.ANIMAL:
return pen_rect
LootSystem.Category.SUPPLY:
return shed_rect
return field_rect
func _steal(es: EnemySystem, i: int, dt: float) -> void:
var h := es.handle_of(i)
var unit := es.target[i]
if unit < 0 or not loot.is_claimed_by(unit, h):
es.state[i] = State.SEEK
return
if loot.category[unit] == LootSystem.Category.ANIMAL \
and loot.position_of(unit).distance_to(Vector2(es.pos_x[i], es.pos_z[i])) > STEAL_REACH + 0.4:
es.state[i] = State.SEEK # it got away (a loose animal): chase it
loot.set_progress(unit, h, 0.0)
return
es.pace[i] = 0.0
es.timer[i] += dt
var need := loot.steal_time(unit) * es.t_steal[es.type[i]]
loot.set_progress(unit, h, es.timer[i] / need)
if es.timer[i] >= need:
if loot.pick_up(unit, h):
es.carry[i] = unit
es.state[i] = State.CARRY
else:
es.state[i] = State.SEEK # nothing left to take there
es.target[i] = -1
es.timer[i] = 0.0
func _flee(es: EnemySystem, i: int, dt: float) -> void:
es.pace[i] = cfg.flee_speed_factor
es.timer[i] -= dt
if es.timer[i] <= 0.0:
es.timer[i] = 0.0
es.state[i] = State.CARRY if es.carry[i] >= 0 else State.SEEK
func _break(es: EnemySystem, i: int) -> void:
var id := es.barrier[i]
if structures == null or structures.campaign.state.structure(id).is_empty():
es.barrier[i] = -1
es.state[i] = es.resume[i]
return
if _aggro(es, i):
_start_fight(es, i)
return
es.pace[i] = 0.0
if es.attack_cd[i] == 0.0:
var t := es.type[i]
es.attack_cd[i] = es.t_hit_interval[t]
structures.damage(id, maxi(es.t_structure_damage[t], 1))
## Following a field into a barrier: stop and break it.
func _check_barrier(es: EnemySystem, i: int, field: PackedInt32Array) -> void:
var id := nav.barrier_ahead(field, es.pos_x[i], es.pos_z[i])
if id < 0:
return
es.barrier[i] = id
es.resume[i] = es.state[i]
es.state[i] = State.BREAK
es.pace[i] = 0.0
func _carry(es: EnemySystem, i: int) -> void:
if _at_exit(es, i):
loot.escape(es.carry[i], es.handle_of(i))
es.carry[i] = -1
es.queue_removal(i, EnemySystem.Removal.ESCAPED)
return
_follow(es, i, escape_field, es.t_carry[es.type[i]])
_check_barrier(es, i, escape_field)
func _leave(es: EnemySystem, i: int) -> void:
if _at_exit(es, i):
es.queue_removal(i, EnemySystem.Removal.LEFT)
return
_follow(es, i, escape_field, 1.0)
_check_barrier(es, i, escape_field)
func _at_exit(es: EnemySystem, i: int) -> bool:
return escape_field[nav.cell_of(es.pos_x[i], es.pos_z[i])] == 0
func _follow(es: EnemySystem, i: int, field: PackedInt32Array, p_pace: float) -> void:
if nav.flow_direction(field, es.pos_x[i], es.pos_z[i], _dir):
es.desire_x[i] = _dir[0]
es.desire_z[i] = _dir[1]
es.pace[i] = p_pace
else:
es.pace[i] = 0.0
func _still(es: EnemySystem, i: int, facing: Vector2) -> void:
es.desire_x[i] = facing.x
es.desire_z[i] = facing.y
es.pace[i] = 0.0

Some files were not shown because too many files have changed in this diff Show more