aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/unit_patrol.rs
blob: c4b3b9694d869bbbd9cba61b7cd8e3ada37c47ae (plain) (blame)
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
use super::{
    autodemo::{MOBILE_UNIT, PLANT_CLASS},
    boarding::WARBOT_CLASS,
    next_crt_rand,
    unit_combat::CombatTarget,
    EngineError, MissionDocument, MissionObjectDraft, MissionScriptBundle, ObjectHandle,
    TerrainWorld, TransformState, World,
};
use fparkan_script::{Handler15TargetPayload, ScriptDispatchSelector, VarSet};
use fparkan_terrain::{NavigationQuery, RouteRequest, SurfaceQuery};
use fparkan_world::{set_transform, transform_state};
use std::collections::{HashSet, VecDeque};

#[derive(Clone)]
pub(super) struct UnitPatrol {
    center: Option<[f32; 2]>,
    units: Vec<PatrollingUnit>,
    shut_down: HashSet<ObjectHandle>,
    clock_ms: u32,
    rng: u32,
    pub(super) factory_raid_clans: usize,
}

#[derive(Clone)]
struct PatrollingUnit {
    handle: ObjectHandle,
    center: [f32; 2],
    center_object: Option<ObjectHandle>,
    destinations: Option<VecDeque<[f32; 2]>>,
    radius: f32,
    points: VecDeque<[f32; 2]>,
    retry_ms: u32,
    attack: Option<ObjectHandle>,
    attack_target: Option<(ObjectHandle, usize)>,
    raid_factory: Option<(ObjectHandle, usize)>,
}

pub(super) struct PreparedPatrol {
    pub(super) state: UnitPatrol,
    poses: Vec<(ObjectHandle, TransformState, TransformState)>,
}

#[derive(Clone, Copy)]
pub(super) struct PatrolAttackLimit {
    center: [f32; 2],
    radius: f32,
    current_target: Option<ObjectHandle>,
}

impl PatrolAttackLimit {
    pub(super) fn allows_attack(self, position: [f32; 3]) -> bool {
        distance_to_patrol(self.center, position) <= self.radius + 60.0
    }

    pub(super) fn allows_target(self, target: ObjectHandle, position: [f32; 3]) -> bool {
        self.current_target == Some(target)
            || distance_to_patrol(self.center, position) < self.radius
    }
}

