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 (DROPPED). ## grazing (LOOSE) #12: where every animal starts, scattered at its own GameConfig. ## animal_loose_spots spot outside the pen. Same calm wander as a penned ## animal, but anchored to that spot instead of the pen, and never walks the ## escape field on its own. A thief may still claim and carry it off (then ## it's DROPPED, below); the scarecrow walking up to it starts it following, ## same as a dropped one. ## loose (DROPPED) dropped by its thief, or wandered out of an open pen: 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 ## A grazing (LOOSE) animal's wander goals stay within this many meters of its loose spot. const LOOSE_WANDER_RADIUS := 0.8 ## 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() ## #12: each animal's grazing spot outside the pen, where it starts (GameConfig.animal_loose_spots, ## cycled if there are more animals than spots) and wanders around while LOOSE. var _loose_spot := PackedVector2Array() 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, _loose_spot]: 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) _loose_spot[id] = config.animal_loose_spots[(id - 1) % config.animal_loose_spots.size()] \ if not config.animal_loose_spots.is_empty() else _start[id] phase[id] = _rng.randf() * TAU sync_from_state() ## Every animal back at its spot -- in the pen if penned, or its loose spot outside it otherwise ## (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): var item := loot.animal_item(id) var home_spot := _start[id] if loot.status[item] == LootSystem.Status.HOME else _loose_spot[id] pos[id] = home_spot prev[id] = home_spot yaw[id] = _start_yaw[id] speed[id] = 0.0 goal[id] = home_spot 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.LOOSE: 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(id, item) 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) ## A HOME animal wanders inside the pen; a LOOSE one grazes within LOOSE_WANDER_RADIUS of its own ## loose spot instead. func _wander_goal(id: int, item: int) -> Vector2: if loot.status[item] == LootSystem.Status.HOME: 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() var center := _loose_spot[id] for attempt in 12: var p := center + Vector2(_rng.randf_range(-LOOSE_WANDER_RADIUS, LOOSE_WANDER_RADIUS), _rng.randf_range(-LOOSE_WANDER_RADIUS, LOOSE_WANDER_RADIUS)) if nav.is_walkable(nav.cell_of(p.x, p.y)): return p return 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