aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/unit_motion.rs
blob: 101a62089a134a9a6fdd096686a02ac8dc76cef8 (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
//! Observations of the temporary unit controller, not a native motion solver.

use crate::{CombatObject, Engine};
use std::collections::BTreeMap;

/// Work performed by the temporary controller for one retained object identity.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct UnitMotionSample {
    pub updates: u64,
    pub first_ms: u32,
    pub last_ms: u32,
    pub discarded_waypoints: u64,
    /// Sum of unused frame intervals, individually rounded to microseconds.
    pub discarded_time_us: u64,
}

/// Counts persist after orders end or the object leaves the world.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct UnitMotionReport {
    pub objects: BTreeMap<CombatObject, UnitMotionSample>,
}

impl UnitMotionReport {
    pub(super) fn update(&mut self, object: CombatObject, now: u32) {
        let sample = self.objects.entry(object).or_insert_with(|| {
            eprintln!("sim_coverage unit_motion_controller_stub=1 object={object} original_id={:?} first_ms={now}", object.original_id);
            UnitMotionSample {
                first_ms: now,
                ..Default::default()
            }
        });
        sample.updates += 1;
        sample.last_ms = now;
    }

    pub(super) fn discard_waypoint_time(&mut self, object: CombatObject, seconds: f32) {
        let time_us = (f64::from(seconds.max(0.0)) * 1_000_000.0).round() as u64;
        if time_us == 0 {
            return;
        }
        let sample = self
            .objects
            .get_mut(&object)
            .expect("recorded motion update");
        sample.discarded_waypoints += 1;
        sample.discarded_time_us += time_us;
    }
}

/// Reads observations shared by the interactive and headless mission paths.
#[must_use]
pub fn loaded_mission_unit_motion_report(engine: &Engine) -> Option<&UnitMotionReport> {
    Some(&engine.loaded.as_ref()?.unit_patrol.as_ref()?.motion_report)
}

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

    #[test]
    fn counts_updates_and_unused_time_separately_for_reused_slots() {
        let object = CombatObject {
            slot: 4,
            generation: 1,
            original_id: Some(17),
        };
        let replacement = CombatObject {
            generation: 2,
            ..object
        };
        let mut report = UnitMotionReport::default();
        report.update(object, 0);
        report.discard_waypoint_time(object, 0.125);
        report.update(object, 500);
        report.discard_waypoint_time(object, 0.0);
        report.update(replacement, 1_000);
        assert_eq!(
            report.objects[&object],
            UnitMotionSample {
                updates: 2,
                first_ms: 0,
                last_ms: 500,
                discarded_waypoints: 1,
                discarded_time_us: 125_000,
            }
        );
        assert_eq!(report.objects[&replacement].updates, 1);
        assert_eq!(report.objects[&replacement].discarded_time_us, 0);
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_stock_patrol_reports_controller_updates_and_lost_time() {
        use crate::{
            create, load_gameplay_mission, simulate_mission_report, EngineServices, MissionMode,
            MissionRequest, MissionStartupInput,
        };
        use fparkan_vfs::DirectoryVfs;
        use std::sync::Arc;
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
        let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
        load_gameplay_mission(
            &mut engine,
            MissionRequest {
                key: "MISSIONS/Autodemo.00/data.tma".into(),
                mode: MissionMode::AutoDemo,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let report = simulate_mission_report(&mut engine, 120_000).unwrap();
        assert_eq!(
            &report.unit_motion,
            loaded_mission_unit_motion_report(&engine).unwrap()
        );
        assert!(!report.unit_motion.objects.is_empty());
        assert!(report
            .unit_motion
            .objects
            .keys()
            .all(|object| object.original_id.is_some()));
        assert!(report
            .unit_motion
            .objects
            .values()
            .any(|sample| sample.updates > 1
                && sample.last_ms > sample.first_ms
                && sample.discarded_waypoints > 0
                && sample.discarded_time_us > 0));
    }
}