impl UnitPatrol {
    pub(super) fn approximate_factory_raid(
        &mut self,
        world: &World,
        mission: &MissionDocument,
        drafts: &[MissionObjectDraft],
        handles: &[ObjectHandle],
        bundle: &MissionScriptBundle,
        declarations: &VarSet,
    ) {
        let attacks_factory = bundle
            .package
            .events
            .iter()
            .filter(|event| event.name_raw == b"PBM_BUILDING_ATTACK_Start\0")
            .flat_map(|event| &event.instructions)
            .filter(|instruction| {
                instruction.dispatch_selector() == ScriptDispatchSelector::Handler(28)
            })
            .any(|instruction| {
                declarations
                    .resolve_handler15(instruction)
                    .is_ok_and(|order| {
                        order.word_1 == 3
                            && order.word_2 == 3
                            && order.word_3 == PLANT_CLASS
                            && matches!(order.target, Handler15TargetPayload::ByLogicId(_))
                    })
            });
        if !attacks_factory {
            return;
        }

        let clan = &mission.clans[bundle.clan_index];
        let factories = drafts.iter().enumerate().filter(|(_, draft)| {
            draft.unit_dat_header_flags == Some(PLANT_CLASS)
                && mission
                    .clans
                    .get(draft.raw_after_resource as usize)
                    .is_some_and(|owner| {
                        clan.relations.iter().any(|relation| {
                            relation.relation_value == 0
                                && relation.other_clan_name.raw == owner.name.raw
                        })
                    })
        });
        // shortcut: route placed battle robots toward the nearest hostile factory until
        // the problem scheduler can select and dispatch a native attack group.
        let mut ordered = false;
        for (draft, &handle) in drafts.iter().zip(handles).filter(|(draft, _)| {
            draft.raw_after_resource as usize == bundle.clan_index
                && draft.unit_dat_header_flags == Some(WARBOT_CLASS)
        }) {
            let distance = |target: &MissionObjectDraft| {
                (draft.position[0] - target.position[0])
                    .hypot(draft.position[1] - target.position[1])
            };
            if let Some((index, factory)) = factories
                .clone()
                .min_by(|(_, a), (_, b)| distance(a).total_cmp(&distance(b)))
            {
                ordered |= self.order(
                    world,
                    handle,
                    [factory.position[0], factory.position[1]],
                    60.0,
                );
                if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) {
                    unit.raid_factory = Some((handles[index], index));
                }
            }
        }
        self.factory_raid_clans += usize::from(ordered);
    }

    pub(super) fn scripted() -> Self {
        Self {
            center: None,
            units: Vec::new(),
            shut_down: HashSet::new(),
            clock_ms: 0,
            rng: 1,
            factory_raid_clans: 0,
        }
    }

    pub(super) fn order(
        &mut self,
        world: &World,
        handle: ObjectHandle,
        center: [f32; 2],
        radius: f32,
    ) -> bool {
        self.shut_down.remove(&handle);
        self.units
            .retain(|unit| transform_state(world, unit.handle).is_ok());
        if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) {
            unit.raid_factory = None;
            let was_attacking = unit.attack_target.take().is_some();
            let was_moving = unit.destinations.take().is_some();
            if unit.center_object.take().is_some()
                || was_moving
                || was_attacking
                || unit.center != center
                || unit.radius != radius
            {
                unit.center = center;
                unit.radius = radius;
                unit.points.clear();
                unit.retry_ms = 0;
                return true;
            }
            return false;
        }
        self.units.push(PatrollingUnit {
            handle,
            center,
            center_object: None,
            destinations: None,
            radius,
            points: VecDeque::new(),
            retry_ms: 0,
            attack: None,
            attack_target: None,
            raid_factory: None,
        });
        true
    }

    pub(super) fn move_to(
        &mut self,
        world: &World,
        handle: ObjectHandle,
        destination: [f32; 2],
        append: bool,
    ) {
        if append {
            if let Some(destinations) = self
                .units
                .iter_mut()
                .find(|unit| unit.handle == handle)
                .and_then(|unit| unit.destinations.as_mut())
            {
                destinations.push_back(destination);
                return;
            }
        }
        self.order(world, handle, destination, 60.0);
        if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) {
            unit.destinations = Some(VecDeque::from([destination]));
            unit.points.clear();
            unit.retry_ms = 0;
        }
    }

    pub(super) fn order_around_object(
        &mut self,
        world: &World,
        handle: ObjectHandle,
        target: ObjectHandle,
        center: [f32; 2],
        radius: f32,
    ) -> bool {
        if self.units.iter().any(|unit| {
            unit.handle == handle
                && unit.attack_target.is_none()
                && unit.center_object == Some(target)
                && unit.radius == radius
        }) {
            return false;
        }
        self.order(world, handle, center, radius);
        if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) {
            unit.center_object = Some(target);
            unit.points.clear();
            unit.retry_ms = 0;
        }
        true
    }

    pub(super) fn is_patrolling(&self, handle: ObjectHandle) -> bool {
        self.units.iter().any(|unit| unit.handle == handle)
    }

    pub(super) fn shut_down(&mut self, handle: ObjectHandle) -> bool {
        // shortcut: stop autonomous movement and fire until the native shutdown task is modeled.
        self.units.retain(|unit| unit.handle != handle);
        self.shut_down.insert(handle)
    }

    pub(super) fn is_shut_down(&self, handle: ObjectHandle) -> bool {
        self.shut_down.contains(&handle)
    }

    pub(super) fn is_moving_to_destination(&self, handle: ObjectHandle) -> bool {
        self.units
            .iter()
            .any(|unit| unit.handle == handle && unit.destinations.is_some())
    }

    pub(super) fn raid_factory(&self, handle: ObjectHandle) -> Option<(ObjectHandle, usize)> {
        self.units
            .iter()
            .find(|unit| unit.handle == handle)?
            .raid_factory
    }

    pub(super) fn set_attack_target(
        &mut self,
        world: &World,
        handle: ObjectHandle,
        target: ObjectHandle,
        target_index: usize,
        center: [f32; 2],
    ) {
        self.order(world, handle, center, 60.0);
        if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) {
            unit.center_object = Some(target);
            unit.attack_target = Some((target, target_index));
        }
    }

    pub(super) fn attack_target(&self, handle: ObjectHandle) -> Option<(ObjectHandle, usize)> {
        self.units
            .iter()
            .find(|unit| unit.handle == handle)?
            .attack_target
    }

    pub(super) fn attack_limit(
        &self,
        world: &World,
        handle: ObjectHandle,
    ) -> Option<PatrolAttackLimit> {
        // A raid starts with an explicit attack order. It never receives PatrolPlace limits.
        let unit = self
            .units
            .iter()
            .find(|unit| unit.handle == handle && unit.raid_factory.is_none())?;
        Some(PatrolAttackLimit {
            center: unit.center(world)?,
            radius: unit.radius,
            current_target: unit.attack,
        })
    }

    pub(super) fn activate(&mut self, world: &World, handle: ObjectHandle) {
        if let Some(center) = self.center {
            self.order(world, handle, center, 150.0);
        }
    }

    pub(super) fn new(
        mission: &MissionDocument,
        drafts: &[MissionObjectDraft],
        handles: &[ObjectHandle],
    ) -> Option<Self> {
        // shortcut: use the observed AutoDemo meeting area from the first clan anchor
        // until we can execute the native producer of the patrol order.
        let center = mission.clans.first()?.anchor.map(f32::round);
        let units = drafts
            .iter()
            .zip(handles)
            .filter(|(draft, _)| {
                draft
                    .unit_dat_header_flags
                    .is_some_and(|class| class & MOBILE_UNIT != 0)
                    && (draft.raw_after_resource as usize) < mission.clans.len()
            })
            .map(|(_, &handle)| PatrollingUnit {
                handle,
                center,
                center_object: None,
                destinations: None,
                radius: 150.0,
                points: VecDeque::new(),
                retry_ms: 0,
                attack: None,
                attack_target: None,
                raid_factory: None,
            })
            .collect();
        Some(Self {
            center: Some(center),
            units,
            shut_down: HashSet::new(),
            clock_ms: 0,
            rng: 1,
            factory_raid_clans: 0,
        })
    }

    pub(super) fn prepare(
        &self,
        world: &World,
        terrain: &TerrainWorld,
        now_ms: u32,
        targets: &[(ObjectHandle, CombatTarget)],
    ) -> Result<PreparedPatrol, EngineError> {
        let mut state = self.clone();
        state.units.retain(|unit| {
            unit.destinations
                .as_ref()
                .is_none_or(|items| !items.is_empty())
                && unit.center(world).is_some()
        });
        let seconds = now_ms.saturating_sub(state.clock_ms) as f32 * 0.001;
        state.clock_ms = state.clock_ms.max(now_ms);
        let mut poses = Vec::new();
        if seconds == 0.0 {
            return Ok(PreparedPatrol { state, poses });
        }
        for unit in &mut state.units {
            let Ok(before) = transform_state(world, unit.handle) else {
                continue;
            };
            let from = before.position.map(f32::from_bits);
            if let Some(destinations) = &mut unit.destinations {
                if destinations
                    .front()
                    .is_some_and(|[x, y]| (x - from[0]).hypot(y - from[1]) <= 0.05)
                {
                    destinations.pop_front();
                    unit.points.clear();
                    unit.retry_ms = 0;
                }
                if destinations.is_empty() {
                    continue;
                }
            }
            let center = unit.center(world).expect("retained patrol center");
            if (center[0] - unit.center[0]).hypot(center[1] - unit.center[1]) >= unit.radius {
                unit.center = center;
                unit.points.clear();
                unit.retry_ms = 0;
            }
            let enemy = targets
                .iter()
                .find(|(handle, _)| *handle == unit.handle)
                .map(|(_, target)| *target);
            if unit.attack != enemy.map(|target| target.handle) {
                unit.points.clear();
                unit.retry_ms = 0;
                unit.attack = enemy.map(|target| target.handle);
            }
            if let Some(enemy) = enemy.filter(|enemy| enemy.in_range) {
                let mut after = before;
                let (yaw, _) = turn_toward(
                    before,
                    [enemy.center[0] - from[0], enemy.center[1] - from[1]],
                    seconds,
                );
                after.orientation[2] = yaw.to_bits();
                if after != before {
                    poses.push((unit.handle, before, after));
                }
                continue;
            }
            if (unit.points.is_empty() || enemy.is_some()) && now_ms >= unit.retry_ms {
                unit.points = if let Some(enemy) = enemy {
                    route_points(terrain, from, enemy.center)?.unwrap_or_default()
                } else if let Some(&[x, y]) =
                    unit.destinations.as_ref().and_then(|items| items.front())
                {
                    // shortcut: route to the same XY using the terrain height until native Go arrival is wired.
                    terrain
                        .height_at([x, y])
                        .map_err(EngineError::Terrain)?
                        .map(|z| route_points(terrain, from, [x, y, z]))
                        .transpose()?
                        .flatten()
                        .unwrap_or_default()
                } else if unit.attack_target.is_some() {
                    VecDeque::new()
                } else {
                    choose_route(terrain, from, center, unit.radius, &mut state.rng)?
                };
                unit.retry_ms = now_ms.saturating_add(1_000);
            }
            let Some(&target) = unit.points.front() else {
                continue;
            };
            let dx = target[0] - from[0];
            let dy = target[1] - from[1];
            let distance = dx.hypot(dy);
            if distance <= 0.05 {
                unit.points.pop_front();
                continue;
            }
            let mut after = before;
            // shortcut: fixed turn rate and patrol speed until the per-chassis Control step is available.
            let (yaw, turn_seconds) = turn_toward(before, [dx, dy], seconds);
            after.orientation[2] = yaw.to_bits();
            let travel = 9.0 * (seconds - turn_seconds);
            if travel > 0.0 {
                let fraction = (travel / distance).min(1.0);
                let xy = [from[0] + dx * fraction, from[1] + dy * fraction];
                if let Some(ground) = terrain.height_at(xy).map_err(EngineError::Terrain)? {
                    let old_ground = terrain
                        .height_at([from[0], from[1]])
                        .map_err(EngineError::Terrain)?;
                    let z = ground + old_ground.map_or(0.0, |height| from[2] - height);
                    after.position = [xy[0], xy[1], z].map(f32::to_bits);
                    if fraction == 1.0 {
                        unit.points.pop_front();
                    }
                } else {
                    unit.points.clear();
                }
            }
            if after != before {
                poses.push((unit.handle, before, after));
            }
        }
        Ok(PreparedPatrol { state, poses })
    }
}

