euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
use super::*;

/// Core operations for `GridPathfinder` including A*, multi-goal Dijkstra, and Jump Point Search.
impl GridPathfinder {
    /// Creates a uniform-cost `GridPathfinder` with every cell initialized to `1.0`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of grid columns.
    /// - `usize` - Number of grid rows.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized uniform-cost grid pathfinder.
    #[must_use]
    pub fn new(width: usize, height: usize) -> Self {
        let count: usize = width.saturating_mul(height);
        let scratch: GridPathScratch = GridPathScratch {
            generation: 0,
            seen_gen: vec![0; count],
            closed_gen: vec![0; count],
            g_scores: vec![f32::INFINITY; count],
            came_from: vec![usize::MAX; count],
            open_heap: Vec::with_capacity(count.min(256)),
            goal_flags: vec![0; count],
            goal_gen: 0,
        };
        Self {
            width,
            height,
            min_walkable_cost: 1.0,
            uniform_walkable: true,
            costs: vec![1.0; count],
            scratch,
        }
    }

    /// Creates a `GridPathfinder` from explicit row-major cell traversal costs (`<= 0.0` blocks).
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of grid columns.
    /// - `usize` - Number of grid rows.
    /// - `Vec<f32>` - Row-major cost array of length `width * height`.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured weighted grid pathfinder.
    #[must_use]
    pub fn from_costs(width: usize, height: usize, mut costs: Vec<f32>) -> Self {
        let count: usize = width.saturating_mul(height);
        costs.resize(count, 0.0);
        let mut pathfinder: Self = Self::new(width, height);
        pathfinder.set_costs(costs);
        pathfinder.recompute_cost_metadata();
        pathfinder
    }

    /// Recomputes minimum walkable cost and uniform-cost flag after modifying cell weights.
    fn recompute_cost_metadata(&mut self) {
        let mut min_cost: f32 = f32::INFINITY;
        let mut first_cost: f32 = 0.0;
        let mut has_walkable: bool = false;
        let mut is_uniform: bool = true;
        for &cost in self.get_costs() {
            if cost.is_finite() && cost > 0.0 {
                if !has_walkable {
                    first_cost = cost;
                    has_walkable = true;
                } else if (cost - first_cost).abs() > 1e-6 {
                    is_uniform = false;
                }
                if cost < min_cost {
                    min_cost = cost;
                }
            }
        }
        self.set_min_walkable_cost(if has_walkable { min_cost } else { 1.0 });
        self.set_uniform_walkable(is_uniform);
    }

    /// Converts a grid coordinate into a flat index if in bounds.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate to check.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Row-major cell index when inside grid bounds.
    #[must_use]
    pub fn index_of(&self, coord: GridCoord) -> Option<usize> {
        if coord.get_x() < self.get_width() && coord.get_y() < self.get_height() {
            Some(coord.get_y() * self.get_width() + coord.get_x())
        } else {
            None
        }
    }

    /// Converts a flat row-major cell index back into a `GridCoord`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Flat cell index.
    ///
    /// # Returns
    ///
    /// - `GridCoord` - Corresponding `(x, y)` coordinate.
    #[must_use]
    pub fn coord_of(&self, index: usize) -> GridCoord {
        let width: usize = self.get_width().max(1);
        GridCoord::new(index % width, index / width)
    }

    /// Returns whether `coord` is in bounds and has a positive finite traversal cost.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate to inspect.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when walkable.
    #[must_use]
    pub fn is_walkable(&self, coord: GridCoord) -> bool {
        if let Some(idx) = self.index_of(coord) {
            let cost: f32 = self.get_costs()[idx];
            cost.is_finite() && cost > 0.0
        } else {
            false
        }
    }

    /// Returns whether signed integer coordinate `(cx, cy)` is in bounds and walkable.
    ///
    /// # Arguments
    ///
    /// - `isize` - Signed column index.
    /// - `isize` - Signed row index.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `(cx, cy)` lies inside the grid and is walkable.
    #[must_use]
    fn is_walkable_signed(&self, cx: isize, cy: isize) -> bool {
        if cx < 0 || cy < 0 {
            return false;
        }
        let ux: usize = cx as usize;
        let uy: usize = cy as usize;
        if ux >= self.get_width() || uy >= self.get_height() {
            return false;
        }
        let cost: f32 = self.get_costs()[uy * self.get_width() + ux];
        cost.is_finite() && cost > 0.0
    }

    /// Sets the traversal cost of `coord` (`<= 0.0` marks the cell blocked).
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate to update.
    /// - `f32` - New traversal cost (`<= 0.0` or non-finite blocks the cell).
    pub fn set_cell_cost(&mut self, coord: GridCoord, cost: f32) {
        if let Some(idx) = self.index_of(coord) {
            let sanitized: f32 = if cost.is_finite() && cost > 0.0 {
                cost
            } else {
                0.0
            };
            self.get_mut_costs()[idx] = sanitized;
            self.recompute_cost_metadata();
        }
    }

    /// Marks `coord` blocked (`blocked == true`) or walkable with cost `1.0` (`blocked == false`).
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate to update.
    /// - `bool` - Whether the cell should be impassable.
    pub fn set_blocked(&mut self, coord: GridCoord, blocked: bool) {
        self.set_cell_cost(coord, if blocked { 0.0 } else { 1.0 });
    }

    /// Advances scratch search generation, resetting stamps only upon `u32::MAX` wraparound.
    ///
    /// # Arguments
    ///
    /// - `&mut GridPathScratch` - Scratch state to prepare.
    /// - `usize` - Total grid cell count.
    ///
    /// # Returns
    ///
    /// - `u32` - Active search generation token.
    fn begin_search_generation(scratch: &mut GridPathScratch, cell_count: usize) -> u32 {
        if scratch.seen_gen.len() != cell_count {
            scratch.seen_gen.resize(cell_count, 0);
            scratch.closed_gen.resize(cell_count, 0);
            scratch.g_scores.resize(cell_count, f32::INFINITY);
            scratch.came_from.resize(cell_count, usize::MAX);
            scratch.goal_flags.resize(cell_count, 0);
        }
        scratch.open_heap.clear();
        if scratch.generation == u32::MAX {
            scratch.seen_gen.fill(0);
            scratch.closed_gen.fill(0);
            scratch.generation = 1;
        } else {
            scratch.generation += 1;
        }
        scratch.generation
    }

    /// Finds an optimal shortest path using the selected algorithm and connectivity policy.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
    /// - `GridSearchAlgorithm` - Search strategy (`AStar`, `Dijkstra`, or `JumpPointSearch`).
    ///
    /// # Returns
    ///
    /// - `Option<GridPathResult>` - Optimal path and cost if reachable.
    #[must_use]
    pub fn find_path(
        &mut self,
        start: GridCoord,
        goal: GridCoord,
        connectivity: GridConnectivity,
        algorithm: GridSearchAlgorithm,
    ) -> Option<GridPathResult> {
        match algorithm {
            GridSearchAlgorithm::AStar => self.find_path_astar(start, goal, connectivity),
            GridSearchAlgorithm::Dijkstra => self.find_path_dijkstra(start, goal, connectivity),
            GridSearchAlgorithm::JumpPointSearch => self.find_path_jps(start, goal, connectivity),
        }
    }

    /// Finds an optimal shortest path using A* with admissible Manhattan or Octile heuristics.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
    ///
    /// # Returns
    ///
    /// - `Option<GridPathResult>` - Optimal path and total cost if reachable.
    #[must_use]
    pub fn find_path_astar(
        &mut self,
        start: GridCoord,
        goal: GridCoord,
        connectivity: GridConnectivity,
    ) -> Option<GridPathResult> {
        let mut path: Vec<GridCoord> = Vec::new();
        let (total_cost, nodes_expanded): (f32, usize) =
            self.search_astar_into(start, goal, connectivity, true, &mut path)?;
        Some(GridPathResult {
            path,
            total_cost,
            nodes_expanded,
        })
    }

