condor-pathfinding-grid 0.4.0

Grid pathfinding, preprocessing, replanning, and multi-agent algorithms for Condor.
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
//! Shared visibility-graph storage and deterministic Dijkstra for any-angle oracles.
//!
//! CSR adjacency ([`VisibilityGraphCsr`]), all-pairs build helpers, collinear elision,
//! and overlay-capable Dijkstra used by the one-shot corner oracle and
//! [`crate::PreparedAnyAngleGrid`]. Not a public consumer entrypoint.

use std::cmp::Ordering;
use std::collections::BinaryHeap;

use crate::{
    Grid,
    any_angle::AnyAngleSearchRequest,
    any_angle::geometry::{approximately_equal, segment_is_legal},
};
use condor_core::{BudgetExhausted, BudgetWatch, Point2};

/// Compact CSR adjacency for a static visibility graph.
///
/// `offsets[i]..offsets[i+1]` indexes directed edges of node `i` into
/// `neighbors` / `weights` (Euclidean segment lengths).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct VisibilityGraphCsr {
    /// Prefix offsets into `neighbors`/`weights` (`len == node_count + 1`).
    pub offsets: Vec<u32>,
    /// Directed neighbor node indices.
    pub neighbors: Vec<u32>,
    /// Euclidean weight of each directed edge.
    pub weights: Vec<f64>,
}

impl VisibilityGraphCsr {
    /// Number of directed adjacency entries in CSR storage.
    #[must_use]
    pub fn directed_edge_count(&self) -> usize {
        self.neighbors.len()
    }

    /// Approximate retained heap bytes for offsets, neighbors, and weights.
    #[must_use]
    pub fn retained_bytes(&self) -> usize {
        self.offsets.len() * size_of::<u32>()
            + self.neighbors.len() * size_of::<u32>()
            + self.weights.len() * size_of::<f64>()
    }

    /// Directed neighbors of `node` as `(neighbor_index, edge_weight)` pairs.
    ///
    /// # Panics
    ///
    /// Panics if `node` is outside `0..node_count` for this CSR.
    pub fn neighbors_of(&self, node: usize) -> impl Iterator<Item = (usize, f64)> + '_ {
        let start = self.offsets[node] as usize;
        let end = self.offsets[node + 1] as usize;
        (start..end).map(move |index| (self.neighbors[index] as usize, self.weights[index]))
    }
}

/// Counters recorded while building a visibility graph.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct VisibilityGraphBuildStats {
    /// Pairwise LOS tests attempted (including rejected pairs).
    pub visibility_checks: usize,
    /// Undirected edges accepted after a legal segment check.
    pub accepted_undirected_edges: usize,
}

/// Counters recorded during one Dijkstra run on the visibility graph.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct DijkstraSearchStats {
    /// Nodes marked settled (first pop with best cost).
    pub settled_nodes: usize,
    /// Successful distance decreases.
    pub relaxations: usize,
    /// Binary-heap pushes (including re-pushes after decrease).
    pub pushes: usize,
    /// Heap pops discarded as stale or dominated.
    pub stale_pops: usize,
    /// Peak open-set size during the run.
    pub frontier_peak: usize,
}

/// Builds an adjacency list and counts visibility tests for the given node set.
pub(crate) fn build_visibility_adjacency(
    grid: &Grid,
    nodes: &[Point2],
    segment_legal: fn(&Grid, Point2, Point2) -> bool,
    stats: &mut VisibilityGraphBuildStats,
) -> Vec<Vec<(usize, f64)>> {
    let node_count = nodes.len();
    let mut adjacency = vec![Vec::new(); node_count];
    for left in 0..node_count {
        for right in left + 1..node_count {
            stats.visibility_checks += 1;
            if !segment_legal(grid, nodes[left], nodes[right]) {
                continue;
            }
            let weight = nodes[left].distance_to(nodes[right]);
            adjacency[left].push((right, weight));
            adjacency[right].push((left, weight));
            stats.accepted_undirected_edges += 1;
        }
    }
    adjacency
}

/// Converts an adjacency list into CSR form with deterministic neighbor order.
pub(crate) fn adjacency_to_csr(adjacency: &[Vec<(usize, f64)>]) -> VisibilityGraphCsr {
    let node_count = adjacency.len();
    let mut offsets = Vec::with_capacity(node_count + 1);
    let mut neighbors = Vec::new();
    let mut weights = Vec::new();
    offsets.push(0);

    for edges in adjacency {
        for &(neighbor, weight) in edges {
            neighbors.push(neighbor as u32);
            weights.push(weight);
        }
        offsets.push(neighbors.len() as u32);
    }

    VisibilityGraphCsr {
        offsets,
        neighbors,
        weights,
    }
}

/// Builds CSR adjacency for all legal pairs among `nodes`.
pub(crate) fn build_visibility_csr(
    grid: &Grid,
    nodes: &[Point2],
    stats: &mut VisibilityGraphBuildStats,
) -> VisibilityGraphCsr {
    let adjacency = build_visibility_adjacency(grid, nodes, segment_is_legal, stats);
    adjacency_to_csr(&adjacency)
}

