aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/unit_patrol/orders.rs
blob: 560f21428c31bf4415aec9f33002eb16f44491e2 (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
684
685
686
687
688
use super::{PatrollingUnit, UnitPatrol};
use crate::{MissionControlDeviceTableState, MissionDocument, MissionObjectDraft};
use fparkan_script::{Handler15Invocation, Handler15TargetPayload};
use fparkan_world::{identity_metadata, transform_state, ObjectHandle, World};
use std::collections::VecDeque;

#[derive(Clone)]
pub(super) enum UnitOrder {
    Move([f32; 2]),
    Attack(ObjectHandle, usize),
    Patrol([f32; 2], f32),
    Shutdown,
    Resume(Box<PatrollingUnit>),
}

impl UnitOrder {
    fn opcode(&self) -> u32 {
        match self {
            Self::Move(_) => 2,
            Self::Attack(..) => 3,
            Self::Patrol(..) => 4,
            Self::Shutdown => 0x13,
            Self::Resume(_) => unreachable!("a suspended order has already started"),
        }
    }

    fn targets_object(&self, target: ObjectHandle) -> bool {
        match self {
            Self::Attack(handle, _) => *handle == target,
            Self::Resume(unit) => unit.has_object_order(target),
            _ => false,
        }
    }
}

pub(crate) fn supports_order(order: &Handler15Invocation) -> bool {
    if matches!(
        (order.word_1, order.word_2, order.target),
        (4, 1, Handler15TargetPayload::ByPlace { .. })
    ) {
        return true;
    }
    matches!(order.word_2, 1 | 3)
        && matches!(
            (order.word_1, order.target),
            (2, Handler15TargetPayload::ByPlace { .. })
                | (3, Handler15TargetPayload::ByLogicId(_))
                | (0x13, Handler15TargetPayload::None)
        )
}

impl UnitPatrol {
    pub(crate) fn satellite_route(&self, actor: ObjectHandle) -> Vec<[f32; 2]> {
        let active = self.units.iter().find(|unit| unit.handle == actor);
        // iron3d+0x77ae0 prefers the path whenever there are unvisited points.
        if let Some(unit) = active.filter(|unit| !unit.points.is_empty()) {
            return unit.points.iter().copied().collect();
        }
        let mut points = Vec::new();
        if let Some(unit) = active {
            unit.append_point_orders(&mut points);
        }
        if let Some((_, queue)) = self
            .script_orders
            .iter()
            .find(|(handle, _)| *handle == actor)
        {
            for order in queue {
                match order {
                    UnitOrder::Move(point) | UnitOrder::Patrol(point, _) => points.push(*point),
                    UnitOrder::Resume(unit) => unit.append_point_orders(&mut points),
                    UnitOrder::Attack(..) | UnitOrder::Shutdown => {}
                }
            }
        }
        points
    }

    pub(crate) fn clear_capture_order(&mut self, unit: ObjectHandle, building: ObjectHandle) {
        self.units
            .retain(|order| order.handle != unit || order.capture_target != Some(building));
        if let Some((_, queue)) = self
            .script_orders
            .iter_mut()
            .find(|(handle, _)| *handle == unit)
        {
            queue.retain(|order| {
                !matches!(order, UnitOrder::Resume(state) if state.capture_target == Some(building))
            });
        }
        self.script_orders.retain(|(_, queue)| !queue.is_empty());
    }

    pub(crate) fn has_object_order(&self, handle: ObjectHandle, target: ObjectHandle) -> bool {
        self.units
            .iter()
            .any(|unit| unit.handle == handle && unit.has_object_order(target))
            || self.script_orders.iter().any(|(unit, queue)| {
                *unit == handle && queue.iter().any(|order| order.targets_object(target))
            })
    }

    pub(crate) fn clear_object_order(&mut self, handle: ObjectHandle, target: ObjectHandle) {
        self.units
            .retain(|unit| unit.handle != handle || !unit.has_object_order(target));
        if let Some((_, queue)) = self
            .script_orders
            .iter_mut()
            .find(|(unit, _)| *unit == handle)
        {
            queue.retain(|order| !order.targets_object(target));
        }
        self.script_orders.retain(|(_, queue)| !queue.is_empty());
    }

    pub(crate) fn prepend_attack(
        &mut self,
        world: &World,
        actor: ObjectHandle,
        target: ObjectHandle,
        target_index: usize,
    ) {
        let mut queue = self
            .script_orders
            .iter()
            .position(|(unit, _)| *unit == actor)
            .map(|index| self.script_orders.remove(index).1)
            .unwrap_or_default();
        let order = UnitOrder::Attack(target, target_index);
        if self.is_leaving_factory(actor) {
            queue.push_front(order);
        } else {
            if let Some(index) = self.units.iter().position(|unit| unit.handle == actor) {
                queue.push_front(UnitOrder::Resume(Box::new(self.units.remove(index))));
            } else if self.is_shut_down(actor) {
                queue.push_front(UnitOrder::Shutdown);
            }
            self.start_script_order(world, actor, order);
        }
        if !queue.is_empty() {
            self.script_orders.push((actor, queue));
        }
    }

    pub(crate) fn script_order(
        &mut self,
        world: &World,
        mission: &MissionDocument,
        drafts: &[MissionObjectDraft],
        order: Handler15Invocation,
    ) -> Option<u32> {
        if !supports_order(&order) {
            return None;
        }
        let Some(actor) =
            crate::script_patrol::unit_by_logic_id(mission, drafts, world, order.word_0, |class| {
                class & crate::autodemo::MOBILE_UNIT != 0 && class != crate::HERO_UNIT_CLASS
            })
        else {
            return Some(5);
        };
        let command = match order.target {
            Handler15TargetPayload::ByPlace { first, second } => {
                let point = [first as f32, second as f32];
                if order.word_1 == 4 {
                    let radius = match order.word_3 {
                        0 | u32::MAX => 60.0,
                        value => value as f32,
                    };
                    UnitOrder::Patrol(point, radius)
                } else {
                    UnitOrder::Move(point)
                }
            }
            Handler15TargetPayload::ByLogicId(id) => {
                let Some(target) =
                    crate::mission_events::placed_logic_objects(mission, world, id).next()
                else {
                    return Some(0);
                };
                let Some(index) = identity_metadata(world, target)
                    .ok()
                    .and_then(|meta| meta.original_id)
                else {
                    return Some(0);
                };
                UnitOrder::Attack(target, index.0 as usize)
            }
            Handler15TargetPayload::None => UnitOrder::Shutdown,
            _ => unreachable!("supported target form checked above"),
        };
        self.enqueue_script_order(world, actor, command, order.word_2 == 1);
        Some(1)
    }

    fn enqueue_script_order(
        &mut self,
        world: &World,
        actor: ObjectHandle,
        order: UnitOrder,
        append: bool,
    ) {
        let count = self
            .script_order_counts
            .entry((actor.slot, order.opcode()))
            .or_default();
        *count += 1;
        if *count == 1 {
            eprintln!(
                "sim_coverage script_unit_queue_approx=1 unit={} order={} append={append}",
                actor.slot,
                order.opcode()
            );
        }
        if self.is_leaving_factory(actor)
            || (append && (self.is_patrolling(actor) || self.is_shut_down(actor)))
        {
            if let Some((_, queue)) = self
                .script_orders
                .iter_mut()
                .find(|(unit, _)| *unit == actor)
            {
                queue.push_back(order);
            } else {
                self.script_orders.push((actor, VecDeque::from([order])));
            }
            return;
        }
        self.script_orders.retain(|(unit, _)| *unit != actor);
        self.start_script_order(world, actor, order);
    }

    fn start_script_order(&mut self, world: &World, actor: ObjectHandle, order: UnitOrder) -> bool {
        if let UnitOrder::Resume(unit) = order {
            let mut unit = *unit;
            unit.points.clear();
            unit.retry_ms = 0;
            unit.attack = None;
            self.units.retain(|current| current.handle != actor);
            self.units.push(unit);
            return true;
        }
        match &order {
            UnitOrder::Move(point) => {
                self.move_to(world, actor, *point, false);
                eprintln!(
                    "sim_coverage script_move_approx=1 unit={} destination={point:?}",
                    actor.slot
                );
            }
            UnitOrder::Attack(target, index) => {
                let Ok(pose) = transform_state(world, *target) else {
                    return false;
                };
                let [x, y, _] = pose.position.map(f32::from_bits);
                self.set_attack_target(world, actor, *target, *index, [x, y]);
                eprintln!(
                    "sim_coverage script_attack_approx=1 unit={} target_unit={}",
                    actor.slot, target.slot
                );
            }
            UnitOrder::Shutdown => {
                self.shut_down(actor);
                eprintln!("sim_coverage unit_shutdown_approx=1 unit={}", actor.slot);
            }
            UnitOrder::Patrol(point, radius) => {
                self.order(world, actor, *point, *radius);
                eprintln!("sim_coverage script_point_patrol_approx=1 unit={} center={point:?} radius={radius}", actor.slot);
            }
            UnitOrder::Resume(_) => unreachable!("handled above"),
        }
        eprintln!(
            "script_unit_order_started unit={} order={}",
            actor.slot,
            order.opcode()
        );
        true
    }

    pub(super) fn advance_script_orders(
        &mut self,
        world: &World,
        controls: &[MissionControlDeviceTableState],
    ) {
        self.units.retain(|unit| {
            let Some((target, _)) = unit.attack_target else {
                return true;
            };
            if !crate::attack_target::complete(world, controls, target) {
                return true;
            }
            eprintln!(
                "script_attack_finished unit={} target={}",
                unit.handle.slot, target.slot
            );
            false
        });
        for (actor, mut queue) in std::mem::take(&mut self.script_orders) {
            let Ok(pose) = transform_state(world, actor) else {
                continue;
            };
            // shortcut: Go still uses the temporary arrival tolerance.
            let complete = !self.is_leaving_factory(actor)
                && !self.is_shut_down(actor)
                && self
                    .units
                    .iter()
                    .find(|unit| unit.handle == actor)
                    .is_none_or(|unit| {
                        if unit.capture_target.is_some() {
                            return false;
                        }
                        if let Some(points) = &unit.destinations {
                            let [x, y, _] = pose.position.map(f32::from_bits);
                            return points.is_empty()
                                || (points.len() == 1
                                    && points.front().is_some_and(|point| {
                                        (point[0] - x).hypot(point[1] - y) <= 0.05
                                    }));
                        }
                        false
                    });
            if complete {
                while let Some(order) = queue.pop_front() {
                    if self.start_script_order(world, actor, order) {
                        break;
                    }
                }
            }
            if !queue.is_empty() {
                self.script_orders.push((actor, queue));
            }
        }
    }

    pub(crate) fn script_order_counts(&self) -> impl Iterator<Item = (u32, u32, u64)> + '_ {
        self.script_order_counts
            .iter()
            .map(|(&(unit, order), &count)| (unit, order, count))
    }
}