    /// Finds an optimal shortest path using A* while writing waypoints into a caller-owned buffer.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - 4-way or 8-way connectivity.
    /// - `&mut Vec<GridCoord>` - Reusable output path buffer.
    ///
    /// # Returns
    ///
    /// - `Option<f32>` - Optimal total path cost when reachable.
    #[must_use]
    pub fn find_path_astar_into(
        &mut self,
        start: GridCoord,
        goal: GridCoord,
        connectivity: GridConnectivity,
        out_path: &mut Vec<GridCoord>,
    ) -> Option<f32> {
        let (total_cost, _): (f32, usize) =
            self.search_astar_into(start, goal, connectivity, true, out_path)?;
        Some(total_cost)
    }

    /// Finds an optimal shortest path to a single goal using Dijkstra's algorithm.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - 4-way or 8-way connectivity.
    ///
    /// # Returns
    ///
    /// - `Option<GridPathResult>` - Optimal path and total cost if reachable.
    #[must_use]
    pub fn find_path_dijkstra(
        &mut self,
        start: GridCoord,
        goal: GridCoord,
        connectivity: GridConnectivity,
    ) -> Option<GridPathResult> {
        let mut path: Vec<GridCoord> = Vec::new();
        let (total_cost, nodes_expanded): (f32, usize) =
            self.search_astar_into(start, goal, connectivity, false, &mut path)?;
        Some(GridPathResult {
            path,
            total_cost,
            nodes_expanded,
        })
    }

