waymark 0.1.0

Pathfinding and spatial queries on navigation meshes
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
//! Concurrency safety tests for advanced navigation functions
//!
//! This module tests the thread safety of navigation mesh operations,
//! including concurrent read operations and proper synchronization for
//! write operations (poly flags/area modifications).

#![allow(unused)]

use crate::test_mesh_helpers::*;
use crate::{NavMeshQuery, PolyFlags, PolyRef, QueryFilter};
use glam::Vec3;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Duration;

#[cfg(test)]
mod concurrent_read_tests {
    use super::*;

    #[test]
    fn test_concurrent_move_along_surface() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(create_complex_test_navmesh()?);
        let num_threads = 4;
        let operations_per_thread = 100;

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        let query = NavMeshQuery::new(&nav_mesh_clone);
                        let filter = QueryFilter::default();

                        // Find starting position
                        let start_pos = get_test_position_complex();
                        let extents = get_test_extents();
                        let (start_ref, actual_start_pos) = query.find_nearest_poly(
                            Vec3::from(start_pos),
                            Vec3::from(extents),
                            &filter,
                        )?;

                        // Perform many operations
                        for i in 0..operations_per_thread {
                            let offset = (thread_id as f32 * 0.1) + (i as f32 * 0.01);
                            let end_pos = Vec3::new(
                                actual_start_pos[0] + offset,
                                actual_start_pos[1],
                                actual_start_pos[2] + offset,
                            );

                            let result = query.move_along_surface(
                                start_ref,
                                actual_start_pos,
                                end_pos,
                                &filter,
                            )?;

                            // Verify results are consistent
                            assert!(
                                !result.visited.is_empty(),
                                "Should visit at least one polygon"
                            );
                            assert!(
                                result.visited[0] == start_ref,
                                "First visited should be start polygon"
                            );
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle
                .join()
                .expect("Thread panicked")
                .expect("Thread operation failed");
        }

        Ok(())
    }

    #[test]
    fn test_concurrent_find_local_neighbourhood() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(create_complex_test_navmesh()?);
        let num_threads = 8;
        let operations_per_thread = 50;

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        let query = NavMeshQuery::new(&nav_mesh_clone);
                        let filter = QueryFilter::default();

                        // Find starting position
                        let center_pos = get_test_position_complex();
                        let extents = get_test_extents();
                        let (start_ref, actual_center_pos) = query.find_nearest_poly(
                            Vec3::from(center_pos),
                            Vec3::from(extents),
                            &filter,
                        )?;

                        // Perform operations with varying parameters
                        for i in 0..operations_per_thread {
                            let radius = 0.1 + (thread_id as f32 * 0.1) + (i as f32 * 0.02);
                            let max_result = 5 + (thread_id % 10);

                            let (polys, parents) = query.find_local_neighbourhood(
                                start_ref,
                                actual_center_pos,
                                radius,
                                &filter,
                                max_result,
                            )?;

                            // Verify results are consistent
                            assert!(!polys.is_empty(), "Should find at least one polygon");
                            assert_eq!(
                                polys.len(),
                                parents.len(),
                                "Polys and parents should be same length"
                            );
                            assert_eq!(polys[0], start_ref, "First polygon should be start");
                            assert!(
                                !parents[0].is_valid(),
                                "Start polygon should have no parent"
                            );
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle
                .join()
                .expect("Thread panicked")
                .expect("Thread operation failed");
        }

        Ok(())
    }

    #[test]
    fn test_concurrent_mixed_read_operations() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(create_large_test_navmesh()?);
        let num_threads = 6;

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        let query = NavMeshQuery::new(&nav_mesh_clone);
                        let filter = QueryFilter::default();

                        let start_pos = get_test_position_large();
                        let extents = [5.0, 5.0, 5.0];
                        let (start_ref, actual_start_pos) = query.find_nearest_poly(
                            Vec3::from(start_pos),
                            Vec3::from(extents),
                            &filter,
                        )?;

                        // Mix different types of read operations
                        for i in 0..50 {
                            match (thread_id + i) % 3 {
                                0 => {
                                    // moveAlongSurface
                                    let end_pos = Vec3::new(
                                        actual_start_pos[0] + (i as f32 * 0.1),
                                        actual_start_pos[1],
                                        actual_start_pos[2] + (i as f32 * 0.1),
                                    );
                                    query.move_along_surface(
                                        start_ref,
                                        actual_start_pos,
                                        end_pos,
                                        &filter,
                                    )?;
                                }
                                1 => {
                                    // findLocalNeighbourhood
                                    let radius = 1.0 + (i as f32 * 0.1);
                                    query.find_local_neighbourhood(
                                        start_ref,
                                        actual_start_pos,
                                        radius,
                                        &filter,
                                        10,
                                    )?;
                                }
                                2 => {
                                    // find_nearest_poly (baseline operation)
                                    let test_pos = [
                                        actual_start_pos[0] + (i as f32 * 0.05),
                                        actual_start_pos[1],
                                        actual_start_pos[2] + (i as f32 * 0.05),
                                    ];
                                    query.find_nearest_poly(
                                        Vec3::from(test_pos),
                                        Vec3::from(extents),
                                        &filter,
                                    )?;
                                }
                                _ => unreachable!(),
                            }
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle
                .join()
                .expect("Thread panicked")
                .expect("Thread operation failed");
        }

        Ok(())
    }
}

