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

@ -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