    /// Shared zero-allocation A* / Dijkstra search writing the optimal path into `out_path`.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - Neighbor connectivity policy.
    /// - `bool` - `true` for A* heuristic guidance, `false` for pure Dijkstra.
    /// - `&mut Vec<GridCoord>` - Reusable output path buffer.
    ///
    /// # Returns
    ///
    /// - `Option<(f32, usize)>` - `(total_cost, nodes_expanded)` when reachable.
    fn search_astar_into(
        &mut self,
        start: GridCoord,
        goal: GridCoord,
        connectivity: GridConnectivity,
        use_heuristic: bool,
        out_path: &mut Vec<GridCoord>,
    ) -> Option<(f32, usize)> {
        out_path.clear();
        let start_idx: usize = self.index_of(start)?;
        let goal_idx: usize = self.index_of(goal)?;
        if !self.is_walkable(start) || !self.is_walkable(goal) {
            return None;
        }
        if start_idx == goal_idx {
            out_path.push(start);
            return Some((0.0, 1));
        }
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        let cell_count: usize = width * height;
        let min_cost: f32 = self.get_min_walkable_cost();
        let mut scratch: GridPathScratch = take(self.get_mut_scratch());
        let gen_id: u32 = Self::begin_search_generation(&mut scratch, cell_count);
        scratch.seen_gen[start_idx] = gen_id;
        scratch.g_scores[start_idx] = 0.0;
        scratch.came_from[start_idx] = usize::MAX;
        let start_h: f32 = if use_heuristic {
            grid_heuristic(start, goal, connectivity, min_cost)
        } else {
            0.0
        };
        min_heap_f32_push(&mut scratch.open_heap, start_h, start_idx);
        let dirs_4: [(isize, isize, f32); 4] =
            [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0)];
        let dirs_8: [(isize, isize, f32); 8] = [
            (1, 0, 1.0),
            (-1, 0, 1.0),
            (0, 1, 1.0),
            (0, -1, 1.0),
            (1, 1, SQRT_2),
            (1, -1, SQRT_2),
            (-1, 1, SQRT_2),
            (-1, -1, SQRT_2),
        ];
        let dirs: &[(isize, isize, f32)] = match connectivity {
            GridConnectivity::FourWay => &dirs_4,
            GridConnectivity::EightWay => &dirs_8,
        };
        let mut nodes_expanded: usize = 0;
        let mut found: bool = false;
        while let Some((_, current_idx)) = min_heap_f32_pop(&mut scratch.open_heap) {
            if scratch.closed_gen[current_idx] == gen_id {
                continue;
            }
            scratch.closed_gen[current_idx] = gen_id;
            nodes_expanded += 1;
            if current_idx == goal_idx {
                found = true;
                break;
            }
            let cx: isize = (current_idx % width) as isize;
            let cy: isize = (current_idx / width) as isize;
            let current_g: f32 = scratch.g_scores[current_idx];
            for &(dx, dy, dist_mult) in dirs {
                let nx: isize = cx + dx;
                let ny: isize = cy + dy;
                if !self.is_walkable_signed(nx, ny) {
                    continue;
                }
                if dx != 0
                    && dy != 0
                    && (!self.is_walkable_signed(cx + dx, cy)
                        || !self.is_walkable_signed(cx, cy + dy))
                {
                    continue;
                }
                let next_idx: usize = (ny as usize) * width + (nx as usize);
                if scratch.closed_gen[next_idx] == gen_id {
                    continue;
                }
                let step_cost: f32 = self.get_costs()[next_idx] * dist_mult;
                let tentative_g: f32 = current_g + step_cost;
                let is_better: bool = scratch.seen_gen[next_idx] != gen_id
                    || tentative_g < scratch.g_scores[next_idx];
                if is_better {
                    scratch.seen_gen[next_idx] = gen_id;
                    scratch.g_scores[next_idx] = tentative_g;
                    scratch.came_from[next_idx] = current_idx;
                    let next_coord: GridCoord = GridCoord::new(nx as usize, ny as usize);
                    let heuristic: f32 = if use_heuristic {
                        grid_heuristic(next_coord, goal, connectivity, min_cost)
                    } else {
                        0.0
                    };
                    min_heap_f32_push(&mut scratch.open_heap, tentative_g + heuristic, next_idx);
                }
            }
        }
        let outcome: Option<(f32, usize)> = if found {
            let total_cost: f32 = scratch.g_scores[goal_idx];
            let mut cursor: usize = goal_idx;
            while cursor != usize::MAX {
                out_path.push(self.coord_of(cursor));
                if cursor == start_idx {
                    break;
                }
                cursor = scratch.came_from[cursor];
            }
            out_path.reverse();
            Some((total_cost, nodes_expanded))
        } else {
            None
        };
        self.set_scratch(scratch);
        outcome
    }

    /// Finds the optimal shortest path to the nearest reachable goal in `goals` using Dijkstra.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `&[GridCoord]` - Candidate target goal cells.
    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
    ///
    /// # Returns
    ///
    /// - `Option<GridPathResult>` - Shortest path to whichever goal has minimum total cost.
    #[must_use]
    pub fn find_path_dijkstra_multi_goal(
        &mut self,
        start: GridCoord,
        goals: &[GridCoord],
        connectivity: GridConnectivity,
    ) -> Option<GridPathResult> {
        let start_idx: usize = self.index_of(start)?;
        if !self.is_walkable(start) || goals.is_empty() {
            return None;
        }
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        let cell_count: usize = width * height;
        let mut scratch: GridPathScratch = take(self.get_mut_scratch());
        let gen_id: u32 = Self::begin_search_generation(&mut scratch, cell_count);
        if scratch.goal_gen == u32::MAX {
            scratch.goal_flags.fill(0);
            scratch.goal_gen = 1;
        } else {
            scratch.goal_gen += 1;
        }
        let goal_stamp: u32 = scratch.goal_gen;
        let mut valid_goals: usize = 0;
        for &goal in goals {
            if let Some(g_idx) = self.index_of(goal)
                && self.is_walkable(goal)
            {
                scratch.goal_flags[g_idx] = goal_stamp;
                valid_goals += 1;
            }
        }
        if valid_goals == 0 {
            self.set_scratch(scratch);
            return None;
        }
        scratch.seen_gen[start_idx] = gen_id;
        scratch.g_scores[start_idx] = 0.0;
        scratch.came_from[start_idx] = usize::MAX;
        min_heap_f32_push(&mut scratch.open_heap, 0.0, start_idx);
        let dirs_4: [(isize, isize, f32); 4] =
            [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0)];
        let dirs_8: [(isize, isize, f32); 8] = [
            (1, 0, 1.0),
            (-1, 0, 1.0),
            (0, 1, 1.0),
            (0, -1, 1.0),
            (1, 1, SQRT_2),
            (1, -1, SQRT_2),
            (-1, 1, SQRT_2),
            (-1, -1, SQRT_2),
        ];
        let dirs: &[(isize, isize, f32)] = match connectivity {
            GridConnectivity::FourWay => &dirs_4,
            GridConnectivity::EightWay => &dirs_8,
        };
        let mut nodes_expanded: usize = 0;
        let mut reached_goal: Option<usize> = None;
        while let Some((_, current_idx)) = min_heap_f32_pop(&mut scratch.open_heap) {
            if scratch.closed_gen[current_idx] == gen_id {
                continue;
            }
            scratch.closed_gen[current_idx] = gen_id;
            nodes_expanded += 1;
            if scratch.goal_flags[current_idx] == goal_stamp {
                reached_goal = Some(current_idx);
                break;
            }
            let cx: isize = (current_idx % width) as isize;
            let cy: isize = (current_idx / width) as isize;
            let current_g: f32 = scratch.g_scores[current_idx];
            for &(dx, dy, dist_mult) in dirs {
                let nx: isize = cx + dx;
                let ny: isize = cy + dy;
                if !self.is_walkable_signed(nx, ny) {
                    continue;
                }
                if dx != 0
                    && dy != 0
                    && (!self.is_walkable_signed(cx + dx, cy)
                        || !self.is_walkable_signed(cx, cy + dy))
                {
                    continue;
                }
                let next_idx: usize = (ny as usize) * width + (nx as usize);
                if scratch.closed_gen[next_idx] == gen_id {
                    continue;
                }
                let tentative_g: f32 = current_g + self.get_costs()[next_idx] * dist_mult;
                if scratch.seen_gen[next_idx] != gen_id || tentative_g < scratch.g_scores[next_idx]
                {
                    scratch.seen_gen[next_idx] = gen_id;
                    scratch.g_scores[next_idx] = tentative_g;
                    scratch.came_from[next_idx] = current_idx;
                    min_heap_f32_push(&mut scratch.open_heap, tentative_g, next_idx);
                }
            }
        }
        let result: Option<GridPathResult> = if let Some(goal_idx) = reached_goal {
            let total_cost: f32 = scratch.g_scores[goal_idx];
            let mut path: Vec<GridCoord> = Vec::new();
            let mut cursor: usize = goal_idx;
            while cursor != usize::MAX {
                path.push(self.coord_of(cursor));
                if cursor == start_idx {
                    break;
                }
                cursor = scratch.came_from[cursor];
            }
            path.reverse();
            Some(GridPathResult {
                path,
                total_cost,
                nodes_expanded,
            })
        } else {
            None
        };
        self.set_scratch(scratch);
        result
    }

    /// Performs a single directional Jump Point Search ray scan on a uniform-cost grid.
    ///
    /// # Arguments
    ///
    /// - `isize` - Origin X coordinate.
    /// - `isize` - Origin Y coordinate.
    /// - `isize` - Step X direction in `{-1, 0, 1}`.
    /// - `isize` - Step Y direction in `{-1, 0, 1}`.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Flat index of the next jump point or goal along `(dx, dy)`.
    fn jps_jump(
        &self,
        origin_x: isize,
        origin_y: isize,
        dx: isize,
        dy: isize,
        goal: GridCoord,
        connectivity: GridConnectivity,
    ) -> Option<usize> {
        let goal_x: isize = goal.get_x() as isize;
        let goal_y: isize = goal.get_y() as isize;
        let width: usize = self.get_width();
        let mut x: isize = origin_x;
        let mut y: isize = origin_y;
        loop {
            let nx: isize = x + dx;
            let ny: isize = y + dy;
            if !self.is_walkable_signed(nx, ny) {
                return None;
            }
            if dx != 0
                && dy != 0
                && (!self.is_walkable_signed(x + dx, y) || !self.is_walkable_signed(x, y + dy))
            {
                return None;
            }
            x = nx;
            y = ny;
            if x == goal_x && y == goal_y {
                return Some((y as usize) * width + (x as usize));
            }
            match connectivity {
                GridConnectivity::FourWay => {
                    if dx != 0 {
                        if self.jps_jump(x, y, 0, 1, goal, connectivity).is_some()
                            || self.jps_jump(x, y, 0, -1, goal, connectivity).is_some()
                        {
                            return Some((y as usize) * width + (x as usize));
                        }
                    } else if (!self.is_walkable_signed(x - 1, y - dy)
                        && self.is_walkable_signed(x - 1, y))
                        || (!self.is_walkable_signed(x + 1, y - dy)
                            && self.is_walkable_signed(x + 1, y))
                    {
                        return Some((y as usize) * width + (x as usize));
                    }
                }
                GridConnectivity::EightWay => {
                    if dx != 0 && dy != 0 {
                        if self.jps_jump(x, y, dx, 0, goal, connectivity).is_some()
                            || self.jps_jump(x, y, 0, dy, goal, connectivity).is_some()
                        {
                            return Some((y as usize) * width + (x as usize));
                        }
                    } else if dx != 0 {
                        if (!self.is_walkable_signed(x - dx, y + 1)
                            && self.is_walkable_signed(x, y + 1))
                            || (!self.is_walkable_signed(x - dx, y - 1)
                                && self.is_walkable_signed(x, y - 1))
                        {
                            return Some((y as usize) * width + (x as usize));
                        }
                    } else if (!self.is_walkable_signed(x + 1, y - dy)
                        && self.is_walkable_signed(x + 1, y))
                        || (!self.is_walkable_signed(x - 1, y - dy)
                            && self.is_walkable_signed(x - 1, y))
                    {
                        return Some((y as usize) * width + (x as usize));
                    }
                }
            }
        }
    }

    /// Collects pruned natural and forced JPS successor directions from `current` given `parent`.
    ///
    /// # Arguments
    ///
    /// - `isize` - Current cell X coordinate.
    /// - `isize` - Current cell Y coordinate.
    /// - `Option<GridCoord>` - Parent jump point coordinate (`None` at start).
    /// - `GridConnectivity` - 4-way or 8-way connectivity.
    /// - `&mut [(isize, isize); 8]` - Fixed stack buffer receiving candidate directions.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of valid directions written into the output array.
    fn jps_pruned_directions(
        &self,
        cx: isize,
        cy: isize,
        parent: Option<GridCoord>,
        connectivity: GridConnectivity,
        out_dirs: &mut [(isize, isize); 8],
    ) -> usize {
        let mut count: usize = 0;
        let Some(prev) = parent else {
            let initial_4: [(isize, isize); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];
            let initial_8: [(isize, isize); 8] = [
                (1, 0),
                (-1, 0),
                (0, 1),
                (0, -1),
                (1, 1),
                (1, -1),
                (-1, 1),
                (-1, -1),
            ];
            let slice: &[(isize, isize)] = match connectivity {
                GridConnectivity::FourWay => &initial_4,
                GridConnectivity::EightWay => &initial_8,
            };
            for &dir in slice {
                out_dirs[count] = dir;
                count += 1;
            }
            return count;
        };
        let dx: isize = (cx - prev.get_x() as isize).signum();
        let dy: isize = (cy - prev.get_y() as isize).signum();
        match connectivity {
            GridConnectivity::FourWay => {
                if dx != 0 {
                    out_dirs[count] = (dx, 0);
                    count += 1;
                    out_dirs[count] = (0, 1);
                    count += 1;
                    out_dirs[count] = (0, -1);
                    count += 1;
                } else if dy != 0 {
                    out_dirs[count] = (0, dy);
                    count += 1;
                    if !self.is_walkable_signed(cx - 1, cy - dy)
                        && self.is_walkable_signed(cx - 1, cy)
                    {
                        out_dirs[count] = (-1, 0);
                        count += 1;
                    }
                    if !self.is_walkable_signed(cx + 1, cy - dy)
                        && self.is_walkable_signed(cx + 1, cy)
                    {
                        out_dirs[count] = (1, 0);
                        count += 1;
                    }
                }
            }
            GridConnectivity::EightWay => {
                if dx != 0 && dy != 0 {
                    out_dirs[count] = (dx, 0);
                    count += 1;
                    out_dirs[count] = (0, dy);
                    count += 1;
                    out_dirs[count] = (dx, dy);
                    count += 1;
                } else if dx != 0 {
                    out_dirs[count] = (dx, 0);
                    count += 1;
                    if !self.is_walkable_signed(cx - dx, cy + 1)
                        && self.is_walkable_signed(cx, cy + 1)
                    {
                        out_dirs[count] = (0, 1);
                        count += 1;
                        if self.is_walkable_signed(cx + dx, cy) {
                            out_dirs[count] = (dx, 1);
                            count += 1;
                        }
                    }
                    if !self.is_walkable_signed(cx - dx, cy - 1)
                        && self.is_walkable_signed(cx, cy - 1)
                    {
                        out_dirs[count] = (0, -1);
                        count += 1;
                        if self.is_walkable_signed(cx + dx, cy) {
                            out_dirs[count] = (dx, -1);
                            count += 1;
                        }
                    }
                } else if dy != 0 {
                    out_dirs[count] = (0, dy);
                    count += 1;
                    if !self.is_walkable_signed(cx + 1, cy - dy)
                        && self.is_walkable_signed(cx + 1, cy)
                    {
                        out_dirs[count] = (1, 0);
                        count += 1;
                        if self.is_walkable_signed(cx, cy + dy) {
                            out_dirs[count] = (1, dy);
                            count += 1;
                        }
                    }
                    if !self.is_walkable_signed(cx - 1, cy - dy)
                        && self.is_walkable_signed(cx - 1, cy)
                    {
                        out_dirs[count] = (-1, 0);
                        count += 1;
                        if self.is_walkable_signed(cx, cy + dy) {
                            out_dirs[count] = (-1, dy);
                            count += 1;
                        }
                    }
                }
            }
        }
        count
    }

    /// Finds an optimal shortest path using Jump Point Search on uniform-cost grids (falling back to A* if weighted).
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Start cell coordinate.
    /// - `GridCoord` - Goal cell coordinate.
    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
    ///
    /// # Returns
    ///
    /// - `Option<GridPathResult>` - Optimal expanded cell-by-cell path with exact shortest cost.
    #[must_use]
    pub fn find_path_jps(
        &mut self,
        start: GridCoord,
        goal: GridCoord,
        connectivity: GridConnectivity,
    ) -> Option<GridPathResult> {
        if !self.get_uniform_walkable() {
            return self.find_path_astar(start, goal, connectivity);
        }
        let start_idx: usize = self.index_of(start)?;
        let goal_idx: usize = self.index_of(goal)?;
        if !self.is_walkable(start) || !self.is_walkable(goal) {
            return None;
        }
        if start_idx == goal_idx {
            return Some(GridPathResult {
                path: vec![start],
                total_cost: 0.0,
                nodes_expanded: 1,
            });
        }
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        let cell_count: usize = width * height;
        let unit_cost: f32 = self.get_min_walkable_cost();
        let mut scratch: GridPathScratch = take(self.get_mut_scratch());
        let gen_id: u32 = Self::begin_search_generation(&mut scratch, cell_count);
        scratch.seen_gen[start_idx] = gen_id;
        scratch.g_scores[start_idx] = 0.0;
        scratch.came_from[start_idx] = usize::MAX;
        min_heap_f32_push(
            &mut scratch.open_heap,
            grid_heuristic(start, goal, connectivity, unit_cost),
            start_idx,
        );
        let mut nodes_expanded: usize = 0;
        let mut found: bool = false;
        let mut dir_buf: [(isize, isize); 8] = [(0, 0); 8];
        while let Some((_, current_idx)) = min_heap_f32_pop(&mut scratch.open_heap) {
            if scratch.closed_gen[current_idx] == gen_id {
                continue;
            }
            scratch.closed_gen[current_idx] = gen_id;
            nodes_expanded += 1;
            if current_idx == goal_idx {
                found = true;
                break;
            }
            let current_coord: GridCoord = self.coord_of(current_idx);
            let parent_idx: usize = scratch.came_from[current_idx];
            let parent_coord: Option<GridCoord> = if parent_idx == usize::MAX {
                None
            } else {
                Some(self.coord_of(parent_idx))
            };
            let cx: isize = current_coord.get_x() as isize;
            let cy: isize = current_coord.get_y() as isize;
            let dir_count: usize =
                self.jps_pruned_directions(cx, cy, parent_coord, connectivity, &mut dir_buf);
            let current_g: f32 = scratch.g_scores[current_idx];
            for &(dx, dy) in &dir_buf[..dir_count] {
                if let Some(jump_idx) = self.jps_jump(cx, cy, dx, dy, goal, connectivity) {
                    if scratch.closed_gen[jump_idx] == gen_id {
                        continue;
                    }
                    let jump_coord: GridCoord = self.coord_of(jump_idx);
                    let seg_cost: f32 =
                        grid_heuristic(current_coord, jump_coord, connectivity, unit_cost);
                    let tentative_g: f32 = current_g + seg_cost;
                    if scratch.seen_gen[jump_idx] != gen_id
                        || tentative_g < scratch.g_scores[jump_idx]
                    {
                        scratch.seen_gen[jump_idx] = gen_id;
                        scratch.g_scores[jump_idx] = tentative_g;
                        scratch.came_from[jump_idx] = current_idx;
                        let h_val: f32 = grid_heuristic(jump_coord, goal, connectivity, unit_cost);
                        min_heap_f32_push(&mut scratch.open_heap, tentative_g + h_val, jump_idx);
                    }
                }
            }
        }
        let result: Option<GridPathResult> = if found {
            let total_cost: f32 = scratch.g_scores[goal_idx];
            let mut jump_points: Vec<GridCoord> = Vec::new();
            let mut cursor: usize = goal_idx;
            while cursor != usize::MAX {
                jump_points.push(self.coord_of(cursor));
                if cursor == start_idx {
                    break;
                }
                cursor = scratch.came_from[cursor];
            }
            jump_points.reverse();
            let mut full_path: Vec<GridCoord> = Vec::with_capacity(jump_points.len() * 2);
            if let Some(&first) = jump_points.first() {
                full_path.push(first);
                for pair in jump_points.windows(2) {
                    let from_pt: GridCoord = pair[0];
                    let to_pt: GridCoord = pair[1];
                    let mut x: isize = from_pt.get_x() as isize;
                    let mut y: isize = from_pt.get_y() as isize;
                    let tx: isize = to_pt.get_x() as isize;
                    let ty: isize = to_pt.get_y() as isize;
                    let step_x: isize = (tx - x).signum();
                    let step_y: isize = (ty - y).signum();
                    while x != tx || y != ty {
                        x += step_x;
                        y += step_y;
                        full_path.push(GridCoord::new(x as usize, y as usize));
                    }
                }
            }
            Some(GridPathResult {
                path: full_path,
                total_cost,
                nodes_expanded,
            })
        } else {
            None
        };
        self.set_scratch(scratch);
        result
    }
}