#[cfg(test)]
mod concurrent_write_tests {
    use super::*;

    #[test]
    fn test_concurrent_poly_flags_modification() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(Mutex::new(create_complex_test_navmesh()?));
        let num_threads = 4;
        let operations_per_thread = 100;

        // Find a polygon to test with
        let poly_ref = {
            let mesh = nav_mesh.lock().unwrap();
            let query = NavMeshQuery::new(&mesh);
            let filter = QueryFilter::default();
            let center_pos = get_test_position_complex();
            let extents = get_test_extents();
            let (poly_ref, _) =
                query.find_nearest_poly(Vec3::from(center_pos), Vec3::from(extents), &filter)?;
            poly_ref
        };

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        for i in 0..operations_per_thread {
                            let mut mesh = nav_mesh_clone.lock().unwrap();

                            // Each thread sets different flags to test concurrent access
                            let flags = match thread_id % 3 {
                                0 => PolyFlags::WALK,
                                1 => PolyFlags::SWIM,
                                2 => PolyFlags::WALK | PolyFlags::SWIM,
                                _ => PolyFlags::DOOR,
                            };

                            mesh.set_poly_flags(poly_ref, flags)?;
                            let retrieved_flags = mesh.get_poly_flags(poly_ref)?;

                            // The retrieved flags should be some valid flag combination
                            // (exact value depends on thread scheduling)
                            assert!(
                                !retrieved_flags.is_empty() || retrieved_flags.is_empty(),
                                "Flags should be in a valid state"
                            );

                            // Small delay to increase chance of contention
                            if i % 10 == 0 {
                                drop(mesh); // Release lock
                                thread::sleep(Duration::from_nanos(1000));
                            }
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle
                .join()
                .expect("Thread panicked")
                .expect("Thread operation failed");
        }