/// Runs Dijkstra on a prepared CSR plus sparse per-node overlay edges.
///
/// Overlay edges supplement CSR adjacency for prepared nodes and provide the
/// sole adjacency for query-local nodes appended beyond `prepared_count`.
pub(crate) fn run_dijkstra_csr_with_overlay(
    csr: &VisibilityGraphCsr,
    prepared_count: usize,
    overlay_edges: &[Vec<(usize, f64)>],
    start_index: usize,
    goal_index: usize,
    stats: &mut DijkstraSearchStats,
    watch: &BudgetWatch,
) -> Result<Option<Vec<Option<usize>>>, BudgetExhausted> {
    let node_count = overlay_edges.len();
    debug_assert!(prepared_count <= node_count);

    let mut dist = vec![f64::INFINITY; node_count];
    let mut predecessors = vec![None; node_count];
    let mut settled = vec![false; node_count];
    dist[start_index] = 0.0;

    let mut frontier = BinaryHeap::new();
    frontier.push(QueueEntry {
        node: start_index,
        cost: 0.0,
    });
    stats.pushes += 1;
    stats.frontier_peak = stats.frontier_peak.max(frontier.len());

    while let Some(current) = frontier.pop() {
        if settled[current.node] {
            stats.stale_pops += 1;
            continue;
        }
        if current.cost > dist[current.node] + 1e-15 {
            stats.stale_pops += 1;
            continue;
        }

        settled[current.node] = true;
        stats.settled_nodes += 1;
        if current.node == goal_index {
            return Ok(Some(predecessors));
        }

        watch.check(stats.settled_nodes)?;

        relax_neighbors(
            current.node,
            csr,
            prepared_count,
            overlay_edges,
            &mut dist,
            &mut predecessors,
            &mut settled,
            &mut frontier,
            stats,
        );
    }

    Ok(None)
}

/// Runs Dijkstra on a dense adjacency list (one-shot oracle path).
///
/// Returns predecessor indices when the goal settles, `Ok(None)` when no path
/// exists, or [`BudgetExhausted`] when `watch` stops expansion. Costs are
/// Euclidean edge weights; ties prefer the lower predecessor index.
pub(crate) fn run_dijkstra(
    adjacency: &[Vec<(usize, f64)>],
    start_index: usize,
    goal_index: usize,
    stats: &mut DijkstraSearchStats,
    watch: &BudgetWatch,
) -> Result<Option<Vec<Option<usize>>>, BudgetExhausted> {
    let node_count = adjacency.len();
    let mut dist = vec![f64::INFINITY; node_count];
    let mut predecessors = vec![None; node_count];
    let mut settled = vec![false; node_count];
    dist[start_index] = 0.0;

    let mut frontier = BinaryHeap::new();
    frontier.push(QueueEntry {
        node: start_index,
        cost: 0.0,
    });
    stats.pushes += 1;
    stats.frontier_peak = stats.frontier_peak.max(frontier.len());

    while let Some(current) = frontier.pop() {
        if settled[current.node] {
            stats.stale_pops += 1;
            continue;
        }
        if current.cost > dist[current.node] + 1e-15 {
            stats.stale_pops += 1;
            continue;
        }

        settled[current.node] = true;
        stats.settled_nodes += 1;
        if current.node == goal_index {
            return Ok(Some(predecessors));
        }

        watch.check(stats.settled_nodes)?;

        for &(neighbor, weight) in &adjacency[current.node] {
            relax_edge(
                current.node,
                neighbor,
                weight,
                &mut dist,
                &mut predecessors,
                &settled,
                &mut frontier,
                stats,
            );
        }
    }

    Ok(None)
}

#[allow(clippy::too_many_arguments)]
fn relax_neighbors(
    node: usize,
    csr: &VisibilityGraphCsr,
    prepared_count: usize,
    overlay_edges: &[Vec<(usize, f64)>],
    dist: &mut [f64],
    predecessors: &mut [Option<usize>],
    settled: &mut [bool],
    frontier: &mut BinaryHeap<QueueEntry>,
    stats: &mut DijkstraSearchStats,
) {
    if node < prepared_count {
        for (neighbor, weight) in csr.neighbors_of(node) {
            relax_edge(
                node,
                neighbor,
                weight,
                dist,
                predecessors,
                settled,
                frontier,
                stats,
            );
        }
    }

    for &(neighbor, weight) in &overlay_edges[node] {
        relax_edge(
            node,
            neighbor,
            weight,
            dist,
            predecessors,
            settled,
            frontier,
            stats,
        );
    }
}