/// Construction and point-containment helpers for `NavPolygon2D`.
impl NavPolygon2D {
    /// Constructs a convex `NavPolygon2D`, automatically normalizing vertices to CCW winding.
    ///
    /// # Arguments
    ///
    /// - `Vec<Vec2>` - Convex polygon vertices in either CW or CCW order.
    /// - `f32` - Positive traversal cost multiplier (clamped to `>= 1e-4`).
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized CCW navigation polygon.
    #[must_use]
    pub fn new(mut vertices: Vec<Vec2>, cost_multiplier: f32) -> Self {
        let mut signed_area_2: f32 = 0.0;
        let len: usize = vertices.len();
        for idx in 0..len {
            let curr: Vec2 = vertices[idx];
            let next: Vec2 = vertices[(idx + 1) % len];
            signed_area_2 += pf_vec2_det(curr, next);
        }
        if signed_area_2 < 0.0 {
            vertices.reverse();
        }
        let mut sum: Vec2 = Vec2::zero();
        for &vertex in &vertices {
            sum = pf_vec2_add(sum, vertex);
        }
        let center: Vec2 = if len > 0 {
            pf_vec2_scale(sum, 1.0 / (len as f32))
        } else {
            Vec2::zero()
        };
        let safe_cost: f32 = if cost_multiplier.is_finite() && cost_multiplier > 1e-4 {
            cost_multiplier
        } else {
            1.0
        };
        Self {
            vertices,
            cost_multiplier: safe_cost,
            center,
        }
    }

