class_name FarmNavigation extends RefCounted ## Navigation grid for ground movement on the farm. ## ## * Occupancy is rasterized from the farm's own collision: every CollisionShape3D under a ## StaticBody3D on the given layers, so physics and navigation can't drift apart. Walkable ## terrain is skipped (trimesh ground and road tiles, and anything that stays below BAND_LOW, ## 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)) 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 ## 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 var cell_size: float var inv_cell: float var origin_x: float # world position of cell (0, 0)'s min corner 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() func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer_mask: int = 1) -> void: var t0 := Time.get_ticks_usec() cell_size = p_cell_size inv_cell = 1.0 / cell_size width = ceili(bounds.size.x * inv_cell) + 2 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 for cz in height: blocked[cz * width] = 1 blocked[cz * width + width - 1] = 1 shapes_rasterized = 0 for node in world.find_children("*", "CollisionShape3D", true, false): var cs := node as CollisionShape3D var body := cs.get_parent() as StaticBody3D if body == null or cs.disabled or cs.shape == null or (body.collision_layer & layer_mask) == 0: continue if cs.shape is ConcavePolygonShape3D or cs.shape is WorldBoundaryShape3D: continue var outline := _outline(cs) if outline.size() > 0: _rasterize(outline, inflate) shapes_rasterized += 1 var w := width # Orthogonal first (indices 0..3), then diagonals (4..7) with their two side cells. _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]) 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 func cell_of(x: float, z: float) -> int: var cx := clampi(int((x - origin_x) * inv_cell), 0, width - 1) var cz := clampi(int((z - origin_z) * inv_cell), 0, height - 1) return cz * width + cx func cell_center(i: int) -> Vector2: @warning_ignore("integer_division") var cz := i / width var cx := i - cz * width return Vector2(origin_x + (cx + 0.5) * cell_size, origin_z + (cz + 0.5) * cell_size) func is_free(i: int) -> bool: return blocked[i] == 0 ## Nearest free cell to i (breadth-first over 4-neighbors), or -1 if none within max_cells. func nearest_free(i: int, max_cells: int = 4096) -> int: if blocked[i] == 0: return i var seen := {i: true} var queue: Array[int] = [i] var head := 0 while head < queue.size() and head < max_cells: var c := queue[head] head += 1 for k in 4: var nb := c + _offsets[k] if nb < 0 or nb >= blocked.size() or seen.has(nb): continue if blocked[nb] == 0: return nb seen[nb] = true queue.append(nb) return -1 ## Free cells whose centers lie inside a world rectangle on the XZ plane. func free_cells_in(rect: Rect2) -> PackedInt32Array: var out := PackedInt32Array() var c0 := cell_of(rect.position.x, rect.position.y) var c1 := cell_of(rect.end.x, rect.end.y) @warning_ignore("integer_division") for cz in range(c0 / width, c1 / width + 1): for cx in range(c0 % width, c1 % width + 1): var i := cz * width + cx if blocked[i] == 0 and rect.has_point(cell_center(i)): out.append(i) 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, computed at once (load, tests). ## Goals that aren't walkable are ignored. func distance_field(goals: PackedInt32Array) -> PackedInt32Array: 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 ## stays out of the obstruction band. func _outline(cs: CollisionShape3D) -> PackedVector2Array: var mesh := cs.shape.get_debug_mesh() var xf := cs.global_transform var points := PackedVector2Array() var lo := INF var hi := -INF for s in mesh.get_surface_count(): var verts: PackedVector3Array = mesh.surface_get_arrays(s)[Mesh.ARRAY_VERTEX] for v in verts: var p := xf * v lo = minf(lo, p.y) hi = maxf(hi, p.y) points.append(Vector2(p.x, p.z)) if points.is_empty() or hi < BAND_LOW or lo > BAND_HIGH: return PackedVector2Array() return Geometry2D.convex_hull(points) 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: lo = lo.min(p) hi = hi.max(p) var c0 := cell_of(lo.x - inflate, lo.y - inflate) var c1 := cell_of(hi.x + inflate, hi.y + inflate) var r2 := inflate * inflate var solid := hull.size() >= 4 # closed hull of at least a triangle @warning_ignore("integer_division") for cz in range(c0 / width, c1 / width + 1): for cx in range(c0 % width, c1 % width + 1): var i := cz * width + cx if blocked[i] == 1: continue var p := cell_center(i) if (solid and Geometry2D.is_point_in_polygon(p, hull)) or _dist2_to_outline(p, hull) <= r2: if id < 0: blocked[i] = 1 else: structure_at[i] = id static func _dist2_to_outline(p: Vector2, hull: PackedVector2Array) -> float: var best := INF for k in hull.size() - 1: var q := Geometry2D.get_closest_point_to_segment(p, hull[k], hull[k + 1]) best = minf(best, p.distance_squared_to(q)) 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