class_name AnimalSystem extends Node3D ## The farm's animals as moving entities. Their theft state lives in LootSystem; this moves and ## shows them: ## loose (LOOSE) #12, #21: where every animal starts, at its own GameConfig.animal_loose_spots ## spot outside the pen, and where a loose one is back every morning. It roams ## the whole farm, day and night: each walk goes to a spot ROAM_MIN..ROAM_MAX ## meters away that it can reach in a straight line, inside the playable map ## (ROAM_MARGIN in from its edge) and outside the pen, and then it stops to ## graze. Structures stop it. It never leaves the farm on its own and never ## walks into the pen by itself. A thief may claim and carry it off; a stopped ## carrier drops it loose where it fell (inside the pen, it's home again). The ## scarecrow walking up to it starts it following. ## 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: nothing built yet, or its gate broken or ## taken down), one calm animal gets out every animal_wander_interval: it's ## loose at once (and no longer penned), walks out of the pen along the escape ## field at stray_speed, and then roams like any loose animal. If the pen shuts ## before it's out, it stays home. ## 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. A follower whose scarecrow got FOLLOW_LEASH away is ## loose where it stands. ## carried held under its thief, wriggling. ## An animal is never left DROPPED (that's for crops and sacks), and the only way to lose one is a ## thief carrying it off the farm (LootSystem.escape). ## 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 ## #21: a loose (LOOSE) animal's next wander goal is this many meters from where it stands... const ROAM_MIN := 4.0 const ROAM_MAX := 8.0 ## ...and at least this far inside the playable map's edge. const ROAM_MARGIN := 2.0 ## Loose animals keep this far out of the pen's rectangle (goals), and never cut across it. const PEN_KEEP_OUT := 1.0 ## Seconds an animal walking out of an open pen keeps at it before it settles back in. const LEAVE_TIME := 30.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 ## The playable map (FarmZones.playable): loose animals roam inside it. var farm_rect := Rect2() ## Set by FarmSim: the field toward the farm's nearest edge. An animal getting out of an open pen ## walks down it until it's out of the pen (and no further). 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() ## Loose and walking out of the open pen, not out yet (so being inside doesn't make it home). var leaving := PackedByteArray() var kinds: Array[String] = [] var _start := PackedVector2Array() var _start_yaw := PackedFloat32Array() ## #12: each animal's spot outside the pen (GameConfig.animal_loose_spots, cycled if there are ## more animals than spots), where it starts and where it's back every morning 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 ## p_farm_rect: the playable map (FarmZones.playable), where loose animals roam; empty means the ## whole navigation grid. func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNavigation, p_loot: LootSystem, p_enemies: EnemySystem, p_player: Node3D, p_farm_rect: Rect2 = Rect2()) -> 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() farm_rect = p_farm_rect if p_farm_rect.has_area() \ else Rect2(nav.origin_x, nav.origin_z, nav.width * nav.cell_size, nav.height * nav.cell_size).grow(-nav.cell_size) _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, ## wherever it roamed (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 leaving[id] = 0 timer[id] = _rng.randf_range(0.6, 1.2) # a moment's shock before it wanders off 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, LootSystem.Status.DROPPED: slot[id] = -1 if loot.status[item] == LootSystem.Status.DROPPED: loot.animal_loose(item, pos[id]) # #21: an animal is never left lying dropped if leaving[id] == 1: _leave_pen(id, item, dt) elif pen.has_point(pos[id]): loot.animal_home(item) # dropped inside the pen: it's home again _rest(id) else: _wander(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 if loot.status[item] == LootSystem.Status.LOOSE: timer[id] = maxf(timer[id], pos[id].distance_to(goal[id]) / speed[id] + 2.0) # a longer walk 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) ## A loose animal that got out of the open pen walks down the escape field until it's out of the ## pen (then it roams like any loose animal). If the pen shuts first, or it can't get out in ## LEAVE_TIME, it settles: back home if it's still inside the pen. func _leave_pen(id: int, item: int, dt: float) -> void: var out := not pen.grow(0.75).has_point(pos[id]) timer[id] -= dt if not out and pen_open and timer[id] > 0.0 and escape_field.size() > 0 \ and nav.flow_direction(escape_field, pos[id].x, pos[id].y, _dir): speed[id] = config.stray_speed _move(id, Vector2(_dir[0], _dir[1]), speed[id], dt) return leaving[id] = 0 if pen.has_point(pos[id]): loot.animal_home(item) _rest(id) 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.animal_loose(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 (#21) roams the farm: its next goal is ## ROAM_MIN..ROAM_MAX meters away, inside the playable map (ROAM_MARGIN in from the edge), ## walkable, in a clear straight line (no obstacle or structure in the way), and neither inside the ## pen (PEN_KEEP_OUT around it) nor across it. With no such goal it stays put a while. 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 from := pos[id] var area := farm_rect.grow(-ROAM_MARGIN) var keep_out := pen.grow(PEN_KEEP_OUT) # Dropped off the map by a carrier: reach far enough to get back on. var reach := ROAM_MAX + from.distance_to(Vector2(clampf(from.x, area.position.x, area.end.x), clampf(from.y, area.position.y, area.end.y))) for attempt in 16: var p := from + Vector2.from_angle(_rng.randf() * TAU) * _rng.randf_range(ROAM_MIN, reach) if not area.has_point(p) or keep_out.has_point(p) or not nav.is_walkable(nav.cell_of(p.x, p.y)): continue if _crosses(pen, from, p) or not nav.line_clear(from.x, from.y, p.x, p.y): continue return p return from ## Whether the segment a..b touches the rectangle. static func _crosses(r: Rect2, a: Vector2, b: Vector2) -> bool: if r.has_point(a) or r.has_point(b): return true var corners := [r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y)] for k in 4: if Geometry2D.segment_intersects_segment(a, b, corners[k], corners[(k + 1) % 4]) != null: return true return false ## At night, while the pen is open, a calm animal gets out now and then: it's loose (LootSystem. ## animal_strays) and walks out of the pen (_leave_pen). 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] = LEAVE_TIME 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