    /// Tests whether `point` lies inside or on the boundary of this convex CCW polygon.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query point in 2D space.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when contained within the polygon.
    #[must_use]
    pub fn contains_point(&self, point: Vec2) -> bool {
        let verts: &[Vec2] = self.get_vertices();
        let len: usize = verts.len();
        if len < 3 {
            return false;
        }
        for idx in 0..len {
            let v0: Vec2 = verts[idx];
            let v1: Vec2 = verts[(idx + 1) % len];
            if pf_tri_area_2(v0, v1, point) < -NAV_EDGE_EPSILON {
                return false;
            }
        }
        true
    }
}

/// Portal graph construction, A* corridor search, and funnel string-pulling for `NavMesh2D`.
impl NavMesh2D {
    /// Builds a `NavMesh2D` from convex polygons and automatically wires shared-edge portals.
    ///
    /// # Arguments
    ///
    /// - `Vec<NavPolygon2D>` - Convex navigation polygons.
    ///
    /// # Returns
    ///
    /// - `Self` - Connected navigation mesh ready for pathfinding.
    #[must_use]
    pub fn from_polygons(polygons: Vec<NavPolygon2D>) -> Self {
        let count: usize = polygons.len();
        let mut adjacency: Vec<Vec<NavPortal2D>> = vec![Vec::new(); count];
        let eps_sq: f32 = NAV_EDGE_EPSILON * NAV_EDGE_EPSILON;
        for poly_a in 0..count {
            let verts_a: &[Vec2] = polygons[poly_a].get_vertices();
            let len_a: usize = verts_a.len();
            if len_a < 3 {
                continue;
            }
            for poly_b in (poly_a + 1)..count {
                let verts_b: &[Vec2] = polygons[poly_b].get_vertices();
                let len_b: usize = verts_b.len();
                if len_b < 3 {
                    continue;
                }
                for ea in 0..len_a {
                    let a0: Vec2 = verts_a[ea];
                    let a1: Vec2 = verts_a[(ea + 1) % len_a];
                    for eb in 0..len_b {
                        let b0: Vec2 = verts_b[eb];
                        let b1: Vec2 = verts_b[(eb + 1) % len_b];
                        let match_opp: bool =
                            pf_vec2_dist_sq(a0, b1) <= eps_sq && pf_vec2_dist_sq(a1, b0) <= eps_sq;
                        let match_same: bool =
                            pf_vec2_dist_sq(a0, b0) <= eps_sq && pf_vec2_dist_sq(a1, b1) <= eps_sq;
                        if match_opp || match_same {
                            let midpoint: Vec2 = pf_vec2_scale(pf_vec2_add(a0, a1), 0.5);
                            adjacency[poly_a].push(NavPortal2D::new(poly_b, a1, a0, midpoint));
                            adjacency[poly_b].push(NavPortal2D::new(poly_a, a0, a1, midpoint));
                        }
                    }
                }
            }
        }
        let scratch: NavMeshScratch = NavMeshScratch {
            generation: 0,
            seen_gen: vec![0; count],
            closed_gen: vec![0; count],
            g_scores: vec![f32::INFINITY; count],
            came_from_poly: vec![usize::MAX; count],
            came_from_portal: vec![usize::MAX; count],
            open_heap: Vec::with_capacity(count.min(128)),
            portal_corridor: Vec::with_capacity(32),
        };
        Self {
            polygons,
            adjacency,
            scratch,
        }
    }

    /// Locates the index of the polygon containing `point`.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query position.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Containing polygon index if `point` lies on the mesh.
    #[must_use]
    pub fn find_polygon(&self, point: Vec2) -> Option<usize> {
        for (idx, poly) in self.get_polygons().iter().enumerate() {
            if poly.contains_point(point) {
                return Some(idx);
            }
        }
        None
    }

    /// Finds a taut string-pulled waypoint path between `start` and `goal` via portal A* and Funnel.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Start world position on the navmesh.
    /// - `Vec2` - Goal world position on the navmesh.
    ///
    /// # Returns
    ///
    /// - `Option<Vec<Vec2>>` - Smooth taut waypoint sequence from `start` to `goal` if connected.
    #[must_use]
    pub fn find_path(&mut self, start: Vec2, goal: Vec2) -> Option<Vec<Vec2>> {
        let mut out: Vec<Vec2> = Vec::new();
        if self.find_path_into(start, goal, &mut out) {
            Some(out)
        } else {
            None
        }
    }