        Ok(())
    }

    #[test]
    fn test_concurrent_poly_area_modification() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(Mutex::new(create_complex_test_navmesh()?));
        let num_threads = 4;
        let operations_per_thread = 100;

        // Find a polygon to test with
        let poly_ref = {
            let mesh = nav_mesh.lock().unwrap();
            let query = NavMeshQuery::new(&mesh);
            let filter = QueryFilter::default();
            let center_pos = get_test_position_complex();
            let extents = get_test_extents();
            let (poly_ref, _) =
                query.find_nearest_poly(Vec3::from(center_pos), Vec3::from(extents), &filter)?;
            poly_ref
        };

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        for i in 0..operations_per_thread {
                            let mut mesh = nav_mesh_clone.lock().unwrap();

                            // Each thread sets different areas
                            let area = ((thread_id * 50) + (i % 50)) as u8;

                            mesh.set_poly_area(poly_ref, area)?;
                            let retrieved_area = mesh.get_poly_area(poly_ref)?;

                            // The retrieved area should be some valid area value
                            assert!(retrieved_area <= 255, "Area should be valid u8 value");

                            // Small delay to increase chance of contention
                            if i % 10 == 0 {
                                drop(mesh); // Release lock
                                thread::sleep(Duration::from_nanos(1000));
                            }
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle
                .join()
                .expect("Thread panicked")
                .expect("Thread operation failed");
        }

        Ok(())
    }

    #[test]
    fn test_concurrent_mixed_read_write_operations() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(RwLock::new(create_complex_test_navmesh()?));
        let num_readers = 6;
        let num_writers = 2;

        // Find test polygon
        let poly_ref = {
            let mesh = nav_mesh.read().unwrap();
            let query = NavMeshQuery::new(&mesh);
            let filter = QueryFilter::default();
            let center_pos = get_test_position_complex();
            let extents = get_test_extents();
            let (poly_ref, _) =
                query.find_nearest_poly(Vec3::from(center_pos), Vec3::from(extents), &filter)?;
            poly_ref
        };

        // Start reader threads
        let reader_handles: Vec<_> = (0..num_readers)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        for i in 0..100 {
                            let mesh = nav_mesh_clone.read().unwrap();
                            let query = NavMeshQuery::new(&mesh);
                            let filter = QueryFilter::default();

                            let start_pos = get_test_position_complex();
                            let extents = get_test_extents();
                            let (start_ref, actual_start_pos) = query.find_nearest_poly(
                                Vec3::from(start_pos),
                                Vec3::from(extents),
                                &filter,
                            )?;

                            // Perform read operations
                            match i % 2 {
                                0 => {
                                    let end_pos = Vec3::new(
                                        actual_start_pos[0] + 0.1,
                                        actual_start_pos[1],
                                        actual_start_pos[2] + 0.1,
                                    );
                                    query.move_along_surface(
                                        start_ref,
                                        actual_start_pos,
                                        end_pos,
                                        &filter,
                                    )?;
                                }
                                1 => {
                                    query.find_local_neighbourhood(
                                        start_ref,
                                        actual_start_pos,
                                        0.5,
                                        &filter,
                                        5,
                                    )?;
                                }
                                _ => unreachable!(),
                            }

                            // Small delay
                            if i % 20 == 0 {
                                drop(mesh); // Release read lock
                                thread::sleep(Duration::from_millis(1));
                            }
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Start writer threads
        let writer_handles: Vec<_> = (0..num_writers)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        for i in 0..50 {
                            let mut mesh = nav_mesh_clone.write().unwrap();

                            // Perform write operations
                            let flags = if thread_id == 0 {
                                PolyFlags::WALK
                            } else {
                                PolyFlags::SWIM
                            };
                            let area = ((thread_id * 100) + i) as u8;

                            mesh.set_poly_flags(poly_ref, flags)?;
                            mesh.set_poly_area(poly_ref, area)?;

                            // Verify writes
                            let retrieved_flags = mesh.get_poly_flags(poly_ref)?;
                            let retrieved_area = mesh.get_poly_area(poly_ref)?;

                            assert!(
                                !retrieved_flags.is_empty() || retrieved_flags.is_empty(),
                                "Flags should be in valid state"
                            );
                            assert!(retrieved_area <= 255, "Area should be valid");

                            // Delay to allow readers to interleave
                            if i % 5 == 0 {
                                drop(mesh); // Release write lock
                                thread::sleep(Duration::from_millis(2));
                            }
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in reader_handles {
            handle
                .join()
                .expect("Reader thread panicked")
                .expect("Reader operation failed");
        }
        for handle in writer_handles {
            handle
                .join()
                .expect("Writer thread panicked")
                .expect("Writer operation failed");
        }

        Ok(())
    }
}

#[cfg(test)]
mod stress_concurrency_tests {
    use super::*;

    #[test]
    fn test_high_contention_scenario() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(Mutex::new(create_large_test_navmesh()?));
        let num_threads = 16;
        let operations_per_thread = 200;

        // Find multiple polygons for testing
        let poly_refs: Vec<PolyRef> = {
            let mesh = nav_mesh.lock().unwrap();
            let query = NavMeshQuery::new(&mesh);
            let filter = QueryFilter::default();

            let mut refs = Vec::new();
            for i in 0..10 {
                let pos = [5.0 + (i as f32), 0.0, 5.0 + (i as f32)];
                let extents = [1.0, 1.0, 1.0];
                if let Ok((poly_ref, _)) =
                    query.find_nearest_poly(Vec3::from(pos), Vec3::from(extents), &filter)
                {
                    refs.push(poly_ref);
                }
            }
            refs
        };

