harvest/game/scripts/farm_navigation.gd
2026-10-03 12:14:28 -04:00

238 lines
7.6 KiB
GDScript

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.
## * 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.
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
## 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
var shapes_rasterized: int = 0
var build_usec: int = 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:
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
var n := width * height
blocked = PackedByteArray()
blocked.resize(n)
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])
_bucket_buf = PackedInt32Array()
_bucket_buf.resize(n * BUCKETS)
_bucket_cnt = PackedInt32Array()
_bucket_cnt.resize(BUCKETS)
build_usec = Time.get_ticks_usec() - t0
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
## 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).
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
## 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:
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:
blocked[i] = 1
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