    /// Finds a taut string-pulled waypoint path writing directly into reusable buffer `out_path`.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Start world position on the navmesh.
    /// - `Vec2` - Goal world position on the navmesh.
    /// - `&mut Vec<Vec2>` - Reusable output waypoint buffer.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if a connected corridor exists and `out_path` was populated.
    pub fn find_path_into(&mut self, start: Vec2, goal: Vec2, out_path: &mut Vec<Vec2>) -> bool {
        out_path.clear();
        let Some(start_poly) = self.find_polygon(start) else {
            return false;
        };
        let Some(goal_poly) = self.find_polygon(goal) else {
            return false;
        };
        if start_poly == goal_poly {
            out_path.push(start);
            if pf_vec2_dist_sq(start, goal) > 1e-10 {
                out_path.push(goal);
            }
            return true;
        }
        let poly_count: usize = self.get_polygons().len();
        let mut scratch: NavMeshScratch = take(self.get_mut_scratch());
        if scratch.seen_gen.len() != poly_count {
            scratch.seen_gen.resize(poly_count, 0);
            scratch.closed_gen.resize(poly_count, 0);
            scratch.g_scores.resize(poly_count, f32::INFINITY);
            scratch.came_from_poly.resize(poly_count, usize::MAX);
            scratch.came_from_portal.resize(poly_count, usize::MAX);
        }
        scratch.open_heap.clear();
        scratch.portal_corridor.clear();
        if scratch.generation == u32::MAX {
            scratch.seen_gen.fill(0);
            scratch.closed_gen.fill(0);
            scratch.generation = 1;
        } else {
            scratch.generation += 1;
        }
        let gen_id: u32 = scratch.generation;
        scratch.seen_gen[start_poly] = gen_id;
        scratch.g_scores[start_poly] = 0.0;
        scratch.came_from_poly[start_poly] = usize::MAX;
        scratch.came_from_portal[start_poly] = usize::MAX;
        let start_center: Vec2 = self.get_polygons()[start_poly].get_center();
        min_heap_f32_push(
            &mut scratch.open_heap,
            pf_vec2_dist(start_center, goal),
            start_poly,
        );
        let mut found: bool = false;
        while let Some((_, current_poly)) = min_heap_f32_pop(&mut scratch.open_heap) {
            if scratch.closed_gen[current_poly] == gen_id {
                continue;
            }
            scratch.closed_gen[current_poly] = gen_id;
            if current_poly == goal_poly {
                found = true;
                break;
            }
            let current_g: f32 = scratch.g_scores[current_poly];
            let entry_point: Vec2 = if current_poly == start_poly {
                start
            } else {
                let parent_p: usize = scratch.came_from_poly[current_poly];
                let portal_idx: usize = scratch.came_from_portal[current_poly];
                self.get_adjacency()[parent_p][portal_idx].get_midpoint()
            };
            let current_cost_mult: f32 = self.get_polygons()[current_poly].get_cost_multiplier();
            for (portal_idx, portal) in self.get_adjacency()[current_poly].iter().enumerate() {
                let neighbor: usize = portal.get_target_polygon();
                if scratch.closed_gen[neighbor] == gen_id {
                    continue;
                }
                let step_dist: f32 =
                    pf_vec2_dist(entry_point, portal.get_midpoint()) * current_cost_mult;
                let tentative_g: f32 = current_g + step_dist;
                if scratch.seen_gen[neighbor] != gen_id || tentative_g < scratch.g_scores[neighbor]
                {
                    scratch.seen_gen[neighbor] = gen_id;
                    scratch.g_scores[neighbor] = tentative_g;
                    scratch.came_from_poly[neighbor] = current_poly;
                    scratch.came_from_portal[neighbor] = portal_idx;
                    let heuristic: f32 = pf_vec2_dist(portal.get_midpoint(), goal);
                    min_heap_f32_push(&mut scratch.open_heap, tentative_g + heuristic, neighbor);
                }
            }
        }
        if found {
            let mut cursor: usize = goal_poly;
            while cursor != start_poly && cursor != usize::MAX {
                let parent_p: usize = scratch.came_from_poly[cursor];
                let portal_idx: usize = scratch.came_from_portal[cursor];
                let portal: NavPortal2D = self.get_adjacency()[parent_p][portal_idx];
                scratch
                    .portal_corridor
                    .push((portal.get_left(), portal.get_right()));
                cursor = parent_p;
            }
            scratch.portal_corridor.reverse();
            funnel_string_pull(start, goal, &scratch.portal_corridor, out_path);
        }
        self.set_scratch(scratch);
        found
    }
}

/// Integration and flow-vector construction and O(1) lookup for `FlowFieldGrid`.
impl FlowFieldGrid {
    /// Creates a walkable `FlowFieldGrid` with uniform cost `1` per cell.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of columns.
    /// - `usize` - Number of rows.
    /// - `f32` - World-space cell width and height (clamped to `>= 1e-4`).
    /// - `Vec2` - World-space origin `(min_x, min_y)` of cell `(0, 0)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized flow field grid.
    #[must_use]
    pub fn new(width: usize, height: usize, cell_size: f32, origin: Vec2) -> Self {
        let count: usize = width.saturating_mul(height);
        let safe_size: f32 = if cell_size.is_finite() && cell_size > 1e-4 {
            cell_size
        } else {
            1.0
        };
        Self {
            width,
            height,
            cell_size: safe_size,
            origin,
            costs: vec![1; count],
            integration: vec![u32::MAX; count],
            flow_vectors: vec![Vec2::zero(); count],
            scratch: FlowFieldScratch {
                open_heap: Vec::with_capacity(count.min(256)),
            },
        }
    }

    /// Sets the traversal cost of `coord` (`0` clamped to `1`, `255` marks impassable).
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate to modify.
    /// - `u8` - Cost byte (`1..=254` walkable, `255` wall).
    pub fn set_cost(&mut self, coord: GridCoord, cost: u8) {
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        if coord.get_x() < width && coord.get_y() < height {
            let idx: usize = coord.get_y() * width + coord.get_x();
            self.get_mut_costs()[idx] = if cost == 0 { 1 } else { cost };
        }
    }

    /// Marks `coord` as impassable (`blocked == true`) or normal cost `1` (`blocked == false`).
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate to update.
    /// - `bool` - Whether the cell is a solid obstacle.
    pub fn set_blocked(&mut self, coord: GridCoord, blocked: bool) {
        self.set_cost(coord, if blocked { FLOW_IMPASSABLE } else { 1 });
    }

    /// Computes Dijkstra integration distances and smooth downhill flow vectors toward `goals`.
    ///
    /// # Arguments
    ///
    /// - `&[GridCoord]` - One or more goal cell coordinates.
    pub fn build_for_goals(&mut self, goals: &[GridCoord]) {
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        let count: usize = width * height;
        if count == 0 {
            return;
        }
        let mut integration: Vec<u32> = take(self.get_mut_integration());
        integration.resize(count, u32::MAX);
        integration.fill(u32::MAX);
        let mut flow_vectors: Vec<Vec2> = take(self.get_mut_flow_vectors());
        flow_vectors.resize(count, Vec2::zero());
        flow_vectors.fill(Vec2::zero());
        let mut scratch: FlowFieldScratch = take(self.get_mut_scratch());
        scratch.open_heap.clear();
        let costs: &[u8] = self.get_costs();
        for &goal in goals {
            if goal.get_x() < width && goal.get_y() < height {
                let idx: usize = goal.get_y() * width + goal.get_x();
                if costs[idx] < FLOW_IMPASSABLE {
                    integration[idx] = 0;
                    min_heap_u32_push(&mut scratch.open_heap, 0, idx);
                }
            }
        }
        let dirs_8: [(isize, isize, u32); 8] = [
            (1, 0, 10),
            (-1, 0, 10),
            (0, 1, 10),
            (0, -1, 10),
            (1, 1, 14),
            (1, -1, 14),
            (-1, 1, 14),
            (-1, -1, 14),
        ];
        while let Some((dist, current_idx)) = min_heap_u32_pop(&mut scratch.open_heap) {
            if dist > integration[current_idx] {
                continue;
            }
            let cx: isize = (current_idx % width) as isize;
            let cy: isize = (current_idx / width) as isize;
            for &(dx, dy, base_step) in &dirs_8 {
                let nx: isize = cx + dx;
                let ny: isize = cy + dy;
                let in_x: bool = nx >= 0 && nx < width as isize;
                let in_y: bool = ny >= 0 && ny < height as isize;
                if !in_x || !in_y {
                    continue;
                }
                let next_idx: usize = (ny as usize) * width + (nx as usize);
                let cell_cost: u8 = costs[next_idx];
                if cell_cost == FLOW_IMPASSABLE {
                    continue;
                }
                if dx != 0 && dy != 0 {
                    let adj_x: usize = (cy as usize) * width + ((cx + dx) as usize);
                    let adj_y: usize = ((cy + dy) as usize) * width + (cx as usize);
                    if costs[adj_x] == FLOW_IMPASSABLE || costs[adj_y] == FLOW_IMPASSABLE {
                        continue;
                    }
                }
                let next_dist: u32 =
                    dist.saturating_add(base_step.saturating_mul(cell_cost as u32));
                if next_dist < integration[next_idx] {
                    integration[next_idx] = next_dist;
                    min_heap_u32_push(&mut scratch.open_heap, next_dist, next_idx);
                }
            }
        }
        for y in 0..height {
            for x in 0..width {
                let idx: usize = y * width + x;
                let cur_dist: u32 = integration[idx];
                if cur_dist == 0 || cur_dist == u32::MAX {
                    flow_vectors[idx] = Vec2::zero();
                    continue;
                }
                let mut best_dist: u32 = cur_dist;
                let mut best_dir: Vec2 = Vec2::zero();
                let cx: isize = x as isize;
                let cy: isize = y as isize;
                for &(dx, dy, _) in &dirs_8 {
                    let nx: isize = cx + dx;
                    let ny: isize = cy + dy;
                    let in_x: bool = nx >= 0 && nx < width as isize;
                    let in_y: bool = ny >= 0 && ny < height as isize;
                    if !in_x || !in_y {
                        continue;
                    }
                    let n_idx: usize = (ny as usize) * width + (nx as usize);
                    if costs[n_idx] == FLOW_IMPASSABLE {
                        continue;
                    }
                    if dx != 0 && dy != 0 {
                        let adj_x: usize = (cy as usize) * width + ((cx + dx) as usize);
                        let adj_y: usize = ((cy + dy) as usize) * width + (cx as usize);
                        if costs[adj_x] == FLOW_IMPASSABLE || costs[adj_y] == FLOW_IMPASSABLE {
                            continue;
                        }
                    }
                    if integration[n_idx] < best_dist {
                        best_dist = integration[n_idx];
                        best_dir = Vec2::new(dx as f32, dy as f32);
                    }
                }
                flow_vectors[idx] = pf_vec2_normalize_or_zero(best_dir);
            }
        }
        self.set_integration(integration);
        self.set_flow_vectors(flow_vectors);
        self.set_scratch(scratch);
    }

