diff --git a/CHANGELOG.md b/CHANGELOG.md index f33c0588..3d5bcd54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -397,6 +397,14 @@ Changes that land in the main branch after phases C–E (`0.4.0`) go here. content is the simulation's whoever asked for it first (a tick, a tool that only looks, a snapshot being loaded), so a replay names the same definitions. Tests: `a_goal_by_a_wall_under_the_walkway_is_on_the_floor`, `a_doorway_the_grid_misses_is_walked_on_the_local_grid`. +- A door, a shutter or a lift that starts or stops no longer stalls the tick on a large navmesh. Each start and stop changes + the static solids, and carving rebuilt the whole tile graph of every body class one after another, measuring the costs + inside every tile or chunk again: on a game's four hand-made levels (44 chunks, four classes) every such tick took about + 200 ms. The graph build now keeps the costs inside each tile or chunk (`InstanceCosts`) and measures again only where the + switched-off nodes or the graph's nodes changed, makes its compressed rows node by node instead of sorting every edge at + once, and the classes are carved at once on the compute pool, as a build makes them: the same door's tick now takes about + 9 ms. The navmesh is the same as before (routes, replays and snapshots do not change). Tests: + `a_navmesh_carved_again_routes_as_one_built_now`, `rows_sorted_one_by_one_are_every_edge_sorted_at_once`. - The engine rule `npc.strike_spacing` no longer blames an NPC whose strike began on the tick a boss later in `AiId` order that `ignores_spacing` began its own: the planner judges in `AiId` order, so the earlier NPC could not see the later press. Of two starts on one tick, the later in that order is the one held to the rule (two NPCs that both wait for the spacing still break it). Found by N8d's tests, the first to spawn a boss after its add. Test: `invariants.rs` (`a_noting_only_npc_is_not_held_to_the_rule_but_holds_the_others`, extended). - An NPC whose target stands at the edge of its leash reaches it to strike. The leash pulls an approach goal 0.5 m short of such a target (the room for a body), and the planner walked the NPC to within 0.85 of its window of that goal, so it could stop up to 0.5 m beyond its window and never strike (the den guard of `npc_navmesh.scenario`, from some start ticks: 2.06 m off with a window of 1.84 m). Both approaches of `shards_npc::planner` (to the chosen window and, with nothing chosen, to the nearest) now take `reach(within, goal, target)`: `within` less the pull, at least 0.3 m, never more than asked; an approach the leash does not pull is unchanged. `downed.scenario` loses the 60 ticks B5 added for this. Re-recorded: `npc_navmesh.json` (from tick 60 the den guard walks nearer its pulled goal: its `NpcDrive` `within`) and `downed.json` (60 ticks shorter); the other 17 reference replays are byte-identical; the template's `valley.json` (its raider `e17` reaches a player at the edge of its leash from tick 480: `NavAgent`, `NpcDrive`; `smoke.json` is unchanged). Tests: `planner::tests` (1), `tests/npc/nav.rs` (1: a grunt strikes a target at the edge of its leash). diff --git a/crates/shards_npc/src/nav/region.rs b/crates/shards_npc/src/nav/region.rs index 6d9dfc65..1ef8dde7 100644 --- a/crates/shards_npc/src/nav/region.rs +++ b/crates/shards_npc/src/nav/region.rs @@ -191,6 +191,34 @@ pub(crate) struct TileGraph { pub edges: Vec<(u32, u32)>, } +/// The costs inside one instance between its graph nodes, as the last graph build measured them +/// ([`NavRegion::build_graph`]). They are a function of the instance's bake, its switched-off +/// nodes and which of its nodes are graph nodes, so an instance that a change left alone keeps +/// them, and only the instances it touched are measured again: a door that comes to rest +/// re-measures the chunks round its doorway, not every chunk of the levels. +#[derive(Clone, Debug, Default)] +pub(crate) struct InstanceCosts { + /// The bake they were measured on. + nav: Option>, + /// The node each of the instance's graph nodes measures from, in `TileGraph::of_instance` + /// order. + keys: Vec>, + /// The instance's switched-off nodes then. + disabled: Vec, + /// `(from, to, cost)`: indices into `keys`. + edges: Vec<(u32, u32, u32)>, +} + +impl InstanceCosts { + /// Whether these are the costs of `instance` with `keys` (graph node ids into `nodes`). + fn hold(&self, instance: &Instance, keys: &[u32], nodes: &[GraphNode]) -> bool { + self.nav.as_ref().is_some_and(|nav| Arc::ptr_eq(nav, &instance.nav)) + && self.disabled == instance.disabled + && self.keys.len() == keys.len() + && self.keys.iter().zip(keys).all(|(kept, &k)| *kept == nodes[k as usize].node) + } +} + /// What a build did, for the journal and the tools. #[derive(Clone, Debug, Default, PartialEq)] pub struct NavReport { @@ -430,6 +458,9 @@ pub struct NavRegion { pub(crate) extras: Vec, pub navlinks: Vec, pub(crate) graph: TileGraph, + /// The costs inside each instance that the last graph build measured, by instance: what the + /// next build keeps where nothing changed (see [`InstanceCosts`]). + pub(crate) costs: Vec, /// Which nodes reach which (links taken both ways, switched-off nodes left out): a label /// per node. components: Vec, @@ -875,8 +906,17 @@ pub fn refresh(world: &mut World) { class.build_graph(); } }; - carve(&mut nav); - nav.bodies.iter_mut().for_each(carve); + // Every class at once on the compute pool, as a build makes them: each is a pure function of + // its own navmesh and the solids standing, so the order the tasks finish in changes nothing. + let mut bodies = std::mem::take(&mut nav.bodies); + let carve = &carve; + bevy::tasks::ComputeTaskPool::get_or_init(bevy::tasks::TaskPool::default).scope(|scope| { + scope.spawn(async { carve(&mut nav) }); + for class in &mut bodies { + scope.spawn(async move { carve(class) }); + } + }); + nav.bodies = bodies; world.insert_resource(nav); // A solid the levels' chunks were baked from went or moved: they are baked again. if world.get_resource::().is_none() && !world.get_resource::().is_some_and(|nav| levels::current(world, nav)) { @@ -979,6 +1019,7 @@ fn build(world: &mut World, settings: &NavSettings, prebaked: Option<(Prebaked, extras: Vec::new(), navlinks: Vec::new(), graph: TileGraph::default(), + costs: Vec::new(), components: Vec::new(), report, voxel: None, @@ -1575,26 +1616,39 @@ impl NavRegion { } let mut edges: Vec<(u32, u32, u32)> = Vec::new(); // Inside each instance: the bake's costs, or measured again where it is carved or has - // navlink or hop ends. + // navlink or hop ends; kept from the last build where none of that changed. + let mut costs = std::mem::take(&mut self.costs); + costs.resize_with(self.instances.len(), InstanceCosts::default); for (inst, instance) in self.instances.iter().enumerate() { let keys = &graph.of_instance[inst]; - let plain = instance.disabled.is_empty() && keys.len() == instance.nav.portals.len(); - for &a in keys { - let Some(from) = graph.nodes[a as usize].node else { continue }; - let dist = if plain { None } else { Some(dijkstra(&instance.nav, from - self.base[inst], Some(&instance.disabled))) }; - for &b in keys { - let Some(to) = graph.nodes[b as usize].node.filter(|_| a != b) else { continue }; - let cost = match (&dist, graph.nodes[a as usize].portal, graph.nodes[b as usize].portal) { - (None, Some(p), Some(q)) => instance.nav.portal_cost(p as usize, q as usize), - (Some(dist), ..) => Some(dist[(to - self.base[inst]) as usize]).filter(|c| *c != u32::MAX), - _ => None, - }; - if let Some(cost) = cost { - edges.push((a, b, cost)); + let kept = &mut costs[inst]; + if !kept.hold(instance, keys, &graph.nodes) { + *kept = InstanceCosts { + nav: Some(instance.nav.clone()), + keys: keys.iter().map(|&k| graph.nodes[k as usize].node).collect(), + disabled: instance.disabled.clone(), + edges: Vec::new(), + }; + let plain = instance.disabled.is_empty() && keys.len() == instance.nav.portals.len(); + for (i, &a) in keys.iter().enumerate() { + let Some(from) = graph.nodes[a as usize].node else { continue }; + let dist = if plain { None } else { Some(dijkstra(&instance.nav, from - self.base[inst], Some(&instance.disabled))) }; + for (j, &b) in keys.iter().enumerate() { + let Some(to) = graph.nodes[b as usize].node.filter(|_| a != b) else { continue }; + let cost = match (&dist, graph.nodes[a as usize].portal, graph.nodes[b as usize].portal) { + (None, Some(p), Some(q)) => instance.nav.portal_cost(p as usize, q as usize), + (Some(dist), ..) => Some(dist[(to - self.base[inst]) as usize]).filter(|c| *c != u32::MAX), + _ => None, + }; + if let Some(cost) = cost { + kept.edges.push((i as u32, j as u32, cost)); + } } } } + edges.extend(kept.edges.iter().map(|&(i, j, cost)| (keys[i as usize], keys[j as usize], cost))); } + self.costs = costs; // Across tiles: a stitch joins the portals of the two sides; a navlink, a hop or a diagonal its // two ends. for extra in &self.extras { @@ -1607,16 +1661,7 @@ impl NavRegion { edges.push((a, b, extra.cost)); } } - edges.sort_unstable(); - edges.dedup_by_key(|e| (e.0, e.1)); - graph.first = vec![0; graph.nodes.len() + 1]; - for &(a, ..) in &edges { - graph.first[a as usize + 1] += 1; - } - for n in 0..graph.nodes.len() { - graph.first[n + 1] += graph.first[n]; - } - graph.edges = edges.into_iter().map(|(_, b, c)| (b, c)).collect(); + (graph.first, graph.edges) = adjacency(graph.nodes.len(), &edges); self.graph = graph; self.find_components(); } @@ -1689,6 +1734,41 @@ impl NavRegion { } } +/// The graph's edges in compressed rows from `(from, to, cost)` triples in any order: the edges +/// leaving node `n` are `edges[first[n]..first[n + 1]]`, by `to`, and of two between the same +/// nodes the cheaper one. Each node's row is sorted on its own (a few dozen edges), which is what +/// sorting every triple at once comes to, at a fraction of its cost. +fn adjacency(nodes: usize, triples: &[(u32, u32, u32)]) -> (Vec, Vec<(u32, u32)>) { + let mut start = vec![0u32; nodes + 1]; + for &(a, ..) in triples { + start[a as usize + 1] += 1; + } + for n in 0..nodes { + start[n + 1] += start[n]; + } + let mut rows = vec![(0u32, 0u32); triples.len()]; + let mut next = start.clone(); + for &(a, b, cost) in triples { + rows[next[a as usize] as usize] = (b, cost); + next[a as usize] += 1; + } + let mut first = Vec::with_capacity(nodes + 1); + let mut edges: Vec<(u32, u32)> = Vec::with_capacity(triples.len()); + first.push(0); + for n in 0..nodes { + let row = &mut rows[start[n] as usize..start[n + 1] as usize]; + row.sort_unstable(); + let begin = edges.len(); + for &(b, cost) in row.iter() { + if edges.len() == begin || edges[edges.len() - 1].0 != b { + edges.push((b, cost)); + } + } + first.push(edges.len() as u32); + } + (first, edges) +} + #[cfg(test)] mod tests { use super::*; @@ -1739,6 +1819,30 @@ mod tests { assert_eq!(inst.to_global(0, 0), [10 + 5, 20]); } + /// The rows sorted node by node are what sorting every edge at once made: each node's edges by + /// `to`, and of two between the same nodes the cheaper, with empty rows where a node has none. + #[test] + fn rows_sorted_one_by_one_are_every_edge_sorted_at_once() { + let mut seed: u32 = 12_345; + let mut next = |below: u32| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + (seed >> 8) % below + }; + let triples: Vec<(u32, u32, u32)> = (0..5000).map(|_| (next(97), next(97), next(50))).collect(); + let mut all = triples.clone(); + all.sort_unstable(); + all.dedup_by_key(|e| (e.0, e.1)); + let mut first = vec![0u32; 101]; + for &(a, ..) in &all { + first[a as usize + 1] += 1; + } + for n in 0..100 { + first[n + 1] += first[n]; + } + let edges: Vec<(u32, u32)> = all.iter().map(|&(_, b, cost)| (b, cost)).collect(); + assert_eq!(adjacency(100, &triples), (first, edges)); + } + /// The navmesh of body class `body`, baked for `agent`, with nothing in it: what choosing /// a class looks at. fn class(body: &str, agent: CharacterParams) -> NavRegion { @@ -1762,6 +1866,7 @@ mod tests { extras: Vec::new(), navlinks: Vec::new(), graph: TileGraph::default(), + costs: Vec::new(), components: Vec::new(), report: NavReport::default(), voxel: None, diff --git a/crates/shards_npc/src/nav/region/levels.rs b/crates/shards_npc/src/nav/region/levels.rs index fb4ed7b6..1c5316be 100644 --- a/crates/shards_npc/src/nav/region/levels.rs +++ b/crates/shards_npc/src/nav/region/levels.rs @@ -474,6 +474,7 @@ fn assemble(physics: &PhysicsWorld, settings: &NavSettings, source: &Source, com extras: Vec::new(), navlinks: Vec::new(), graph: TileGraph::default(), + costs: Vec::new(), components: Vec::new(), report, voxel: None, diff --git a/crates/shards_npc/src/nav/region/volume.rs b/crates/shards_npc/src/nav/region/volume.rs index 4cdf7c97..964183b0 100644 --- a/crates/shards_npc/src/nav/region/volume.rs +++ b/crates/shards_npc/src/nav/region/volume.rs @@ -432,6 +432,7 @@ pub(super) fn build(world: &mut World, settings: &NavSettings, cut: Cut, prebake extras: Vec::new(), navlinks: Vec::new(), graph: TileGraph::default(), + costs: Vec::new(), components: Vec::new(), report, voxel: None, diff --git a/crates/shards_npc/tests/npc/navmesh.rs b/crates/shards_npc/tests/npc/navmesh.rs index d3ff6f31..c53f8655 100644 --- a/crates/shards_npc/tests/npc/navmesh.rs +++ b/crates/shards_npc/tests/npc/navmesh.rs @@ -538,6 +538,57 @@ fn carving_is_the_solids_standing_now_not_their_history() { } } +/// Routes on a navmesh carved again and again are the routes of one built around the solids +/// standing now: the costs inside the tiles a change left alone are kept from the build before, +/// and those of the tiles it touched are measured again. Wall `a` shuts the north-east tile's +/// way from its west side to its south side and stays clear of both sides' middles (where the +/// tile graph measures from), so only a cost measured again sends the route round by the +/// south-west tile. +#[test] +fn a_navmesh_carved_again_routes_as_one_built_now() { + let rows = ["floor floor", "floor floor"]; + let a = (Vec3::new(8.0, 0.0, 5.5), Vec3::new(16.0, 2.5, 6.0)); + let b = (Vec3::new(2.0, 0.0, 10.0), Vec3::new(3.0, 2.5, 11.0)); + let c = (Vec3::new(13.0, 0.0, 13.0), Vec3::new(14.0, 2.5, 14.0)); + let pairs = [ + (Vec3::new(6.0, 0.0, 2.0), Vec3::new(14.0, 0.0, 10.0)), + (Vec3::new(2.0, 0.0, 6.0), Vec3::new(13.0, 0.0, 3.0)), + (Vec3::new(14.0, 0.0, 14.0), Vec3::new(12.0, 0.0, 2.0)), + (Vec3::new(3.0, 0.0, 13.0), Vec3::new(10.0, 0.0, 7.0)), + (Vec3::new(1.0, 0.0, 1.0), Vec3::new(15.0, 0.0, 15.0)), + ]; + // Lengths to the millimetre and the tiles crossed, or why there is no route. + type Routes = Vec), String>>; + let routes = |app: &App| -> Routes { + pairs.iter().map(|(from, to)| route(app, *from, *to).map(|p| ((p.length * 1000.0).round() as i64, p.tiles))).collect() + }; + // The routes of the region built with `walls` standing from the start. + let built_with = |walls: &[(Vec3, Vec3)]| { + let mut fresh = app(); + for (min, max) in walls { + wall(fresh.world_mut(), *min, *max); + } + load_region(&mut fresh, &rows); + routes(&fresh) + }; + assert_ne!(built_with(&[a]), built_with(&[]), "wall a changes a route"); + let mut carved = app(); + load_region(&mut carved, &rows); + assert_eq!(routes(&carved), built_with(&[]), "as built"); + let wa = wall(carved.world_mut(), a.0, a.1); + step(&mut carved, 1); + assert_eq!(routes(&carved), built_with(&[a]), "a put up"); + wall(carved.world_mut(), b.0, b.1); + step(&mut carved, 1); + assert_eq!(routes(&carved), built_with(&[a, b]), "b put up"); + carved.world_mut().despawn(wa); + step(&mut carved, 1); + assert_eq!(routes(&carved), built_with(&[b]), "a taken down"); + wall(carved.world_mut(), c.0, c.1); + step(&mut carved, 1); + assert_eq!(routes(&carved), built_with(&[b, c]), "c put up"); +} + /// A solid that moves (it keeps its collider id) is carved where it stands now. #[test] fn a_solid_that_moves_is_carved_where_it_stands() { diff --git a/docs/manual.md b/docs/manual.md index bbfb52bd..96188891 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -3922,7 +3922,11 @@ that does not say so keeps the local grid, so a game that changes nothing plays - **Kept up to date.** The navmesh is made again when a level is placed, taken away or loaded again, and when content changes. A baked solid that goes or moves (the game took a wall away) makes it again too, and only the chunks it stood in are baked. Making it again places, carves and stitches every chunk, for every body class at once - on the compute pool: about 0.1 s for 50 chunks, so give what goes in play `Health` or make it a mover. + on the compute pool: about 0.1 s for 50 chunks, so give what goes in play `Health` or make it a mover. Carving + is far cheaper: a mover that starts or stops, or a solid that comes or goes, decides again only the nodes and the + links near it, and the graph keeps the costs inside every chunk it did not touch, for every class at once on the + compute pool (about 9 ms a door on 44 chunks and four classes, where it was 200 ms when every chunk was measured + again). - **Body classes and `safe_drop`** come from the `nav` settings, as for a region. An NPC routes on the tightest class that serves its body; one no class serves, or one that stands outside the levels that have a navmesh, plans on the local grid (`npc_state` says which: `navmesh, body agent`, or `local grid: …`).