#[cfg(test)]
#[test]
fn new_patrol_replaces_a_script_attack_order() {
    let world = fparkan_world::new(fparkan_world::WorldConfig::default());
    let actor = ObjectHandle {
        slot: 0,
        generation: 1,
    };
    let target = ObjectHandle {
        slot: 1,
        generation: 1,
    };
    let mut patrol = UnitPatrol::scripted();
    patrol.set_attack_target(&world, actor, target, 1, [50.0, 60.0]);
    assert_eq!(patrol.attack_target(actor), Some((target, 1)));
    assert!(patrol.order_around_object(&world, actor, target, [50.0, 60.0], 60.0));
    assert_eq!(patrol.attack_target(actor), None);
}

impl PatrollingUnit {
    fn center(&self, world: &World) -> Option<[f32; 2]> {
        // shortcut: use the target's transform as the patrol center until native building approaches are wired.
        match self.center_object {
            None => Some(self.center),
            Some(handle) => {
                let [x, y, _] = transform_state(world, handle)
                    .ok()?
                    .position
                    .map(f32::from_bits);
                Some([x, y])
            }
        }
    }
}

#[cfg(test)]
#[test]
fn shutdown_clears_patrol_until_a_new_order_arrives() {
    let mut world = fparkan_world::new(fparkan_world::WorldConfig::default());
    let handle = fparkan_world::construct_object(
        &mut world,
        fparkan_world::ObjectDraft { original_id: None },
    )
    .unwrap();
    fparkan_world::register_object(&mut world, handle).unwrap();
    let mut patrol = UnitPatrol::scripted();
    assert!(patrol.order(&world, handle, [20.0, 30.0], 60.0));
    assert!(patrol.shut_down(handle));
    assert!(patrol.is_shut_down(handle));
    assert!(!patrol.is_patrolling(handle));
    assert!(patrol.order(&world, handle, [35.0, 45.0], 60.0));
    assert!(!patrol.is_shut_down(handle));
    assert!(patrol.is_patrolling(handle));
}