    /// Returns the unit flow direction at integer cell `coord` in O(1) time.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate.
    ///
    /// # Returns
    ///
    /// - `Vec2` - Unit flow direction, or `(0, 0)` at goals, walls, or out of bounds.
    #[must_use]
    pub fn direction_at_cell(&self, coord: GridCoord) -> Vec2 {
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        if coord.get_x() < width && coord.get_y() < height {
            self.get_flow_vectors()[coord.get_y() * width + coord.get_x()]
        } else {
            Vec2::zero()
        }
    }

    /// Returns the integration distance at `coord` (`u32::MAX` if unreachable or out of bounds).
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate.
    ///
    /// # Returns
    ///
    /// - `u32` - Integration distance to the nearest goal.
    #[must_use]
    pub fn integration_at(&self, coord: GridCoord) -> u32 {
        let width: usize = self.get_width();
        let height: usize = self.get_height();
        if coord.get_x() < width && coord.get_y() < height {
            self.get_integration()[coord.get_y() * width + coord.get_x()]
        } else {
            u32::MAX
        }
    }

    /// Converts a world position to its enclosing `GridCoord` if within bounds.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - World-space 2D position.
    ///
    /// # Returns
    ///
    /// - `Option<GridCoord>` - Containing cell coordinate if inside grid extents.
    #[must_use]
    pub fn world_to_cell(&self, world_pos: Vec2) -> Option<GridCoord> {
        let rel: Vec2 = pf_vec2_sub(world_pos, self.get_origin());
        let inv_size: f32 = 1.0 / self.get_cell_size();
        let gx: isize = (rel.get_x() * inv_size).floor() as isize;
        let gy: isize = (rel.get_y() * inv_size).floor() as isize;
        if gx >= 0
            && gy >= 0
            && (gx as usize) < self.get_width()
            && (gy as usize) < self.get_height()
        {
            Some(GridCoord::new(gx as usize, gy as usize))
        } else {
            None
        }
    }

    /// Converts a `GridCoord` into the world-space center of that cell.
    ///
    /// # Arguments
    ///
    /// - `GridCoord` - Cell coordinate.
    ///
    /// # Returns
    ///
    /// - `Vec2` - World-space center of the cell.
    #[must_use]
    pub fn cell_center(&self, coord: GridCoord) -> Vec2 {
        let size: f32 = self.get_cell_size();
        let origin: Vec2 = self.get_origin();
        Vec2::new(
            origin.get_x() + (coord.get_x() as f32 + 0.5) * size,
            origin.get_y() + (coord.get_y() as f32 + 0.5) * size,
        )
    }

    /// Samples the flow direction at continuous world position `world_pos` in O(1) time.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - World-space agent position.
    ///
    /// # Returns
    ///
    /// - `Vec2` - Unit steering direction toward the nearest goal.
    #[must_use]
    pub fn sample_direction(&self, world_pos: Vec2) -> Vec2 {
        if let Some(cell) = self.world_to_cell(world_pos) {
            self.direction_at_cell(cell)
        } else {
            Vec2::zero()
        }
    }
}

/// Default configuration for `OrcaCrowdConfig`.
impl Default for OrcaCrowdConfig {
    /// Returns balanced default neighbor radius, lookahead horizon, and neighbor cap.
    ///
    /// # Returns
    ///
    /// - `Self` - Default ORCA crowd configuration.
    fn default() -> Self {
        Self {
            default_neighbor_dist: DEFAULT_ORCA_NEIGHBOR_DIST,
            default_time_horizon: DEFAULT_ORCA_TIME_HORIZON,
            max_neighbors: 16,
        }
    }
}

/// Constructors for `OrcaAgent2D`.
impl OrcaAgent2D {
    /// Creates an ORCA agent with explicit position, radius, and maximum speed.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Initial 2D position.
    /// - `f32` - Agent collision disk radius.
    /// - `f32` - Maximum movement speed.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized crowd agent.
    #[must_use]
    pub fn new(position: Vec2, radius: f32, max_speed: f32) -> Self {
        let safe_radius: f32 = if radius.is_finite() && radius > 1e-4 {
            radius
        } else {
            0.5
        };
        let safe_speed: f32 = if max_speed.is_finite() && max_speed > 0.0 {
            max_speed
        } else {
            1.0
        };
        Self {
            position,
            velocity: Vec2::zero(),
            preferred_velocity: Vec2::zero(),
            radius: safe_radius,
            max_speed: safe_speed,
            neighbor_dist: DEFAULT_ORCA_NEIGHBOR_DIST,
            time_horizon: DEFAULT_ORCA_TIME_HORIZON,
        }
    }
}

/// Multi-agent ORCA / RVO2 half-plane solver implementation for `OrcaCrowdSolver`.
impl OrcaCrowdSolver {
    /// Creates a new `OrcaCrowdSolver` with the supplied configuration defaults.
    ///
    /// # Arguments
    ///
    /// - `OrcaCrowdConfig` - Default neighbor search and horizon parameters.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty ORCA crowd solver.
    #[must_use]
    pub fn new(config: OrcaCrowdConfig) -> Self {
        Self {
            config,
            agents: Vec::new(),
            scratch: OrcaScratch {
                orca_lines: Vec::with_capacity(32),
                proj_lines: Vec::with_capacity(32),
                new_velocities: Vec::with_capacity(64),
                neighbor_indices: Vec::with_capacity(32),
            },
        }
    }

    /// Adds an agent to the crowd solver and returns its stable index.
    ///
    /// # Arguments
    ///
    /// - `OrcaAgent2D` - Agent descriptor to register.
    ///
    /// # Returns
    ///
    /// - `usize` - Index of the added agent.
    pub fn add_agent(&mut self, mut agent: OrcaAgent2D) -> usize {
        let cfg: OrcaCrowdConfig = self.get_config();
        if agent.get_neighbor_dist() <= 0.0 || !agent.get_neighbor_dist().is_finite() {
            agent.set_neighbor_dist(cfg.get_default_neighbor_dist());
        }
        if agent.get_time_horizon() <= 0.0 || !agent.get_time_horizon().is_finite() {
            agent.set_time_horizon(cfg.get_default_time_horizon());
        }
        let idx: usize = self.get_agents().len();
        self.get_mut_agents().push(agent);
        idx
    }

