raasta 1.0.0

Raasta — navigation and pathfinding engine for AGNOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! Multi-layer NavMesh — overlapping navigation surfaces for bridges and buildings.

use std::collections::HashMap;

use hisab::Vec2;
use serde::{Deserialize, Serialize};

use crate::mesh::{NavMesh, NavPolyId};

#[cfg(feature = "logging")]
use tracing::instrument;

/// Identifies a layer in the multi-layer navmesh.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LayerId(pub u32);

/// A polygon ID scoped to a specific layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LayeredPolyId {
    pub layer: LayerId,
    pub poly: NavPolyId,
}

/// Connection between layers (stairs, elevators, ramps).
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct LayerConnection {
    pub from: LayeredPolyId,
    pub to: LayeredPolyId,
    pub cost: f32,
    pub bidirectional: bool,
}

/// Multi-layer navmesh — multiple overlapping navigation surfaces.
///
/// Each layer is an independent `NavMesh` (e.g., ground floor, second floor,
/// bridge surface). Layers are connected by explicit connections (stairs, etc.).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultiLayerNavMesh {
    layers: HashMap<LayerId, NavMesh>,
    connections: Vec<LayerConnection>,
}

impl MultiLayerNavMesh {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a navigation layer.
    pub fn add_layer(&mut self, id: LayerId, mesh: NavMesh) {
        self.layers.insert(id, mesh);
    }

    /// Remove a layer.
    pub fn remove_layer(&mut self, id: LayerId) -> bool {
        if self.layers.remove(&id).is_some() {
            self.connections
                .retain(|c| c.from.layer != id && c.to.layer != id);
            true
        } else {
            false
        }
    }

    /// Get a layer's navmesh.
    #[must_use]
    pub fn get_layer(&self, id: LayerId) -> Option<&NavMesh> {
        self.layers.get(&id)
    }

    /// Number of layers.
    #[must_use]
    pub fn layer_count(&self) -> usize {
        self.layers.len()
    }

    /// Add a connection between layers.
    pub fn add_connection(&mut self, conn: LayerConnection) {
        self.connections.push(conn);
    }

    /// Get all connections.
    #[must_use]
    pub fn connections(&self) -> &[LayerConnection] {
        &self.connections
    }