#[cfg(test)]
#[test]
fn object_patrol_tracks_its_center_and_ignores_repeated_orders() {
    let mut world = fparkan_world::new(fparkan_world::WorldConfig::default());
    let mut make_actor = || {
        let actor = fparkan_world::construct_object(
            &mut world,
            fparkan_world::ObjectDraft { original_id: None },
        )
        .unwrap();
        fparkan_world::register_object(&mut world, actor).unwrap();
        actor
    };
    let actor = make_actor();
    let target = make_actor();
    let mut patrol = UnitPatrol::scripted();
    assert!(patrol.order_around_object(&world, actor, target, [0.0; 2], 60.0));
    assert!(!patrol.order_around_object(&world, actor, target, [0.0; 2], 60.0));
    let mut position = transform_state(&world, target).unwrap();
    position.position = [20.0_f32, 35.0, 0.0].map(f32::to_bits);
    set_transform(&mut world, target, position).unwrap();
    assert_eq!(
        patrol.attack_limit(&world, actor).unwrap().center,
        [20.0, 35.0]
    );
    patrol.order(&world, actor, [0.0; 2], 60.0);
    assert_eq!(patrol.attack_limit(&world, actor).unwrap().center, [0.0; 2]);
}

#[cfg(test)]
#[test]
fn move_orders_append_and_replace_destinations() {
    let mut world = fparkan_world::new(fparkan_world::WorldConfig::default());
    let actor = fparkan_world::construct_object(
        &mut world,
        fparkan_world::ObjectDraft { original_id: None },
    )
    .unwrap();
    fparkan_world::register_object(&mut world, actor).unwrap();
    let mut patrol = UnitPatrol::scripted();
    patrol.move_to(&world, actor, [10.0, 20.0], false);
    patrol.move_to(&world, actor, [30.0, 40.0], true);
    assert_eq!(
        patrol.units[0].destinations,
        Some(VecDeque::from([[10.0, 20.0], [30.0, 40.0]]))
    );
    patrol.move_to(&world, actor, [45.0, 50.0], false);
    assert_eq!(
        patrol.units[0].destinations,
        Some(VecDeque::from([[45.0, 50.0]]))
    );
}