impl PatrollingUnit {
    fn append_point_orders(&self, points: &mut Vec<[f32; 2]>) {
        if let Some(destinations) = &self.destinations {
            points.extend(destinations);
        } else if self.patrols_point(self.center) && self.raid_factory.is_none() {
            points.push(self.center);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fparkan_world::{
        construct_object, register_object, request_delete, set_transform, ObjectDraft,
    };

    fn object(world: &mut World) -> ObjectHandle {
        let handle = construct_object(world, ObjectDraft { original_id: None }).unwrap();
        register_object(world, handle).unwrap();
        handle
    }

    fn place(world: &mut World, actor: ObjectHandle, x: f32) {
        let mut pose = transform_state(world, actor).unwrap();
        pose.position = [x, 0.0, 0.0].map(f32::to_bits);
        set_transform(world, actor, pose).unwrap();
    }

    #[test]
    fn satellite_route_prefers_remaining_waypoints_to_coordinate_orders() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let enemy = object(&mut world);
        let mut patrol = UnitPatrol::scripted();
        patrol.enqueue_script_order(&world, actor, UnitOrder::Move([20.0, 30.0]), false);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Attack(enemy, 1), true);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Patrol([40.0, 50.0], 60.0), true);
        assert_eq!(patrol.satellite_route(actor), [[20.0, 30.0], [40.0, 50.0]]);