    /// Find a path across layers.
    ///
    /// Returns a sequence of `LayeredPolyId`s from start to goal.
    #[cfg_attr(feature = "logging", instrument(skip(self)))]
    #[must_use]
    pub fn find_path(
        &self,
        start_layer: LayerId,
        start_pos: Vec2,
        goal_layer: LayerId,
        goal_pos: Vec2,
    ) -> Option<Vec<LayeredPolyId>> {
        // Same layer — use local pathfinding
        if start_layer == goal_layer {
            let mesh = self.layers.get(&start_layer)?;
            let poly_path = mesh.find_path(start_pos, goal_pos)?;
            return Some(
                poly_path
                    .into_iter()
                    .map(|p| LayeredPolyId {
                        layer: start_layer,
                        poly: p,
                    })
                    .collect(),
            );
        }

        // Cross-layer A*
        // Build node list
        use std::cmp::Ordering;
        use std::collections::BinaryHeap;

        let mut nodes: Vec<LayeredPolyId> = Vec::new();
        let mut positions: Vec<Vec2> = Vec::new();
        let mut node_map: HashMap<LayeredPolyId, usize> = HashMap::new();

        for (&lid, mesh) in &self.layers {
            for poly in mesh.polys() {
                let lpid = LayeredPolyId {
                    layer: lid,
                    poly: poly.id,
                };
                let idx = nodes.len();
                node_map.insert(lpid, idx);
                nodes.push(lpid);
                positions.push(poly.centroid());
            }
        }

        let n = nodes.len();
        if n == 0 {
            return None;
        }

        // Find start/goal nodes
        let start_mesh = self.layers.get(&start_layer)?;
        let start_poly = start_mesh.find_poly_at(start_pos)?;
        let start_id = LayeredPolyId {
            layer: start_layer,
            poly: start_poly,
        };
        let start_idx = *node_map.get(&start_id)?;

        let goal_mesh = self.layers.get(&goal_layer)?;
        let goal_poly = goal_mesh.find_poly_at(goal_pos)?;
        let goal_id = LayeredPolyId {
            layer: goal_layer,
            poly: goal_poly,
        };
        let goal_idx = *node_map.get(&goal_id)?;

        // Build adjacency
        let mut adj: Vec<Vec<(usize, f32)>> = vec![Vec::new(); n];

        // Local neighbors
        for (&lid, mesh) in &self.layers {
            for poly in mesh.polys() {
                let from = LayeredPolyId {
                    layer: lid,
                    poly: poly.id,
                };
                let fi = node_map[&from];
                for &nid in &poly.neighbors {
                    let to = LayeredPolyId {
                        layer: lid,
                        poly: nid,
                    };
                    if let Some(&ti) = node_map.get(&to) {
                        let cost = positions[fi].distance(positions[ti]) * poly.cost;
                        adj[fi].push((ti, cost));
                    }
                }
            }
        }

        // Layer connections
        for conn in &self.connections {
            if let (Some(&fi), Some(&ti)) = (node_map.get(&conn.from), node_map.get(&conn.to)) {
                adj[fi].push((ti, conn.cost));
                if conn.bidirectional {
                    adj[ti].push((fi, conn.cost));
                }
            }
        }

        // A*
        #[derive(Clone, Copy)]
        struct N {
            idx: usize,
            f: f32,
        }
        impl PartialEq for N {
            fn eq(&self, o: &Self) -> bool {
                self.f == o.f
            }
        }
        impl Eq for N {}
        impl PartialOrd for N {
            fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
                Some(self.cmp(o))
            }
        }
        impl Ord for N {
            fn cmp(&self, o: &Self) -> Ordering {
                o.f.partial_cmp(&self.f).unwrap_or(Ordering::Equal)
            }
        }

        let mut g = vec![f32::INFINITY; n];
        let mut came: Vec<Option<usize>> = vec![None; n];
        let mut closed = vec![false; n];
        let mut open = BinaryHeap::new();

        g[start_idx] = 0.0;
        open.push(N {
            idx: start_idx,
            f: positions[start_idx].distance(positions[goal_idx]),
        });

        while let Some(cur) = open.pop() {
            if cur.idx == goal_idx {
                let mut path = Vec::new();
                let mut c = goal_idx;
                loop {
                    path.push(nodes[c]);
                    match came[c] {
                        Some(p) => c = p,
                        None => break,
                    }
                }
                path.reverse();
                return Some(path);
            }
            if closed[cur.idx] {
                continue;
            }
            closed[cur.idx] = true;

            for &(ni, cost) in &adj[cur.idx] {
                if closed[ni] {
                    continue;
                }
                let tg = g[cur.idx] + cost;
                if tg < g[ni] {
                    g[ni] = tg;
                    came[ni] = Some(cur.idx);
                    open.push(N {
                        idx: ni,
                        f: tg + positions[ni].distance(positions[goal_idx]),
                    });
                }
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mesh::{NavMesh, NavPoly, NavPolyId};

    /// Build a simple 2-polygon navmesh for testing.
    fn make_simple_mesh() -> NavMesh {
        let mut mesh = NavMesh::new();
        mesh.add_poly(NavPoly {
            id: NavPolyId(0),
            vertices: vec![
                Vec2::new(0.0, 0.0),
                Vec2::new(5.0, 0.0),
                Vec2::new(5.0, 5.0),
                Vec2::new(0.0, 5.0),
            ],
            neighbors: vec![NavPolyId(1)],
            cost: 1.0,
            layer: 0,
        });
        mesh.add_poly(NavPoly {
            id: NavPolyId(1),
            vertices: vec![
                Vec2::new(5.0, 0.0),
                Vec2::new(10.0, 0.0),
                Vec2::new(10.0, 5.0),
                Vec2::new(5.0, 5.0),
            ],
            neighbors: vec![NavPolyId(0)],
            cost: 1.0,
            layer: 0,
        });
        mesh
    }

    #[test]
    fn same_layer_path() {
        let mut ml = MultiLayerNavMesh::new();
        ml.add_layer(LayerId(0), make_simple_mesh());

        let path = ml.find_path(
            LayerId(0),
            Vec2::new(1.0, 1.0),
            LayerId(0),
            Vec2::new(9.0, 1.0),
        );
        assert!(path.is_some());
        let path = path.unwrap();
        assert_eq!(path.len(), 2);
        assert!(path.iter().all(|lp| lp.layer == LayerId(0)));
    }

    #[test]
    fn cross_layer_path_via_connection() {
        let mut ml = MultiLayerNavMesh::new();
        ml.add_layer(LayerId(0), make_simple_mesh());
        ml.add_layer(LayerId(1), make_simple_mesh());

        // Connect layer 0 poly 1 to layer 1 poly 0 (like stairs)
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(1),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 2.0,
            bidirectional: false,
        });

        let path = ml.find_path(
            LayerId(0),
            Vec2::new(1.0, 1.0),
            LayerId(1),
            Vec2::new(9.0, 1.0),
        );
        assert!(path.is_some());
        let path = path.unwrap();
        // Should traverse: layer0/poly0 -> layer0/poly1 -> layer1/poly0 -> layer1/poly1
        assert!(path.len() >= 3);
        // First node on layer 0, last node on layer 1
        assert_eq!(path.first().unwrap().layer, LayerId(0));
        assert_eq!(path.last().unwrap().layer, LayerId(1));
    }

