Skip to main content

subtr_actor/stats/timeline/
collector.rs

1use crate::collector::frame_resolution::{
2    FinalStatsFrameAction, StatsFramePersistenceController, StatsFrameResolution,
3};
4use crate::stats::analysis_graph::{
5    AnalysisGraph, StatsTimelineEventsNode, StatsTimelineEventsState, StatsTimelineFrameNode,
6    StatsTimelineFrameState,
7};
8use crate::*;
9
10pub fn build_timeline_graph() -> AnalysisGraph {
11    let mut graph = AnalysisGraph::new().with_input_state_type::<FrameInput>();
12    graph.push_boxed_node(Box::new(StatsTimelineFrameNode::new()));
13    graph.push_boxed_node(Box::new(StatsTimelineEventsNode::new()));
14    graph
15}
16
17pub struct StatsTimelineCollector {
18    graph: AnalysisGraph,
19    replay_meta: Option<ReplayMeta>,
20    last_replay_meta_player_count: Option<usize>,
21    frames: Vec<ReplayStatsFrame>,
22    last_sample_time: Option<f32>,
23    frame_persistence: StatsFramePersistenceController,
24}
25
26impl Default for StatsTimelineCollector {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl StatsTimelineCollector {
33    pub fn new() -> Self {
34        let graph = build_timeline_graph();
35        Self {
36            graph,
37            replay_meta: None,
38            last_replay_meta_player_count: None,
39            frames: Vec::new(),
40            last_sample_time: None,
41            frame_persistence: StatsFramePersistenceController::new(StatsFrameResolution::default()),
42        }
43    }
44
45    fn timeline_config(&self) -> StatsTimelineConfig {
46        StatsTimelineConfig {
47            most_back_forward_threshold_y: PositioningCalculatorConfig::default()
48                .most_back_forward_threshold_y,
49            level_ball_depth_margin: PositioningCalculatorConfig::default().level_ball_depth_margin,
50            pressure_neutral_zone_half_width_y: PressureCalculatorConfig::default()
51                .neutral_zone_half_width_y,
52            rush_max_start_y: RushCalculatorConfig::default().max_start_y,
53            rush_attack_support_distance_y: RushCalculatorConfig::default()
54                .attack_support_distance_y,
55            rush_defender_distance_y: RushCalculatorConfig::default().defender_distance_y,
56            rush_min_possession_retained_seconds: RushCalculatorConfig::default()
57                .min_possession_retained_seconds,
58            aerial_goal_min_ball_z: AerialGoalCalculatorConfig::default().min_ball_z,
59            high_aerial_goal_min_ball_z: HighAerialGoalCalculatorConfig::default().min_ball_z,
60            long_distance_goal_max_attacking_y: LongDistanceGoalCalculatorConfig::default()
61                .max_attacking_y,
62            own_half_goal_max_attacking_y: OwnHalfGoalCalculatorConfig::default().max_attacking_y,
63            empty_net_min_defender_y_margin: EmptyNetGoalCalculatorConfig::default()
64                .min_defender_y_margin,
65            empty_net_min_defender_distance: EmptyNetGoalCalculatorConfig::default()
66                .min_defender_distance,
67            empty_net_max_touch_attacking_y: EmptyNetGoalCalculatorConfig::default()
68                .max_touch_attacking_y,
69            flick_goal_max_event_to_goal_seconds: FlickGoalCalculatorConfig::default()
70                .max_event_to_goal_seconds,
71            one_timer_goal_max_event_to_goal_seconds: OneTimerGoalCalculatorConfig::default()
72                .max_event_to_goal_seconds,
73            air_dribble_goal_max_end_to_goal_seconds: AirDribbleGoalCalculatorConfig::default()
74                .max_end_to_goal_seconds,
75            flip_reset_goal_max_event_to_goal_seconds: FlipResetGoalCalculatorConfig::default()
76                .max_event_to_goal_seconds,
77        }
78    }
79
80    fn snapshot_frame(&self) -> SubtrActorResult<ReplayStatsFrame> {
81        self.graph
82            .state::<StatsTimelineFrameState>()
83            .and_then(|state| state.frame.clone())
84            .ok_or_else(|| {
85                SubtrActorError::new(SubtrActorErrorVariant::CallbackError(
86                    "missing StatsTimelineFrame state while building timeline frame".to_owned(),
87                ))
88            })
89    }
90
91    pub fn into_replay_stats_timeline(self) -> SubtrActorResult<ReplayStatsTimeline> {
92        let replay_meta = self
93            .replay_meta
94            .clone()
95            .ok_or_else(|| SubtrActorError::new(SubtrActorErrorVariant::CouldNotBuildReplayMeta))?;
96        let mut events = self
97            .graph
98            .state::<StatsTimelineEventsState>()
99            .map(|state| state.events.clone())
100            .unwrap_or_default();
101        if let Some(boost) = self.graph.state::<BoostCalculator>() {
102            events.boost_pickups = boost.pickup_comparison_events().to_vec();
103        }
104        Ok(ReplayStatsTimeline {
105            config: self.timeline_config(),
106            replay_meta,
107            events,
108            frames: self.frames,
109        })
110    }
111
112    pub fn with_frame_resolution(mut self, resolution: StatsFrameResolution) -> Self {
113        self.frame_persistence = StatsFramePersistenceController::new(resolution);
114        self
115    }
116
117    pub fn get_replay_data(
118        mut self,
119        replay: &boxcars::Replay,
120    ) -> SubtrActorResult<ReplayStatsTimeline> {
121        let mut processor = ReplayProcessor::new(replay)?;
122        processor.process(&mut self)?;
123        self.into_replay_stats_timeline()
124    }
125
126    pub fn into_timeline(self) -> ReplayStatsTimeline {
127        self.into_replay_stats_timeline()
128            .expect("analysis-node timeline collector should build typed stats frames")
129    }
130}
131
132impl Collector for StatsTimelineCollector {
133    fn process_frame(
134        &mut self,
135        processor: &ReplayProcessor,
136        _frame: &boxcars::Frame,
137        frame_number: usize,
138        current_time: f32,
139    ) -> SubtrActorResult<TimeAdvance> {
140        let player_count = processor.player_count();
141        if self.last_replay_meta_player_count != Some(player_count) {
142            let replay_meta = processor.get_replay_meta()?;
143            self.graph.on_replay_meta(&replay_meta)?;
144            self.replay_meta = Some(replay_meta);
145            self.last_replay_meta_player_count = Some(player_count);
146        }
147
148        let dt = self
149            .last_sample_time
150            .map(|last_time| (current_time - last_time).max(0.0))
151            .unwrap_or(0.0);
152        let frame_input = FrameInput::timeline(processor, frame_number, current_time, dt);
153        self.graph.evaluate_with_state(&frame_input)?;
154        self.last_sample_time = Some(current_time);
155
156        if let Some(emitted_dt) = self.frame_persistence.on_frame(frame_number, current_time) {
157            let mut frame = self.snapshot_frame()?;
158            frame.dt = emitted_dt;
159            self.frames.push(frame);
160        }
161
162        Ok(TimeAdvance::NextFrame)
163    }
164
165    fn finish_replay(&mut self, _processor: &ReplayProcessor) -> SubtrActorResult<()> {
166        self.graph.finish()?;
167        let Some(_) = self.replay_meta.as_ref() else {
168            return Ok(());
169        };
170        let Some(_) = self.graph.state::<StatsTimelineFrameState>() else {
171            return Ok(());
172        };
173        let mut final_snapshot = self.snapshot_frame()?;
174        match self
175            .frame_persistence
176            .final_frame_action(final_snapshot.frame_number, final_snapshot.time)
177        {
178            Some(FinalStatsFrameAction::Append { dt }) => {
179                final_snapshot.dt = dt;
180                self.frames.push(final_snapshot);
181            }
182            Some(FinalStatsFrameAction::ReplaceLast { dt }) => {
183                final_snapshot.dt = dt;
184                if let Some(last_frame) = self.frames.last_mut() {
185                    *last_frame = final_snapshot;
186                }
187            }
188            None => {}
189        }
190        Ok(())
191    }
192}