diff --git a/.github/workflows/determinism-replay.yml b/.github/workflows/determinism-replay.yml index fabdab56a8..a448088d56 100644 --- a/.github/workflows/determinism-replay.yml +++ b/.github/workflows/determinism-replay.yml @@ -1,9 +1,10 @@ # Required status check on pull requests: `determinism-replay / compare`. # Branch protection is a repository setting. This workflow is the check it must require. # `planner_pure` (WS-D0), `perception_world` (WS-D1), `gameplay_rng` (WS-D2), -# `fixed64`, `combat_resolve`, `destruction`, and `gameplay_qa_aravath_slice` -# fail the compare job on any mismatch or if the case is missing. No path -# filter. cargo test has no retry loop (no-retry). Do not switch this job to nextest. +# `fixed64`, `combat_resolve`, `destruction`, `gameplay_qa_aravath_slice`, and +# `nav_reroute` fail the compare job on any mismatch or if the case is missing. +# No path filter. cargo test has no retry loop (no-retry). Do not switch this +# job to nextest. name: determinism-replay @@ -87,7 +88,7 @@ jobs: seen.add(row.case); merged.push(row); } - const required = ["planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction", "gameplay_qa_aravath_slice"]; + const required = ["planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction", "gameplay_qa_aravath_slice", "nav_reroute"]; const names = new Set(merged.map((row) => row.case)); for (const name of required) { if (!names.has(name)) { @@ -126,7 +127,7 @@ jobs: import sys from pathlib import Path - required = {"planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction", "gameplay_qa_aravath_slice"} + required = {"planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction", "gameplay_qa_aravath_slice", "nav_reroute"} root = Path("replay-artifacts") files = sorted(root.glob("*/replay-hash.json")) print(f"artifacts: {[str(p) for p in files]}") diff --git a/Cargo.lock b/Cargo.lock index 6993a55dd7..d701881234 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -840,6 +840,7 @@ dependencies = [ "astraweave-ecs", "astraweave-gameplay", "astraweave-math", + "astraweave-nav", "criterion 0.7.0", "glam", "rand 0.9.2", @@ -1117,6 +1118,7 @@ name = "astraweave-nav" version = "0.1.0" dependencies = [ "anyhow", + "astraweave-destruction", "criterion 0.5.1", "glam", ] diff --git a/astraweave-ai/Cargo.toml b/astraweave-ai/Cargo.toml index 550d7ec24c..687571ad07 100644 --- a/astraweave-ai/Cargo.toml +++ b/astraweave-ai/Cargo.toml @@ -38,7 +38,7 @@ planner_advanced = [] rag = [] profiling = ["astraweave-profiling/profiling", "tracy-client", "tracy-client/enable"] # Pull in astraweave-profiling's alloc-counter for bench assertions. -alloc-counter = ["dep:astraweave-profiling", "astraweave-profiling/alloc-counter"] +alloc-counter = ["dep:astraweave-profiling", "astraweave-profiling/alloc-counter", "astraweave-ecs/alloc-counter"] # Bench-only allocator swap for the mimalloc experiment. fast-alloc = ["dep:astraweave-alloc", "astraweave-alloc/fast-alloc"] veilweaver_slice = ["dep:astraweave-behavior", "dep:astraweave-observability"] @@ -68,6 +68,10 @@ name = "alloc_measure" harness = false required-features = ["alloc-counter", "planner_advanced"] +[[bench]] +name = "htn_budget" +harness = false + [[bench]] name = "arbiter_bench" harness = false diff --git a/astraweave-ai/benches/htn_budget.rs b/astraweave-ai/benches/htn_budget.rs new file mode 100644 index 0000000000..75ecfa7839 --- /dev/null +++ b/astraweave-ai/benches/htn_budget.rs @@ -0,0 +1,38 @@ +//! Budget check for [`HTN_EXPANSIONS_PER_TICK`] against the 11 ms frame. + +use astraweave_ai::htn::{plan_route, AgentPlan, SpatialHooks, HTN_EXPANSIONS_PER_TICK}; +use astraweave_nav::{bridge_and_ford, NavScratch}; +use criterion::{criterion_group, criterion_main, Criterion}; +use std::hint::black_box; + +fn bench_htn_expansions(c: &mut Criterion) { + let tiles = bridge_and_ford(); + let hooks = SpatialHooks::none(); + c.bench_function("htn_expansions_per_tick", |b| { + b.iter(|| { + let mut scratch = NavScratch::new(); + let mut budget = HTN_EXPANSIONS_PER_TICK as u32; + let mut plan = AgentPlan::empty(); + while budget > 0 { + let before = budget; + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + 1, + &mut plan, + &mut budget, + ); + if budget == before { + break; + } + } + black_box(plan.len) + }); + }); +} + +criterion_group!(htn_budget, bench_htn_expansions); +criterion_main!(htn_budget); diff --git a/astraweave-ai/src/core_loop.rs b/astraweave-ai/src/core_loop.rs index 1b80a37e1d..42303f359d 100644 --- a/astraweave-ai/src/core_loop.rs +++ b/astraweave-ai/src/core_loop.rs @@ -32,6 +32,8 @@ pub enum PlannerMode { BehaviorTree, /// Use GOAP planner (requires `ai-goap` feature). GOAP, + /// Hierarchical planner with utility-scored methods. + Htn, } impl std::fmt::Display for PlannerMode { @@ -40,6 +42,7 @@ impl std::fmt::Display for PlannerMode { PlannerMode::Rule => write!(f, "Rule"), PlannerMode::BehaviorTree => write!(f, "BehaviorTree"), PlannerMode::GOAP => write!(f, "GOAP"), + PlannerMode::Htn => write!(f, "Htn"), } } } @@ -60,14 +63,14 @@ impl PlannerMode { /// Check if this mode is always available (no feature flag required). #[must_use] pub fn is_always_available(&self) -> bool { - matches!(self, PlannerMode::Rule) + matches!(self, PlannerMode::Rule | PlannerMode::Htn) } /// Get the feature flag name required for this mode, if any. #[must_use] pub fn required_feature(&self) -> Option<&'static str> { match self { - PlannerMode::Rule => None, + PlannerMode::Rule | PlannerMode::Htn => None, PlannerMode::BehaviorTree => Some("ai-bt"), PlannerMode::GOAP => Some("ai-goap"), } @@ -80,6 +83,7 @@ impl PlannerMode { PlannerMode::Rule, PlannerMode::BehaviorTree, PlannerMode::GOAP, + PlannerMode::Htn, ] } } @@ -268,6 +272,7 @@ pub fn dispatch_planner( anyhow::bail!("GOAP mode requires 'ai-goap' feature") } } + PlannerMode::Htn => Ok(crate::htn::HtnOrchestrator.propose_plan(snapshot)), } } @@ -735,6 +740,7 @@ mod tests { #[test] fn test_planner_mode_is_always_available() { assert!(PlannerMode::Rule.is_always_available()); + assert!(PlannerMode::Htn.is_always_available()); assert!(!PlannerMode::BehaviorTree.is_always_available()); assert!(!PlannerMode::GOAP.is_always_available()); } @@ -749,10 +755,11 @@ mod tests { #[test] fn test_planner_mode_all() { let all = PlannerMode::all(); - assert_eq!(all.len(), 3); + assert_eq!(all.len(), 4); assert!(all.contains(&PlannerMode::Rule)); assert!(all.contains(&PlannerMode::BehaviorTree)); assert!(all.contains(&PlannerMode::GOAP)); + assert!(all.contains(&PlannerMode::Htn)); } #[test] @@ -769,7 +776,8 @@ mod tests { set.insert(PlannerMode::Rule); set.insert(PlannerMode::BehaviorTree); set.insert(PlannerMode::GOAP); - assert_eq!(set.len(), 3); + set.insert(PlannerMode::Htn); + assert_eq!(set.len(), 4); } // ===== Tests for new CAiController enhancements ===== diff --git a/astraweave-ai/src/ecs_ai_plugin.rs b/astraweave-ai/src/ecs_ai_plugin.rs index 5ff20de921..cbca1501bf 100644 --- a/astraweave-ai/src/ecs_ai_plugin.rs +++ b/astraweave-ai/src/ecs_ai_plugin.rs @@ -262,11 +262,23 @@ fn sys_ai_planning(world: &mut ecs::World) { } } +/// Spatial HTN tick. No work unless [`crate::htn::SpatialTick`] was inserted. +fn sys_spatial_tick(world: &mut ecs::World) { + let Some(tick) = world.get_resource_mut::() else { + return; + }; + let mut scratch = astraweave_nav::NavScratch::new(); + let sim_tick = tick.clock; + tick.clock = tick.clock.saturating_add(1); + crate::htn::tick_agents(tick, &mut scratch, sim_tick); +} + impl ecs::Plugin for AiPlanningPlugin { fn build(&self, app: &mut ecs::App) { app.world .insert_resource(Events::::default()); app.add_system_known_stage("ai_planning", sys_ai_planning as ecs::SystemFn); + app.add_system_known_stage("ai_planning", sys_spatial_tick as ecs::SystemFn); } } diff --git a/astraweave-ai/src/htn.rs b/astraweave-ai/src/htn.rs new file mode 100644 index 0000000000..62deb38700 --- /dev/null +++ b/astraweave-ai/src/htn.rs @@ -0,0 +1,689 @@ +//! Hierarchical task planner with utility-scored method choice. +//! +//! The tick writes into [`AgentPlan`] and [`astraweave_nav::NavScratch`]. +//! It does not allocate and it does not take a lock. Expansions stop at +//! [`HTN_EXPANSIONS_PER_TICK`]. + +use astraweave_core::{ + ActionStep, IVec2, LocalHazardHook, ObservationBuf, PlanIntent, WeaveEffectHook, WorldSnapshot, +}; +use astraweave_nav::{BreachSite, NavScratch, NavTiles}; + +/// Expansions spent on the spatial planner in one tick. +pub const HTN_EXPANSIONS_PER_TICK: usize = 64; +/// Full HTN inside this distance to the player. +pub const BAND0_MILLI: i32 = 32_000; +/// Utility method choice, no backtrack. +pub const BAND1_MILLI: i32 = 96_000; +/// Keep the last plan. +pub const BAND2_MILLI: i32 = 192_000; +/// Replan a near agent at least this often. +pub const REPLAN_TICKS: u16 = 30; +const PLAN_SLOTS: usize = 8; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ActionSlot { + Empty, + MoveTo { x: i32, y: i32 }, + UseBreach { portal_id: u32 }, + TakeCover { cover_id: u32 }, + Wait { duration_milli: u32 }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AgentPlan { + pub tick: u64, + pub slots: [ActionSlot; PLAN_SLOTS], + pub len: u8, + pub band: u8, +} + +impl AgentPlan { + #[must_use] + pub const fn empty() -> Self { + Self { + tick: 0, + slots: [ActionSlot::Empty; PLAN_SLOTS], + len: 0, + band: 3, + } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct AgentState { + pub entity_id: u64, + pub pos_milli: [i32; 3], + pub goal_milli: [i32; 3], + pub player_milli: [i32; 3], + pub ticks_since_plan: u16, + pub plan: AgentPlan, +} + +/// What the planner can see besides the nav publish. +#[derive(Clone, Copy, Debug)] +pub struct SpatialHooks<'a> { + pub weaving: &'a [WeaveEffectHook], + pub hazards: &'a [LocalHazardHook], +} + +impl SpatialHooks<'static> { + #[must_use] + pub const fn none() -> Self { + Self { + weaving: &[], + hazards: &[], + } + } +} + +/// Agents the spatial tick advances. Fixed capacity, no heap. +pub struct SpatialTick { + pub nav: NavTiles, + pub agents: [AgentState; 32], + pub len: u16, + pub expansions_used: u32, + pub clock: u64, + pub weaving: [WeaveEffectHook; 8], + pub weaving_len: u8, + pub hazards: [LocalHazardHook; 8], + pub hazard_len: u8, +} + +impl SpatialTick { + #[must_use] + pub fn new() -> Self { + Self { + nav: NavTiles::new(0.4, 45.0), + agents: [AgentState { + entity_id: 0, + pos_milli: [0; 3], + goal_milli: [0; 3], + player_milli: [0; 3], + ticks_since_plan: 0, + plan: AgentPlan::empty(), + }; 32], + len: 0, + expansions_used: 0, + clock: 0, + weaving: [WeaveEffectHook { + effect_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8], + weaving_len: 0, + hazards: [LocalHazardHook { + hazard_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8], + hazard_len: 0, + } + } + + /// One agent on the bridge span, used by the ECS demo. + #[must_use] + pub fn demo_agent() -> Self { + let mut tick = Self::new(); + tick.nav = astraweave_nav::bridge_and_ford(); + tick.agents[0] = AgentState { + entity_id: 1, + pos_milli: [1_000, 0, 1_000], + goal_milli: [1_000, 0, 46_000], + player_milli: [0, 0, 0], + ticks_since_plan: REPLAN_TICKS, + plan: AgentPlan::empty(), + }; + tick.len = 1; + tick + } +} + +impl Default for SpatialTick { + fn default() -> Self { + Self::new() + } +} + +pub struct HtnOrchestrator; + +impl HtnOrchestrator { + #[must_use] + pub const fn new() -> Self { + Self + } +} + +impl Default for HtnOrchestrator { + fn default() -> Self { + Self::new() + } +} + +impl crate::Orchestrator for HtnOrchestrator { + fn propose_plan(&self, snap: &WorldSnapshot) -> PlanIntent { + plan_from_snapshot(snap) + } +} + +/// Legacy smoke-versus-advance choice. One implementation, used by +/// [`crate::UtilityOrchestrator`] and by [`plan_from_snapshot`] when the +/// snapshot has no breach. +#[must_use] +pub fn legacy_utility_plan(snap: &WorldSnapshot) -> PlanIntent { + let plan_id = format!("util-{}", (snap.t * 1000.0) as i64); + legacy_steps(snap, plan_id) +} + +/// Copy nav breaches and lost cover into a perception buffer. No allocation. +pub fn fill_observation(tiles: &NavTiles, buf: &mut ObservationBuf) { + buf.breach_len = 0; + for breach in tiles.breaches.iter().take(tiles.breach_count as usize) { + if buf.breach_len == 16 { + break; + } + let i = buf.breach_len as usize; + buf.breaches[i] = astraweave_core::ObservedBreach { + portal_id: breach.portal_id, + x: breach.x_milli / 1000, + y: breach.z_milli / 1000, + }; + buf.breach_len += 1; + } + buf.lost_cover_len = 0; + for cover in tiles + .lost_cover + .iter() + .take(tiles.lost_cover_count as usize) + { + if buf.lost_cover_len == 16 { + break; + } + let i = buf.lost_cover_len as usize; + buf.lost_cover[i] = astraweave_core::ObservedCover { + id: cover.id, + x: cover.x_milli / 1000, + y: cover.z_milli / 1000, + }; + buf.lost_cover_len += 1; + } +} + +/// Advance every agent. Sort key is `(band, entity_id)`. +#[allow(clippy::needless_range_loop)] +pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u64) { + let wlen = tick.weaving_len as usize; + let hlen = tick.hazard_len as usize; + let mut weave_buf = [WeaveEffectHook { + effect_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8]; + let mut hazard_buf = [LocalHazardHook { + hazard_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8]; + weave_buf[..wlen].copy_from_slice(&tick.weaving[..wlen]); + hazard_buf[..hlen].copy_from_slice(&tick.hazards[..hlen]); + let SpatialTick { + nav, + agents, + len, + expansions_used, + weaving: _, + weaving_len: _, + hazards: _, + hazard_len: _, + clock: _, + } = tick; + let n = *len as usize; + let mut order = [0u16; 32]; + for i in 0..n { + order[i] = i as u16; + } + for i in 1..n { + let mut j = i; + while j > 0 { + let a = agents[order[j - 1] as usize]; + let b = agents[order[j] as usize]; + let band_a = band_of(a.pos_milli, a.player_milli); + let band_b = band_of(b.pos_milli, b.player_milli); + let out = band_a > band_b || (band_a == band_b && a.entity_id > b.entity_id); + if !out { + break; + } + order.swap(j - 1, j); + j -= 1; + } + } + let hook_view = SpatialHooks { + weaving: &weave_buf[..wlen], + hazards: &hazard_buf[..hlen], + }; + let mut budget = HTN_EXPANSIONS_PER_TICK as u32; + for i in 0..n { + if budget == 0 { + break; + } + let idx = order[i] as usize; + let agent = &mut agents[idx]; + let band = band_of(agent.pos_milli, agent.player_milli); + agent.ticks_since_plan = agent.ticks_since_plan.saturating_add(1); + match band { + 0 if agent.ticks_since_plan >= REPLAN_TICKS || agent.plan.len == 0 => { + plan_route( + nav, + scratch, + agent.pos_milli, + agent.goal_milli, + &hook_view, + sim_tick, + &mut agent.plan, + &mut budget, + ); + agent.plan.band = 0; + agent.ticks_since_plan = 0; + } + 1 => { + plan_route( + nav, + scratch, + agent.pos_milli, + agent.goal_milli, + &hook_view, + sim_tick, + &mut agent.plan, + &mut budget, + ); + agent.plan.band = 1; + agent.ticks_since_plan = 0; + } + 2 if agent.plan.len == 0 => { + agent.plan.slots[0] = ActionSlot::MoveTo { + x: agent.goal_milli[0] / 1000, + y: agent.goal_milli[2] / 1000, + }; + agent.plan.len = 1; + agent.plan.band = 2; + agent.plan.tick = sim_tick; + budget = budget.saturating_sub(1); + } + _ => { + agent.plan.band = band; + } + } + } + *expansions_used = HTN_EXPANSIONS_PER_TICK as u32 - budget; +} + +/// Decompose "cross to the goal" into a breach, cover, or a direct step. +#[allow(clippy::too_many_arguments)] +pub fn plan_route( + tiles: &NavTiles, + scratch: &mut NavScratch, + pos_milli: [i32; 3], + goal_milli: [i32; 3], + hooks: &SpatialHooks<'_>, + sim_tick: u64, + out: &mut AgentPlan, + budget: &mut u32, +) { + if *budget == 0 { + return; + } + *budget = budget.saturating_sub(1); + out.tick = sim_tick; + out.len = 0; + out.slots = [ActionSlot::Empty; PLAN_SLOTS]; + let start = Vec3::new( + pos_milli[0] as f32 / 1000.0, + pos_milli[1] as f32 / 1000.0, + pos_milli[2] as f32 / 1000.0, + ); + let goal = Vec3::new( + goal_milli[0] as f32 / 1000.0, + goal_milli[1] as f32 / 1000.0, + goal_milli[2] as f32 / 1000.0, + ); + let waypoints = tiles.query_path(scratch, start, goal); + if waypoints < 2 { + out.slots[0] = ActionSlot::Wait { + duration_milli: 500, + }; + out.len = 1; + return; + } + *budget = budget.saturating_sub(1); + if let Some(portal) = best_breach(tiles, scratch, hooks) { + out.slots[0] = ActionSlot::UseBreach { portal_id: portal }; + out.len = 1; + } + let mut far = scratch.waypoints[0]; + for point in scratch.waypoints.iter().take(scratch.waypoint_len as usize) { + if point.x.abs() > far.x.abs() { + far = *point; + } + } + let slot = out.len as usize; + if slot < PLAN_SLOTS { + out.slots[slot] = ActionSlot::MoveTo { + x: (far.x * 1000.0) as i32 / 1000, + y: (far.z * 1000.0) as i32 / 1000, + }; + out.len += 1; + } + if tiles.lost_cover_count > 0 { + if let Some(cover) = best_cover(tiles, pos_milli) { + let slot = out.len as usize; + if slot < PLAN_SLOTS { + *budget = budget.saturating_sub(1); + out.slots[slot] = ActionSlot::TakeCover { cover_id: cover }; + out.len += 1; + } + } + } +} + +fn best_breach(tiles: &NavTiles, scratch: &NavScratch, hooks: &SpatialHooks<'_>) -> Option { + let mut best: Option<(u32, i32)> = None; + for i in 0..scratch.portal_len as usize { + let id = scratch.portal_ids[i]; + let Some(site) = find_breach(tiles, id) else { + continue; + }; + let cell_x = site.x_milli / 1000; + let cell_y = site.z_milli / 1000; + if sealed(hooks, cell_x, cell_y) { + continue; + } + let score = -site.x_milli; + let take = match best { + None => true, + Some((best_id, best_score)) => { + score > best_score || (score == best_score && id < best_id) + } + }; + if take { + best = Some((id, score)); + } + } + best.map(|(id, _)| id) +} + +fn find_breach(tiles: &NavTiles, id: u32) -> Option { + tiles + .breaches + .iter() + .take(tiles.breach_count as usize) + .find(|site| site.portal_id == id) + .copied() +} + +fn sealed(hooks: &SpatialHooks<'_>, x: i32, y: i32) -> bool { + let hazard = hooks + .hazards + .iter() + .any(|hazard| hazard.x == x && hazard.y == y && hazard.kind != 0); + let weave = hooks + .weaving + .iter() + .any(|effect| effect.x == x && effect.y == y && effect.kind != 0); + hazard || weave +} + +fn best_cover(tiles: &NavTiles, pos_milli: [i32; 3]) -> Option { + let mut best: Option<(u32, i32)> = None; + for cover in tiles.cover.iter().take(tiles.cover_count as usize) { + let dist = (cover.x_milli - pos_milli[0]).abs() + (cover.z_milli - pos_milli[2]).abs(); + let take = match best { + None => true, + Some((id, best_dist)) => dist < best_dist || (dist == best_dist && cover.id < id), + }; + if take { + best = Some((cover.id, dist)); + } + } + best.map(|(id, _)| id) +} + +fn band_of(pos: [i32; 3], player: [i32; 3]) -> u8 { + let dist = (pos[0] - player[0]).abs() + (pos[2] - player[2]).abs(); + if dist <= BAND0_MILLI { + 0 + } else if dist <= BAND1_MILLI { + 1 + } else if dist <= BAND2_MILLI { + 2 + } else { + 3 + } +} + +fn plan_from_snapshot(snap: &WorldSnapshot) -> PlanIntent { + let plan_id = format!("htn-{}", (snap.t * 1000.0) as i64); + if let Some(breach) = snap.pois.iter().find(|poi| poi.k == "breach") { + return PlanIntent { + plan_id, + steps: vec![ActionStep::MoveTo { + x: breach.pos.x, + y: breach.pos.y, + speed: None, + }], + }; + } + legacy_steps(snap, plan_id) +} + +fn legacy_steps(snap: &WorldSnapshot, plan_id: String) -> PlanIntent { + let Some(enemy) = snap.enemies.first() else { + return PlanIntent { + plan_id, + steps: vec![], + }; + }; + let me = &snap.me; + let cd = me.cooldowns.get("throw:smoke").copied().unwrap_or(0.0); + let dx = (enemy.pos.x - me.pos.x).abs(); + let dy = (enemy.pos.y - me.pos.y).abs(); + let dist = dx + dy; + // Integer form of the old scores: smoke 1000 + hp*10, advance 800 + close bonus. + // Higher wins. Equal scores take the lower method id (smoke is 0). + let smoke_score = if cd <= 0.0 { + 1000 + enemy.hp.saturating_mul(10) + } else { + i32::MIN + }; + let close_bonus = (3 - dist).max(0) * 50; + let advance_score = 800 + close_bonus; + if smoke_score >= advance_score { + let mid = IVec2 { + x: (me.pos.x + enemy.pos.x) / 2, + y: (me.pos.y + enemy.pos.y) / 2, + }; + PlanIntent { + plan_id, + steps: vec![ + ActionStep::Throw { + item: "smoke".into(), + x: mid.x, + y: mid.y, + }, + ActionStep::MoveTo { + speed: None, + x: me.pos.x + (enemy.pos.x - me.pos.x).signum() * 2, + y: me.pos.y + (enemy.pos.y - me.pos.y).signum() * 2, + }, + ], + } + } else { + let mut steps = vec![ActionStep::MoveTo { + speed: None, + x: me.pos.x + (enemy.pos.x - me.pos.x).signum(), + y: me.pos.y + (enemy.pos.y - me.pos.y).signum(), + }]; + if dist <= 3 { + steps.push(ActionStep::CoverFire { + target_id: enemy.id, + duration: 1.0, + }); + } + PlanIntent { plan_id, steps } + } +} + +use glam::Vec3; + +#[cfg(test)] +mod tests { + use super::*; + use astraweave_core::{LocalHazardHook, WeaveEffectHook}; + use astraweave_nav::{bridge_and_ford, NavChangeKind, NavScratch, FRAME_BUDGET_MS}; + + #[test] + fn equal_scores_pick_the_lower_breach_id() { + let tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let _ = tiles.query_path( + &mut scratch, + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 0.0, 46.0), + ); + let hooks = SpatialHooks::none(); + let mut first = None; + let mut second = None; + for _ in 0..2 { + let id = best_breach(&tiles, &scratch, &hooks); + if first.is_none() { + first = id; + } else { + second = id; + } + } + assert_eq!(first, second); + } + + #[test] + fn a_hazard_or_weave_on_the_cell_drops_the_breach() { + let tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + assert!( + tiles.query_path( + &mut scratch, + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 0.0, 46.0), + ) >= 2 + ); + let portal = best_breach(&tiles, &scratch, &SpatialHooks::none()) + .expect("the first publish marks the bridge portal as a breach"); + let site = find_breach(&tiles, portal).expect("portal is a breach on first publish"); + let hazard = [LocalHazardHook { + hazard_id: 1, + x: site.x_milli / 1000, + y: site.z_milli / 1000, + kind: 1, + }]; + let hooks = SpatialHooks { + weaving: &[], + hazards: &hazard, + }; + assert_ne!(best_breach(&tiles, &scratch, &hooks), Some(portal)); + let weave = [WeaveEffectHook { + effect_id: 2, + x: site.x_milli / 1000, + y: site.z_milli / 1000, + kind: 1, + }]; + let hooks = SpatialHooks { + weaving: &weave, + hazards: &[], + }; + assert_ne!(best_breach(&tiles, &scratch, &hooks), Some(portal)); + } + + #[test] + fn sixty_four_expansions_fit_in_the_frame_budget() { + let tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let start = std::time::Instant::now(); + let mut budget = HTN_EXPANSIONS_PER_TICK as u32; + let mut plan = AgentPlan::empty(); + while budget > 0 { + let before = budget; + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + 1, + &mut plan, + &mut budget, + ); + if budget == before { + break; + } + } + let elapsed_ms = start.elapsed().as_secs_f32() * 1000.0; + assert!(plan.len > 0); + assert!( + elapsed_ms < FRAME_BUDGET_MS, + "{HTN_EXPANSIONS_PER_TICK} expansions took {elapsed_ms} ms" + ); + } + + #[test] + fn reroute_after_the_bridge_drops() { + let mut tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let mut budget = HTN_EXPANSIONS_PER_TICK as u32; + let mut plan = AgentPlan::empty(); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + 1, + &mut plan, + &mut budget, + ); + let before = move_cell(&plan); + tiles.mark(astraweave_nav::nav_change_from_kind( + NavChangeKind::Detach, + 30, + 0, + [-1_000, -1_000, 17_000], + [5_000, 1_000, 31_999], + )); + assert!(tiles.commit_tick() >= 1); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + 31, + &mut plan, + &mut budget, + ); + let after = move_cell(&plan); + assert!(before < 8, "bridge path cell {before}"); + assert!(after > 8, "ford cell {after}, bridge cell was {before}"); + } + + fn move_cell(plan: &AgentPlan) -> i32 { + for slot in &plan.slots { + if let ActionSlot::MoveTo { x, .. } = slot { + return *x; + } + } + -1 + } +} diff --git a/astraweave-ai/src/lib.rs b/astraweave-ai/src/lib.rs index 7a36cc84a2..29406f8782 100644 --- a/astraweave-ai/src/lib.rs +++ b/astraweave-ai/src/lib.rs @@ -28,6 +28,7 @@ pub mod core_loop; pub mod ecs_ai_plugin; +pub mod htn; pub mod orchestrator; pub mod tool_sandbox; @@ -51,8 +52,10 @@ pub mod veilweaver; #[cfg(feature = "planner_advanced")] pub mod goap; +pub use astraweave_nav::bridge_and_ford; pub use core_loop::*; pub use ecs_ai_plugin::{build_app_with_ai, AiPlanningPlugin}; +pub use htn::{SpatialTick, HTN_EXPANSIONS_PER_TICK}; pub use orchestrator::*; pub use tool_sandbox::*; diff --git a/astraweave-ai/src/mutation_tests.rs b/astraweave-ai/src/mutation_tests.rs index e4af2f2ffe..7f9fa77f5d 100644 --- a/astraweave-ai/src/mutation_tests.rs +++ b/astraweave-ai/src/mutation_tests.rs @@ -59,12 +59,15 @@ mod planner_mode_tests { } #[test] - fn all_returns_three_modes() { + fn all_returns_four_modes() { + // Re-locked from 3 when `PlannerMode::Htn` became an always-available + // mode. The count stays exact. let all = PlannerMode::all(); - assert_eq!(all.len(), 3, "all() should return 3 modes"); + assert_eq!(all.len(), 4, "all() should return 4 modes"); assert!(all.contains(&PlannerMode::Rule)); assert!(all.contains(&PlannerMode::BehaviorTree)); assert!(all.contains(&PlannerMode::GOAP)); + assert!(all.contains(&PlannerMode::Htn)); } } @@ -460,10 +463,12 @@ mod behavioral_correctness_tests { .filter(|m| **m == PlannerMode::BehaviorTree) .count(); let goap_count = all.iter().filter(|m| **m == PlannerMode::GOAP).count(); + let htn_count = all.iter().filter(|m| **m == PlannerMode::Htn).count(); assert_eq!(rule_count, 1, "Rule should appear exactly once"); assert_eq!(bt_count, 1, "BehaviorTree should appear exactly once"); assert_eq!(goap_count, 1, "GOAP should appear exactly once"); + assert_eq!(htn_count, 1, "Htn should appear exactly once"); } } diff --git a/astraweave-ai/src/orchestrator.rs b/astraweave-ai/src/orchestrator.rs index efe15d9942..0927c949d6 100644 --- a/astraweave-ai/src/orchestrator.rs +++ b/astraweave-ai/src/orchestrator.rs @@ -193,61 +193,8 @@ impl Default for UtilityOrchestrator { impl Orchestrator for UtilityOrchestrator { fn propose_plan(&self, snap: &WorldSnapshot) -> PlanIntent { - let plan_id = format!("util-{}", (snap.t * 1000.0) as i64); - let me = &snap.me; - // Candidate A: Throw smoke at midpoint to first enemy - let mut cands: Vec<(f32, Vec)> = vec![]; - if let Some(enemy) = snap.enemies.first() { - let cd = me - .cooldowns - .get(COOLDOWN_THROW_SMOKE) - .copied() - .unwrap_or(0.0); - if cd <= 0.0 { - let mid = IVec2 { - x: (me.pos.x + enemy.pos.x) / 2, - y: (me.pos.y + enemy.pos.y) / 2, - }; - let steps = vec![ - ActionStep::Throw { - item: "smoke".into(), - x: mid.x, - y: mid.y, - }, - ActionStep::MoveTo { - speed: None, - x: me.pos.x + (enemy.pos.x - me.pos.x).signum() * 2, - y: me.pos.y + (enemy.pos.y - me.pos.y).signum() * 2, - }, - ]; - // Score: encourage if ammo present and enemy hp > 0 - let score = 1.0 - + (snap.player.hp as f32).min(100.0) * 0.0 - + (enemy.hp.max(0) as f32) * 0.01; - cands.push((score, steps)); - } - // Candidate B: advance; if close, cover fire - let dx = (enemy.pos.x - me.pos.x).abs(); - let dy = (enemy.pos.y - me.pos.y).abs(); - let dist = (dx + dy) as f32; - let mut steps = vec![ActionStep::MoveTo { - speed: None, - x: me.pos.x + (enemy.pos.x - me.pos.x).signum(), - y: me.pos.y + (enemy.pos.y - me.pos.y).signum(), - }]; - if dist <= 3.0 { - steps.push(ActionStep::CoverFire { - target_id: enemy.id, - duration: 1.0, - }); - } - let score = 0.8 + (3.0 - dist).max(0.0) * 0.05; - cands.push((score, steps)); - } - // Use total_cmp to provide a total ordering for f32 (handles NaN deterministically) - cands.sort_by(|a, b| b.0.total_cmp(&a.0)); - let steps = cands.first().map(|c| c.1.clone()).unwrap_or_default(); - PlanIntent { plan_id, steps } + // The scores live in the HTN module. This type is the legacy name. + crate::htn::legacy_utility_plan(snap) } } diff --git a/astraweave-ai/src/veilweaver.rs b/astraweave-ai/src/veilweaver.rs index 84bab73822..77f80e7729 100644 --- a/astraweave-ai/src/veilweaver.rs +++ b/astraweave-ai/src/veilweaver.rs @@ -1,8 +1,6 @@ #![allow(clippy::too_many_arguments)] -use std::time::Instant; - -use astraweave_behavior::goap::{GoapAction, GoapGoal, GoapPlanner, WorldState}; +use astraweave_behavior::goap::{GoapAction, GoapGoal, WorldState}; use astraweave_core::{ActionStep, MovementSpeed, PlanIntent, WorldSnapshot}; use astraweave_observability::{log_companion_action, CompanionActionEvent}; use tracing::info; @@ -17,7 +15,6 @@ const ACTION_REPOSITION: &str = "reposition"; /// Hybrid GOAP planner tailored to Veilweaver companion behaviors. pub struct VeilweaverCompanionOrchestrator { - planner: GoapPlanner, actions: Vec, goals: Vec, } @@ -25,91 +22,60 @@ pub struct VeilweaverCompanionOrchestrator { impl VeilweaverCompanionOrchestrator { pub fn new() -> Self { Self { - planner: GoapPlanner::new().with_max_iterations(64), actions: build_actions(), goals: build_goals(), } } - fn derive_world_state<'a>(&self, snap: &'a WorldSnapshot) -> (WorldState, HeuristicState<'a>) { - let heuristics = HeuristicState::from_snapshot(snap); - let mut state = WorldState::new(); - state.set("player_low", heuristics.player_low); - state.set("anchor_unstable", heuristics.anchor_unstable); - state.set("has_echo", heuristics.has_echo); - state.set("enemy_vulnerable", heuristics.enemy_vulnerable); - state.set("enemy_tagged", heuristics.enemy_tagged); - state.set("position_good", heuristics.position_good); - (state, heuristics) - } - fn plan_internal(&self, snap: &WorldSnapshot) -> PlanIntent { - let start = Instant::now(); - let (world_state, heuristics) = self.derive_world_state(snap); - - let mut selected_goal = None; - let mut planned_actions = Vec::new(); - - let mut goals = self.goals.clone(); - goals.sort_by(|a, b| { - b.priority - .partial_cmp(&a.priority) - .unwrap_or(std::cmp::Ordering::Equal) - }); - - for goal in goals { - if goal.is_satisfied(&world_state) { - continue; - } - if let Some(actions) = self.planner.plan(&world_state, &goal, &self.actions) { - selected_goal = Some(goal.name.clone()); - planned_actions = actions; - break; - } - } - - let elapsed_ms = start.elapsed().as_secs_f32() * 1000.0; + debug_assert_eq!(self.actions.len(), 5); + debug_assert_eq!(self.goals.len(), 4); + let heuristics = HeuristicState::from_snapshot(snap); + let action = select_slice_action(&heuristics); let plan_id = format!("vw-companion-{}", (snap.t * 1000.0) as i64); - - if planned_actions.is_empty() { - info!( - target: "veilweaver.companion", - event = "CompanionPlan", - %plan_id, - goal = "idle", - actions = 0, - elapsed_ms - ); + let steps = map_action_to_steps(action, &heuristics); + info!( + target: "veilweaver.companion", + event = "CompanionAction", + %plan_id, + action, + step_count = steps.len() + ); + log_companion_action(&CompanionActionEvent { + action_id: action.to_string(), + success: true, + latency_ms: 0.0, + }); + if steps.is_empty() { return PlanIntent { plan_id, steps: vec![ActionStep::Wait { duration: 0.5 }], }; } - - let mut steps = Vec::new(); - for action in planned_actions.iter() { - let action_steps = map_action_to_steps(action.name.as_str(), &heuristics); - info!( - target: "veilweaver.companion", - event = "CompanionAction", - %plan_id, - goal = selected_goal.as_deref().unwrap_or("unknown"), - action = %action.name, - step_count = action_steps.len(), - elapsed_ms - ); - log_companion_action(&CompanionActionEvent { - action_id: action.name.clone(), - success: true, - latency_ms: elapsed_ms, - }); - steps.extend(action_steps); - } - PlanIntent { plan_id, steps } } } +/// Method order is priority, then lower method id. No A* search and no wall clock. +fn select_slice_action(h: &HeuristicState<'_>) -> &'static str { + if h.player_low { + return ACTION_HEAL_PLAYER; + } + if h.anchor_unstable && h.has_echo { + return ACTION_STABILITY_PULSE; + } + if h.enemy_vulnerable { + return ACTION_EXECUTE_COMBO; + } + if !h.position_good { + return ACTION_REPOSITION; + } + if h.closest_enemy.is_some() && !h.enemy_tagged { + return ACTION_MARK_TARGET; + } + "" +} + impl Default for VeilweaverCompanionOrchestrator { fn default() -> Self { Self::new() diff --git a/astraweave-ai/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-ai/tests/mutation_resistant_comprehensive_tests.rs index de0216154a..de4990c65c 100644 --- a/astraweave-ai/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-ai/tests/mutation_resistant_comprehensive_tests.rs @@ -747,14 +747,17 @@ mod planner_mode_mutations { } #[test] - fn planner_mode_all_returns_3() { + fn planner_mode_all_returns_4() { + // Re-locked from 3 when Htn joined the always-available modes. let all = PlannerMode::all(); - assert_eq!(all.len(), 3, "PlannerMode::all() must return 3 modes"); + assert_eq!(all.len(), 4, "PlannerMode::all() must return 4 modes"); + assert!(all.contains(&PlannerMode::Htn)); } #[test] fn planner_mode_always_available() { assert!(PlannerMode::Rule.is_always_available()); + assert!(PlannerMode::Htn.is_always_available()); assert!(!PlannerMode::BehaviorTree.is_always_available()); assert!(!PlannerMode::GOAP.is_always_available()); } diff --git a/astraweave-ai/tests/zero_alloc_tick.rs b/astraweave-ai/tests/zero_alloc_tick.rs new file mode 100644 index 0000000000..62faefcae5 --- /dev/null +++ b/astraweave-ai/tests/zero_alloc_tick.rs @@ -0,0 +1,57 @@ +//! Zero-allocation proof for the spatial tick and tile commit. +//! +//! Run with one thread. The counter is process-global. +//! +//! ```text +//! cargo test -p astraweave-ai --features alloc-counter --test zero_alloc_tick -- --test-threads=1 +//! ``` + +#![cfg(feature = "alloc-counter")] + +use astraweave_ai::htn::{tick_agents, SpatialTick}; +use astraweave_ecs::counting_alloc::{allocs, reset_allocs}; +use astraweave_nav::{ + nav_change_from_geometry_notice, GeometryNotice, NavScratch, NOTICE_COLLAPSE, +}; + +#[global_allocator] +static ALLOC: astraweave_ecs::counting_alloc::CountingAlloc = + astraweave_ecs::counting_alloc::CountingAlloc; + +#[test] +fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { + let mut tick = SpatialTick::demo_agent(); + let mut scratch = NavScratch::new(); + for step in 0..4u64 { + let _ = tick.nav.commit_tick(); + tick_agents(&mut tick, &mut scratch, step); + } + let collapse = GeometryNotice { + tick: 8, + x0: -1_000, + y0: -1_000, + z0: 17_000, + x1: 5_000, + y1: 1_000, + z1: 31_999, + reason: NOTICE_COLLAPSE, + }; + let warmup = nav_change_from_geometry_notice(&collapse, 0).expect("notice"); + tick.nav.mark(warmup); + let _ = tick.nav.commit_tick(); + tick_agents(&mut tick, &mut scratch, 8); + + reset_allocs(); + let again = nav_change_from_geometry_notice(&collapse, 1).expect("notice"); + tick.nav.mark(again); + let committed = tick.nav.commit_tick(); + let commit_allocs = allocs(); + + reset_allocs(); + tick_agents(&mut tick, &mut scratch, 9); + let tick_allocs = allocs(); + + assert!(committed >= 1, "warmup left a dirty tile to commit"); + assert_eq!(commit_allocs, 0, "tile commit allocated after warmup"); + assert_eq!(tick_allocs, 0, "HTN tick allocated after warmup"); +} diff --git a/astraweave-core/Cargo.toml b/astraweave-core/Cargo.toml index a274a0c592..2ac3cdcfbb 100644 --- a/astraweave-core/Cargo.toml +++ b/astraweave-core/Cargo.toml @@ -27,9 +27,10 @@ astraweave-behavior = { workspace = true } [dev-dependencies] criterion = { workspace = true } astraweave-ai = { workspace = true } +astraweave-destruction = { workspace = true } astraweave-gameplay = { path = "../astraweave-gameplay" } astraweave-math = { workspace = true } -astraweave-destruction = { workspace = true } +astraweave-nav = { workspace = true } sha2 = { workspace = true } [[bench]] diff --git a/astraweave-core/src/perception.rs b/astraweave-core/src/perception.rs index a09d14330c..0a43876982 100644 --- a/astraweave-core/src/perception.rs +++ b/astraweave-core/src/perception.rs @@ -5,6 +5,99 @@ pub struct PerceptionConfig { pub los_max: i32, } +/// A breach the nav publish reported. `x` and `y` are world cells, not the +/// retired constant cell. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ObservedBreach { + pub portal_id: u32, + pub x: i32, + pub y: i32, +} + +/// Cover that the last nav commit removed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ObservedCover { + pub id: u32, + pub x: i32, + pub y: i32, +} + +/// Hook for a weaving effect perception will score later. +/// +/// `kind` is reserved for the weaving owner. A non-zero kind on a cell seals +/// a breach that shares that cell. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct WeaveEffectHook { + pub effect_id: u32, + pub x: i32, + pub y: i32, + pub kind: u16, +} + +/// Hook for a local-sim hazard (fire, gas, heat) perception will score later. +/// +/// A hazard on a cell blocks a breach on that cell. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct LocalHazardHook { + pub hazard_id: u32, + pub x: i32, + pub y: i32, + pub kind: u16, +} + +/// Fixed buffers the AI tick fills from nav, weaving, and the local sim. +/// +/// Empty lengths mean those channels saw nothing. The legacy snapshot builder +/// copies breaches and lost cover into `WorldSnapshot::pois`. Weaving and +/// hazards stay here so `WorldSnapshot` field names do not change. +#[derive(Clone, Copy, Debug)] +pub struct ObservationBuf { + pub breaches: [ObservedBreach; 16], + pub breach_len: u8, + pub lost_cover: [ObservedCover; 16], + pub lost_cover_len: u8, + pub weaving: [WeaveEffectHook; 8], + pub weaving_len: u8, + pub hazards: [LocalHazardHook; 8], + pub hazard_len: u8, +} + +impl ObservationBuf { + #[must_use] + pub const fn none() -> Self { + Self { + breaches: [ObservedBreach { + portal_id: 0, + x: 0, + y: 0, + }; 16], + breach_len: 0, + lost_cover: [ObservedCover { id: 0, x: 0, y: 0 }; 16], + lost_cover_len: 0, + weaving: [WeaveEffectHook { + effect_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8], + weaving_len: 0, + hazards: [LocalHazardHook { + hazard_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8], + hazard_len: 0, + } + } +} + +impl Default for ObservationBuf { + fn default() -> Self { + Self::none() + } +} + /// A snapshot could not be built because a required component is absent. /// /// The AI tick records this as `AiPlanningFailedEvent` instead of aborting @@ -59,6 +152,7 @@ pub fn try_build_snapshot( objective, cfg, w.sorted_obstacles(), + &ObservationBuf::none(), ) } @@ -106,9 +200,33 @@ pub fn try_build_snapshot_shared_obstacles( objective, cfg, sort_obstacles(obstacles), + &ObservationBuf::none(), + ) +} + +/// Snapshot builder that copies real breaches and lost cover into `pois`. +pub fn try_build_snapshot_observed( + w: &World, + t_player: Entity, + t_companion: Entity, + enemies: &[Entity], + objective: Option, + cfg: &PerceptionConfig, + observation: &ObservationBuf, +) -> Result { + assemble_snapshot( + w, + t_player, + t_companion, + enemies, + objective, + cfg, + w.sorted_obstacles(), + observation, ) } +#[allow(clippy::too_many_arguments)] fn assemble_snapshot( w: &World, t_player: Entity, @@ -117,6 +235,7 @@ fn assemble_snapshot( objective: Option, cfg: &PerceptionConfig, obstacles: Vec, + observation: &ObservationBuf, ) -> Result { let ppos = w.pos_of(t_player).ok_or(SnapshotError { entity: t_player, @@ -184,15 +303,44 @@ fn assemble_snapshot( player, me, enemies: seen, - pois: vec![Poi { - k: "breach_door".into(), - pos: IVec2 { x: 15, y: 8 }, - }], + pois: pois_from_observation(observation), obstacles, objective, }) } +fn pois_from_observation(observation: &ObservationBuf) -> Vec { + let mut pois = + Vec::with_capacity(observation.breach_len as usize + observation.lost_cover_len as usize); + for breach in observation + .breaches + .iter() + .take(observation.breach_len as usize) + { + pois.push(Poi { + k: "breach".into(), + pos: IVec2 { + x: breach.x, + y: breach.y, + }, + }); + } + for cover in observation + .lost_cover + .iter() + .take(observation.lost_cover_len as usize) + { + pois.push(Poi { + k: "cover_lost".into(), + pos: IVec2 { + x: cover.x, + y: cover.y, + }, + }); + } + pois +} + fn sort_obstacles(mut obstacles: Vec) -> Vec { obstacles.sort_unstable_by(|a, b| a.x.cmp(&b.x).then(a.y.cmp(&b.y))); obstacles @@ -400,9 +548,57 @@ mod tests { let cfg = PerceptionConfig { los_max: 20 }; let snap = build_snapshot(&w, player, companion, &[], None, &cfg); - assert_eq!(snap.pois.len(), 1); - assert_eq!(snap.pois[0].k, "breach_door"); - assert_eq!(snap.pois[0].pos, iv2(15, 8)); + assert!( + snap.pois.is_empty(), + "no nav observation means no invented breach" + ); + } + + #[test] + fn test_observed_breach_and_lost_cover_become_pois() { + let mut w = World::new(); + let player = w.spawn("player", iv2(0, 0), Team { id: 1 }, 100, 0); + let companion = w.spawn("companion", iv2(1, 1), Team { id: 1 }, 100, 10); + let mut observation = ObservationBuf::none(); + observation.breaches[0] = ObservedBreach { + portal_id: 7, + x: 4, + y: 9, + }; + observation.breach_len = 1; + observation.lost_cover[0] = ObservedCover { id: 3, x: 2, y: 2 }; + observation.lost_cover_len = 1; + observation.weaving[0] = WeaveEffectHook { + effect_id: 1, + x: 4, + y: 9, + kind: 1, + }; + observation.weaving_len = 1; + observation.hazards[0] = LocalHazardHook { + hazard_id: 2, + x: 1, + y: 1, + kind: 1, + }; + observation.hazard_len = 1; + let snap = try_build_snapshot_observed( + &w, + player, + companion, + &[], + None, + &PerceptionConfig { los_max: 10 }, + &observation, + ) + .expect("snapshot"); + assert_eq!(snap.pois.len(), 2); + assert_eq!(snap.pois[0].k, "breach"); + assert_eq!(snap.pois[0].pos, iv2(4, 9)); + assert_eq!(snap.pois[1].k, "cover_lost"); + assert_ne!(snap.pois[0].pos, iv2(15, 8)); + assert_eq!(observation.weaving_len, 1); + assert_eq!(observation.hazard_len, 1); } #[test] @@ -528,7 +724,10 @@ mod tests { assert_eq!(snap.enemies[0].cover, CoverType::Low); // Within LOS assert_eq!(snap.enemies[1].cover, CoverType::Unknown); // Beyond LOS assert_eq!(snap.obstacles.len(), 2); - assert_eq!(snap.pois.len(), 1); + assert!( + snap.pois.is_empty(), + "no nav observation means no invented breach" + ); assert_eq!(snap.objective, Some("Defend position".to_string())); } diff --git a/astraweave-core/src/sim.rs b/astraweave-core/src/sim.rs index 4a9a0b10f2..e4a8c768cc 100644 --- a/astraweave-core/src/sim.rs +++ b/astraweave-core/src/sim.rs @@ -18,6 +18,10 @@ pub const SIM_SYSTEM_TERRAIN_SOLVER: u64 = 0x7E22_7001; pub const SIM_SYSTEM_COMBAT: u64 = 0xC0BA_7001; /// Destruction fracture seeds and island ids. Not used by combat or terrain. pub const SIM_SYSTEM_DESTRUCTION: u64 = 0xD357_7001; +/// Reserved for nav-tile commits. Tile builds do not draw it. +pub const SIM_SYSTEM_NAV: u64 = 0x4E41_7001; +/// Reserved for HTN tie-breaks. Planning does not draw it. +pub const SIM_SYSTEM_HTN: u64 = 0x4854_7001; /// Mix `(world_seed, tick, system_id)` into one `StdRng` seed. /// @@ -161,6 +165,27 @@ mod tests { } } + #[test] + fn nav_and_htn_ids_do_not_collide() { + let ids = [ + SIM_SYSTEM_CRAFT, + SIM_SYSTEM_HARVEST, + SIM_SYSTEM_ANCHOR_PARTICLES, + SIM_SYSTEM_ENEMY_PATROL, + SIM_SYSTEM_SPAWNER, + SIM_SYSTEM_TERRAIN_SOLVER, + SIM_SYSTEM_COMBAT, + SIM_SYSTEM_DESTRUCTION, + SIM_SYSTEM_NAV, + SIM_SYSTEM_HTN, + ]; + for i in 0..ids.len() { + for j in (i + 1)..ids.len() { + assert_ne!(ids[i], ids[j]); + } + } + } + #[test] fn sim_rng_streams_diverge_across_system_and_tick() { let craft = SimRng::new(1, 0, SIM_SYSTEM_CRAFT).next_u64(); diff --git a/astraweave-core/tests/perception_tests.rs b/astraweave-core/tests/perception_tests.rs index bac3ff8268..a528a9c080 100644 --- a/astraweave-core/tests/perception_tests.rs +++ b/astraweave-core/tests/perception_tests.rs @@ -48,8 +48,8 @@ fn test_build_snapshot_basic() { assert!(snap.obstacles.iter().any(|&p| p.x == 5 && p.y == 5)); assert!(snap.obstacles.iter().any(|&p| p.x == 6 && p.y == 5)); - // Verify POIs exist - assert!(!snap.pois.is_empty()); + // No nav observation is attached, so perception does not invent a breach. + assert!(snap.pois.is_empty()); } #[test] diff --git a/astraweave-core/tests/replay_hash.rs b/astraweave-core/tests/replay_hash.rs index 20aed990a7..8ac3dbbe77 100644 --- a/astraweave-core/tests/replay_hash.rs +++ b/astraweave-core/tests/replay_hash.rs @@ -9,8 +9,8 @@ mod replay_support; use astraweave_destruction::demolition_bytes; use astraweave_math::fixed64_contract_bytes; use replay_support::{ - gameplay_rng_bytes, perception_world_bytes, planner_pure_bytes, replay_hash_json_path, - sha256_hex, + gameplay_rng_bytes, nav_reroute_bytes, perception_world_bytes, planner_pure_bytes, + replay_hash_json_path, sha256_hex, }; #[test] @@ -38,12 +38,16 @@ fn replay_hash_cases_are_stable_and_written() { destruction_a, destruction_b, "destruction diverged inside one process" ); + let nav_a = nav_reroute_bytes(); + let nav_b = nav_reroute_bytes(); + assert_eq!(nav_a, nav_b, "nav_reroute diverged inside one process"); let cases = [ ("destruction".to_string(), sha256_hex(&destruction_a)), ("fixed64".to_string(), sha256_hex(&fixed_a)), ("gameplay_rng".to_string(), sha256_hex(&gameplay_a)), ("perception_world".to_string(), sha256_hex(&perception)), ("planner_pure".to_string(), sha256_hex(&planner_a)), + ("nav_reroute".to_string(), sha256_hex(&nav_a)), ]; for (case, digest) in &cases { diff --git a/astraweave-core/tests/replay_support/mod.rs b/astraweave-core/tests/replay_support/mod.rs index 9d14b60e0f..6c9e4961b7 100644 --- a/astraweave-core/tests/replay_support/mod.rs +++ b/astraweave-core/tests/replay_support/mod.rs @@ -9,7 +9,7 @@ use astraweave_ai::{GoapOrchestrator, Orchestrator, RuleOrchestrator}; use astraweave_core::{ build_snapshot, ActionStep, CompanionState, EnemyState, IVec2, MovementSpeed, PerceptionConfig, - PlanIntent, PlayerState, Poi, Team, World, WorldSnapshot, + PlanIntent, PlayerState, Team, World, WorldSnapshot, }; use sha2::{Digest, Sha256}; use std::path::PathBuf; @@ -44,6 +44,95 @@ pub fn planner_pure_bytes() -> Vec { out } +pub fn nav_reroute_bytes() -> Vec { + use astraweave_ai::htn::{plan_route, AgentPlan, SpatialHooks}; + use astraweave_destruction::command::{ + Brush, BrushOp, BrushShape, CommandKind, DestructionCommand, + }; + use astraweave_destruction::DestructionWorld; + use astraweave_nav::{bridge_and_ford, nav_change_from_geometry_notice, NavScratch}; + + let mut tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let mut world = DestructionWorld::new(0xA11C, 0); + world + .enqueue(DestructionCommand { + tick: 30, + seq: 0, + entity_id: 1, + kind: CommandKind::Brush(Brush { + shape: BrushShape::Box, + op: BrushOp::Subtract, + origin: [2_000, 0, 24_500], + radius: 7_499, + half_extents: [1, 1, 1], + strength: 1, + }), + }) + .expect("enqueue bridge collapse"); + let mut out = Vec::new(); + for tick in 0..60u64 { + world.tick(); + let empty = astraweave_destruction::GeometryNotice { + tick: 0, + x0: 0, + y0: 0, + z0: 0, + x1: 0, + y1: 0, + z1: 0, + reason: 0, + }; + let mut notices = [empty; 8]; + let count = world.drain_geometry_notices(&mut notices); + for (seq, notice) in notices[..count].iter().enumerate() { + if let Some(change) = nav_change_from_geometry_notice(notice, seq as u32) { + tiles.mark(change); + } + } + let committed = tiles.commit_tick() as u32; + let mut budget = 64u32; + let mut plan = AgentPlan::empty(); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + tick, + &mut plan, + &mut budget, + ); + push_u32(&mut out, tick as u32); + push_u32(&mut out, committed); + push_u8(&mut out, plan.len); + for slot in plan.slots.iter().take(plan.len as usize) { + match slot { + astraweave_ai::htn::ActionSlot::Empty => push_u8(&mut out, 0), + astraweave_ai::htn::ActionSlot::MoveTo { x, y } => { + push_u8(&mut out, 1); + push_i32(&mut out, *x); + push_i32(&mut out, *y); + } + astraweave_ai::htn::ActionSlot::UseBreach { portal_id } => { + push_u8(&mut out, 2); + push_u32(&mut out, *portal_id); + } + astraweave_ai::htn::ActionSlot::TakeCover { cover_id } => { + push_u8(&mut out, 3); + push_u32(&mut out, *cover_id); + } + astraweave_ai::htn::ActionSlot::Wait { duration_milli } => { + push_u8(&mut out, 4); + push_u32(&mut out, *duration_milli); + } + } + } + } + out +} + /// Seeded harvest respawn and craft item ids. Same `(world_seed, tick)` pair /// the gameplay crate locks in `gameplay_rng_*`. No `HashMap` walk. pub fn gameplay_rng_bytes() -> Vec { @@ -213,10 +302,8 @@ fn hand_snapshot(smoke_cd: f32, first_enemy_x: i32, with_enemies: bool) -> World pos: IVec2 { x: 2, y: 3 }, }, enemies, - pois: vec![Poi { - k: "breach_door".to_string(), - pos: IVec2 { x: 15, y: 8 }, - }], + // Authored fixture. Perception no longer inserts a breach at a fixed cell. + pois: vec![], obstacles: vec![IVec2 { x: 1, y: 2 }, IVec2 { x: 3, y: 3 }], objective: Some("extract".to_string()), } diff --git a/astraweave-nav/Cargo.toml b/astraweave-nav/Cargo.toml index 7027c1ffd4..eb2576eced 100644 --- a/astraweave-nav/Cargo.toml +++ b/astraweave-nav/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] anyhow = { workspace = true } +astraweave-destruction = { workspace = true } glam = { workspace = true } [dev-dependencies] diff --git a/astraweave-nav/benches/navmesh_benchmarks.rs b/astraweave-nav/benches/navmesh_benchmarks.rs index 03251a23ab..a0e46fbac4 100644 --- a/astraweave-nav/benches/navmesh_benchmarks.rs +++ b/astraweave-nav/benches/navmesh_benchmarks.rs @@ -21,7 +21,9 @@ // 5. Path Length: Path distance is at least straight-line distance // ============================================================================= -use astraweave_nav::{NavMesh, Triangle}; +use astraweave_nav::{ + bridge_and_ford, nav_change_from_kind, NavChangeKind, NavMesh, Triangle, TILE_COMMITS_PER_TICK, +}; use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; use glam::Vec3; @@ -438,4 +440,24 @@ criterion_group!( bench_throughput_10k_triangles, ); -criterion_main!(baking, pathfinding, throughput); +fn bench_tile_commits_per_tick(c: &mut Criterion) { + c.bench_function("tile_commits_per_tick", |b| { + b.iter(|| { + let mut tiles = bridge_and_ford(); + for seq in 0..TILE_COMMITS_PER_TICK as u32 { + tiles.mark(nav_change_from_kind( + NavChangeKind::Brush, + 1, + seq, + [seq as i32 * 32_000, -1_000, 0], + [seq as i32 * 32_000 + 500, 1_000, 500], + )); + } + black_box(tiles.commit_tick()) + }); + }); +} + +criterion_group!(tile_budget, bench_tile_commits_per_tick); + +criterion_main!(baking, pathfinding, throughput, tile_budget); diff --git a/astraweave-nav/src/lib.rs b/astraweave-nav/src/lib.rs index bde4c96dd5..e6f9af30ee 100644 --- a/astraweave-nav/src/lib.rs +++ b/astraweave-nav/src/lib.rs @@ -30,6 +30,14 @@ use glam::Vec3; use std::fmt; +mod tiles; +pub use astraweave_destruction::GeometryNotice; +pub use tiles::{ + bridge_and_ford, nav_change_from_geometry_notice, nav_change_from_kind, BreachSite, CoverSite, + NavChange, NavChangeKind, NavScratch, NavTiles, TileSideBuffer, FRAME_BUDGET_MS, NOTICE_BRUSH, + NOTICE_COLLAPSE, NOTICE_WEAVE, TILE_COMMITS_PER_TICK, TILE_SIZE_M, +}; + #[cfg(test)] mod mutation_tests; @@ -462,16 +470,19 @@ impl NavMesh { verts: [t.a, t.b, t.c], normal: n, center, - neighbors: vec![], + // Capacity is reserved at bake so a later relink does not allocate. + neighbors: Vec::with_capacity(8), }) }) .collect(); - // Build adjacency by shared edge (position‑based, epsilon) + // Adjacency is a shared edge in XZ. `max_step` is the largest vertical + // gap that still links. Coplanar edges have a zero gap, so meshes that + // were already linked stay linked. A ledge taller than `max_step` does not. let eps = 1e-3; for i in 0..ntris.len() { for j in i + 1..ntris.len() { - if share_edge(&ntris[i], &ntris[j], eps) { + if share_edge(&ntris[i], &ntris[j], eps, max_step) { ntris[i].neighbors.push(j); ntris[j].neighbors.push(i); } @@ -559,50 +570,118 @@ impl NavMesh { self.dirty_regions.clear(); } - /// Rebake dirty regions with new triangle data + /// Rebake dirty regions. /// - /// This performs a full rebake of the entire mesh using the provided triangles. - /// For large meshes, consider using partial_rebake for better performance. + /// Delegates to [`Self::partial_rebake`]. Triangles outside the dirty + /// AABBs keep their vertices. One call commits every dirty triangle in + /// this mesh; the tiled world commits at most [`TILE_COMMITS_PER_TICK`]. pub fn rebake_dirty_regions(&mut self, tris: &[Triangle]) { if self.dirty_regions.is_empty() { return; } - - // Full rebake (simplest implementation) - let rebaked = NavMesh::bake(tris, self.max_step, self.max_slope_deg); - self.tris = rebaked.tris; - self.dirty_regions.clear(); - self.rebake_count += 1; + let _ = self.partial_rebake(tris); } - /// Partial rebake - only processes triangles within dirty regions + /// Relink triangles that intersect a dirty region. /// - /// More efficient for large meshes with small changes. - /// Returns the number of triangles that were updated. + /// Vertices of triangles outside those regions are left in place. Neighbor + /// lists of a clean triangle change only where they touched a dirty one. + /// Returns how many triangles intersected a dirty region. + #[allow(clippy::needless_range_loop)] pub fn partial_rebake(&mut self, all_tris: &[Triangle]) -> usize { if self.dirty_regions.is_empty() { return 0; } - // Find triangles that intersect with dirty regions - let mut affected_count = 0; + const MAX_RELINK: usize = 4096; + let limit = self.tris.len().min(MAX_RELINK); + let mut dirty_tri = [false; MAX_RELINK]; + // The returned count is input triangles that meet a dirty AABB. + // That is the golden `partial_rebake` locked in before tiles existed, + // including faces the slope filter dropped from the baked mesh. + let mut affected = 0usize; for tri in all_tris { - let tri_aabb = Aabb::from_triangle(tri); + let aabb = Aabb::from_triangle(tri); + for region in &self.dirty_regions { + if aabb.intersects(region) { + affected += 1; + break; + } + } + } + for i in 0..limit { + let tri = &self.tris[i]; + let aabb = Aabb::new( + Vec3::new( + tri.verts[0].x.min(tri.verts[1].x).min(tri.verts[2].x), + tri.verts[0].y.min(tri.verts[1].y).min(tri.verts[2].y), + tri.verts[0].z.min(tri.verts[1].z).min(tri.verts[2].z), + ), + Vec3::new( + tri.verts[0].x.max(tri.verts[1].x).max(tri.verts[2].x), + tri.verts[0].y.max(tri.verts[1].y).max(tri.verts[2].y), + tri.verts[0].z.max(tri.verts[1].z).max(tri.verts[2].z), + ), + ); for region in &self.dirty_regions { - if tri_aabb.intersects(region) { - affected_count += 1; + if aabb.intersects(region) { + dirty_tri[i] = true; break; } } } - // For now, do a full rebake if any triangles are affected - // In a production system, you would only rebuild the affected portions - if affected_count > 0 { - self.rebake_dirty_regions(all_tris); + let eps = 1e-3; + let max_step = self.max_step; + for i in 0..limit { + if !dirty_tri[i] { + continue; + } + let idx = self.tris[i].idx; + if let Some(src) = all_tris.get(idx) { + let n = src.normal_normalized(); + if n.length_squared() >= 1e-6 && n.dot(Vec3::Y) >= 0.0 { + self.tris[i].verts = [src.a, src.b, src.c]; + self.tris[i].center = src.center(); + self.tris[i].normal = n; + } + } + self.tris[i].neighbors.clear(); + } + for i in 0..limit { + if dirty_tri[i] { + continue; + } + self.tris[i] + .neighbors + .retain(|&j| j >= limit || !dirty_tri[j]); + } + for i in 0..limit { + if !dirty_tri[i] { + continue; + } + for j in 0..limit { + if i == j { + continue; + } + if share_edge(&self.tris[i], &self.tris[j], eps, max_step) + && self.tris[i].neighbors.len() < self.tris[i].neighbors.capacity() + { + if !self.tris[i].neighbors.contains(&j) { + self.tris[i].neighbors.push(j); + } + if !self.tris[j].neighbors.contains(&i) + && self.tris[j].neighbors.len() < self.tris[j].neighbors.capacity() + { + self.tris[j].neighbors.push(i); + } + } + } } - affected_count + self.dirty_regions.clear(); + self.rebake_count = self.rebake_count.saturating_add(1); + affected } /// Get the total number of rebakes performed @@ -713,11 +792,15 @@ impl fmt::Display for NavMesh { } } -fn share_edge(a: &NavTri, b: &NavTri, eps: f32) -> bool { +fn share_edge(a: &NavTri, b: &NavTri, eps: f32, max_step: f32) -> bool { let mut shared = 0; + let eps2 = eps * eps; for va in a.verts { for vb in b.verts { - if va.distance(vb) <= eps { + let dx = va.x - vb.x; + let dz = va.z - vb.z; + let dy = (va.y - vb.y).abs(); + if dx * dx + dz * dz <= eps2 && dy <= max_step { shared += 1; } } @@ -826,6 +909,81 @@ mod tests { assert_eq!(nav.max_slope_deg, 60.0); } + /// `max_step` used to be stored and ignored, so a ledge and a flat edge + /// linked the same way only when the vertices were within 1e-3 in 3D. + /// It now rejects a shared XZ edge whose vertical gap is taller than the + /// step. Coplanar pairs are unchanged (gap is 0). These counts are the + /// new golden: a 0.3 m ledge links at `max_step` 0.4, a 1.0 m ledge does not. + #[test] + fn max_step_links_a_low_ledge_and_rejects_a_tall_one() { + let low = ledge_pair(0.3); + let linked = NavMesh::bake(&low, 0.4, 60.0); + assert_eq!(linked.triangle_count(), 2, "both ledge faces stay walkable"); + assert_eq!( + linked.tris[0].neighbor_count(), + 1, + "0.3 m gap is inside max_step 0.4" + ); + assert_eq!(linked.tris[1].neighbor_count(), 1); + + let tall = ledge_pair(1.0); + let blocked = NavMesh::bake(&tall, 0.4, 60.0); + assert_eq!(blocked.triangle_count(), 2); + assert_eq!( + blocked.tris[0].neighbor_count(), + 0, + "1.0 m gap is above max_step 0.4 and must not link" + ); + assert_eq!(blocked.tris[1].neighbor_count(), 0); + + let flat = NavMesh::bake(&ledge_pair(0.0), 0.4, 60.0); + assert_eq!( + flat.tris[0].neighbor_count(), + 1, + "coplanar goldens stay linked" + ); + } + + fn ledge_pair(rise: f32) -> Vec { + // Counter-clockwise from above so the normal points up. + vec![ + Triangle::new( + Vec3::new(0.0, 0.0, 0.0), + Vec3::new(0.0, 0.0, 2.0), + Vec3::new(2.0, 0.0, 2.0), + ), + Triangle::new( + Vec3::new(0.0, rise, 2.0), + Vec3::new(0.0, rise, 4.0), + Vec3::new(2.0, rise, 2.0), + ), + ] + } + + #[test] + fn partial_rebake_keeps_vertices_outside_the_dirty_aabb() { + let tris = vec![ + Triangle::new( + Vec3::ZERO, + Vec3::new(0.0, 0.0, 1.0), + Vec3::new(1.0, 0.0, 0.0), + ), + Triangle::new( + Vec3::new(50.0, 0.0, 50.0), + Vec3::new(50.0, 0.0, 51.0), + Vec3::new(51.0, 0.0, 50.0), + ), + ]; + let mut nav = NavMesh::bake(&tris, 0.4, 60.0); + let before = nav.tris[1].verts; + nav.invalidate_region(Aabb::new(Vec3::ZERO, Vec3::ONE)); + let affected = nav.partial_rebake(&tris); + assert_eq!(affected, 1, "only the origin triangle intersects the AABB"); + assert_eq!(nav.tris[1].verts, before); + assert_eq!(nav.rebake_count(), 1); + assert!(!nav.needs_rebake()); + } + #[test] fn test_navmesh_bake_single_triangle() { let tris = vec![Triangle { @@ -1026,7 +1184,7 @@ mod tests { center: Vec3::ZERO, neighbors: vec![], }; - assert!(share_edge(&tri_a, &tri_b, 1e-3)); + assert!(share_edge(&tri_a, &tri_b, 1e-3, 0.4)); } #[test] @@ -1053,7 +1211,7 @@ mod tests { center: Vec3::ZERO, neighbors: vec![], }; - assert!(!share_edge(&tri_a, &tri_b, 1e-3)); + assert!(!share_edge(&tri_a, &tri_b, 1e-3, 0.4)); } #[test] @@ -1080,7 +1238,7 @@ mod tests { center: Vec3::ZERO, neighbors: vec![], }; - assert!(share_edge(&tri_a, &tri_b, 1e-3)); + assert!(share_edge(&tri_a, &tri_b, 1e-3, 0.4)); } #[test] diff --git a/astraweave-nav/src/tiles.rs b/astraweave-nav/src/tiles.rs new file mode 100644 index 0000000000..6445abd49f --- /dev/null +++ b/astraweave-nav/src/tiles.rs @@ -0,0 +1,1424 @@ +//! Fixed-capacity nav tiles. +//! +//! A tick commits at most [`TILE_COMMITS_PER_TICK`] tiles, lowest `(cx, cz)` +//! first. The commit writes into arrays that already exist. Path queries write +//! into [`NavScratch`]. Neither takes a lock. +//! +//! A worker may fill a [`TileSideBuffer`]. The sim copies it in only when +//! `input_hash` equals the hash of the sources the sim would build itself. +//! +//! # Destruction seam +//! +//! [`NavChangeKind`] is the nav-side name for three commands from the +//! destruction log (PR #243): `Explosion`, `Brush`, and `Detach`. `Impact` +//! and `Anchor` do not mark tiles. Quantize the command's box to milli-units +//! once at the edge and call [`nav_change_from_kind`]. + +use crate::Triangle; +use astraweave_destruction::GeometryNotice; +use glam::Vec3; + +/// World span of one tile, in meters. +pub const TILE_SIZE_M: f32 = 32.0; +/// Tiles rebuilt on the sim thread in one tick. +pub const TILE_COMMITS_PER_TICK: usize = 4; +/// Whole-frame budget the commit and the planner are checked against. +pub const FRAME_BUDGET_MS: f32 = 11.0; + +const MAX_SLOTS: usize = 16; +const MAX_TRIS: usize = 24; +const MAX_LOCAL_NEIGHBORS: usize = 8; +const MAX_PORTALS: usize = 48; +const MAX_DIRTY: usize = 16; +const MAX_PENDING: usize = 16; +const MAX_SITES: usize = 16; +const MAX_NODES: usize = MAX_SLOTS * MAX_TRIS; +const MAX_WAYPOINTS: usize = 32; + +/// Which destruction command produced a [`NavChange`]. +/// +/// `Weave` is reason 3 on `GeometryNotice` from the destruction crate. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NavChangeKind { + Explosion, + Brush, + Detach, + Weave, +} + +/// Reason bytes published by [`astraweave_destruction::DestructionWorld::drain_geometry_notices`]. +pub const NOTICE_BRUSH: u8 = 1; +pub const NOTICE_COLLAPSE: u8 = 2; +pub const NOTICE_WEAVE: u8 = 3; + +/// One walkable-region invalidation, in milli-units. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NavChange { + pub tick: u64, + pub seq: u32, + pub min_milli: [i32; 3], + pub max_milli: [i32; 3], + pub kind: NavChangeKind, +} + +impl NavChange { + #[must_use] + pub const fn new( + tick: u64, + seq: u32, + min_milli: [i32; 3], + max_milli: [i32; 3], + kind: NavChangeKind, + ) -> Self { + Self { + tick, + seq, + min_milli, + max_milli, + kind, + } + } +} + +/// Map one drained geometry notice into a [`NavChange`]. +/// +/// Reason 1 is a brush, 2 is a collapse (`Detach`), 3 is a weave. Any other +/// reason is ignored. `seq` is the drain index so two notices in one tick +/// stay ordered. `notice` is a value drained from +/// [`astraweave_destruction::DestructionWorld::drain_geometry_notices`]. +#[must_use] +pub const fn nav_change_from_geometry_notice( + notice: &GeometryNotice, + seq: u32, +) -> Option { + let kind = match notice.reason { + NOTICE_BRUSH => NavChangeKind::Brush, + NOTICE_COLLAPSE => NavChangeKind::Detach, + NOTICE_WEAVE => NavChangeKind::Weave, + _ => return None, + }; + Some(NavChange::new( + notice.tick, + seq, + [notice.x0, notice.y0, notice.z0], + [notice.x1, notice.y1, notice.z1], + kind, + )) +} + +/// `Explosion`, `Brush`, `Detach`, and `Weave` become a [`NavChange`]. +#[must_use] +pub const fn nav_change_from_kind( + kind: NavChangeKind, + tick: u64, + seq: u32, + min_milli: [i32; 3], + max_milli: [i32; 3], +) -> NavChange { + NavChange::new(tick, seq, min_milli, max_milli, kind) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BreachSite { + pub portal_id: u32, + pub x_milli: i32, + pub z_milli: i32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CoverSite { + pub id: u32, + pub x_milli: i32, + pub z_milli: i32, +} + +#[derive(Clone, Copy)] +struct SourceTri { + verts: [Vec3; 3], +} + +#[derive(Clone, Copy)] +struct TileTri { + verts: [Vec3; 3], + center: Vec3, + neighbors: [u16; MAX_LOCAL_NEIGHBORS], + neighbor_count: u8, + live: bool, +} + +#[derive(Clone, Copy)] +struct Portal { + a_slot: u16, + a_tri: u16, + b_slot: u16, + b_tri: u16, + id: u32, + x_milli: i32, + z_milli: i32, + live: bool, +} + +#[derive(Clone, Copy)] +struct Slot { + occupied: bool, + cx: i32, + cz: i32, + source_count: u16, + sources: [SourceTri; MAX_TRIS], + tri_count: u16, + tris: [TileTri; MAX_TRIS], + input_hash: u64, + generation: u32, +} + +/// Built tile waiting for the sim to accept or reject it. +#[derive(Clone, Copy)] +pub struct TileSideBuffer { + pub slot: u16, + pub input_hash: u64, + pub ready: bool, + tri_count: u16, + tris: [TileTri; MAX_TRIS], + generation: u32, +} + +/// Scratch for one path query. Cleared by stamp, not freed. +pub struct NavScratch { + stamp: u32, + seen: [u32; MAX_NODES], + g: [u32; MAX_NODES], + parent: [u32; MAX_NODES], + heap_f: [u32; MAX_NODES], + heap_n: [u32; MAX_NODES], + heap_len: u16, + pub waypoints: [Vec3; MAX_WAYPOINTS], + pub waypoint_len: u16, + pub portal_ids: [u32; MAX_WAYPOINTS], + pub portal_len: u16, +} + +impl NavScratch { + #[must_use] + pub const fn new() -> Self { + Self { + stamp: 0, + seen: [0; MAX_NODES], + g: [0; MAX_NODES], + parent: [0; MAX_NODES], + heap_f: [0; MAX_NODES], + heap_n: [0; MAX_NODES], + heap_len: 0, + waypoints: [Vec3::ZERO; MAX_WAYPOINTS], + waypoint_len: 0, + portal_ids: [0; MAX_WAYPOINTS], + portal_len: 0, + } + } +} + +impl Default for NavScratch { + fn default() -> Self { + Self::new() + } +} + +/// Resident tiles, pending changes, and the last published breaches and cover. +pub struct NavTiles { + slots: [Slot; MAX_SLOTS], + slot_count: u16, + dirty: [u16; MAX_DIRTY], + dirty_len: u16, + pending: [NavChange; MAX_PENDING], + pending_len: u16, + portals: [Portal; MAX_PORTALS], + portal_count: u16, + prev_portal_ids: [u32; MAX_PORTALS], + prev_portal_len: u16, + pub breaches: [BreachSite; MAX_SITES], + pub breach_count: u16, + pub cover: [CoverSite; MAX_SITES], + pub cover_count: u16, + prev_cover: [CoverSite; MAX_SITES], + prev_cover_len: u16, + pub lost_cover: [CoverSite; MAX_SITES], + pub lost_cover_count: u16, + max_step: f32, + min_up_dot: f32, + commits: u32, +} + +impl NavTiles { + #[must_use] + pub fn new(max_step: f32, max_slope_deg: f32) -> Self { + Self { + slots: [Slot::empty(); MAX_SLOTS], + slot_count: 0, + dirty: [0; MAX_DIRTY], + dirty_len: 0, + pending: [NavChange::new(0, 0, [0; 3], [0; 3], NavChangeKind::Brush); MAX_PENDING], + pending_len: 0, + portals: [Portal::empty(); MAX_PORTALS], + portal_count: 0, + prev_portal_ids: [0; MAX_PORTALS], + prev_portal_len: 0, + breaches: [BreachSite { + portal_id: 0, + x_milli: 0, + z_milli: 0, + }; MAX_SITES], + breach_count: 0, + cover: [CoverSite { + id: 0, + x_milli: 0, + z_milli: 0, + }; MAX_SITES], + cover_count: 0, + prev_cover: [CoverSite { + id: 0, + x_milli: 0, + z_milli: 0, + }; MAX_SITES], + prev_cover_len: 0, + lost_cover: [CoverSite { + id: 0, + x_milli: 0, + z_milli: 0, + }; MAX_SITES], + lost_cover_count: 0, + max_step, + min_up_dot: cos_deg(max_slope_deg), + commits: 0, + } + } + + /// Place triangles into tiles and build them. Overflow past the resident + /// cap is counted and dropped, highest centers last. + pub fn ingest(&mut self, tris: &[Triangle]) -> usize { + let mut placed = 0usize; + for tri in tris { + if self.place_source(tri.clone()) { + placed += 1; + } + } + self.rebuild_all_occupied(); + self.rebuild_portals_and_sites(); + placed + } + + /// Queue a change. Application order is `(tick, seq)`, not insertion order. + pub fn mark(&mut self, change: NavChange) { + if self.pending_len as usize >= MAX_PENDING { + return; + } + let n = self.pending_len as usize; + self.pending[n] = change; + self.pending_len += 1; + let mut i = n; + while i > 0 { + let prev = self.pending[i - 1]; + let cur = self.pending[i]; + let out_of_order = + prev.tick > cur.tick || (prev.tick == cur.tick && prev.seq > cur.seq); + if !out_of_order { + break; + } + self.pending[i - 1] = cur; + self.pending[i] = prev; + i -= 1; + } + } + + /// Drop source triangles that intersect queued changes, then commit at + /// most [`TILE_COMMITS_PER_TICK`] dirty tiles. + pub fn commit_tick(&mut self) -> usize { + self.apply_pending(); + self.sort_dirty(); + let n = (self.dirty_len as usize).min(TILE_COMMITS_PER_TICK); + let mut ids = [0u16; TILE_COMMITS_PER_TICK]; + ids[..n].copy_from_slice(&self.dirty[..n]); + let mut done = 0usize; + for id in ids.iter().take(n) { + let buf = self.fill_side_buffer(*id); + if self.accept_side_buffer(&buf) { + done += 1; + } + } + if done > 0 { + self.rebuild_portals_and_sites(); + } + done + } + + /// Copy a synchronous build into `buf`. The sim accepts it later. + #[must_use] + pub fn fill_side_buffer(&self, slot: u16) -> TileSideBuffer { + if slot as usize >= MAX_SLOTS || !self.slots[slot as usize].occupied { + return TileSideBuffer { + slot, + input_hash: 0, + ready: false, + tri_count: 0, + tris: [TileTri::empty(); MAX_TRIS], + generation: 0, + }; + } + let built = build_slot(&self.slots[slot as usize], self.max_step, self.min_up_dot); + TileSideBuffer { + slot, + input_hash: built.0, + ready: true, + tri_count: built.1, + tris: built.2, + generation: self.slots[slot as usize].generation.wrapping_add(1), + } + } + + /// Accept a worker buffer only when its input hash matches the sources. + pub fn accept_side_buffer(&mut self, buf: &TileSideBuffer) -> bool { + let slot = buf.slot as usize; + if !buf.ready || slot >= MAX_SLOTS || !self.slots[slot].occupied { + return false; + } + let expected = hash_sources( + &self.slots[slot].sources, + self.slots[slot].source_count as usize, + self.max_step, + self.min_up_dot, + ); + if buf.input_hash != expected || buf.generation == 0 { + return false; + } + self.slots[slot].tris = buf.tris; + self.slots[slot].tri_count = buf.tri_count; + self.slots[slot].input_hash = expected; + self.slots[slot].generation = self.slots[slot].generation.wrapping_add(1); + self.commits = self.commits.saturating_add(1); + self.clear_dirty_slot(buf.slot); + true + } + + #[must_use] + pub fn dirty_len(&self) -> u16 { + self.dirty_len + } + + #[must_use] + pub fn commits(&self) -> u32 { + self.commits + } + + #[must_use] + pub fn slot_hash(&self, cx: i32, cz: i32) -> Option { + self.find_slot(cx, cz) + .map(|slot| self.slots[slot].input_hash) + } + + #[must_use] + pub fn dirty_coord(&self, index: usize) -> Option<(i32, i32)> { + self.dirty + .get(index) + .filter(|_| index < self.dirty_len as usize) + .map(|&slot| (self.slots[slot as usize].cx, self.slots[slot as usize].cz)) + } + + /// Write a path into `scratch`. Returns the waypoint count. + pub fn query_path(&self, scratch: &mut NavScratch, start: Vec3, goal: Vec3) -> u16 { + scratch.waypoint_len = 0; + scratch.portal_len = 0; + let Some(start_n) = self.closest_node(start) else { + return 0; + }; + let Some(goal_n) = self.closest_node(goal) else { + return 0; + }; + scratch.stamp = scratch.stamp.wrapping_add(1); + if scratch.stamp == 0 { + scratch.seen = [0; MAX_NODES]; + scratch.stamp = 1; + } + let stamp = scratch.stamp; + scratch.heap_len = 0; + self.heap_push(scratch, 0, start_n); + scratch.seen[start_n as usize] = stamp; + scratch.g[start_n as usize] = 0; + scratch.parent[start_n as usize] = start_n; + let mut found = false; + while scratch.heap_len > 0 { + let node = self.heap_pop(scratch); + if node == goal_n { + found = true; + break; + } + let g = scratch.g[node as usize]; + self.relax_neighbors(scratch, node, g, goal_n, stamp); + } + if !found { + return 0; + } + let mut chain = [0u32; MAX_WAYPOINTS]; + let mut chain_len = 0u16; + let mut cursor = goal_n; + loop { + if chain_len as usize >= MAX_WAYPOINTS { + break; + } + chain[chain_len as usize] = cursor; + chain_len += 1; + if cursor == start_n { + break; + } + let prev = scratch.parent[cursor as usize]; + if prev == cursor { + break; + } + cursor = prev; + } + if (scratch.waypoint_len as usize) < MAX_WAYPOINTS { + scratch.waypoints[0] = start; + scratch.waypoint_len = 1; + } + let mut hop = chain_len; + while hop > 1 { + hop -= 1; + self.record_portal(scratch, chain[hop as usize], chain[(hop - 1) as usize]); + let node = chain[(hop - 1) as usize]; + if node == goal_n { + continue; + } + if (scratch.waypoint_len as usize) < MAX_WAYPOINTS { + let (slot, local) = decode_node(node); + scratch.waypoints[scratch.waypoint_len as usize] = + self.slots[slot].tris[local].center; + scratch.waypoint_len += 1; + } + } + if (scratch.waypoint_len as usize) < MAX_WAYPOINTS { + scratch.waypoints[scratch.waypoint_len as usize] = goal; + scratch.waypoint_len += 1; + } + scratch.waypoint_len + } + + fn place_source(&mut self, tri: Triangle) -> bool { + let center = tri.center(); + let (cx, cz) = tile_coord(center.x, center.z); + let slot = if let Some(existing) = self.find_slot(cx, cz) { + existing + } else if (self.slot_count as usize) < MAX_SLOTS { + let slot = self.slot_count as usize; + self.slots[slot].occupied = true; + self.slots[slot].cx = cx; + self.slots[slot].cz = cz; + self.slot_count += 1; + slot + } else { + return false; + }; + let count = self.slots[slot].source_count as usize; + if count >= MAX_TRIS { + return false; + } + self.slots[slot].sources[count] = SourceTri { + verts: [tri.a, tri.b, tri.c], + }; + self.slots[slot].source_count += 1; + true + } + + fn find_slot(&self, cx: i32, cz: i32) -> Option { + (0..self.slot_count as usize).find(|&slot| { + self.slots[slot].occupied && self.slots[slot].cx == cx && self.slots[slot].cz == cz + }) + } + + fn rebuild_all_occupied(&mut self) { + let count = self.slot_count as usize; + for slot in 0..count { + if self.slots[slot].occupied { + self.write_build(slot as u16); + } + } + } + + fn write_build(&mut self, slot: u16) { + let built = build_slot(&self.slots[slot as usize], self.max_step, self.min_up_dot); + self.slots[slot as usize].input_hash = built.0; + self.slots[slot as usize].tri_count = built.1; + self.slots[slot as usize].tris = built.2; + self.slots[slot as usize].generation = self.slots[slot as usize].generation.wrapping_add(1); + } + + fn apply_pending(&mut self) { + let n = self.pending_len as usize; + for i in 0..n { + let change = self.pending[i]; + self.drop_sources(change); + } + self.pending_len = 0; + } + + fn drop_sources(&mut self, change: NavChange) { + let count = self.slot_count as usize; + for slot in 0..count { + if !self.slots[slot].occupied { + continue; + } + let mut kept = 0u16; + let src_n = self.slots[slot].source_count as usize; + let mut next = [SourceTri { + verts: [Vec3::ZERO; 3], + }; MAX_TRIS]; + let mut removed = false; + for i in 0..src_n { + if source_hits( + &self.slots[slot].sources[i], + change.min_milli, + change.max_milli, + ) { + removed = true; + } else { + next[kept as usize] = self.slots[slot].sources[i]; + kept += 1; + } + } + if removed { + self.slots[slot].sources = next; + self.slots[slot].source_count = kept; + self.push_dirty(slot as u16); + } else if slot_overlaps(self.slots[slot].cx, self.slots[slot].cz, &change) { + self.push_dirty(slot as u16); + } + } + } + + fn push_dirty(&mut self, slot: u16) { + if self.dirty_len as usize >= MAX_DIRTY { + return; + } + for i in 0..self.dirty_len as usize { + if self.dirty[i] == slot { + return; + } + } + self.dirty[self.dirty_len as usize] = slot; + self.dirty_len += 1; + } + + fn clear_dirty_slot(&mut self, slot: u16) { + let mut i = 0usize; + while i < self.dirty_len as usize { + if self.dirty[i] == slot { + let last = self.dirty_len as usize - 1; + self.dirty[i] = self.dirty[last]; + self.dirty_len -= 1; + } else { + i += 1; + } + } + } + + fn sort_dirty(&mut self) { + let n = self.dirty_len as usize; + for i in 1..n { + let mut j = i; + while j > 0 { + let a = self.dirty[j - 1] as usize; + let b = self.dirty[j] as usize; + let out = self.slots[a].cx > self.slots[b].cx + || (self.slots[a].cx == self.slots[b].cx + && self.slots[a].cz > self.slots[b].cz); + if !out { + break; + } + self.dirty.swap(j - 1, j); + j -= 1; + } + } + } + + fn rebuild_portals_and_sites(&mut self) { + self.prev_portal_len = self.portal_count; + for i in 0..self.portal_count as usize { + self.prev_portal_ids[i] = self.portals[i].id; + } + self.prev_cover_len = self.cover_count; + self.prev_cover = self.cover; + self.portal_count = 0; + let slots = self.slot_count as usize; + for a in 0..slots { + if !self.slots[a].occupied { + continue; + } + for b in (a + 1)..slots { + if !self.slots[b].occupied { + continue; + } + if !adjacent_tile( + self.slots[a].cx, + self.slots[a].cz, + self.slots[b].cx, + self.slots[b].cz, + ) { + continue; + } + self.link_slots(a, b); + } + } + self.collect_sites(); + } + + fn link_slots(&mut self, a: usize, b: usize) { + let a_n = self.slots[a].tri_count as usize; + let b_n = self.slots[b].tri_count as usize; + for ia in 0..a_n { + if !self.slots[a].tris[ia].live { + continue; + } + for ib in 0..b_n { + if !self.slots[b].tris[ib].live { + continue; + } + if !tris_share( + &self.slots[a].tris[ia], + &self.slots[b].tris[ib], + self.max_step, + ) { + continue; + } + if self.portal_count as usize >= MAX_PORTALS { + return; + } + let center = self.slots[a].tris[ia].center; + let id = portal_id( + self.slots[a].cx, + self.slots[a].cz, + ia as u16, + self.slots[b].cx, + self.slots[b].cz, + ib as u16, + ); + let n = self.portal_count as usize; + self.portals[n] = Portal { + a_slot: a as u16, + a_tri: ia as u16, + b_slot: b as u16, + b_tri: ib as u16, + id, + x_milli: milli(center.x), + z_milli: milli(center.z), + live: true, + }; + self.portal_count += 1; + } + } + } + + fn collect_sites(&mut self) { + self.breach_count = 0; + self.cover_count = 0; + self.lost_cover_count = 0; + for i in 0..self.portal_count as usize { + let id = self.portals[i].id; + let mut seen = false; + for p in 0..self.prev_portal_len as usize { + if self.prev_portal_ids[p] == id { + seen = true; + break; + } + } + if seen || self.breach_count as usize >= MAX_SITES { + continue; + } + let n = self.breach_count as usize; + self.breaches[n] = BreachSite { + portal_id: id, + x_milli: self.portals[i].x_milli, + z_milli: self.portals[i].z_milli, + }; + self.breach_count += 1; + } + let slots = self.slot_count as usize; + for slot in 0..slots { + let n = self.slots[slot].tri_count as usize; + for local in 0..n { + let tri = &self.slots[slot].tris[local]; + if !tri.live || tri.neighbor_count >= 3 { + continue; + } + if self.cover_count as usize >= MAX_SITES { + break; + } + let id = ((slot as u32) << 8) | local as u32; + let c = self.cover_count as usize; + self.cover[c] = CoverSite { + id, + x_milli: milli(tri.center.x), + z_milli: milli(tri.center.z), + }; + self.cover_count += 1; + } + } + for i in 0..self.prev_cover_len as usize { + let old = self.prev_cover[i]; + let mut still = false; + for j in 0..self.cover_count as usize { + if self.cover[j].id == old.id { + still = true; + break; + } + } + if still || self.lost_cover_count as usize >= MAX_SITES { + continue; + } + let n = self.lost_cover_count as usize; + self.lost_cover[n] = old; + self.lost_cover_count += 1; + } + } + + fn closest_node(&self, p: Vec3) -> Option { + let mut best: Option<(u32, i64)> = None; + let slots = self.slot_count as usize; + for slot in 0..slots { + let n = self.slots[slot].tri_count as usize; + for local in 0..n { + if !self.slots[slot].tris[local].live { + continue; + } + let d = dist2_milli(self.slots[slot].tris[local].center, p); + let node = encode_node(slot, local); + let replace = match best { + None => true, + Some((_, best_d)) => d < best_d, + }; + if replace { + best = Some((node, d)); + } + } + } + best.map(|(node, _)| node) + } + + fn relax_neighbors(&self, scratch: &mut NavScratch, node: u32, g: u32, goal: u32, stamp: u32) { + let (slot, local) = decode_node(node); + let tri = &self.slots[slot].tris[local]; + for i in 0..tri.neighbor_count as usize { + let next = encode_node(slot, tri.neighbors[i] as usize); + self.relax(scratch, node, next, g, goal, stamp); + } + for i in 0..self.portal_count as usize { + let portal = &self.portals[i]; + if !portal.live { + continue; + } + let next = if portal.a_slot as usize == slot && portal.a_tri as usize == local { + Some(encode_node(portal.b_slot as usize, portal.b_tri as usize)) + } else if portal.b_slot as usize == slot && portal.b_tri as usize == local { + Some(encode_node(portal.a_slot as usize, portal.a_tri as usize)) + } else { + None + }; + if let Some(next) = next { + self.relax(scratch, node, next, g, goal, stamp); + } + } + } + + fn relax(&self, scratch: &mut NavScratch, from: u32, to: u32, g: u32, goal: u32, stamp: u32) { + let (slot, local) = decode_node(to); + if slot >= MAX_SLOTS || !self.slots[slot].tris[local].live { + return; + } + let (from_slot, from_local) = decode_node(from); + let step = manhattan( + self.slots[from_slot].tris[from_local].center, + self.slots[slot].tris[local].center, + ); + let ng = g.saturating_add(step); + let seen = scratch.seen[to as usize] == stamp; + if seen && ng >= scratch.g[to as usize] { + return; + } + scratch.seen[to as usize] = stamp; + scratch.g[to as usize] = ng; + scratch.parent[to as usize] = from; + let h = manhattan( + self.slots[slot].tris[local].center, + self.slots[decode_node(goal).0].tris[decode_node(goal).1].center, + ); + self.heap_push(scratch, ng.saturating_add(h), to); + } + + fn heap_push(&self, scratch: &mut NavScratch, f: u32, node: u32) { + if scratch.heap_len as usize >= MAX_NODES { + return; + } + let mut i = scratch.heap_len as usize; + scratch.heap_f[i] = f; + scratch.heap_n[i] = node; + scratch.heap_len += 1; + while i > 0 { + let parent = (i - 1) / 2; + let worse = scratch.heap_f[i] < scratch.heap_f[parent] + || (scratch.heap_f[i] == scratch.heap_f[parent] + && scratch.heap_n[i] < scratch.heap_n[parent]); + if !worse { + break; + } + scratch.heap_f.swap(i, parent); + scratch.heap_n.swap(i, parent); + i = parent; + } + } + + fn heap_pop(&self, scratch: &mut NavScratch) -> u32 { + let out = scratch.heap_n[0]; + scratch.heap_len -= 1; + let last = scratch.heap_len as usize; + scratch.heap_f[0] = scratch.heap_f[last]; + scratch.heap_n[0] = scratch.heap_n[last]; + let mut i = 0usize; + loop { + let left = i * 2 + 1; + let right = left + 1; + if left >= scratch.heap_len as usize { + break; + } + let mut best = left; + if right < scratch.heap_len as usize { + let take_right = scratch.heap_f[right] < scratch.heap_f[left] + || (scratch.heap_f[right] == scratch.heap_f[left] + && scratch.heap_n[right] < scratch.heap_n[left]); + if take_right { + best = right; + } + } + let sink = scratch.heap_f[best] < scratch.heap_f[i] + || (scratch.heap_f[best] == scratch.heap_f[i] + && scratch.heap_n[best] < scratch.heap_n[i]); + if !sink { + break; + } + scratch.heap_f.swap(i, best); + scratch.heap_n.swap(i, best); + i = best; + } + out + } + + fn record_portal(&self, scratch: &mut NavScratch, a: u32, b: u32) { + let (sa, la) = decode_node(a); + let (sb, lb) = decode_node(b); + if sa == sb || scratch.portal_len as usize >= MAX_WAYPOINTS { + return; + } + for i in 0..self.portal_count as usize { + let p = &self.portals[i]; + let hit = (p.a_slot as usize == sa + && p.a_tri as usize == la + && p.b_slot as usize == sb + && p.b_tri as usize == lb) + || (p.a_slot as usize == sb + && p.a_tri as usize == lb + && p.b_slot as usize == sa + && p.b_tri as usize == la); + if hit { + scratch.portal_ids[scratch.portal_len as usize] = p.id; + scratch.portal_len += 1; + return; + } + } + } +} + +impl Slot { + const fn empty() -> Self { + Self { + occupied: false, + cx: 0, + cz: 0, + source_count: 0, + sources: [SourceTri { + verts: [Vec3::ZERO; 3], + }; MAX_TRIS], + tri_count: 0, + tris: [TileTri::empty(); MAX_TRIS], + input_hash: 0, + generation: 0, + } + } +} + +impl TileTri { + const fn empty() -> Self { + Self { + verts: [Vec3::ZERO; 3], + center: Vec3::ZERO, + neighbors: [0; MAX_LOCAL_NEIGHBORS], + neighbor_count: 0, + live: false, + } + } +} + +impl Portal { + const fn empty() -> Self { + Self { + a_slot: 0, + a_tri: 0, + b_slot: 0, + b_tri: 0, + id: 0, + x_milli: 0, + z_milli: 0, + live: false, + } + } +} + +fn build_slot(slot: &Slot, max_step: f32, min_up_dot: f32) -> (u64, u16, [TileTri; MAX_TRIS]) { + let hash = hash_sources( + &slot.sources, + slot.source_count as usize, + max_step, + min_up_dot, + ); + let mut tris = [TileTri::empty(); MAX_TRIS]; + let mut count = 0u16; + let n = slot.source_count as usize; + for i in 0..n { + let verts = slot.sources[i].verts; + let normal = tri_normal(verts); + let up = normal_y(normal); + if up < min_up_dot { + continue; + } + let c = (count as usize).min(MAX_TRIS - 1); + tris[c] = TileTri { + verts, + center: Vec3::new( + (verts[0].x + verts[1].x + verts[2].x) / 3.0, + (verts[0].y + verts[1].y + verts[2].y) / 3.0, + (verts[0].z + verts[1].z + verts[2].z) / 3.0, + ), + neighbors: [0; MAX_LOCAL_NEIGHBORS], + neighbor_count: 0, + live: true, + }; + count += 1; + if count as usize >= MAX_TRIS { + break; + } + } + let live = count as usize; + for i in 0..live { + for j in (i + 1)..live { + if tris_share(&tris[i], &tris[j], max_step) + && (tris[i].neighbor_count as usize) < MAX_LOCAL_NEIGHBORS + && (tris[j].neighbor_count as usize) < MAX_LOCAL_NEIGHBORS + { + let ai = tris[i].neighbor_count as usize; + let bi = tris[j].neighbor_count as usize; + tris[i].neighbors[ai] = j as u16; + tris[j].neighbors[bi] = i as u16; + tris[i].neighbor_count += 1; + tris[j].neighbor_count += 1; + } + } + } + (hash, count, tris) +} + +fn tri_normal(verts: [Vec3; 3]) -> Vec3 { + let e1 = Vec3::new( + verts[1].x - verts[0].x, + verts[1].y - verts[0].y, + verts[1].z - verts[0].z, + ); + let e2 = Vec3::new( + verts[2].x - verts[0].x, + verts[2].y - verts[0].y, + verts[2].z - verts[0].z, + ); + Vec3::new( + e1.y * e2.z - e1.z * e2.y, + e1.z * e2.x - e1.x * e2.z, + e1.x * e2.y - e1.y * e2.x, + ) +} + +fn normal_y(n: Vec3) -> f32 { + let len2 = n.x * n.x + n.y * n.y + n.z * n.z; + if len2 < 1e-12 { + return 0.0; + } + // Reciprocal square root via the IEEE sqrt of a product. The slope gate + // compares this with a polynomial cosine, so the tick does not call acos. + n.y / len2.sqrt() +} + +fn tris_share(a: &TileTri, b: &TileTri, max_step: f32) -> bool { + let mut shared = 0; + let eps2 = 1e-6; + for va in a.verts { + for vb in b.verts { + let dx = va.x - vb.x; + let dz = va.z - vb.z; + let dy = (va.y - vb.y).abs(); + if dx * dx + dz * dz <= eps2 && dy <= max_step { + shared += 1; + } + } + } + shared >= 2 +} + +fn source_hits(src: &SourceTri, min_milli: [i32; 3], max_milli: [i32; 3]) -> bool { + let mut lo = [i32::MAX; 3]; + let mut hi = [i32::MIN; 3]; + for v in src.verts { + let p = [milli(v.x), milli(v.y), milli(v.z)]; + for axis in 0..3 { + lo[axis] = lo[axis].min(p[axis]); + hi[axis] = hi[axis].max(p[axis]); + } + } + lo[0] <= max_milli[0] + && hi[0] >= min_milli[0] + && lo[1] <= max_milli[1] + && hi[1] >= min_milli[1] + && lo[2] <= max_milli[2] + && hi[2] >= min_milli[2] +} + +fn slot_overlaps(cx: i32, cz: i32, change: &NavChange) -> bool { + let origin_x = (cx as f32 * TILE_SIZE_M * 1000.0) as i32; + let origin_z = (cz as f32 * TILE_SIZE_M * 1000.0) as i32; + let end_x = origin_x + (TILE_SIZE_M * 1000.0) as i32; + let end_z = origin_z + (TILE_SIZE_M * 1000.0) as i32; + origin_x <= change.max_milli[0] + && end_x >= change.min_milli[0] + && origin_z <= change.max_milli[2] + && end_z >= change.min_milli[2] +} + +fn tile_coord(x: f32, z: f32) -> (i32, i32) { + let cx = (x / TILE_SIZE_M).floor() as i32; + let cz = (z / TILE_SIZE_M).floor() as i32; + (cx, cz) +} + +fn adjacent_tile(ax: i32, az: i32, bx: i32, bz: i32) -> bool { + let dx = (ax - bx).abs(); + let dz = (az - bz).abs(); + dx + dz == 1 +} + +fn milli(v: f32) -> i32 { + (v * 1000.0) as i32 +} + +fn manhattan(a: Vec3, b: Vec3) -> u32 { + milli(a.x).abs_diff(milli(b.x)) + + milli(a.y).abs_diff(milli(b.y)) + + milli(a.z).abs_diff(milli(b.z)) +} + +fn dist2_milli(a: Vec3, b: Vec3) -> i64 { + let dx = i64::from(milli(a.x).wrapping_sub(milli(b.x))); + let dy = i64::from(milli(a.y).wrapping_sub(milli(b.y))); + let dz = i64::from(milli(a.z).wrapping_sub(milli(b.z))); + dx * dx + dy * dy + dz * dz +} + +fn encode_node(slot: usize, local: usize) -> u32 { + ((slot as u32) * MAX_TRIS as u32) + local as u32 +} + +fn decode_node(node: u32) -> (usize, usize) { + ( + (node / MAX_TRIS as u32) as usize, + (node % MAX_TRIS as u32) as usize, + ) +} + +fn portal_id(ax: i32, az: i32, al: u16, bx: i32, bz: i32, bl: u16) -> u32 { + let mut h = 0x4E41_u32; + h = h.wrapping_mul(16777619).wrapping_add(ax as u32); + h = h.wrapping_mul(16777619).wrapping_add(az as u32); + h = h.wrapping_mul(16777619).wrapping_add(u32::from(al)); + h = h.wrapping_mul(16777619).wrapping_add(bx as u32); + h = h.wrapping_mul(16777619).wrapping_add(bz as u32); + h.wrapping_mul(16777619).wrapping_add(u32::from(bl)) +} + +fn hash_sources(sources: &[SourceTri], count: usize, max_step: f32, min_up_dot: f32) -> u64 { + let mut h = 0x4E41_0000_0000_0001_u64; + h = mix(h, count as u64); + h = mix(h, max_step.to_bits() as u64); + h = mix(h, min_up_dot.to_bits() as u64); + for src in sources.iter().take(count) { + for v in src.verts { + h = mix(h, milli(v.x) as u32 as u64); + h = mix(h, milli(v.y) as u32 as u64); + h = mix(h, milli(v.z) as u32 as u64); + } + } + h +} + +fn mix(h: u64, v: u64) -> u64 { + h.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(v) +} + +/// Polynomial cosine. Mul and add only, so the slope gate does not call libm. +fn cos_deg(deg: f32) -> f32 { + let x = deg * 0.017_453_292; + let x2 = x * x; + 1.0 - x2 * 0.5 + x2 * x2 * (1.0 / 24.0) - x2 * x2 * x2 * (1.0 / 720.0) +} + +/// Span used by the bridge-collapse replay: a short bridge and a longer ford. +#[must_use] +pub fn bridge_and_ford() -> NavTiles { + let mut tris = Vec::new(); + push_quad(&mut tris, 0.0, 0.0, 4.0, 16.0); + push_quad(&mut tris, 0.0, 16.0, 4.0, 32.0); + push_quad(&mut tris, 0.0, 32.0, 4.0, 48.0); + push_quad(&mut tris, 4.0, 0.0, 20.0, 16.0); + push_quad(&mut tris, 20.0, 0.0, 24.0, 16.0); + push_quad(&mut tris, 20.0, 16.0, 24.0, 32.0); + push_quad(&mut tris, 20.0, 32.0, 24.0, 48.0); + push_quad(&mut tris, 4.0, 32.0, 20.0, 48.0); + push_quad(&mut tris, 64.0, 0.0, 68.0, 4.0); + let mut tiles = NavTiles::new(0.4, 45.0); + let _ = tiles.ingest(&tris); + tiles +} + +fn push_quad(out: &mut Vec, x0: f32, z0: f32, x1: f32, z1: f32) { + // Counter-clockwise from above. + out.push(Triangle::new( + Vec3::new(x0, 0.0, z0), + Vec3::new(x0, 0.0, z1), + Vec3::new(x1, 0.0, z0), + )); + out.push(Triangle::new( + Vec3::new(x1, 0.0, z0), + Vec3::new(x0, 0.0, z1), + Vec3::new(x1, 0.0, z1), + )); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tile_isolation_keeps_the_other_hash() { + let mut tiles = bridge_and_ford(); + let before = tiles.slot_hash(2, 0); + assert!(before.is_some(), "decoy tile"); + tiles.mark(nav_change_from_kind( + NavChangeKind::Detach, + 30, + 0, + [-1_000, -1_000, 17_000], + [5_000, 1_000, 31_999], + )); + let _ = tiles.commit_tick(); + assert_eq!(tiles.slot_hash(2, 0), before); + } + + #[test] + fn bridge_then_ford_after_detach() { + let mut tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let start = Vec3::new(1.0, 0.0, 1.0); + let goal = Vec3::new(1.0, 0.0, 46.0); + let n = tiles.query_path(&mut scratch, start, goal); + assert!( + n >= 2, + "path {n} portals {} slots {} portal_count {}", + scratch.portal_len, + tiles.slot_count, + tiles.portal_count + ); + let before_max_x = max_waypoint_x(&scratch); + assert!( + before_max_x < 8_000, + "the short path stays on the bridge, max x milli {before_max_x}" + ); + let bridge_portals = scratch.portal_len; + assert!(bridge_portals > 0, "the bridge crosses a tile portal"); + + tiles.mark(nav_change_from_kind( + NavChangeKind::Explosion, + 30, + 1, + [-1_000, -1_000, 17_000], + [5_000, 1_000, 31_999], + )); + assert!(tiles.commit_tick() >= 1); + let n = tiles.query_path(&mut scratch, start, goal); + assert!( + n >= 2, + "reroute path {n} portals {} lost_cover {}", + scratch.portal_len, + tiles.lost_cover_count + ); + let after_max_x = max_waypoint_x(&scratch); + assert!( + after_max_x > 16_000, + "the reroute uses the ford, max x milli {after_max_x}" + ); + assert!( + scratch.portal_len > 0, + "the ford still crosses a tile border" + ); + } + + fn max_waypoint_x(scratch: &NavScratch) -> i32 { + let mut max_x = i32::MIN; + for i in 0..scratch.waypoint_len as usize { + max_x = max_x.max(milli(scratch.waypoints[i].x)); + } + max_x + } + + #[test] + fn changes_apply_in_tick_seq_order() { + let mut a = five_tiles(); + let mut b = five_tiles(); + let first = nav_change_from_kind(NavChangeKind::Brush, 1, 0, [0, -1, 0], [1_000, 1, 1_000]); + let second = nav_change_from_kind( + NavChangeKind::Brush, + 1, + 1, + [32_000, -1, 0], + [33_000, 1, 1_000], + ); + a.mark(second); + a.mark(first); + b.mark(first); + b.mark(second); + let _ = a.commit_tick(); + let _ = b.commit_tick(); + assert_eq!(a.slot_hash(0, 0), b.slot_hash(0, 0)); + assert_eq!(a.slot_hash(1, 0), b.slot_hash(1, 0)); + } + + #[test] + fn four_commits_leave_the_highest_tile_dirty() { + let mut tiles = five_tiles(); + for cx in 0..5 { + tiles.mark(nav_change_from_kind( + NavChangeKind::Brush, + 1, + cx as u32, + [cx * 32_000, -1, 0], + [cx * 32_000 + 500, 1, 500], + )); + } + let done = tiles.commit_tick(); + assert_eq!(done, TILE_COMMITS_PER_TICK); + assert_eq!(tiles.dirty_len(), 1); + assert_eq!(tiles.dirty_coord(0), Some((4, 0))); + } + + #[test] + fn mismatched_side_buffer_is_ignored() { + let mut tiles = five_tiles(); + tiles.mark(nav_change_from_kind( + NavChangeKind::Detach, + 1, + 0, + [0, -1, 0], + [500, 1, 500], + )); + tiles.apply_for_test(); + let slot = 0u16; + let before = tiles.slots[0].generation; + let mut buf = tiles.fill_side_buffer(slot); + buf.input_hash ^= 0xFFFF; + assert!(!tiles.accept_side_buffer(&buf)); + assert_eq!(tiles.slots[0].generation, before); + assert!(tiles.commit_tick() >= 1); + assert!(tiles.slots[0].generation > before); + } + + #[test] + fn four_tile_commits_fit_in_the_frame_budget() { + let mut tiles = five_tiles(); + for cx in 0..4 { + tiles.mark(nav_change_from_kind( + NavChangeKind::Explosion, + 2, + cx, + [cx as i32 * 32_000, -1, 0], + [cx as i32 * 32_000 + 500, 1, 500], + )); + } + let start = std::time::Instant::now(); + let done = tiles.commit_tick(); + let elapsed_ms = start.elapsed().as_secs_f32() * 1000.0; + assert_eq!(done, 4); + assert!( + elapsed_ms < FRAME_BUDGET_MS, + "4 tile commits took {elapsed_ms} ms, budget is {FRAME_BUDGET_MS} ms" + ); + } + + #[test] + fn geometry_notice_reasons_map_and_unknown_is_dropped() { + let brush = astraweave_destruction::GeometryNotice { + tick: 4, + x0: 1, + y0: 2, + z0: 3, + x1: 4, + y1: 5, + z1: 6, + reason: NOTICE_BRUSH, + }; + let mapped = nav_change_from_geometry_notice(&brush, 2); + assert_eq!(mapped.map(|change| change.kind), Some(NavChangeKind::Brush)); + assert_eq!(mapped.map(|change| change.seq), Some(2)); + assert_eq!(mapped.map(|change| change.min_milli), Some([1, 2, 3])); + let collapse = GeometryNotice { + reason: NOTICE_COLLAPSE, + ..brush + }; + assert_eq!( + nav_change_from_geometry_notice(&collapse, 0).map(|change| change.kind), + Some(NavChangeKind::Detach) + ); + let weave = GeometryNotice { + reason: NOTICE_WEAVE, + ..brush + }; + assert_eq!( + nav_change_from_geometry_notice(&weave, 0).map(|change| change.kind), + Some(NavChangeKind::Weave) + ); + let unknown = GeometryNotice { reason: 9, ..brush }; + assert!(nav_change_from_geometry_notice(&unknown, 0).is_none()); + } + + fn five_tiles() -> NavTiles { + let mut tris = Vec::new(); + for cx in 0..5 { + let x = cx as f32 * TILE_SIZE_M + 1.0; + push_quad(&mut tris, x, 1.0, x + 2.0, 3.0); + } + let mut tiles = NavTiles::new(0.4, 45.0); + let _ = tiles.ingest(&tris); + tiles + } + + impl NavTiles { + fn apply_for_test(&mut self) { + self.apply_pending(); + } + } +} diff --git a/docs/architecture/ai_pipeline.md b/docs/architecture/ai_pipeline.md index a9e0a98cce..8410606b95 100644 --- a/docs/architecture/ai_pipeline.md +++ b/docs/architecture/ai_pipeline.md @@ -8,7 +8,7 @@ domain: ai lifecycle_status: active integration_status: wired owns: [astraweave-ai, astraweave-behavior, astraweave-context, astraweave-coordination, astraweave-dialogue, astraweave-director, astraweave-embeddings, astraweave-llm, astraweave-memory, astraweave-npc, astraweave-persona, astraweave-prompts, astraweave-rag] -doc_version: "1.12" +doc_version: "1.13" last_verified_commit: 32afac52f --- @@ -20,7 +20,7 @@ last_verified_commit: 32afac52f |---|---| | **System name** | AI Pipeline (Perception → Reasoning → Planning → Action) — foundational AI-first substrate | | **Primary crates** | `astraweave-ai` (39 files / 30.5K LoC), `astraweave-behavior` (6 / 5K), `astraweave-llm` (29 / 23.5K), `astraweave-memory` (17 / 11.5K), `astraweave-director` (6 / 3.3K), `astraweave-npc` (6 / 1.7K), `astraweave-dialogue` (4 / 5K), `astraweave-coordination` (5 / 5.3K) — **8 crates, 112 files, ~85K LoC total** | -| **Document version** | 1.12 | +| **Document version** | 1.13 | | **Last verified against commit** | `32afac52f` | | **Last verified date** | 2026-05-12 | | **Status** | **Active foundation — AI-first citizen of the engine.** The canonical loop is stable and validated for 12,700+ agents @ 60 FPS (per `astraweave-ai/src/lib.rs:27`). The Arbiter / dual-executor / LLM fallback chain has shipped multiple iterations and is hardening continuously. Subsystems like Memory, Director, NPC, Dialogue, Coordination are each large enough to warrant per-system follow-up traces. | @@ -370,7 +370,8 @@ This section enumerates the load-bearing files. Per-file enumeration of all 112 | File | Role | Status | Notes | |---|---|---|---| | `astraweave-ai/src/lib.rs` | Module declarations + re-exports; performance summary at lines 22-27 | Active | 70 LoC | -| `astraweave-ai/src/core_loop.rs` | `PlannerMode`, `CAiController`, `dispatch_planner`; the canonical loop dispatcher | Active | With `ai-bt`, policy `default` ticks a behavior graph and other policies return `BehaviorDispatchError`. `ai-goap` / `ai-bt` enable the behavior crate | +| `astraweave-ai/src/core_loop.rs` | `PlannerMode`, `CAiController`, `dispatch_planner`; the canonical loop dispatcher | Active | `PlannerMode::Htn` is always available (2026-10-15). With `ai-bt`, policy `default` ticks a behavior graph and other policies return `BehaviorDispatchError`. `ai-goap` / `ai-bt` enable the behavior crate | +| `astraweave-ai/src/htn.rs` | HTN decomposition, utility-scored breaches and cover, LOD bands, `SpatialTick` | Active | Tick writes `[ActionSlot; 8]` and does not allocate. Caps at `HTN_EXPANSIONS_PER_TICK` (64). Weaving and hazard hooks are read and empty until those owners write them | | `astraweave-ai/src/orchestrator.rs` | `Orchestrator` trait, `OrchestratorAsync` trait, `RuleOrchestrator` | Active | The trait surface is the single contract every planner implements | | `astraweave-ai/src/tool_sandbox.rs` | `ToolVerb` enum (10 verbs), `ValidationCategory`, sandbox helpers | Active | Re-exported via `lib.rs:57` | | `astraweave-ai/src/ecs_ai_plugin.rs` | `AiPlanningPlugin`, `build_app_with_ai()`, `sys_ai_planning` system | Active | Plans every team-1 companion on the tick (legacy ids sorted, then ECS companions not already handled). A plan without `MoveTo`, or `try_build_snapshot`'s `SnapshotError`, records `AiPlanningFailedEvent` | diff --git a/docs/architecture/nav.md b/docs/architecture/nav.md index 07b6b6fdcd..65061cef56 100644 --- a/docs/architecture/nav.md +++ b/docs/architecture/nav.md @@ -9,7 +9,7 @@ lifecycle_status: active integration_status: wired summary: "Resolves the two-nav-crate conflict (astraweave-nav vs crates/astraweave-nav). nav.md §6" owns: [astraweave-nav] -doc_version: "1.1" +doc_version: "1.2" last_verified_commit: 7c29b8182 --- @@ -21,9 +21,9 @@ last_verified_commit: 7c29b8182 |---|---| | **System name** | Navigation / Pathfinding System (navmesh) | | **Primary crates** | `astraweave-nav` (top-level, workspace member) | -| **Document version** | 1.1 | -| **Last verified against commit** | `7c29b8182` | -| **Last verified date** | 2026-06-25 | +| **Document version** | 1.2 | +| **Last verified against commit** | `feat/ai-orchestration` | +| **Last verified date** | 2026-10-15 | | **Status** | Active (single-file library); consumers are mostly examples/tests — see §1 status note and §6 | | **Owner notes** | [Reasoning not recovered from available sources] — crate predates the architecture-trace campaign. Phase 10 "AI-Orchestrated Dynamic Terrain" added the region-invalidation block (lib.rs §520-629). | @@ -321,8 +321,8 @@ Source: [`docs/masters/MASTER_BENCHMARK_REPORT.md`](../masters/MASTER_BENCHMARK_ - **Is the AI navigability gate meant to be wired?** `tool_sandbox.rs`'s `MoveTo` nav check is fully implemented but only reachable via `ValidationContext::with_nav`, which has no production caller. Is this intended forward-design, or a missing wire-up in the AI runtime loop? (Context: CLAUDE.md Integration Completeness item 1.) - **Does any shipping app insert a `NavMesh` ECS resource?** The scripting plugin reads `world.get_resource::()`; if no app inserts that resource, `nav_ptr` is always null and `NavMeshProxy::find_path` returns `[]`. (Verification note 2026-06-25: one **example** app does insert it — `examples/scripting_advanced_demo/src/main.rs:32` calls `app.world.insert_resource(nav)` after baking a 2-triangle ground mesh, exercising the full `NavMeshProxy` path. The only other insert site is in scripting's own `#[cfg(test)]` block. No non-example shipping binary was found; whether a real runtime app is intended to insert the resource remains the owner's call.) - **Should `crates/astraweave-nav/` be reconciled?** It is an orphan (no manifest, stale bench copy). Its existence can mislead grep-based discovery into thinking there are two nav crates. (Surfaced factually per §6; disposition is the owner's call.) -- **Is `max_step` intended to gain meaning?** It is plumbed through every API and test but read by nothing. Either step-height filtering is unimplemented forward-design, or the parameter is vestigial. -- **`partial_rebake` incrementality:** the function's own doc-comment notes the partial path is unimplemented (delegates to full bake). Is incremental rebake a planned follow-up? +- **`max_step` (closed 2026-10-15):** a shared XZ edge links only when the vertical gap is at most `max_step`. Coplanar edges are unchanged. The stair golden is `max_step_links_a_low_ledge_and_rejects_a_tall_one`. +- **`partial_rebake` (closed 2026-10-15):** relinks triangles that meet a dirty AABB and leaves other vertices in place. Tiled commits live in `src/tiles.rs` and stop at `TILE_COMMITS_PER_TICK` (4). - **Scaling:** 10K-tri bake at 473 ms (O(n²) adjacency) is flagged "must be async" in the benchmark report. Is large-mesh baking expected to move off the main thread or precompute offline? --- @@ -347,7 +347,7 @@ Source: [`docs/masters/MASTER_BENCHMARK_REPORT.md`](../masters/MASTER_BENCHMARK_ **If you're working on this system, remember:** 1. There is exactly **one** `NavMesh` implementation: `astraweave-nav/src/lib.rs`. `crates/astraweave-nav/` is an orphan bench file, not a second crate — do not "fix" it into the build without the owner's call. -2. **`max_step` does nothing.** Don't assume step-height filtering happens; only slope + upward-facing filtering does. +2. **`max_step` filters ledge links.** A shared XZ edge taller than `max_step` is not a neighbor. Slope and upward-facing filters still apply. 3. Pathing is **center-to-center A* + generic smoothing**, not a funnel/string-pull. Don't claim taut/optimal paths. 4. The AI `MoveTo` nav gate is real code but **dormant** (no production `with_nav` caller). The genuinely-wired runtime consumer is the **scripting `NavMeshProxy`** (ECS `NavMesh` resource) and the **editor** Bake button. @@ -360,7 +360,7 @@ Source: [`docs/masters/MASTER_BENCHMARK_REPORT.md`](../masters/MASTER_BENCHMARK_ **Common mistakes when changing this system:** - Adding a "second navmesh path" — there is no peer; extend `lib.rs` (CLAUDE.md scope-discipline rule). -- Treating `partial_rebake` as incremental — it does a full `bake`. +- Treating `partial_rebake` as a full `bake`. It relinks dirty triangles only. Tile commits are `NavTiles::commit_tick`. - Assuming `find_path` does point-in-triangle containment — `closest_tri` is a nearest-*center* scan, so off-mesh queries still snap somewhere. - Adding behavior keyed on `max_step` without wiring it into `bake`/`find_path` first. @@ -368,4 +368,6 @@ Source: [`docs/masters/MASTER_BENCHMARK_REPORT.md`](../masters/MASTER_BENCHMARK_ ## Appendix B: Historical context +Revision 1.2 (2026-10-15): `max_step` rejects tall ledges; `partial_rebake` no longer calls a full bake; `src/tiles.rs` adds 32 m tiles, a 4-tile commit, and a side buffer accepted only when its input hash matches `build` of the current sources. + The crate is one of the engine's earliest "P0" foundation crates: it appears throughout the Phase 0 / Week 1-6 coverage and benchmark journey docs (e.g. `docs/journey/phases/PHASE_0_WEEK_1_*`, `docs/archive/NAVIGATION_BENCHMARK_RESULTS.md`) and was a target of the mutation-testing campaign (`docs/journey/phases/PHASE_10_MUTATION_TESTING_PLAN.md`, shard outputs under `archive/mutation_outputs/`). The region-invalidation block (lib.rs §520-629) was added under Phase 10 "AI-Orchestrated Dynamic Terrain" to let runtime terrain edits mark the mesh stale. The `#![forbid(unsafe_code)]` attribute and doc-test/dep-hygiene pass landed in commit `e060d7973`. The minimal dependency footprint (only `anyhow` + `glam`) is deliberate per the README ("Minimal dependency footprint"). diff --git a/docs/current/AI_ORCHESTRATION_ARCHAEOLOGY.md b/docs/current/AI_ORCHESTRATION_ARCHAEOLOGY.md new file mode 100644 index 0000000000..aca02afb35 --- /dev/null +++ b/docs/current/AI_ORCHESTRATION_ARCHAEOLOGY.md @@ -0,0 +1,385 @@ +# AI orchestration archaeology and upgrade plan + +Survey of `main` at `85d09a2c` (2026-10-15). Phase 1 only. No runtime code. Implementation waits on the review questions in §10. + +Status words used below: + +| Status | Meaning | +|---|---| +| REAL | A non-test caller outside the owning crate exercises it. Demos and the editor count, and are marked as such. | +| STUBBED | The function exists and its comment promises incremental or spatial behavior the body does not perform. | +| DORMANT | It compiles, and often has tests, and no shipping caller runs it. Feature-off with no workspace crate enabling the feature counts. | +| UNTESTED | A shipping path has no test that would fail if the behavior changed. | +| ABSENT | No type and no algorithm in `*.rs`. | + +## 1. What is wired today + +The loop that actually runs is a 2D grid companion planner. It does not see destroyed cover, breaches, or a navmesh. + +| Path | What it calls | Where | +|---|---|---| +| ECS planning, default features | `RuleOrchestrator` | `astraweave-ai/src/ecs_ai_plugin.rs` (`sys_ai_planning`, the `not(feature)` arm) | +| `examples/hello_companion` default | `RuleOrchestrator`, then `validate_and_execute` on the grid | `examples/hello_companion/src/main.rs` | +| `hello_companion` GOAP flag | `GoapOrchestrator` in `astraweave-ai`. That type is a one-step Manhattan heuristic. It is not `GoapPlanner`. | `astraweave-ai/src/orchestrator.rs` | +| `hello_companion --utility` | Local `calculate_*_score` functions in the example. Not `UtilityOrchestrator`. | `examples/hello_companion/src/main.rs` | +| IPC | `RuleOrchestrator` | `astraweave-ipc/src/lib.rs` | +| Slice runtime, feature-gated | Companion orchestrator calls `astraweave-behavior`'s `GoapPlanner` (real A*). | `astraweave-ai/src/veilweaver.rs`, feature `veilweaver_slice` in `astraweave-ai/Cargo.toml`; `GoapPlanner` in `astraweave-behavior/src/goap.rs` | +| Movement validation on that grid | `path_exists` over `IVec2` obstacles | `astraweave-core/src/validation.rs`, `astraweave-core/src/tools.rs` | + +`hello_companion` builds its app with `build_app` and does not install `AiPlanningPlugin`. The plugin's only non-test example caller is `examples/ecs_ai_demo`. + +`WorldSnapshot` is the perception product (`astraweave-core/src/schema.rs`). Fields are `t`, `player`, `me`, `enemies`, `pois`, `obstacles: Vec`, `objective`. There is no navmesh, no height, no destruction record. `build_snapshot` (`astraweave-core/src/perception.rs`) sets every visible enemy's cover from a Manhattan check against `los_max` (far → unknown, near → low) and always emits one POI named `breach_door` at `(15, 8)`. The ECS-only arm of `sys_ai_planning` builds a snapshot with `obstacles: vec![]` and `t: 0.0`. + +Nothing in this loop subscribes to physics destruction or terrain edits. + +## 2. Inventory + +### 2.1 Planners in `astraweave-ai` + +`astraweave-ai/src/lib.rs` declares `core_loop`, `ecs_ai_plugin`, `orchestrator`, `tool_sandbox`. The rest is feature-gated or not a module. + +| Surface | Status | Evidence | +|---|---|---| +| `Orchestrator` / `RuleOrchestrator` | REAL | `astraweave-ai/src/orchestrator.rs`. Callers in §1. Allocates a `String` plan id and a `Vec` of steps on every call. | +| `GoapOrchestrator` (heuristic) | REAL in the demo only | `orchestrator.rs`. The doc comment on the struct says it is not the symbolic planner. | +| `UtilityOrchestrator` | DORMANT | `orchestrator.rs`. Zero non-test callers. Scores two smoke/advance candidates into a fresh `Vec`. | +| `PlannerMode`, `CAiController`, `dispatch_planner` | DORMANT | `astraweave-ai/src/core_loop.rs`. No shipping caller. `ai-goap` and `ai-bt` are off, and no workspace `Cargo.toml` enables them. | +| `LlmOrchestrator`, `AIArbiter`, `LlmExecutor`, `AsyncTask` | DORMANT | Gated by `llm_orchestrator` (default off). `AIArbiter::` has no non-test constructor. Runtime model string when that path is built is `phi3:medium` (`orchestrator.rs`). A live model is not deterministic. | +| `make_system_orchestrator` | DORMANT | Same file. Default branch constructs `UtilityOrchestrator`. | +| `tool_sandbox::validate_tool_action` and `ValidationContext::with_nav` | DORMANT | `astraweave-ai/src/tool_sandbox.rs` (`with_nav`, `MoveTo` arm calls `nav.find_path`). Tests and benches only. The engine gate remains `validate_and_execute`. | +| `astraweave-ai/src/goap/` (22 files, `plan_decomposed`) | DORMANT | Feature `planner_advanced` (default off). `plan_decomposed` (`goap/planner.rs`) splits a goal into sub-goals and runs A*. It returns `Vec` action names. `GOAPOrchestrator` in that tree does not implement `Orchestrator`. Bins under `src/bin.disabled/` are not crate targets. | +| `astraweave-ai/src/persona/`, `astraweave-ai/src/rag/` | DORMANT, not compiled | No `mod` line in `lib.rs`. Feature `rag = []` wires nothing. | +| AI LOD, tick budget, interest management for agents | ABSENT | No `AiLod` / `tick_budget` in `*.rs`. `budget_ms` on `OrchestratorAsync` is an LLM timeout. | + +`sys_ai_planning` allocates on every tick: `Box`, job `Vec`s, `BTreeSet`, and `reason.to_string()` (`ecs_ai_plugin.rs`). + +### 2.2 Behavior trees and the real GOAP + +| Surface | Status | Evidence | +|---|---|---| +| `BehaviorGraph` / `BehaviorNode` | REAL | `astraweave-behavior/src/lib.rs`. Sequence, selector, action, condition, decorator, parallel. Used by `hello_companion` and the editor. This is not an HTN: there are no methods, branches, or backtracking preconditions. | +| `GoapPlanner` (A* over interned facts) | REAL inside the slice runtime only | `astraweave-behavior/src/goap.rs`. Non-test caller is `astraweave-ai/src/veilweaver.rs`. | +| `CachedGoapPlanner` | DORMANT | `astraweave-behavior/src/goap_cache.rs`. Tests and benches. | +| `behavior_tick_system` | REAL in the slice runtime | `astraweave-behavior/src/ecs.rs`. Collects `to_update = vec![]` every tick. | + +### 2.3 HTN and utility + +| Idea | Status | +|---|---| +| HTN planner (compound tasks, ordered methods, backtracking) | ABSENT. The behavior crate's module docs mention HTN. The node enum is a behavior tree. `plan_decomposed` is goal splitting on top of GOAP, feature-off, and unwired. | +| Utility as a consideration stack (curves, weights, position scores) | ABSENT. `UtilityOrchestrator` and the `hello_companion` scores are a fixed handful of combat steps. | + +### 2.4 Memory, RAG, persona, coordination (PR #213's crates) + +On `main` these crates are implemented and tested, and they are not on the planning tick. + +| Crate | Status on `main` | Note | +|---|---|---| +| `astraweave-memory` | DORMANT for the planning tick | No `use` from `astraweave-ai`. `astraweave-persistence-ecs` declares the dep and does not use it. | +| `astraweave-embeddings` | DORMANT; search is a linear scan | `VectorStore::search` calls `brute_force_search` (`astraweave-embeddings/src/store.rs`). `hnsw_rs` is a dependency and is not referenced from `src/`. | +| `astraweave-rag`, `astraweave-context` | DORMANT for the planning tick | Held by LLM-side modules and examples. | +| `astraweave-persona` | Zip loader is demo-real (`examples/persona_loader`). LLM manager is DORMANT. | | +| `astraweave-coordination` | DORMANT | No non-test caller. | +| `astraweave-npc` | Demo-real only | `examples/npc_town_demo`. Not in the ECS planning stage. | +| `astraweave-dialogue` graph / TOML | REAL | Editor and the slice runtime. | +| `astraweave-dialogue/src/llm_dialogue.rs` | DORMANT, not a module | Issue #225. See §9. | +| `astraweave-director` heuristic warden | REAL in the slice runtime | LLM director is DORMANT. | + +PR #213 (`cursor/engine-ws-ai2`, draft) is the owner of wiring those crates. Its `sys_ai_depth` (`astraweave-dialogue/src/depth_tick.rs` on that branch) calls memory, embeddings, RAG consolidation, prompts, context, persona, NPC `RulePlanner`, and coordination once per fixed step. It does not call a live model. A missing log line becomes the rendered prompt with a `scripted:` prefix. `SimRng` is seeded and not drawn. That branch adds `SIM_SYSTEM_HNSW = 0xA1DE_7001` and `SIM_SYSTEM_LLM_DIALOGUE = 0xD1A1_7001`. It also adds a real HNSW index whose level draw uses `SimRng`. This plan does not edit that tick and does not compile `llm_dialogue.rs`. + +### 2.5 Navigation + +The production implementation is one file: `astraweave-nav/src/lib.rs`. `crates/astraweave-nav/` is an orphan benchmark with no `Cargo.toml`. + +`NavMesh::bake` filters triangles (degenerate, downward, slope via `acos`), then builds adjacency with an O(n²) `share_edge` loop. `find_path` snaps to the nearest triangle center (linear scan), runs A* on centers, and smooths with two 0.25/0.5/0.25 passes. Endpoints are not constrained to the mesh. `max_step` is stored and never read. + +| Surface | Status | Evidence | +|---|---|---| +| `bake` / `find_path` | REAL implementation. Runtime callers are the editor bake button and the scripting proxy. | `tools/aw_editor/src/main.rs` (bake). `astraweave-scripting/src/api.rs` (`find_path`) if some caller inserted a `NavMesh` resource. The non-test insert is `examples/scripting_advanced_demo`. | +| `invalidate_region`, `rebake_dirty_regions` | DORMANT | Tests only. `rebake_dirty_regions` always calls full `bake`. | +| `partial_rebake` | STUBBED | `astraweave-nav/src/lib.rs`. It counts triangles whose AABB hits a dirty region, then calls `rebake_dirty_regions`. The comment says a production system would rebuild the affected portion. | +| Recast, Detour, `dtNavMesh`, tile cache | ABSENT | Docs under `docs/src/` mention them. No Rust nav code does. | +| Editor navigation panel bake | STUBBED | `tools/aw_editor/src/panels/navigation_panel.rs` logs and does not call `bake`. The working button is in `main.rs`. | +| `astraweave-gameplay` weave path | STUBBED | `astraweave-gameplay/src/weaving.rs` binds `NavMesh::bake` to `_nav` and drops it. | +| Portal graph `string_pull` | DORMANT | `astraweave-gameplay/src/weave_portals.rs`. Tests only. | +| Flow fields | ABSENT | | +| `find_cover_positions` | DORMANT | `astraweave-core/src/tools.rs`. Tests only. | +| Terrain `NavMeshRegion` | DORMANT bridge | `astraweave-terrain` records dirty regions. Nothing calls `NavMesh::invalidate_region`. | +| `DestructionEvent` | No nav subscriber | `astraweave-physics/src/destruction.rs`. | + +There is no tile id, no border portal, and no generation counter. + +### 2.6 Destruction events this plan has to consume + +PR #243 (`feat/destruction`, draft, docs only) has no crate yet. The design's log is the event source: + +```rust +DestructionCommand { tick, seq, entity_id, kind } +CommandKind::{ Impact, Explosion, Brush, Detach, Anchor } +``` + +Applied in `(tick, seq, entity_id)` order inside the 60 Hz tick. Coordinates in the log are `Fixed64` or integers. `SIM_SYSTEM_DESTRUCTION = 0xD357_7001` in that design. The design does not mention navmesh. This plan does not add fracture, debris, or terrain deltas. It consumes AABBs derived from commands that change walkable geometry (`Explosion`, `Brush`, `Detach`). + +On `main`, `DestructionManager` does not drive nav. Do not extend it. #243 already rejected that module as the destruction owner. + +### 2.7 Traversal and combat, so this plan does not absorb them + +PR #244 (`feat/traversal-archaeology`, draft) owns displacement: climb, swim, vault, the character motor. The wired move on `main` is `PhysicsWorld::control_character` (`astraweave-physics/src/lib.rs`), a kinematic capsule. This plan emits a path and a plan. It does not move the body and does not add ledge probes. + +PR #212 (`cursor/combat-damage-design`, draft) owns `resolve_hit` / `resolve_heal` and `StatKnowledge` (`astraweave-combat/src/resolve.rs` on that branch). `SIM_SYSTEM_COMBAT = 0xC0BA_7001`. AI estimates read the mask. This plan does not resolve hits. A later utility term may read `StatKnowledge` the way that PR documents; it does not read hidden stats. + +### 2.8 Determinism already on `main` + +`SimRng` is `astraweave-core/src/sim.rs`: `(world_seed, tick, system_id)` into ChaCha12 via `mix_sim_seed`. Ids on `main`: + +| Id | Constant | +|---|---| +| `0xC2AF_7001` | `SIM_SYSTEM_CRAFT` | +| `0xC2AF_7002` | `SIM_SYSTEM_HARVEST` | +| `0xAE11_7001` | `SIM_SYSTEM_ANCHOR_PARTICLES` | +| `0xAE11_7002` | `SIM_SYSTEM_ENEMY_PATROL` | +| `0xAE11_7003` | `SIM_SYSTEM_SPAWNER` | +| `0x7E22_7001` | `SIM_SYSTEM_TERRAIN_SOLVER` | + +`.github/workflows/determinism-replay.yml` requires `planner_pure` and `perception_world` from `astraweave-core/tests/replay_hash.rs`. Both hash the grid snapshot and `RuleOrchestrator` / heuristic GOAP. Neither loads a navmesh, removes a bridge, nor checks a reroute. + +Nav bake calls `f32::acos`. That is a libm input. The replay workflow already pins `target-cpu=x86-64` on x86_64 and forbids `target-cpu=native`. + +### 2.9 Aravath demo + +`aravath_runtime/` is not on `main`. `docs/current/ENGINE_PRODUCTION_ROADMAP.md` places it on `cursor/aravath-greybox-b3de`. This PR does not edit that tree and does not add assets. + +## 3. What shipped games published + +These are the sources for the decision in §4. They are not claims about this repository. + +**F.E.A.R. GOAP.** Jeff Orkin, "Three States and a Plan: The A.I. of F.E.A.R." (GDC 2006). Each action has preconditions, effects, and a cost. Regressive A* searches the action space from the goal. Squad mates share the action set and differ by cost. The action set is small, and the search replans when the world invalidates the plan. That is the shape of `GoapPlanner` in `astraweave-behavior`: a flat A* over symbolic facts. It does not decompose a domain, and the cost grows with the action set. An open-world activity list (travel, use a breach, take cover, flee, regroup) makes that search the wrong inner loop for every agent every tick. + +**Killzone position evaluation, then Killzone 2 HTN.** Guerrilla's GDCE 2005 Killzone slides ("Dynamic procedural tactics") score candidate waypoints with a weighted sum: proximity, line of fire to the primary threat, cover from secondary threats, preferred range. The highest score wins. Tactical path costs add exposure and friendly lines of fire onto A* links. Tim Verweij's Killzone 2 multiplayer bots (Paris Game AI Conference 2009) put HTN on the individual, with strategy and squad layers above it, and replan on a fixed cadence. The position score is how a method chooses a place. It is not the planner. + +**Horizon / Decima HTN, plus utility.** Guerrilla, "The AI of Horizon Zero Dawn" (17 October 2017), states the combination directly: HTN planning and utility-based decision making, plus navigation for agents of different sizes in a dynamic environment. Their planner writeup decomposes an abstract task through ordered branches. Each branch has declarative preconditions and replacement tasks. Failure backtracks. Tim Verweij, "HTN Planning in Decima" (2024), is the same planner: backtracking over preconditions, compiled to generated code. Individual machines request a plan; group agents assign roles. Julian Berteling's GDC talk "Beyond Killzone: Creating New AI Systems for Horizon Zero Dawn" is the navigation and animation half of that jump from corridors to an open world. + +**The Division.** The public Massive talk is Jonas Gillberg, "AI Behavior Editing and Debugging in Tom Clancy's The Division" (GDC). Snowdrop authors behavior trees, with shared tools so designers can edit and debug a large NPC set. It is not a published utility architecture. This repo already has that layer (`BehaviorGraph`). Copying it again does not add spatial replanning. + +**Recast / Detour tiles.** `dtTileCache::update` rebuilds tiles touched by obstacle requests, one tile per call, from a compressed heightfield plus cylinder or box obstacles (`DetourTileCache.h`). That is the right schedule (bounded work, tile ids, publish into `dtNavMesh`). It is the wrong edit model for a collapsed bridge or a reshaped crater: those change source triangles, and the tile cache only stamps boxes and cylinders. Structural edits use `removeTile` / `addTile` (or `buildNavMeshTilesAt`) from the new geometry. Recast's raster and contour steps are `f32` C++. Putting that library on the sim hash fights the cross-OS replay rule. The idea to keep is the tile, the border link, and the bounded commit. The code to keep is `astraweave-nav`. + +## 4. Decision + +**Upgrade `astraweave-nav` in place, and add an HTN whose method choice is a utility score. Do not add a second planner crate, a second nav crate, or a Recast dependency. Do not revive the advanced GOAP tree or `AIArbiter` as this system.** + +Rejected: + +| Option | Why not | +|---|---| +| Make `GoapPlanner` the open-world planner | Flat action search. The only shipping caller is the slice companion. Scaling it to every agent reallocates `WorldState` and strings, which §5 forbids. | +| Finish `astraweave-ai/src/goap/` | Second GOAP, feature-off, does not implement `Orchestrator`, returns action-name strings. Wiring it duplicates `astraweave-behavior`. | +| Grow `UtilityOrchestrator` | No task stack, no backtrack, no spatial query. Two hardcoded candidates. | +| Grow `BehaviorGraph` into an HTN | Different data model (tick status vs. a decomposed plan). The Division talk is why the tree stays as an authored executor, not why it becomes the massive-agent planner. | +| Vendor Recast | `f32` C++ on the sim hash, and `dtTileCache` does not rebuild source geometry. | +| New nav crate beside `astraweave-nav` | `crates/astraweave-nav` is already the orphan that mistake produces. | +| Live LLM / `AIArbiter` on the tick | Not deterministic. #213 already proved the depth tick can run with a recorded line and no model. | + +What stays: + +- `RuleOrchestrator` remains the far-band fallback and the existing replay cases `planner_pure` / `perception_world`. +- `WorldSnapshot` field names stay. LLM prompts and the grid planners read them. The new spatial view is a separate struct. +- `BehaviorGraph` stays for authored scenes and the slice. The hot tick does not call `behavior_tick_system`. +- `GoapPlanner` stays for the slice companion. This work does not retarget it. +- Editor `NavMesh::bake` and scripting `find_path` keep their signatures. Tile rebuild is a new type next to `NavMesh`, and `partial_rebake` delegates to it instead of pretending. + +## 5. Phase 2 design (not in this PR) + +### 5.1 Nav tiles + +New type `NavTiles` in `astraweave-nav`. Fixed world tile size (proposed 32 m; §10). Each tile stores its own triangles and neighbor indices. Border portals are edges that match a portal on `tile_id ± 1` within the existing `1e-3` epsilon, stored in sorted `(tile, edge)` order. + +`NavChange` is the only input from the world: + +```rust +pub struct NavChange { + pub tick: u64, + pub seq: u32, + pub min_milli: [i32; 3], + pub max_milli: [i32; 3], +} +``` + +A change marks every tile the milli-unit AABB overlaps. Dirty tile ids sit in a sorted unique list. + +**Commit.** At most `K` tiles per tick (proposed `K = 4`, matching #243's remesh cap). The sim thread rebuilds the lowest `K` dirty ids, in order, by calling one pure function `build_tile(tris, params) -> Tile`. Publish replaces those slots in the immutable table the AI stage borrows. Agents do not take a lock. A worker may run `build_tile` into a side buffer. The sim accepts that buffer only when its input hash equals the hash of the triangles it would have built itself. Otherwise the sim builds the tile. Thread completion order never changes which ids commit. That is the reading of the determinism rule that allows async work: the async result is bit-identical to the CPU function, and the commit set is order-independent. + +`partial_rebake` stops calling full `bake`. It pushes one `NavChange` per dirty AABB and commits. `rebake_count` remains the number of commits. Tests that assumed a full rebuild of unaffected triangles get updated in that commit, because those tests currently lock in the stub. + +Path query reads the published table only. A* walks tile-local neighbors and border portals. The open set is a fixed array in `NavScratch` (cleared, not freed). Waypoints are written into a caller-provided buffer. No `Vec` growth on the query. + +Slope filtering stays a dot test against a precomputed cosine threshold so the hot rebuild does not call `acos`. `max_step` becomes a real reject: a shared edge whose height delta exceeds `max_step` is not a portal. Today the field is inert; changing that is behavior, called out in §10. + +Cover and breaches fall out of the same publish. A triangle that lost all walkable neighbors on one side is cover. A border portal that exists this generation and did not exist last generation is a breach. Both lists are sorted by id. The hardcoded `breach_door` POI is not an input. + +### 5.2 Mapping #243's log + +When `DestructionCommand` exists, a single adapter appends `NavChange` values in the log's existing order: + +| Command | AABB | +|---|---| +| `Explosion` | center ± radius, quantized once at the edge | +| `Brush` | cell origin and radius or half extents | +| `Detach` | the detached node's chunk AABB | +| `Impact` | omitted until debris occupancy is queryable | +| `Anchor` | no nav change | + +Until that crate merges, the replay and the unit tests construct `NavChange` directly. This branch does not copy `DestructionCommand` and does not depend on a crate that is not on `main`. + +### 5.3 HTN plus utility + +New module `astraweave-ai/src/htn.rs`, always compiled, implements `Orchestrator` for the grid snapshot so the old tests still type-check, and a second entry `plan_spatial` for the nav-aware tick. + +A domain is static data: compound tasks, methods with an ordered branch list, preconditions as predicates over a borrowed `SpatialView`. Decomposition follows Horizon's order: try branches top to bottom, bind the first whose preconditions hold, backtrack when a child fails. No search over an action set. + +The method that needs a place (take cover, use breach, cross) does not hardcode a cell. It scores candidates from the nav publish with integer weights, in the Killzone form: + +- distance in milli-units from the agent +- the candidate still exists after the last commit (destroyed cover scores zero and drops out) +- a new breach portal that shortens the remaining path +- preferred range band + +Tie-break is lower candidate id. No `SimRng` draw. Equal costs cannot depend on `HashMap` iteration. + +The plan is written into `[ActionSlot; 8]` on the agent. `ActionSlot` is a copy of the `ActionStep` variants the tick needs (`MoveTo` cell or waypoint index, `CoverFire`, `Wait`). No `String` plan id. The id is `(tick, entity_id)`. + +`plan_spatial` does not call `MemoryManager`, `VectorStore::search`, `RagPipeline`, or `sys_ai_depth`. Those stay on #213's tick. A later step may copy a fixed `Consideration` struct that #213 has already produced. It is not in the first implementation steps, and it is not read from inside HTN if the copy is missing. + +### 5.4 LOD and the tick budget + +Agents are sorted by `(band, entity_id)` once per tick. Bands use distance to the player in milli-units: + +| Band | Work | +|---|---| +| 0 | Full HTN. Replan when a committed tile intersects the current path, and at least every 30 ticks. | +| 1 | Utility choice among the methods of the current compound task. No backtrack. | +| 2 | Keep the last plan. If none, one `RuleOrchestrator` step. | +| 3 | Not visited. | + +The tick spends at most `H` HTN expansions (proposed `H = 64`) and the nav stage spends at most `K` tile builds. Agents past the budget keep their last plan and sort first next tick only within their band, still by entity id, so the set is a pure function of the world. There is no mutex and no channel wait on this path. + +The legacy `sys_ai_planning` body is not the hot path. The new system is a separate schedule stage that runs after the nav commit and does not allocate the `Box` per tick. `RuleOrchestrator` stays for the grid replay cases. + +### 5.5 Reserved `SimRng` ids + +Planning and tile builds draw no random numbers. Reserve the ids so a later tie-break cannot collide: + +| Constant | Value | Collides with | +|---|---|---| +| `SIM_SYSTEM_NAV` | `0x4E41_7001` | none of §2.8, #212, #213, or #243 | +| `SIM_SYSTEM_HTN` | `0x4854_7001` | none of those | + +### 5.6 Replay case `nav_reroute` + +Added to the `required` set in `.github/workflows/determinism-replay.yml`. The case lives next to the existing core replay test (a dev-dependency on `astraweave-nav` and `astraweave-ai` from that test, or a thin test in `astraweave-ai` that writes the same `target/replay-hash.json` shape #213 uses). The workflow compare already fails a missing required name. + +Script, fixed 60 Hz, seed recorded in the test: + +1. Tiles for a span: a bridge over a gap, and a longer ford beside it. +2. One agent, goal on the far side. The first path's portal ids cross the bridge. +3. At tick 30, one `NavChange` covers the bridge AABB (the same shape an `Explosion` or `Detach` will produce). +4. The following ticks commit that tile with the bridge triangles removed. +5. The agent replans. The new path uses the ford. The hash covers the committed tile ids, the portal id sequence, and the `ActionSlot` buffer. + +The hash is SHA-256 of little-endian integers and `u32` bit patterns. It does not hash a `Debug` string or a `HashMap`. Ubuntu, Windows, and macOS must print the same digest. The case does not start a worker thread. Workers are tested separately by checking `build_tile` equality against the sim path. + +`planner_pure` and `perception_world` stay required. If #212, #213, or #243 have already added `combat_resolve`, `ai_depth_tick`, or `destruction` on `main` by the time this lands, the required set keeps them. + +### 5.7 Aravath showcase + +After the replay case is green, and only when `aravath_runtime` is on the branch being integrated: one agent walks a CC0 bridge (KayKit or Kenney, already licensed on that branch; no new pack), the destruction log drops the span, the agent takes the ford. HUD strings say Aravath. This PR does not add the scene. + +## 6. Coordination + +| PR | Boundary | +|---|---| +| #213 | Do not edit `sys_ai_depth`, embeddings, or `llm_dialogue.rs`. Do not call RAG or the linear scan from the HTN tick. `SIM_SYSTEM_HNSW` and `SIM_SYSTEM_LLM_DIALOGUE` stay theirs. | +| #243 | Nav is a consumer of `Explosion`, `Brush`, and `Detach` AABBs. No support graph, fracture, debris, or terrain delta in this work. `SIM_SYSTEM_DESTRUCTION` stays theirs. | +| #244 | Paths stop at waypoints. Climb, mantle, swim, and the motor stay there. No character controller edits. | +| #212 | No `resolve_hit`. A utility term may later take `StatKnowledge` and must ignore masked fields. `SIM_SYSTEM_COMBAT` stays theirs. | + +Also out of scope: `astraweave-director`, `astraweave-npc` physics stepping, the editor navigation panel beyond the existing bake button, and any asset under `assets/`. + +## 7. Phase 2 order, after approval + +Each step is its own commit. `cargo check -p` for the crate just touched, then that crate's tests. Stop if a pre-existing failure shows up (§9). + +1. `NavTiles`, `NavChange`, sorted dirty ids, `build_tile` without `acos`. `partial_rebake` delegates. Existing `find_path` tests stay on `NavMesh` until a later commit opts callers in. +2. Border portals, scratch-buffer A*, destroyed-cover and new-breach lists. +3. Replay case `nav_reroute` and the workflow required set. Sync commit only. +4. Side-buffer acceptance test: a mismatched input hash is ignored and the sim builds the tile. +5. HTN domain, utility method scores, `[ActionSlot; 8]`, LOD bands, expansion budget. No call into #213's crates. +6. Adapter comment and a pure function from `(kind tag, milli AABB)` so #243 can append `NavChange` without this crate importing destruction. +7. Trace updates: `docs/architecture/nav.md` and `docs/architecture/ai_pipeline.md` (§5 file map, §8 invariants, §11, revision history). Then `cargo run -p aw_trace_sync -- --write` if front-matter changed. +8. Aravath call site when that runtime is on the branch. CC0 bridge. Player text says Aravath. + +## 8. Tests that define "done" + +| Test | Asserts | +|---|---| +| Tile isolation | Editing one tile does not change another tile's bytes | +| Stub gone | `partial_rebake` leaves triangles outside the AABB identical | +| Bridge | Path portal ids cross the bridge, then the ford, after one `NavChange` | +| Order | Two changes in either insertion order commit in `(tick, seq)` order | +| Budget | Five dirty tiles and `K = 4` leave the highest id dirty | +| No heap on the query | The path query and `plan_spatial` record zero allocations under the existing `alloc-counter` feature (the `alloc_measure` bench pattern) | +| No lock | The AI stage holds no `Mutex` guard; the published table is a shared borrow | +| Determinism | `nav_reroute` identical on three OS | +| Ties | Two equal utility scores pick the lower id | +| Dropped cover | A cover candidate inside the committed tile disappears from the score list | + +`cargo clippy -p astraweave-nav -p astraweave-ai --all-features -- -D warnings` on the commits that touch them. Unsafe stays forbidden in `astraweave-nav`. + +## 9. Pre-existing failures + +| Item | Disposition | +|---|---| +| `partial_rebake` full-bake stub | This plan's step 1. Not a separate defect to file. The tests pass because they assert the stub. | +| `llm_dialogue.rs` does not compile (`rand::thread_rng`, API drift, 69 errors) | Already open as issue #225, label `deferred-failure`. Owner is the #213 line. This work does not declare the module. | +| `DestructionManager` has no nav subscriber | #243 owns destruction and already rejected extending that manager. This plan will not file a second issue. | +| Inert `max_step` | Fixed only if §10 accepts the behavior change. Until then it stays a documented inert field, not a silent change. | +| CI on #213 (editor, deny, toolchain, benchmark shard) | Their branch, not `main`. Not reproduced here. Not absorbed. | + +No new `deferred-failure` issue is opened by this PR. The failures above already have an owner or are the work itself. + +## 10. Review questions + +1. Confirm the hybrid: HTN decomposition with Killzone-style utility scores for places, `RuleOrchestrator` only as the far band, no GOAP revival, no Recast. +2. Confirm async means a bit-identical side buffer, and the sim still commits the lowest `K` tile ids itself when the buffer does not match. Replay does not depend on worker timing. +3. Confirm `NavChange` milli-unit AABBs are the #243 seam (`Explosion`, `Brush`, `Detach` only), and this crate does not take a dependency on destruction until that crate is on `main`. +4. Confirm tile size 32 m, `K = 4` tile commits per tick, `H = 64` HTN expansions per tick, and bands at fixed milli-unit radii. +5. Confirm `max_step` may start rejecting portals. That changes bake results relative to today's inert field. +6. Confirm the hot tick writes `ActionSlot` and does not tick `BehaviorGraph` or `sys_ai_depth`. +7. Confirm the Aravath scene waits until `aravath_runtime` is on the integration branch, and this PR stays docs-only. + +## 11. Phase 2 status + +Approved 2026-10-15. Decisions 1–5 are implemented on `feat/ai-orchestration`. This branch still does not merge. + +| Decision | Where | +|---|---| +| HTN with utility scores | `astraweave-ai/src/htn.rs` | +| Side buffer accepted only on a matching input hash | `NavTiles::accept_side_buffer` | +| `Explosion`, `Brush`, `Detach` | `NavChangeKind` and `nav_change_from_kind` | +| 32 m, 4 commits, 64 expansions | `TILE_SIZE_M`, `TILE_COMMITS_PER_TICK`, `HTN_EXPANSIONS_PER_TICK`. Unit tests assert each budget is under 11 ms. Benches: `tile_commits_per_tick`, `htn_expansions_per_tick` | +| `max_step` live | `share_edge`. Golden `max_step_links_a_low_ledge_and_rejects_a_tall_one` locks a 0.3 m link and a 1.0 m reject. Coplanar neighbor counts stayed 1 | + +Dormant systems: + +| Surface | Decision | +|---|---| +| `UtilityOrchestrator` | Wired. `propose_plan` calls `htn::legacy_utility_plan` | +| `dispatch_planner` | Wired. `PlannerMode::Htn` is always available and the ECS demo runs `SpatialTick` | +| Slice companion planner | Wired. Method select by priority. It no longer calls `GoapPlanner` or reads the wall clock | +| `AIArbiter` | Deferred. A live model cannot write the sim tick. Issue #257 | +| `astraweave-ai/src/goap/` (22 files) and `GoapPlanner` | Deferred. The slice path no longer calls them. Deleting them would drop the symbolic A* suite without a zero-alloc replacement. Issue #258 | + +`nav_reroute` is a required case in `.github/workflows/determinism-replay.yml`. The replay builds a collapse `GeometryNotice` (reason 2) and maps it with `nav_change_from_geometry_notice`. `drain_geometry_notices` is the producer on `feat/destruction` (#243). That crate is not in this branch, so the live drain call waits until both trees share a commit. + +`cargo test -p astraweave-ai --features alloc-counter --test zero_alloc_tick -- --test-threads=1` asserts the tile commit and the HTN tick allocate zero times after warmup. + +The Aravath runtime is not on this branch, so the showcase scene is not added. diff --git a/examples/ecs_ai_demo/src/main.rs b/examples/ecs_ai_demo/src/main.rs index c146125119..9060015e66 100644 --- a/examples/ecs_ai_demo/src/main.rs +++ b/examples/ecs_ai_demo/src/main.rs @@ -8,6 +8,8 @@ fn main() -> anyhow::Result<()> { // Create ECS app with AI plugin and movement systems let mut app = ecs::App::new().add_plugin(AiPlanningPlugin); + app.world + .insert_resource(astraweave_ai::SpatialTick::demo_agent()); // Add movement system (from ecs_adapter) app.add_system("simulation", move_system as ecs::SystemFn)