    #[test]
    fn no_path_without_connection() {
        let mut ml = MultiLayerNavMesh::new();
        ml.add_layer(LayerId(0), make_simple_mesh());
        ml.add_layer(LayerId(1), make_simple_mesh());

        // No connection between layers — path should fail
        let path = ml.find_path(
            LayerId(0),
            Vec2::new(1.0, 1.0),
            LayerId(1),
            Vec2::new(9.0, 1.0),
        );
        assert!(path.is_none());
    }

    #[test]
    fn bidirectional_connection() {
        let mut ml = MultiLayerNavMesh::new();
        ml.add_layer(LayerId(0), make_simple_mesh());
        ml.add_layer(LayerId(1), make_simple_mesh());

        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(1),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 2.0,
            bidirectional: true,
        });

        // Forward: layer 0 -> layer 1
        let fwd = ml.find_path(
            LayerId(0),
            Vec2::new(1.0, 1.0),
            LayerId(1),
            Vec2::new(9.0, 1.0),
        );
        assert!(fwd.is_some());

        // Reverse: layer 1 -> layer 0
        let rev = ml.find_path(
            LayerId(1),
            Vec2::new(1.0, 1.0),
            LayerId(0),
            Vec2::new(9.0, 1.0),
        );
        assert!(rev.is_some());
    }

    #[test]
    fn remove_layer() {
        let mut ml = MultiLayerNavMesh::new();
        ml.add_layer(LayerId(0), make_simple_mesh());
        ml.add_layer(LayerId(1), make_simple_mesh());
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: false,
        });

        assert_eq!(ml.layer_count(), 2);
        assert_eq!(ml.connections().len(), 1);

        assert!(ml.remove_layer(LayerId(1)));
        assert_eq!(ml.layer_count(), 1);
        // Connection referencing removed layer should be cleaned up
        assert_eq!(ml.connections().len(), 0);

        // Removing non-existent layer returns false
        assert!(!ml.remove_layer(LayerId(99)));
    }

    #[test]
    fn serde_roundtrip() {
        let mut ml = MultiLayerNavMesh::new();
        ml.add_layer(LayerId(0), make_simple_mesh());
        ml.add_layer(LayerId(1), make_simple_mesh());
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(1),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 3.0,
            bidirectional: true,
        });

        let json = serde_json::to_string(&ml).unwrap();
        let deserialized: MultiLayerNavMesh = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.layer_count(), 2);
        assert_eq!(deserialized.connections().len(), 1);
        assert!((deserialized.connections()[0].cost - 3.0).abs() < f32::EPSILON);
    }

    /// Build a single-polygon navmesh for layer connection tests.
    fn make_single_poly_mesh() -> NavMesh {
        let mut mesh = NavMesh::new();
        mesh.add_poly(NavPoly {
            id: NavPolyId(0),
            vertices: vec![
                Vec2::ZERO,
                Vec2::new(10.0, 0.0),
                Vec2::new(10.0, 10.0),
                Vec2::new(0.0, 10.0),
            ],
            neighbors: vec![],
            cost: 1.0,
            layer: 0,
        });
        mesh
    }

    #[test]
    fn multilayer_cyclic_connections() {
        let mut ml = MultiLayerNavMesh::new();
        // Three layers
        for lid in 0..3u32 {
            ml.add_layer(LayerId(lid), make_single_poly_mesh());
        }
        // Cyclic: 0->1, 1->2, 2->0
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: false,
        });
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(2),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: false,
        });
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(2),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: false,
        });

        // Should find path from layer 0 to layer 2 via layer 1
        let path = ml.find_path(
            LayerId(0),
            Vec2::new(5.0, 5.0),
            LayerId(2),
            Vec2::new(5.0, 5.0),
        );
        assert!(path.is_some());
    }

    #[test]
    fn multilayer_many_layers() {
        let mut ml = MultiLayerNavMesh::new();
        for lid in 0..10u32 {
            ml.add_layer(LayerId(lid), make_single_poly_mesh());
            if lid > 0 {
                ml.add_connection(LayerConnection {
                    from: LayeredPolyId {
                        layer: LayerId(lid - 1),
                        poly: NavPolyId(0),
                    },
                    to: LayeredPolyId {
                        layer: LayerId(lid),
                        poly: NavPolyId(0),
                    },
                    cost: 1.0,
                    bidirectional: true,
                });
            }
        }
        assert_eq!(ml.layer_count(), 10);
        let path = ml.find_path(
            LayerId(0),
            Vec2::new(5.0, 5.0),
            LayerId(9),
            Vec2::new(5.0, 5.0),
        );
        assert!(path.is_some());
    }

    #[test]
    fn multilayer_three_layer_path() {
        let mut ml = MultiLayerNavMesh::new();
        for lid in 0..3u32 {
            ml.add_layer(LayerId(lid), make_single_poly_mesh());
        }
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: true,
        });
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(2),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: true,
        });
        let path = ml.find_path(
            LayerId(0),
            Vec2::new(5.0, 5.0),
            LayerId(2),
            Vec2::new(5.0, 5.0),
        );
        assert!(path.is_some());
        assert_eq!(path.unwrap().len(), 3); // Through all three layers
    }

    #[test]
    fn multilayer_remove_connected_layer() {
        let mut ml = MultiLayerNavMesh::new();
        for lid in 0..3u32 {
            ml.add_layer(LayerId(lid), make_single_poly_mesh());
        }
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(0),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: true,
        });
        ml.add_connection(LayerConnection {
            from: LayeredPolyId {
                layer: LayerId(1),
                poly: NavPolyId(0),
            },
            to: LayeredPolyId {
                layer: LayerId(2),
                poly: NavPolyId(0),
            },
            cost: 1.0,
            bidirectional: true,
        });

        // Remove middle layer — connections should be cleaned up
        ml.remove_layer(LayerId(1));
        assert_eq!(ml.layer_count(), 2);
        // Connections involving layer 1 should be gone
        assert!(
            ml.connections()
                .iter()
                .all(|c| c.from.layer != LayerId(1) && c.to.layer != LayerId(1))
        );
        // No path from 0 to 2 anymore
        assert!(
            ml.find_path(
                LayerId(0),
                Vec2::new(5.0, 5.0),
                LayerId(2),
                Vec2::new(5.0, 5.0),
            )
            .is_none()
        );
    }
}