    /// Updates an agent's preferred velocity (clamped to its maximum speed).
    ///
    /// # Arguments
    ///
    /// - `usize` - Target agent index.
    /// - `Vec2` - Desired preferred velocity vector.
    pub fn set_preferred_velocity(&mut self, index: usize, preferred: Vec2) {
        if let Some(agent) = self.get_mut_agents().get_mut(index) {
            let max_speed: f32 = agent.get_max_speed();
            agent.set_preferred_velocity(pf_vec2_clamp_len(preferred, max_speed));
        }
    }

    /// Solves collision-free velocities for all agents and advances their positions by `dt`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Simulation time step in seconds (must be positive and finite).
    pub fn step(&mut self, dt: f32) {
        if !dt.is_finite() || dt <= 1e-6 {
            return;
        }
        let count: usize = self.get_agents().len();
        if count == 0 {
            return;
        }
        let max_neighbors: usize = self.get_config().get_max_neighbors().max(1);
        let inv_time_step: f32 = 1.0 / dt;
        let mut scratch: OrcaScratch = take(self.get_mut_scratch());
        scratch.new_velocities.clear();
        scratch.new_velocities.resize(count, Vec2::zero());
        let agents: &[OrcaAgent2D] = self.get_agents();
        for idx in 0..count {
            let agent_i: OrcaAgent2D = agents[idx];
            let pos_i: Vec2 = agent_i.get_position();
            let vel_i: Vec2 = agent_i.get_velocity();
            let pref_i: Vec2 =
                pf_vec2_clamp_len(agent_i.get_preferred_velocity(), agent_i.get_max_speed());
            let rad_i: f32 = agent_i.get_radius();
            let max_speed_i: f32 = agent_i.get_max_speed();
            let neighbor_dist_sq: f32 = agent_i.get_neighbor_dist() * agent_i.get_neighbor_dist();
            let inv_tau: f32 = 1.0 / agent_i.get_time_horizon().max(dt);
            scratch.neighbor_indices.clear();
            for (other_idx, other) in agents.iter().enumerate() {
                if other_idx == idx {
                    continue;
                }
                let d_sq: f32 = pf_vec2_dist_sq(pos_i, other.get_position());
                if d_sq <= neighbor_dist_sq {
                    scratch.neighbor_indices.push((d_sq, other_idx));
                }
            }
            scratch
                .neighbor_indices
                .sort_by(|lhs: &(f32, usize), rhs: &(f32, usize)| lhs.0.total_cmp(&rhs.0));
            let active_neighbors: usize = scratch.neighbor_indices.len().min(max_neighbors);
            scratch.orca_lines.clear();
            let mut has_head_on: bool = false;
            for n_slot in 0..active_neighbors {
                let other_idx: usize = scratch.neighbor_indices[n_slot].1;
                let agent_j: OrcaAgent2D = agents[other_idx];
                let rel_pos: Vec2 = pf_vec2_sub(agent_j.get_position(), pos_i);
                let rel_vel: Vec2 = pf_vec2_sub(vel_i, agent_j.get_velocity());
                let dist_sq: f32 = pf_vec2_len_sq(rel_pos);
                let comb_r: f32 = rad_i + agent_j.get_radius();
                let comb_r_sq: f32 = comb_r * comb_r;
                if pf_vec2_det(rel_pos, pref_i).abs() < 1e-3 * comb_r.max(1.0)
                    && rel_pos.dot(pref_i) > 0.0
                {
                    has_head_on = true;
                }
                let (u_vec, direction): (Vec2, Vec2) = if dist_sq > comb_r_sq {
                    let w_vec: Vec2 = pf_vec2_sub(rel_vel, pf_vec2_scale(rel_pos, inv_tau));
                    let w_len_sq: f32 = pf_vec2_len_sq(w_vec);
                    let dot_product: f32 = w_vec.dot(rel_pos);
                    if dot_product < 0.0 && dot_product * dot_product > comb_r_sq * w_len_sq {
                        let w_len: f32 = w_len_sq.sqrt();
                        let unit_w: Vec2 = if w_len > ORCA_EPSILON {
                            pf_vec2_scale(w_vec, 1.0 / w_len)
                        } else {
                            pf_vec2_normalize_or_zero(pf_vec2_scale(rel_pos, -1.0))
                        };
                        let dir: Vec2 = Vec2::new(unit_w.get_y(), -unit_w.get_x());
                        let u_out: Vec2 = pf_vec2_scale(unit_w, comb_r * inv_tau - w_len);
                        (u_out, dir)
                    } else {
                        let leg: f32 = (dist_sq - comb_r_sq).max(0.0).sqrt();
                        let side_det: f32 = pf_vec2_det(rel_pos, w_vec);
                        let dir: Vec2 = if side_det > 0.0 {
                            pf_vec2_scale(
                                Vec2::new(
                                    rel_pos.get_x() * leg - rel_pos.get_y() * comb_r,
                                    rel_pos.get_x() * comb_r + rel_pos.get_y() * leg,
                                ),
                                1.0 / dist_sq,
                            )
                        } else {
                            pf_vec2_scale(
                                Vec2::new(
                                    rel_pos.get_x() * leg + rel_pos.get_y() * comb_r,
                                    -rel_pos.get_x() * comb_r + rel_pos.get_y() * leg,
                                ),
                                -1.0 / dist_sq,
                            )
                        };
                        let proj: f32 = rel_vel.dot(dir);
                        let u_out: Vec2 = pf_vec2_sub(pf_vec2_scale(dir, proj), rel_vel);
                        (u_out, dir)
                    }
                } else {
                    let w_vec: Vec2 = pf_vec2_sub(rel_vel, pf_vec2_scale(rel_pos, inv_time_step));
                    let w_len: f32 = pf_vec2_len(w_vec);
                    let unit_w: Vec2 = if w_len > ORCA_EPSILON {
                        pf_vec2_scale(w_vec, 1.0 / w_len)
                    } else if dist_sq > 1e-10 {
                        pf_vec2_normalize_or_zero(pf_vec2_scale(rel_pos, -1.0))
                    } else {
                        let angle: f32 = (idx as f32) * 2.399_963_1;
                        Vec2::new(angle.cos(), angle.sin())
                    };
                    let dir: Vec2 = Vec2::new(unit_w.get_y(), -unit_w.get_x());
                    let u_out: Vec2 = pf_vec2_scale(unit_w, comb_r * inv_time_step - w_len);
                    (u_out, dir)
                };
                let point: Vec2 = pf_vec2_add(vel_i, pf_vec2_scale(u_vec, 0.5));
                scratch.orca_lines.push(OrcaLine2D::new(point, direction));
            }
            let opt_vel: Vec2 = if has_head_on {
                let right_dir: Vec2 =
                    pf_vec2_normalize_or_zero(Vec2::new(pref_i.get_y(), -pref_i.get_x()));
                pf_vec2_clamp_len(
                    pf_vec2_add(
                        pref_i,
                        pf_vec2_scale(right_dir, ORCA_PASSING_BIAS * max_speed_i * 50.0),
                    ),
                    max_speed_i,
                )
            } else {
                pref_i
            };
            let mut solved_vel: Vec2 = Vec2::zero();
            let fail_line: usize = orca_linear_program2(
                &scratch.orca_lines,
                max_speed_i,
                opt_vel,
                false,
                &mut solved_vel,
            );
            if fail_line < scratch.orca_lines.len() {
                orca_linear_program3(
                    &scratch.orca_lines,
                    fail_line,
                    max_speed_i,
                    &mut scratch.proj_lines,
                    &mut solved_vel,
                );
            }
            scratch.new_velocities[idx] = pf_vec2_clamp_len(solved_vel, max_speed_i);
        }
        for (idx, agent) in self.get_mut_agents().iter_mut().enumerate() {
            let next_vel: Vec2 = scratch.new_velocities[idx];
            let next_pos: Vec2 = pf_vec2_add(agent.get_position(), pf_vec2_scale(next_vel, dt));
            agent.set_velocity(next_vel);
            agent.set_position(next_pos);
        }
        self.set_scratch(scratch);
    }
}