M4: Bot navigation

NavGrid is the map bots plan on: a point per 2 m terrain sample, solid on cliffs and
where solids stand between step and head height, and costlier where the water is
deeper than wading. Path search uses Godot's AStarGrid2D. The grid syncs every tick:
new solids (walls, pieces) block points at once, removed ones are found by a rolling
scan, and points turn wet as the tide and flood reach them. Each change is stamped
with its tick.

NavBot follows a path with ordinary PlayerCommands: it steers at waypoints, sprints
on long dry stretches, jumps when stalled, and marks a point blocked after repeated
stalls. Every half second it checks its remaining path against the change stamps and
plans again if water or a wall now crosses it. One path is planned per server tick
across all bots.

The server builds the grid while the lobby waits and its bots now roam between
random reachable places, replacing the placeholder wander bot.

Tests: 150 of 150 random reachable targets reached on 50 islands in the sweep; the
test runs 2 per island and needs 95%. New walls and rising water both cause a new
path around them; a broken wall opens the grid again; with no dry way round, the bot
swims. 23 roaming bots on an island: p99 tick 1.6 ms against the 12 ms budget.

Closes #27

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 23:38:36 -05:00
co-authored by Claude Opus 5.5
parent 6e1c87fe32
commit cc652de46e
14 changed files with 863 additions and 39 deletions
+57
View File
@@ -0,0 +1,57 @@
## Walks a bot to random reachable targets on many islands and counts how many it
## reaches. Shared by the test and `make nav-sweep`.
class_name NavSweep
extends RefCounted
## Results: {"trials", "reached", "failures": [{"seed", "from", "to", "status", "left"}]}
static func run(seeds: Array[int], targets_per_seed: int) -> Dictionary:
var trials: int = 0
var reached: int = 0
var failures: Array[Dictionary] = []
for seed_value: int in seeds:
var sim: Simulation = Simulation.new(seed_value)
var grid: NavGrid = NavGrid.build(sim)
var player_id: int = sim.add_player()
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
rng.seed = seed_value
for _target: int in targets_per_seed:
var player: SimEntity = sim.entities.find(player_id)
var goal: Vector3 = _reachable_goal(grid, player.position, rng)
if goal.y <= -999.0:
continue
trials += 1
var bot: NavBot = NavBot.new(player_id)
bot.set_goal(goal)
var start: Vector3 = player.position
var limit: int = roundi((start.distance_to(goal) * 2.5 / Tuning.WALK_SPEED + 15.0) * Tuning.TICK_RATE_HZ)
for _tick: int in limit:
grid.sync(sim)
sim.submit_command(player_id, bot.think(sim, grid))
sim.step()
if bot.status != NavBot.MOVING:
break
var left: float = Vector2(goal.x - player.position.x, goal.z - player.position.z).length()
if bot.status == NavBot.ARRIVED:
reached += 1
else:
failures.append({"seed": seed_value, "from": start, "to": goal, "status": bot.status_name(), "left": left, "plans": bot.plans})
# Start the next trial from wherever this one ended, back on its feet.
player.health = Tuning.PLAYER_MAX_HEALTH
Water.reset(player)
return {"trials": trials, "reached": reached, "failures": failures}
## A dry open point 40 to 160 m away with a complete path from `from`, or y = -1000.
static func _reachable_goal(grid: NavGrid, from: Vector3, rng: RandomNumberGenerator) -> Vector3:
for _try: int in 40:
var angle: float = rng.randf() * TAU
var reach: float = rng.randf_range(40.0, 160.0)
var point: Vector2i = grid.point_of(from + Vector3(cos(angle), 0.0, sin(angle)) * reach)
if not grid.is_open(point) or grid.wet[grid.index_of(point)] != 0:
continue
var goal: Vector3 = grid.position_of(point)
if goal.y <= Tuning.ISLAND_BEACH_TOP:
continue
if not grid.find_path(from, goal).is_empty():
return goal
return Vector3(0.0, -1000.0, 0.0)
+1
View File
@@ -0,0 +1 @@
uid://bx7pvcewg5whp
+214
View File
@@ -0,0 +1,214 @@
extends TestCase
## Bot navigation from issue M4: bots reach random reachable places on 50 islands,
## plan again when water or new walls cross their path, and 23 of them stay inside the
## server's tick budget. Bots only ever send PlayerCommands.
const FLOOR: float = 8.0
## Building level whose base is FLOOR.
const LEVEL: int = 4
const START: Vector3 = Vector3(100.0, FLOOR, 100.0)
const GOAL: Vector3 = Vector3(100.0, FLOOR, 170.0)
func test_bots_reach_random_reachable_targets_on_50_islands() -> void:
var seeds: Array[int] = []
for seed_value: int in range(100, 150):
seeds.append(seed_value)
var result: Dictionary = NavSweep.run(seeds, 2)
var trials: int = result["trials"]
var reached: int = result["reached"]
assert_true(trials >= 95, "found reachable targets for %d trials" % trials)
var rate: float = float(reached) / maxi(trials, 1)
for failure: Dictionary in result["failures"]:
print(" nav miss: %s" % failure)
assert_true(rate >= 0.95, "reached %d of %d (%.1f%%)" % [reached, trials, rate * 100.0])
## A flat world with one player at START and a bot walking it to `goal`.
func _flat() -> Simulation:
var sim: Simulation = Simulation.new(7, SimGround.flat(FLOOR))
var player: SimEntity = sim.entities.find(sim.add_player())
player.position = START
player.on_ground = true
return sim
## Steps the bot until it stops moving or `limit` ticks pass, calling `each` (if
## given) with the tick number before every step.
func _walk(sim: Simulation, grid: NavGrid, bot: NavBot, limit: int, each: Callable = Callable()) -> void:
for index: int in limit:
if each.is_valid():
each.call(index)
grid.sync(sim)
var command: PlayerCommand = bot.think(sim, grid)
assert_true(command is PlayerCommand)
sim.submit_command(bot.player_id, command)
sim.step()
if bot.status != NavBot.MOVING:
return
func test_a_bot_walks_straight_across_open_ground() -> void:
var sim: Simulation = _flat()
var grid: NavGrid = NavGrid.build(sim)
var bot: NavBot = NavBot.new(1)
bot.set_goal(GOAL)
_walk(sim, grid, bot, 30 * 30)
assert_eq(bot.status_name(), "arrived")
assert_eq(bot.plans, 1)
var feet: Vector3 = sim.entities.find(1).position
assert_true(Vector2(feet.x - GOAL.x, feet.z - GOAL.z).length() <= bot.arrive_radius)
func test_a_new_wall_across_the_path_triggers_a_new_path_around_it() -> void:
var sim: Simulation = _flat()
var grid: NavGrid = NavGrid.build(sim)
var bot: NavBot = NavBot.new(1)
bot.set_goal(GOAL)
# Lambdas capture locals by value, so the first path goes into a shared array.
var first_path: Array[Vector2i] = []
var build_wall: Callable = func(index: int) -> void:
if index == 1:
first_path.append_array(bot.path)
if index == 20:
# A row of real wooden walls across the way, 30 m ahead: x 80 to 120 m, z 136 m.
for x: int in range(20, 30):
sim.structures.add(StructureSet.WALL, 0, Vector4i(x, LEVEL, 34, StructureSet.SLOT_WALL_Z), 0, 0, sim.tick, sim.ground)
_walk(sim, grid, bot, 60 * 30, build_wall)
assert_eq(bot.status_name(), "arrived")
assert_true(bot.plans >= 2, "planned again after the wall went up (%d plans)" % bot.plans)
var crosses: bool = false
for point: Vector2i in first_path:
if point.x * 2.0 > 80.0 and point.x * 2.0 < 120.0 and point.y * 2.0 == 136.0:
crosses = true
assert_true(crosses, "the first path went straight through where the wall is")
for point: Vector2i in bot.path:
var x: float = point.x * NavGrid.CELL
var z: float = point.y * NavGrid.CELL
assert_false(x > 79.0 and x < 121.0 and absf(z - 136.0) < 1.0, "the new path avoids the wall at %s" % point)
func test_a_broken_wall_opens_the_way_again() -> void:
var sim: Simulation = _flat()
var wall: StructureSet.Piece = sim.structures.add(StructureSet.WALL, 0, Vector4i(25, LEVEL, 34, StructureSet.SLOT_WALL_Z), 0, 0, 0, sim.ground)
var grid: NavGrid = NavGrid.build(sim)
var blocked_point: Vector2i = grid.point_of(Vector3(102.0, FLOOR, 136.0))
assert_false(grid.is_open(blocked_point), "the wall blocks the grid")
sim.structures.remove(wall.id, sim.ground)
for _index: int in 40:
sim.step()
grid.sync(sim)
assert_true(grid.is_open(blocked_point), "the scan frees points once the wall is gone")
assert_true(grid.changed_tick[grid.index_of(blocked_point)] > 0)
## Ground at 3 m with a sunken strip, x 60 to 140 m and z 124 to 136 m, whose floor is
## level with the starting sea. Its banks slope over 6 m, so it's walkable while the
## sea is low.
func _strip_ground() -> SimGround:
var side: int = roundi(Tuning.WORLD_SIZE_METRES / 2.0) + 1
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side)
for z: int in side:
for x: int in side:
var wx: float = x * 2.0
var wz: float = z * 2.0
var dx: float = maxf(maxf(60.0 - wx, wx - 140.0), 0.0)
var dz: float = maxf(maxf(124.0 - wz, wz - 136.0), 0.0)
var distance: float = sqrt(dx * dx + dz * dz)
values[z * side + x] = lerpf(0.0, 3.0, clampf(distance / 6.0, 0.0, 1.0))
return SimGround.from_heights(values, side, 2.0)
func test_rising_water_across_the_path_triggers_a_new_path_around_it() -> void:
var sim: Simulation = Simulation.new(7, _strip_ground())
var player: SimEntity = sim.entities.find(sim.add_player())
player.position = Vector3(100.0, 3.0, 100.0)
player.on_ground = true
var grid: NavGrid = NavGrid.build(sim)
var bot: NavBot = NavBot.new(1)
var goal: Vector3 = Vector3(100.0, 3.0, 160.0)
bot.set_goal(goal)
var swam: Array[bool] = [false]
var crossed_strip: Array[bool] = [false]
var flood: Callable = func(index: int) -> void:
if index == 1:
for point: Vector2i in bot.path:
if point.y * 2.0 > 124.0 and point.y * 2.0 < 136.0 and point.x * 2.0 > 60.0 and point.x * 2.0 < 140.0:
crossed_strip[0] = true
if index == 15:
sim.set_sea_level(2.0)
if player.swimming:
swam[0] = true
_walk(sim, grid, bot, 90 * 30, flood)
assert_true(crossed_strip[0], "the first path crossed the dry strip")
assert_eq(bot.status_name(), "arrived")
assert_true(bot.plans >= 2, "planned again when the strip flooded")
assert_false(swam[0], "walked around the water instead of swimming")
for point: Vector2i in bot.path:
assert_eq(grid.wet[grid.index_of(point)], 0, "the new path stays dry")
func test_with_no_dry_way_round_the_bot_swims() -> void:
# The same strip, but the sea rises over everything around it too: the only way is
# through water, and the bot takes it.
var sim: Simulation = Simulation.new(7, _strip_ground())
var player: SimEntity = sim.entities.find(sim.add_player())
player.position = Vector3(100.0, 3.0, 100.0)
player.on_ground = true
var grid: NavGrid = NavGrid.build(sim)
sim.set_sea_level(4.5)
grid.sync(sim)
var bot: NavBot = NavBot.new(1)
bot.set_goal(Vector3(100.0, 3.0, 130.0))
_walk(sim, grid, bot, 60 * 30)
assert_eq(bot.status_name(), "arrived")
func test_a_goal_inside_a_solid_block_is_unreachable() -> void:
var sim: Simulation = _flat()
# A closed box of solid rock around the goal.
sim.ground.add_solid(AABB(Vector3(90.0, FLOOR - 1.0, 150.0), Vector3(20.0, 10.0, 20.0)))
var grid: NavGrid = NavGrid.build(sim)
var bot: NavBot = NavBot.new(1)
bot.set_goal(Vector3(100.0, FLOOR, 160.0))
_walk(sim, grid, bot, 30)
assert_eq(bot.status_name(), "unreachable")
func test_planning_is_limited_per_tick() -> void:
var sim: Simulation = _flat()
for _index: int in 3:
var other: SimEntity = sim.entities.find(sim.add_player())
other.position = START
other.on_ground = true
var grid: NavGrid = NavGrid.build(sim)
grid.sync(sim)
var bots: Array[NavBot] = []
for id: int in [1, 2, 3, 4]:
var bot: NavBot = NavBot.new(id)
bot.set_goal(GOAL)
bots.append(bot)
bot.think(sim, grid)
var planned: int = 0
for bot: NavBot in bots:
planned += bot.plans
assert_eq(planned, Tuning.BOT_NAV_PATHS_PER_TICK, "one tick plans at most the budget")
func test_23_bots_stay_within_the_tick_budget_and_get_somewhere() -> void:
var loop: ServerLoop = ServerLoop.new(20261111, 1, 23)
var ticks: int = 75 * Tuning.TICK_RATE_HZ
for _index: int in ticks:
loop.run_tick()
var stats: Dictionary = loop.timing_stats()
print(" 23 bots, %d ticks: p50 %d us, p99 %d us, max %d us, %d over budget" % [stats["ticks"], stats["p50_us"], stats["p99_us"], stats["max_us"], stats["over_budget"]])
assert_true(stats["p99_us"] < ServerLoop.TICK_BUDGET_USEC, "p99 tick under budget")
assert_true(stats["over_budget"] <= ticks / 200, "at most 0.5% of ticks over budget (a busy shared host)")
var walking: int = 0
for bot: NavBot in loop.bots:
if bot.plans > 0:
walking += 1
assert_true(walking >= 20, "%d of 23 bots planned paths after landing" % walking)
assert_eq(loop.bots.size(), 23)
+1
View File
@@ -0,0 +1 @@
uid://c45gq3yi0pda3
+1 -1
View File
@@ -77,7 +77,7 @@ func test_server_returns_to_the_lobby_and_starts_the_next_match() -> void:
assert_eq(loop.match_flow.phase, Match.DROP)
assert_eq(loop.bots.size(), 3)
var first_seed: int = loop.match_flow.current_seed()
for bot: WanderBot in loop.bots.slice(1):
for bot: NavBot in loop.bots.slice(1):
loop.sim.entities.find(bot.player_id).health = 0
loop.run_tick()
assert_eq(loop.match_flow.phase, Match.RESULTS)