fn distance_to_patrol([x, y]: [f32; 2], [px, py, _]: [f32; 3]) -> f32 {
    // shortcut: use the horizontal distance until patrol orders carry their native Z.
    (px - x).hypot(py - y)
}

#[cfg(test)]
#[test]
fn patrol_limits_new_targets_and_ends_pursuit_at_the_outer_boundary() {
    let tracked = ObjectHandle {
        slot: 1,
        generation: 1,
    };
    let candidate = ObjectHandle {
        slot: 2,
        generation: 1,
    };
    let patrol = PatrolAttackLimit {
        center: [500.0, 752.0],
        radius: 150.0,
        current_target: Some(tracked),
    };
    assert!(patrol.allows_target(candidate, [649.0, 752.0, 0.0]));
    assert!(!patrol.allows_target(candidate, [650.0, 752.0, 0.0]));
    assert!(patrol.allows_target(tracked, [650.0, 752.0, 0.0]));
    assert!(patrol.allows_attack([710.0, 752.0, 0.0]));
    assert!(!patrol.allows_attack([711.0, 752.0, 0.0]));
    assert!(!patrol.allows_attack([650.0, 902.0, 0.0]));
}

fn turn_toward(pose: TransformState, [dx, dy]: [f32; 2], seconds: f32) -> (f32, f32) {
    let yaw = f32::from_bits(pose.orientation[2]);
    let goal_yaw = (-dx).atan2(dy);
    let turn = (goal_yaw - yaw + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU)
        - std::f32::consts::PI;
    let turn_budget = 2.0 * seconds;
    (
        yaw + turn.clamp(-turn_budget, turn_budget),
        seconds.min(turn.abs() * 0.5),
    )
}

fn choose_route(
    terrain: &TerrainWorld,
    from: [f32; 3],
    center: [f32; 2],
    radius: f32,
    rng: &mut u32,
) -> Result<VecDeque<[f32; 2]>, EngineError> {
    // shortcut: choose one routed patrol point at a time with separate RNG state.
    for _ in 0..16 {
        let [x, y] =
            center.map(|axis| axis + (next_crt_rand(rng) as f32 / 32767.0 * 2.0 - 1.0) * radius);
        let Some(z) = terrain.height_at([x, y]).map_err(EngineError::Terrain)? else {
            continue;
        };
        if let Some(points) = route_points(terrain, from, [x, y, z])? {
            return Ok(points);
        }
    }
    Ok(VecDeque::new())
}

fn route_points(
    terrain: &TerrainWorld,
    from: [f32; 3],
    goal: [f32; 3],
) -> Result<Option<VecDeque<[f32; 2]>>, EngineError> {
    let route = terrain
        .route(RouteRequest { start: from, goal })
        .map_err(EngineError::Terrain)?;
    Ok(route.and_then(|route| {
        let mut points = route
            .areas
            .windows(2)
            .map(|pair| terrain.route_crossing(pair[0], pair[1]))
            .collect::<Option<VecDeque<_>>>()?;
        points.push_back([goal[0], goal[1]]);
        Some(points)
    }))
}

impl PreparedPatrol {
    pub(super) fn apply_poses(&self, world: &mut World) -> Result<(), EngineError> {
        // These handles were read during preparation and the world has yet to step.
        for &(handle, _, after) in &self.poses {
            set_transform(world, handle, after)?;
        }
        Ok(())
    }

    pub(super) fn restore_poses(&self, world: &mut World) -> Result<(), EngineError> {
        for &(handle, before, _) in &self.poses {
            set_transform(world, handle, before)?;
        }
        Ok(())
    }
}