        patrol.units[0].points = VecDeque::from([[10.0, 18.0], [20.0, 30.0]]);
        assert_eq!(patrol.satellite_route(actor), [[10.0, 18.0], [20.0, 30.0]]);
        patrol.units[0].points.pop_front();
        assert_eq!(patrol.satellite_route(actor), [[20.0, 30.0]]);
        assert!(patrol.satellite_route(enemy).is_empty());
    }

    #[test]
    fn move_attack_and_shutdown_wait_for_the_preceding_task() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let target = object(&mut world);
        place(&mut world, target, 50.0);
        let mut patrol = UnitPatrol::scripted();
        patrol.shut_down(actor);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Move([10.0, 0.0]), false);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Move([20.0, 0.0]), true);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Attack(target, 1), true);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Shutdown, true);
        patrol.advance_script_orders(&world, &[]);
        assert!(!patrol.is_shut_down(actor));
        assert!(patrol.attack_target(actor).is_none());
        assert_eq!(
            patrol.units[0].destinations.as_ref().unwrap()[0],
            [10.0, 0.0]
        );
        place(&mut world, actor, 10.0);
        patrol.advance_script_orders(&world, &[]);
        assert_eq!(
            patrol.units[0].destinations.as_ref().unwrap()[0],
            [20.0, 0.0]
        );
        place(&mut world, actor, 20.0);
        patrol.advance_script_orders(&world, &[]);
        assert_eq!(patrol.attack_target(actor), Some((target, 1)));
        assert!(!patrol.is_shut_down(actor));
        request_delete(&mut world, target).unwrap();
        fparkan_world::step(&mut world, &Default::default()).unwrap();
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.is_shut_down(actor));
        assert!(!patrol.is_patrolling(actor));
    }

    #[test]
    fn prepended_attack_interrupts_the_current_order_and_preserves_its_tail() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let target = object(&mut world);
        place(&mut world, target, 50.0);
        let mut patrol = UnitPatrol::scripted();
        patrol.enqueue_script_order(&world, actor, UnitOrder::Move([10.0, 0.0]), false);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Shutdown, true);
        patrol.prepend_attack(&world, actor, target, 1);
        assert_eq!(patrol.attack_target(actor), Some((target, 1)));
        assert!(!patrol.is_moving_to_destination(actor));
        request_delete(&mut world, target).unwrap();
        fparkan_world::step(&mut world, &Default::default()).unwrap();
        patrol.advance_script_orders(&world, &[]);
        assert_eq!(
            patrol.units[0].destinations.as_ref().unwrap()[0],
            [10.0, 0.0]
        );
        assert!(!patrol.is_shut_down(actor));
        place(&mut world, actor, 10.0);
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.is_shut_down(actor));
    }

    #[test]
    fn replacing_an_order_discards_the_queued_tail() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let mut patrol = UnitPatrol::scripted();
        patrol.enqueue_script_order(&world, actor, UnitOrder::Move([10.0, 0.0]), false);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Shutdown, true);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Move([20.0, 0.0]), false);
        place(&mut world, actor, 10.0);
        patrol.advance_script_orders(&world, &[]);
        assert!(!patrol.is_shut_down(actor));
        assert_eq!(
            patrol.units[0].destinations.as_ref().unwrap()[0],
            [20.0, 0.0]
        );
        assert!(patrol.script_orders.is_empty());
    }

    #[test]
    fn capture_holds_an_appended_order_until_released() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let building = object(&mut world);
        let mut patrol = UnitPatrol::scripted();
        patrol.move_to_capture(&world, actor, building, [10.0, 0.0], None);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Shutdown, true);
        place(&mut world, actor, 10.0);
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.has_capture_order(actor, building));
        assert!(!patrol.is_shut_down(actor));
        patrol.clear_capture_order(actor, building);
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.is_shut_down(actor));
    }

    #[test]
    fn attack_holds_an_appended_patrol_until_the_target_is_removed() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let target = object(&mut world);
        place(&mut world, target, 50.0);
        let mut patrol = UnitPatrol::scripted();
        patrol.enqueue_script_order(&world, actor, UnitOrder::Attack(target, 1), false);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Patrol([20.0, 30.0], 60.0), true);
        patrol.advance_script_orders(&world, &[]);
        assert_eq!(patrol.attack_target(actor), Some((target, 1)));
        request_delete(&mut world, target).unwrap();
        fparkan_world::step(&mut world, &Default::default()).unwrap();
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.has_point_order(actor, [20.0, 30.0]));
        assert!(patrol.attack_target(actor).is_none());
    }

    #[test]
    fn depleted_target_finishes_with_or_without_a_queued_successor() {
        use crate::{
            tests::synthetic_control_device_table_with_providers, MissionControlDeviceTableStatus,
            MissionControlNodeProviderTableStatus,
        };
        for queued in [false, true] {
            let mut world = fparkan_world::new(Default::default());
            let actor = object(&mut world);
            let target = object(&mut world);
            place(&mut world, target, 50.0);
            let mut patrol = UnitPatrol::scripted();
            patrol.enqueue_script_order(&world, actor, UnitOrder::Attack(target, 1), false);
            if queued {
                patrol.enqueue_script_order(&world, actor, UnitOrder::Shutdown, true);
            }
            let mut control = synthetic_control_device_table_with_providers(
                MissionControlDeviceTableStatus::Available(Vec::new()),
                MissionControlNodeProviderTableStatus::Available(Vec::new()),
            );
            control.handle = ObjectHandle {
                generation: target.generation + 1,
                ..target
            };
            control.node_provider_depletion_marked = true;
            patrol.advance_script_orders(&world, std::slice::from_ref(&control));
            assert_eq!(
                patrol.attack_target(actor),
                Some((target, 1)),
                "another generation must not finish this target"
            );
            control.handle = target;
            patrol.advance_script_orders(&world, &[control]);
            assert!(transform_state(&world, target).is_ok());
            assert!(patrol.attack_target(actor).is_none());
            assert!(!patrol.is_patrolling(actor));
            assert_eq!(patrol.is_shut_down(actor), queued);
        }
    }

    #[test]
    fn native_zero_position_sentinel_finishes_an_otherwise_live_target() {
        let mut world = fparkan_world::new(Default::default());
        let actor = object(&mut world);
        let target = object(&mut world);
        let mut patrol = UnitPatrol::scripted();
        place(&mut world, target, 50.0);
        patrol.enqueue_script_order(&world, actor, UnitOrder::Attack(target, 1), false);
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.attack_target(actor).is_some());
        place(&mut world, target, -0.0);
        patrol.advance_script_orders(&world, &[]);
        assert!(patrol.attack_target(actor).is_none());
        assert!(transform_state(&world, target).is_ok());
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_stock_raid_stops_firing_and_reaches_shutdown_after_bunker_depletion() {
        use crate::{
            create, frame, load_gameplay_mission, AutoDemoCombatEvent, EngineServices, MissionMode,
            MissionRequest, MissionStartupInput,
        };
        use fparkan_vfs::DirectoryVfs;
        use std::sync::Arc;
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root");
        let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
        load_gameplay_mission(
            &mut engine,
            MissionRequest {
                key: "MISSIONS/CAMPAIGN/CAMPAIGN.04/Mission.02/data.tma".into(),
                mode: MissionMode::SingleMission,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let loaded = engine.loaded.as_ref().unwrap();
        let actor = crate::script_patrol::warbot_by_logic_id(
            &loaded.mission,
            &loaded.object_drafts,
            &engine.world,
            15,
        )
        .unwrap();
        let bunker = loaded.control_device_tables[0].handle;
        let mut depleted = false;
        for now in (0..=900_000).step_by(50) {
            let result = frame(&mut engine, now).unwrap();
            if depleted {
                assert!(!result.autodemo_combat_events.iter().any(|event| matches!(event, AutoDemoCombatEvent::Shot { shooter, target, .. } if *shooter == actor && *target == bunker)), "a completed Attack released another shot at {now}");
            }
            let loaded = engine.loaded.as_ref().unwrap();
            depleted |= loaded.control_device_tables[0].node_provider_depletion_marked;
            if depleted {
                let targets = engine.autodemo_combat.as_ref().unwrap().targets(
                    &engine.world,
                    &loaded.mission_assets,
                    loaded.unit_patrol.as_ref(),
                    &loaded.control_device_tables,
                );
                assert!(
                    !targets
                        .iter()
                        .any(|(shooter, target)| *shooter == actor && target.handle == bunker),
                    "depleted bunker was reacquired for firing"
                );
            }
            if depleted && loaded.unit_patrol.as_ref().unwrap().is_shut_down(actor) {
                assert!(transform_state(&engine.world, bunker).is_ok());
                return;
            }
        }
        panic!("stock raid never completed Attack and its queued retreat");
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_mission_19_queues_and_starts_its_scripted_raid() {
        use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput};
        use fparkan_vfs::DirectoryVfs;
        use std::sync::Arc;

        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root");
        let mut engine =
            crate::create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
        crate::load_gameplay_mission(
            &mut engine,
            MissionRequest {
                key: "MISSIONS/CAMPAIGN/CAMPAIGN.04/Mission.02/data.tma".into(),
                mode: MissionMode::SingleMission,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let loaded = engine.loaded.as_ref().unwrap();
        let actor = crate::script_patrol::warbot_by_logic_id(
            &loaded.mission,
            &loaded.object_drafts,
            &engine.world,
            15,
        )
        .unwrap();
        let before = transform_state(&engine.world, actor).unwrap().position;
        assert!(loaded.unit_patrol.as_ref().unwrap().is_shut_down(actor));
        let mut notices = Vec::new();
        for now in (0..=63_000).step_by(100) {
            notices.extend(crate::frame(&mut engine, now).unwrap().clan_notices);
        }
        let loaded = engine.loaded.as_ref().unwrap();
        let patrol = loaded.unit_patrol.as_ref().unwrap();
        assert!(!patrol.is_shut_down(actor));
        assert!(patrol.is_moving_to_destination(actor));
        assert!(patrol.attack_target(actor).is_none());
        let queue = &patrol
            .script_orders
            .iter()
            .find(|(unit, _)| *unit == actor)
            .unwrap()
            .1;
        assert_eq!(queue.len(), 5);
        assert!(matches!(queue[0], UnitOrder::Move([1528.0, 855.0])));
        assert!(matches!(queue[1], UnitOrder::Attack(..)));
        assert!(matches!(queue[4], UnitOrder::Shutdown));
        assert!(notices.contains(&crate::MissionNotice::Information(0)));
        assert!(loaded
            .clan_ai_events
            .stops()
            .all(|(stop, _)| !stop.reason.starts_with("Handler(15)")));
        for now in (63_100..=70_000).step_by(100) {
            crate::frame(&mut engine, now).unwrap();
        }
        assert_ne!(
            transform_state(&engine.world, actor).unwrap().position[..2],
            before[..2]
        );
    }
}