        let poly_refs = Arc::new(poly_refs);

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);
                let poly_refs_clone = Arc::clone(&poly_refs);

                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        for i in 0..operations_per_thread {
                            let mut mesh = nav_mesh_clone.lock().unwrap();

                            // Randomly select a polygon to modify
                            let poly_idx = (thread_id + i) % poly_refs_clone.len();
                            if poly_idx < poly_refs_clone.len() {
                                let poly_ref = poly_refs_clone[poly_idx];

                                // Perform random operations
                                match i % 4 {
                                    0 => {
                                        let flags = PolyFlags::from_bits_truncate(
                                            thread_id as u16 + i as u16,
                                        );
                                        mesh.set_poly_flags(poly_ref, flags)?;
                                    }
                                    1 => {
                                        let area = ((thread_id + i) % 256) as u8;
                                        mesh.set_poly_area(poly_ref, area)?;
                                    }
                                    2 => {
                                        mesh.get_poly_flags(poly_ref)?;
                                    }
                                    3 => {
                                        mesh.get_poly_area(poly_ref)?;
                                    }
                                    _ => unreachable!(),
                                }
                            }

                            // Brief contention-inducing delay
                            if i % 50 == 0 {
                                drop(mesh);
                                thread::sleep(Duration::from_nanos(100));
                            }
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle
                .join()
                .expect("High contention thread panicked")
                .expect("High contention operation failed");
        }

        Ok(())
    }

    #[test]
    fn test_deadlock_prevention() -> Result<(), Box<dyn std::error::Error>> {
        let nav_mesh = Arc::new(Mutex::new(create_complex_test_navmesh()?));
        let num_threads = 8;

        // This test attempts to trigger potential deadlock scenarios
        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let nav_mesh_clone = Arc::clone(&nav_mesh);

                thread::spawn(
                    move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                        for i in 0..100 {
                            // Different threads acquire locks in different patterns
                            // to test for potential deadlocks

                            if thread_id % 2 == 0 {
                                // Even threads: short operations with frequent lock release
                                for _ in 0..5 {
                                    let mesh = nav_mesh_clone.lock().unwrap();
                                    let query = NavMeshQuery::new(&mesh);
                                    let filter = QueryFilter::default();
                                    let pos = get_test_position_complex();
                                    let extents = get_test_extents();

                                    if let Ok((poly_ref, _)) = query.find_nearest_poly(
                                        Vec3::from(pos),
                                        Vec3::from(extents),
                                        &filter,
                                    ) {
                                        drop(mesh); // Release lock early
                                        let mut mesh = nav_mesh_clone.lock().unwrap();
                                        mesh.get_poly_flags(poly_ref)?;
                                    }

                                    thread::sleep(Duration::from_nanos(500));
                                }
                            } else {
                                // Odd threads: longer operations with less frequent release
                                for j in 0..3 {
                                    let pos = [
                                        get_test_position_complex()[0] + (j as f32 * 0.1),
                                        0.0,
                                        get_test_position_complex()[2] + (j as f32 * 0.1),
                                    ];
                                    let extents = get_test_extents();

                                    // Acquire lock for read operation
                                    let poly_ref = {
                                        let mesh = nav_mesh_clone.lock().unwrap();
                                        let query = NavMeshQuery::new(&mesh);
                                        let filter = QueryFilter::default();

                                        if let Ok((poly_ref, _)) = query.find_nearest_poly(
                                            Vec3::from(pos),
                                            Vec3::from(extents),
                                            &filter,
                                        ) {
                                            poly_ref
                                        } else {
                                            continue;
                                        }
                                    };

                                    // Acquire lock for write operations
                                    {
                                        let mut mesh = nav_mesh_clone.lock().unwrap();
                                        mesh.set_poly_flags(poly_ref, PolyFlags::WALK)?;
                                    }

                                    // Brief delay to allow other threads
                                    thread::sleep(Duration::from_millis(1));

                                    // Acquire lock for second write operation
                                    {
                                        let mut mesh = nav_mesh_clone.lock().unwrap();
                                        mesh.set_poly_area(poly_ref, (j + thread_id) as u8)?;
                                    }
                                }
                            }

                            // Random delay to vary timing
                            thread::sleep(Duration::from_nanos((thread_id * 1000) as u64));
                        }

                        Ok(())
                    },
                )
            })
            .collect();

        // Use a timeout to detect potential deadlocks
        let timeout = Duration::from_secs(30);
        let start_time = std::time::Instant::now();

        for (i, handle) in handles.into_iter().enumerate() {
            if start_time.elapsed() > timeout {
                panic!("Potential deadlock detected - test took too long");
            }

            handle
                .join()
                .map_err(|_| format!("Thread {} panicked", i))
                .expect("Thread join failed")
                .expect("Thread operation failed");
        }

        Ok(())
    }
}