#[allow(clippy::too_many_arguments)]
fn relax_edge(
    node: usize,
    neighbor: usize,
    weight: f64,
    dist: &mut [f64],
    predecessors: &mut [Option<usize>],
    settled: &[bool],
    frontier: &mut BinaryHeap<QueueEntry>,
    stats: &mut DijkstraSearchStats,
) {
    if settled[neighbor] {
        return;
    }
    let candidate = dist[node] + weight;
    let better = candidate < dist[neighbor]
        || (approximately_equal(candidate, dist[neighbor])
            && better_predecessor(node, predecessors[neighbor]));
    if better {
        dist[neighbor] = candidate;
        predecessors[neighbor] = Some(node);
        stats.relaxations += 1;
        frontier.push(QueueEntry {
            node: neighbor,
            cost: candidate,
        });
        stats.pushes += 1;
        stats.frontier_peak = stats.frontier_peak.max(frontier.len());
    }
}

/// Walks `predecessors` from `goal_index` back to the start and returns the vertex path.
pub(crate) fn reconstruct_path(
    nodes: &[Point2],
    predecessors: &[Option<usize>],
    goal_index: usize,
) -> Vec<Point2> {
    let mut path = vec![nodes[goal_index]];
    let mut current = goal_index;
    while let Some(previous) = predecessors[current] {
        path.push(nodes[previous]);
        if previous == current {
            break;
        }
        current = previous;
    }
    path.reverse();
    path
}

/// Drops intermediate collinear vertices when every simplified segment stays legal.
///
/// Applies only when the simplified polyline still passes `segment_legal` on each
/// consecutive pair; otherwise the original points are retained.
pub(crate) fn elide_collinear_with_predicate(
    grid: &Grid,
    points: &mut Vec<Point2>,
    segment_legal: fn(&Grid, Point2, Point2) -> bool,
) {
    if points.len() < 3 {
        return;
    }
    let mut simplified = Vec::with_capacity(points.len());
    simplified.push(points[0]);
    for index in 1..points.len() - 1 {
        let prev = simplified[simplified.len() - 1];
        let current = points[index];
        let next = points[index + 1];
        if !are_collinear(prev, current, next) {
            simplified.push(current);
        }
    }
    simplified.push(*points.last().expect("non-empty path"));
    if simplified
        .windows(2)
        .all(|pair| segment_legal(grid, pair[0], pair[1]))
    {
        *points = simplified;
    }
}

/// Collinear elision under the authority [`segment_is_legal`] predicate.
pub(crate) fn elide_collinear_points(grid: &Grid, points: &mut Vec<Point2>) {
    elide_collinear_with_predicate(grid, points, segment_is_legal);
}

/// Sorts by `(x, y)` then removes approximately-equal consecutive duplicates.
pub(crate) fn dedup_points(points: &mut Vec<Point2>) {
    points.sort_by(|left, right| {
        left.x
            .partial_cmp(&right.x)
            .unwrap_or(Ordering::Equal)
            .then_with(|| left.y.partial_cmp(&right.y).unwrap_or(Ordering::Equal))
    });
    points.dedup_by(|left, right| points_equal(*left, *right));
}

/// Approximate equality of two continuous vertices (shared any-angle tolerance).
#[must_use]
pub(crate) fn points_equal(left: Point2, right: Point2) -> bool {
    approximately_equal(left.x, right.x) && approximately_equal(left.y, right.y)
}

/// Index of `point` in `nodes` under [`points_equal`], if present.
pub(crate) fn node_index(nodes: &[Point2], point: Point2) -> Option<usize> {
    nodes.iter().position(|node| points_equal(*node, point))
}

/// Whether a built any-angle path still starts and ends at the request endpoints.
pub(crate) fn path_endpoints_match_request(
    path: &crate::any_angle::AnyAnglePath,
    request: AnyAngleSearchRequest,
) -> bool {
    path.points().first() == Some(&request.start) && path.points().last() == Some(&request.goal)
}

/// Inserts a bidirectional edge once; no-ops when `left == right` or the edge exists.
pub(crate) fn add_undirected_edge(
    adjacency: &mut [Vec<(usize, f64)>],
    left: usize,
    right: usize,
    weight: f64,
) {
    if left == right {
        return;
    }
    if !adjacency[left]
        .iter()
        .any(|(neighbor, _)| *neighbor == right)
    {
        adjacency[left].push((right, weight));
    }
    if !adjacency[right]
        .iter()
        .any(|(neighbor, _)| *neighbor == left)
    {
        adjacency[right].push((left, weight));
    }
}

fn are_collinear(a: Point2, b: Point2, c: Point2) -> bool {
    let abx = b.x - a.x;
    let aby = b.y - a.y;
    let bcx = c.x - b.x;
    let bcy = c.y - b.y;
    (abx * bcy - aby * bcx).abs() <= 1e-12
}

fn better_predecessor(candidate: usize, current: Option<usize>) -> bool {
    match current {
        None => true,
        Some(existing) => candidate < existing,
    }
}

#[derive(Debug, PartialEq)]
struct QueueEntry {
    node: usize,
    cost: f64,
}

impl Eq for QueueEntry {}

impl Ord for QueueEntry {
    fn cmp(&self, other: &Self) -> Ordering {
        other
            .cost
            .partial_cmp(&self.cost)
            .unwrap_or(Ordering::Equal)
            .then_with(|| self.node.cmp(&other.node))
    }
}

impl PartialOrd for QueueEntry {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}