subtr-actor 0.7.3

Rocket League replay transformer
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
use super::*;

const GOAL_AFTER_KICKOFF_BUCKET_KICKOFF_MAX_SECONDS: f32 = 10.0;
const GOAL_AFTER_KICKOFF_BUCKET_SHORT_MAX_SECONDS: f32 = 20.0;
const GOAL_AFTER_KICKOFF_BUCKET_MEDIUM_MAX_SECONDS: f32 = 40.0;
const GOAL_BUILDUP_LOOKBACK_SECONDS: f32 = 12.0;
const COUNTER_ATTACK_MAX_ATTACK_SECONDS: f32 = 4.0;
const COUNTER_ATTACK_MIN_DEFENSIVE_HALF_SECONDS: f32 = 6.0;
const COUNTER_ATTACK_MIN_DEFENSIVE_THIRD_SECONDS: f32 = 2.5;
const SUSTAINED_PRESSURE_MIN_ATTACK_SECONDS: f32 = 6.0;
const SUSTAINED_PRESSURE_MIN_OFFENSIVE_HALF_SECONDS: f32 = 7.0;
const SUSTAINED_PRESSURE_MIN_OFFENSIVE_THIRD_SECONDS: f32 = 3.5;
const GOAL_CONTEXT_BOOST_LEADUP_SECONDS: f32 = 5.0;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct GoalAfterKickoffStats {
    pub kickoff_goal_count: u32,
    pub short_goal_count: u32,
    pub medium_goal_count: u32,
    pub long_goal_count: u32,
    #[serde(default, skip_serializing)]
    goal_times: Vec<f32>,
}

impl GoalAfterKickoffStats {
    pub fn goal_times(&self) -> &[f32] {
        &self.goal_times
    }

    pub fn record_goal(&mut self, time_after_kickoff: f32) {
        let clamped_time = time_after_kickoff.max(0.0);
        self.goal_times.push(clamped_time);
        if clamped_time < GOAL_AFTER_KICKOFF_BUCKET_KICKOFF_MAX_SECONDS {
            self.kickoff_goal_count += 1;
        } else if clamped_time < GOAL_AFTER_KICKOFF_BUCKET_SHORT_MAX_SECONDS {
            self.short_goal_count += 1;
        } else if clamped_time < GOAL_AFTER_KICKOFF_BUCKET_MEDIUM_MAX_SECONDS {
            self.medium_goal_count += 1;
        } else {
            self.long_goal_count += 1;
        }
    }

    pub fn average_goal_time_after_kickoff(&self) -> f32 {
        if self.goal_times.is_empty() {
            0.0
        } else {
            self.goal_times.iter().sum::<f32>() / self.goal_times.len() as f32
        }
    }

    pub fn median_goal_time_after_kickoff(&self) -> f32 {
        if self.goal_times.is_empty() {
            return 0.0;
        }

        let mut sorted_times = self.goal_times.clone();
        sorted_times.sort_by(|a, b| a.total_cmp(b));
        let midpoint = sorted_times.len() / 2;
        if sorted_times.len().is_multiple_of(2) {
            (sorted_times[midpoint - 1] + sorted_times[midpoint]) * 0.5
        } else {
            sorted_times[midpoint]
        }
    }

    fn merge(&mut self, other: &Self) {
        self.kickoff_goal_count += other.kickoff_goal_count;
        self.short_goal_count += other.short_goal_count;
        self.medium_goal_count += other.medium_goal_count;
        self.long_goal_count += other.long_goal_count;
        self.goal_times.extend(other.goal_times.iter().copied());
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GoalBuildupKind {
    CounterAttack,
    SustainedPressure,
    Other,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct GoalBuildupStats {
    pub counter_attack_goal_count: u32,
    pub sustained_pressure_goal_count: u32,
    pub other_buildup_goal_count: u32,
}

impl GoalBuildupStats {
    fn record(&mut self, kind: GoalBuildupKind) {
        match kind {
            GoalBuildupKind::CounterAttack => self.counter_attack_goal_count += 1,
            GoalBuildupKind::SustainedPressure => self.sustained_pressure_goal_count += 1,
            GoalBuildupKind::Other => self.other_buildup_goal_count += 1,
        }
    }

    fn merge(&mut self, other: &Self) {
        self.counter_attack_goal_count += other.counter_attack_goal_count;
        self.sustained_pressure_goal_count += other.sustained_pressure_goal_count;
        self.other_buildup_goal_count += other.other_buildup_goal_count;
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct PlayerScoringContextStats {
    pub goals_conceded_while_last_defender: u32,
    pub goals_for_while_most_back: u32,
    pub goals_against_while_most_back: u32,
    pub goal_against_boost_sample_count: u32,
    pub cumulative_boost_on_goals_against: f32,
    pub last_boost_on_goal_against: Option<f32>,
    pub goal_against_boost_leadup_sample_count: u32,
    pub cumulative_average_boost_in_goal_against_leadup: f32,
    pub cumulative_min_boost_in_goal_against_leadup: f32,
    pub last_average_boost_in_goal_against_leadup: Option<f32>,
    pub last_min_boost_in_goal_against_leadup: Option<f32>,
    pub goal_against_position_sample_count: u32,
    pub cumulative_goal_against_position_x: f32,
    pub cumulative_goal_against_position_y: f32,
    pub cumulative_goal_against_position_z: f32,
    pub last_goal_against_position: Option<GoalContextPosition>,
    pub scoring_goal_last_touch_position_sample_count: u32,
    pub cumulative_scoring_goal_last_touch_position_x: f32,
    pub cumulative_scoring_goal_last_touch_position_y: f32,
    pub cumulative_scoring_goal_last_touch_position_z: f32,
    pub last_scoring_goal_last_touch_position: Option<GoalContextPosition>,
    #[serde(flatten)]
    pub goal_after_kickoff: GoalAfterKickoffStats,
    #[serde(flatten)]
    pub goal_buildup: GoalBuildupStats,
}

impl PlayerScoringContextStats {
    fn record_goal_against_snapshot(
        &mut self,
        boost_amount: Option<f32>,
        position: Option<GoalContextPosition>,
        boost_leadup: Option<BoostLeadupStats>,
    ) {
        if let Some(boost_amount) = boost_amount {
            self.goal_against_boost_sample_count += 1;
            self.cumulative_boost_on_goals_against += boost_amount;
            self.last_boost_on_goal_against = Some(boost_amount);
        }

        if let Some(boost_leadup) = boost_leadup {
            self.goal_against_boost_leadup_sample_count += 1;
            self.cumulative_average_boost_in_goal_against_leadup += boost_leadup.average_boost;
            self.cumulative_min_boost_in_goal_against_leadup += boost_leadup.min_boost;
            self.last_average_boost_in_goal_against_leadup = Some(boost_leadup.average_boost);
            self.last_min_boost_in_goal_against_leadup = Some(boost_leadup.min_boost);
        }

        if let Some(position) = position {
            self.goal_against_position_sample_count += 1;
            self.cumulative_goal_against_position_x += position.x;
            self.cumulative_goal_against_position_y += position.y;
            self.cumulative_goal_against_position_z += position.z;
            self.last_goal_against_position = Some(position);
        }
    }

    fn record_scoring_goal_last_touch_position(&mut self, position: GoalContextPosition) {
        self.scoring_goal_last_touch_position_sample_count += 1;
        self.cumulative_scoring_goal_last_touch_position_x += position.x;
        self.cumulative_scoring_goal_last_touch_position_y += position.y;
        self.cumulative_scoring_goal_last_touch_position_z += position.z;
        self.last_scoring_goal_last_touch_position = Some(position);
    }

    fn average_boost_on_goals_against(&self) -> f32 {
        if self.goal_against_boost_sample_count == 0 {
            0.0
        } else {
            self.cumulative_boost_on_goals_against / self.goal_against_boost_sample_count as f32
        }
    }

    fn average_boost_in_goal_against_leadup(&self) -> f32 {
        if self.goal_against_boost_leadup_sample_count == 0 {
            0.0
        } else {
            self.cumulative_average_boost_in_goal_against_leadup
                / self.goal_against_boost_leadup_sample_count as f32
        }
    }

    fn average_min_boost_in_goal_against_leadup(&self) -> f32 {
        if self.goal_against_boost_leadup_sample_count == 0 {
            0.0
        } else {
            self.cumulative_min_boost_in_goal_against_leadup
                / self.goal_against_boost_leadup_sample_count as f32
        }
    }

    fn average_goal_against_position_x(&self) -> f32 {
        if self.goal_against_position_sample_count == 0 {
            0.0
        } else {
            self.cumulative_goal_against_position_x / self.goal_against_position_sample_count as f32
        }
    }

    fn average_goal_against_position_y(&self) -> f32 {
        if self.goal_against_position_sample_count == 0 {
            0.0
        } else {
            self.cumulative_goal_against_position_y / self.goal_against_position_sample_count as f32
        }
    }

    fn average_goal_against_position_z(&self) -> f32 {
        if self.goal_against_position_sample_count == 0 {
            0.0
        } else {
            self.cumulative_goal_against_position_z / self.goal_against_position_sample_count as f32
        }
    }

    fn average_scoring_goal_last_touch_position_x(&self) -> f32 {
        if self.scoring_goal_last_touch_position_sample_count == 0 {
            0.0
        } else {
            self.cumulative_scoring_goal_last_touch_position_x
                / self.scoring_goal_last_touch_position_sample_count as f32
        }
    }

    fn average_scoring_goal_last_touch_position_y(&self) -> f32 {
        if self.scoring_goal_last_touch_position_sample_count == 0 {
            0.0
        } else {
            self.cumulative_scoring_goal_last_touch_position_y
                / self.scoring_goal_last_touch_position_sample_count as f32
        }
    }

    fn average_scoring_goal_last_touch_position_z(&self) -> f32 {
        if self.scoring_goal_last_touch_position_sample_count == 0 {
            0.0
        } else {
            self.cumulative_scoring_goal_last_touch_position_z
                / self.scoring_goal_last_touch_position_sample_count as f32
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct CorePlayerStats {
    pub score: i32,
    pub goals: i32,
    pub assists: i32,
    pub saves: i32,
    pub shots: i32,
    #[serde(flatten)]
    pub scoring_context: PlayerScoringContextStats,
}

impl CorePlayerStats {
    pub fn shooting_percentage(&self) -> f32 {
        if self.shots == 0 {
            0.0
        } else {
            self.goals as f32 * 100.0 / self.shots as f32
        }
    }

    pub fn average_goal_time_after_kickoff(&self) -> f32 {
        self.scoring_context
            .goal_after_kickoff
            .average_goal_time_after_kickoff()
    }

    pub fn median_goal_time_after_kickoff(&self) -> f32 {
        self.scoring_context
            .goal_after_kickoff
            .median_goal_time_after_kickoff()
    }

    pub fn average_boost_on_goals_against(&self) -> f32 {
        self.scoring_context.average_boost_on_goals_against()
    }

    pub fn average_boost_in_goal_against_leadup(&self) -> f32 {
        self.scoring_context.average_boost_in_goal_against_leadup()
    }

    pub fn average_min_boost_in_goal_against_leadup(&self) -> f32 {
        self.scoring_context
            .average_min_boost_in_goal_against_leadup()
    }

    pub fn average_goal_against_position_x(&self) -> f32 {
        self.scoring_context.average_goal_against_position_x()
    }

    pub fn average_goal_against_position_y(&self) -> f32 {
        self.scoring_context.average_goal_against_position_y()
    }

    pub fn average_goal_against_position_z(&self) -> f32 {
        self.scoring_context.average_goal_against_position_z()
    }

    pub fn average_scoring_goal_last_touch_position_x(&self) -> f32 {
        self.scoring_context
            .average_scoring_goal_last_touch_position_x()
    }

    pub fn average_scoring_goal_last_touch_position_y(&self) -> f32 {
        self.scoring_context
            .average_scoring_goal_last_touch_position_y()
    }

    pub fn average_scoring_goal_last_touch_position_z(&self) -> f32 {
        self.scoring_context
            .average_scoring_goal_last_touch_position_z()
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct TeamScoringContextStats {
    #[serde(flatten)]
    pub goal_after_kickoff: GoalAfterKickoffStats,
    #[serde(flatten)]
    pub goal_buildup: GoalBuildupStats,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct CoreTeamStats {
    pub score: i32,
    pub goals: i32,
    pub assists: i32,
    pub saves: i32,
    pub shots: i32,
    #[serde(flatten)]
    pub scoring_context: TeamScoringContextStats,
}

impl CoreTeamStats {
    pub fn shooting_percentage(&self) -> f32 {
        if self.shots == 0 {
            0.0
        } else {
            self.goals as f32 * 100.0 / self.shots as f32
        }
    }

    pub fn average_goal_time_after_kickoff(&self) -> f32 {
        self.scoring_context
            .goal_after_kickoff
            .average_goal_time_after_kickoff()
    }

    pub fn median_goal_time_after_kickoff(&self) -> f32 {
        self.scoring_context
            .goal_after_kickoff
            .median_goal_time_after_kickoff()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub enum TimelineEventKind {
    Goal,
    Shot,
    Save,
    Assist,
    Kill,
    Death,
}

#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
#[ts(export)]
pub struct TimelineEvent {
    pub time: f32,
    pub kind: TimelineEventKind,
    #[ts(as = "Option<crate::ts_bindings::RemoteIdTs>")]
    pub player_id: Option<PlayerId>,
    pub is_team_0: Option<bool>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
pub struct GoalContextPosition {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl From<glam::Vec3> for GoalContextPosition {
    fn from(position: glam::Vec3) -> Self {
        Self {
            x: position.x,
            y: position.y,
            z: position.z,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
#[ts(export)]
pub struct GoalPlayerContext {
    #[ts(as = "crate::ts_bindings::RemoteIdTs")]
    pub player: PlayerId,
    pub is_team_0: bool,
    pub position: Option<GoalContextPosition>,
    pub boost_amount: Option<f32>,
    pub average_boost_in_leadup: Option<f32>,
    pub min_boost_in_leadup: Option<f32>,
    pub is_most_back: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
#[ts(export)]
pub struct GoalTouchContext {
    pub time: f32,
    pub frame: usize,
    #[ts(as = "crate::ts_bindings::RemoteIdTs")]
    pub player: PlayerId,
    pub is_team_0: bool,
    pub ball_position: Option<GoalContextPosition>,
    pub player_position: Option<GoalContextPosition>,
    pub players: Vec<GoalPlayerContext>,
}

#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
#[ts(export)]
pub struct GoalContextEvent {
    pub time: f32,
    pub frame: usize,
    pub scoring_team_is_team_0: bool,
    #[ts(as = "Option<crate::ts_bindings::RemoteIdTs>")]
    pub scorer: Option<PlayerId>,
    #[ts(as = "Option<crate::ts_bindings::RemoteIdTs>")]
    pub scoring_team_most_back_player: Option<PlayerId>,
    #[ts(as = "Option<crate::ts_bindings::RemoteIdTs>")]
    pub defending_team_most_back_player: Option<PlayerId>,
    pub ball_position: Option<GoalContextPosition>,
    pub scorer_last_touch: Option<GoalTouchContext>,
    pub players: Vec<GoalPlayerContext>,
}

#[derive(Debug, Clone)]
struct PendingGoalEvent {
    event: GoalEvent,
    time_after_kickoff: Option<f32>,
}

#[derive(Debug, Clone)]
struct GoalBuildupSample {
    time: f32,
    dt: f32,
    ball_y: f32,
}

#[derive(Debug, Clone, Copy)]
struct BoostLeadupSample {
    time: f32,
    boost_amount: f32,
}

#[derive(Debug, Clone, Copy)]
struct BoostLeadupStats {
    average_boost: f32,
    min_boost: f32,
}

#[derive(Debug, Clone, Default)]
pub struct MatchStatsCalculator {
    player_stats: HashMap<PlayerId, CorePlayerStats>,
    player_teams: HashMap<PlayerId, bool>,
    previous_player_stats: HashMap<PlayerId, CorePlayerStats>,
    timeline: Vec<TimelineEvent>,
    pending_goal_events: Vec<PendingGoalEvent>,
    previous_team_scores: Option<(i32, i32)>,
    kickoff_waiting_for_first_touch: bool,
    active_kickoff_touch_time: Option<f32>,
    goal_buildup_samples: Vec<GoalBuildupSample>,
    goal_context_events: Vec<GoalContextEvent>,
    last_touch_context_by_player: HashMap<PlayerId, GoalTouchContext>,
    boost_leadup_samples_by_player: HashMap<PlayerId, VecDeque<BoostLeadupSample>>,
}

impl MatchStatsCalculator {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn player_stats(&self) -> &HashMap<PlayerId, CorePlayerStats> {
        &self.player_stats
    }

    pub fn timeline(&self) -> &[TimelineEvent] {
        &self.timeline
    }

    pub fn goal_context_events(&self) -> &[GoalContextEvent] {
        &self.goal_context_events
    }

    pub fn team_zero_stats(&self) -> CoreTeamStats {
        self.team_stats_for_side(true)
    }

    pub fn team_one_stats(&self) -> CoreTeamStats {
        self.team_stats_for_side(false)
    }

    fn team_stats_for_side(&self, is_team_0: bool) -> CoreTeamStats {
        let mut stats = self
            .player_stats
            .iter()
            .filter(|(player_id, _)| self.player_teams.get(*player_id) == Some(&is_team_0))
            .fold(CoreTeamStats::default(), |mut stats, (_, player_stats)| {
                stats.score += player_stats.score;
                stats.goals += player_stats.goals;
                stats.assists += player_stats.assists;
                stats.saves += player_stats.saves;
                stats.shots += player_stats.shots;
                stats
                    .scoring_context
                    .goal_after_kickoff
                    .merge(&player_stats.scoring_context.goal_after_kickoff);
                stats
                    .scoring_context
                    .goal_buildup
                    .merge(&player_stats.scoring_context.goal_buildup);
                stats
            });
        stats
            .scoring_context
            .goal_after_kickoff
            .goal_times
            .sort_by(|left, right| left.total_cmp(right));
        stats
    }

    fn emit_timeline_events(
        &mut self,
        time: f32,
        kind: TimelineEventKind,
        player_id: &PlayerId,
        is_team_0: bool,
        delta: i32,
    ) {
        for _ in 0..delta.max(0) {
            self.timeline.push(TimelineEvent {
                time,
                kind,
                player_id: Some(player_id.clone()),
                is_team_0: Some(is_team_0),
            });
        }
    }

    fn kickoff_phase_active(gameplay: &GameplayState) -> bool {
        gameplay.game_state == Some(GAME_STATE_KICKOFF_COUNTDOWN)
            || gameplay.kickoff_countdown_time.is_some_and(|time| time > 0)
            || gameplay.ball_has_been_hit == Some(false)
    }

    fn update_kickoff_reference(&mut self, gameplay: &GameplayState, events: &FrameEventsState) {
        if let Some(first_touch_time) = events
            .touch_events
            .iter()
            .map(|event| event.time)
            .min_by(|a, b| a.total_cmp(b))
        {
            self.active_kickoff_touch_time = Some(first_touch_time);
            self.kickoff_waiting_for_first_touch = false;
            return;
        }

        if Self::kickoff_phase_active(gameplay) {
            self.kickoff_waiting_for_first_touch = true;
            self.active_kickoff_touch_time = None;
        }
    }

    fn take_pending_goal_event(
        &mut self,
        player_id: &PlayerId,
        is_team_0: bool,
    ) -> Option<PendingGoalEvent> {
        if let Some(index) = self.pending_goal_events.iter().position(|event| {
            event.event.scoring_team_is_team_0 == is_team_0
                && event.event.player.as_ref() == Some(player_id)
        }) {
            return Some(self.pending_goal_events.remove(index));
        }

        self.pending_goal_events
            .iter()
            .position(|event| event.event.scoring_team_is_team_0 == is_team_0)
            .map(|index| self.pending_goal_events.remove(index))
    }

    fn last_defender(
        &self,
        players: &PlayerFrameState,
        defending_team_is_team_0: bool,
    ) -> Option<PlayerId> {
        players
            .players
            .iter()
            .filter(|player| player.is_team_0 == defending_team_is_team_0)
            .filter_map(|player| {
                player
                    .position()
                    .map(|position| (player.player_id.clone(), position.y))
            })
            .reduce(|current, candidate| {
                if defending_team_is_team_0 {
                    if candidate.1 < current.1 {
                        candidate
                    } else {
                        current
                    }
                } else if candidate.1 > current.1 {
                    candidate
                } else {
                    current
                }
            })
            .map(|(player_id, _)| player_id)
    }

    fn most_back_player(players: &PlayerFrameState, team_is_team_0: bool) -> Option<PlayerId> {
        players
            .players
            .iter()
            .filter(|player| player.is_team_0 == team_is_team_0)
            .filter_map(|player| {
                player.position().map(|position| {
                    (
                        player.player_id.clone(),
                        normalized_y(team_is_team_0, position),
                    )
                })
            })
            .min_by(|left, right| left.1.total_cmp(&right.1))
            .map(|(player_id, _)| player_id)
    }

    fn player_position(players: &PlayerFrameState, player_id: &PlayerId) -> Option<glam::Vec3> {
        players
            .players
            .iter()
            .find(|player| &player.player_id == player_id)
            .and_then(PlayerSample::position)
    }

    fn update_last_touch_contexts(
        &mut self,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        events: &FrameEventsState,
    ) {
        let ball_position = ball.position().map(GoalContextPosition::from);
        for touch in &events.touch_events {
            let Some(player_id) = touch.player.clone() else {
                continue;
            };
            let touch_team_most_back_player = Self::most_back_player(players, touch.team_is_team_0);
            let other_team_most_back_player =
                Self::most_back_player(players, !touch.team_is_team_0);
            let touch_players = self.goal_player_contexts(
                players,
                touch.team_is_team_0,
                touch_team_most_back_player.as_ref(),
                other_team_most_back_player.as_ref(),
            );
            self.last_touch_context_by_player.insert(
                player_id.clone(),
                GoalTouchContext {
                    time: touch.time,
                    frame: touch.frame,
                    player: player_id.clone(),
                    is_team_0: touch.team_is_team_0,
                    ball_position,
                    player_position: Self::player_position(players, &player_id)
                        .map(GoalContextPosition::from),
                    players: touch_players,
                },
            );
        }
    }

    fn update_boost_leadup_samples(&mut self, frame: &FrameInfo, players: &PlayerFrameState) {
        let cutoff_time = frame.time - GOAL_CONTEXT_BOOST_LEADUP_SECONDS;
        for player in &players.players {
            let Some(boost_amount) = player.boost_amount.or(player.last_boost_amount) else {
                continue;
            };
            let samples = self
                .boost_leadup_samples_by_player
                .entry(player.player_id.clone())
                .or_default();
            samples.push_back(BoostLeadupSample {
                time: frame.time,
                boost_amount,
            });
            while samples
                .front()
                .is_some_and(|sample| sample.time < cutoff_time)
            {
                samples.pop_front();
            }
        }

        self.boost_leadup_samples_by_player
            .retain(|_, samples| !samples.is_empty());
    }

    fn boost_leadup_for_player(&self, player_id: &PlayerId) -> Option<BoostLeadupStats> {
        let samples = self.boost_leadup_samples_by_player.get(player_id)?;
        if samples.is_empty() {
            return None;
        }

        let mut sum = 0.0;
        let mut min_boost = f32::INFINITY;
        for sample in samples {
            sum += sample.boost_amount;
            min_boost = min_boost.min(sample.boost_amount);
        }

        Some(BoostLeadupStats {
            average_boost: sum / samples.len() as f32,
            min_boost,
        })
    }

    fn goal_player_contexts(
        &self,
        players: &PlayerFrameState,
        scoring_team_is_team_0: bool,
        scoring_team_most_back_player: Option<&PlayerId>,
        defending_team_most_back_player: Option<&PlayerId>,
    ) -> Vec<GoalPlayerContext> {
        players
            .players
            .iter()
            .map(|player| {
                let most_back_player = if player.is_team_0 == scoring_team_is_team_0 {
                    scoring_team_most_back_player
                } else {
                    defending_team_most_back_player
                };
                let boost_leadup = self.boost_leadup_for_player(&player.player_id);
                GoalPlayerContext {
                    player: player.player_id.clone(),
                    is_team_0: player.is_team_0,
                    position: player.position().map(GoalContextPosition::from),
                    boost_amount: player.boost_amount.or(player.last_boost_amount),
                    average_boost_in_leadup: boost_leadup.map(|stats| stats.average_boost),
                    min_boost_in_leadup: boost_leadup.map(|stats| stats.min_boost),
                    is_most_back: most_back_player == Some(&player.player_id),
                }
            })
            .collect()
    }

    fn record_goal_context_stats(
        &mut self,
        players: &PlayerFrameState,
        goal_event: &GoalEvent,
        scoring_team_most_back_player: Option<&PlayerId>,
        defending_team_most_back_player: Option<&PlayerId>,
        scorer_last_touch: Option<&GoalTouchContext>,
    ) {
        if let Some(player_id) = scoring_team_most_back_player {
            self.player_stats
                .entry(player_id.clone())
                .or_default()
                .scoring_context
                .goals_for_while_most_back += 1;
        }

        if let Some(player_id) = defending_team_most_back_player {
            self.player_stats
                .entry(player_id.clone())
                .or_default()
                .scoring_context
                .goals_against_while_most_back += 1;
        }

        for player in players
            .players
            .iter()
            .filter(|player| player.is_team_0 != goal_event.scoring_team_is_team_0)
        {
            let boost_leadup = self.boost_leadup_for_player(&player.player_id);
            self.player_stats
                .entry(player.player_id.clone())
                .or_default()
                .scoring_context
                .record_goal_against_snapshot(
                    player.boost_amount.or(player.last_boost_amount),
                    player.position().map(GoalContextPosition::from),
                    boost_leadup,
                );
        }

        if let Some(scorer) = goal_event.player.as_ref() {
            if let Some(touch_position) = scorer_last_touch.and_then(|touch| touch.ball_position) {
                self.player_stats
                    .entry(scorer.clone())
                    .or_default()
                    .scoring_context
                    .record_scoring_goal_last_touch_position(touch_position);
            }
        }
    }

    fn record_goal_context_events(
        &mut self,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        events: &FrameEventsState,
    ) {
        let ball_position = ball.position().map(GoalContextPosition::from);
        for goal_event in &events.goal_events {
            let scoring_team_most_back_player =
                Self::most_back_player(players, goal_event.scoring_team_is_team_0);
            let defending_team_most_back_player =
                Self::most_back_player(players, !goal_event.scoring_team_is_team_0);
            let scorer_last_touch = goal_event
                .player
                .as_ref()
                .and_then(|player_id| self.last_touch_context_by_player.get(player_id))
                .filter(|touch| touch.is_team_0 == goal_event.scoring_team_is_team_0)
                .cloned();

            self.record_goal_context_stats(
                players,
                goal_event,
                scoring_team_most_back_player.as_ref(),
                defending_team_most_back_player.as_ref(),
                scorer_last_touch.as_ref(),
            );

            self.goal_context_events.push(GoalContextEvent {
                time: goal_event.time,
                frame: goal_event.frame,
                scoring_team_is_team_0: goal_event.scoring_team_is_team_0,
                scorer: goal_event.player.clone(),
                scoring_team_most_back_player: scoring_team_most_back_player.clone(),
                defending_team_most_back_player: defending_team_most_back_player.clone(),
                ball_position,
                scorer_last_touch,
                players: self.goal_player_contexts(
                    players,
                    goal_event.scoring_team_is_team_0,
                    scoring_team_most_back_player.as_ref(),
                    defending_team_most_back_player.as_ref(),
                ),
            });
        }
    }

    fn prune_goal_buildup_samples(&mut self, current_time: f32) {
        self.goal_buildup_samples
            .retain(|entry| current_time - entry.time <= GOAL_BUILDUP_LOOKBACK_SECONDS);
    }

    fn record_goal_buildup_sample(&mut self, frame: &FrameInfo, ball: &BallFrameState) {
        let Some(ball) = ball.sample() else {
            return;
        };
        if frame.dt <= 0.0 {
            return;
        }
        self.goal_buildup_samples.push(GoalBuildupSample {
            time: frame.time,
            dt: frame.dt,
            ball_y: ball.position().y,
        });
    }

    fn classify_goal_buildup(
        &self,
        goal_time: f32,
        scoring_team_is_team_0: bool,
    ) -> GoalBuildupKind {
        let relevant_samples: Vec<_> = self
            .goal_buildup_samples
            .iter()
            .filter(|entry| goal_time - entry.time <= GOAL_BUILDUP_LOOKBACK_SECONDS)
            .collect();
        if relevant_samples.is_empty() {
            return GoalBuildupKind::Other;
        }

        let mut defensive_half_time = 0.0;
        let mut defensive_third_time = 0.0;
        let mut offensive_half_time = 0.0;
        let mut offensive_third_time = 0.0;
        let mut current_attack_time = 0.0;

        for entry in &relevant_samples {
            let normalized_ball_y = if scoring_team_is_team_0 {
                entry.ball_y
            } else {
                -entry.ball_y
            };
            if normalized_ball_y < 0.0 {
                defensive_half_time += entry.dt;
            } else {
                offensive_half_time += entry.dt;
            }
            if normalized_ball_y < -FIELD_ZONE_BOUNDARY_Y {
                defensive_third_time += entry.dt;
            }
            if normalized_ball_y > FIELD_ZONE_BOUNDARY_Y {
                offensive_third_time += entry.dt;
            }
        }

        for entry in relevant_samples.iter().rev() {
            let normalized_ball_y = if scoring_team_is_team_0 {
                entry.ball_y
            } else {
                -entry.ball_y
            };
            if normalized_ball_y > 0.0 {
                current_attack_time += entry.dt;
            } else {
                break;
            }
        }

        if current_attack_time <= COUNTER_ATTACK_MAX_ATTACK_SECONDS
            && defensive_half_time >= COUNTER_ATTACK_MIN_DEFENSIVE_HALF_SECONDS
            && defensive_third_time >= COUNTER_ATTACK_MIN_DEFENSIVE_THIRD_SECONDS
        {
            GoalBuildupKind::CounterAttack
        } else if current_attack_time >= SUSTAINED_PRESSURE_MIN_ATTACK_SECONDS
            && offensive_half_time >= SUSTAINED_PRESSURE_MIN_OFFENSIVE_HALF_SECONDS
            && offensive_third_time >= SUSTAINED_PRESSURE_MIN_OFFENSIVE_THIRD_SECONDS
        {
            GoalBuildupKind::SustainedPressure
        } else {
            GoalBuildupKind::Other
        }
    }
}

impl MatchStatsCalculator {
    pub fn update_parts(
        &mut self,
        frame: &FrameInfo,
        gameplay: &GameplayState,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        events: &FrameEventsState,
        live_play_state: &LivePlayState,
    ) -> SubtrActorResult<()> {
        self.update_kickoff_reference(gameplay, events);
        self.prune_goal_buildup_samples(frame.time);
        if live_play_state.is_live_play {
            self.record_goal_buildup_sample(frame, ball);
            self.update_boost_leadup_samples(frame, players);
        } else if events.goal_events.is_empty() {
            self.last_touch_context_by_player.clear();
            self.boost_leadup_samples_by_player.clear();
        }
        self.update_last_touch_contexts(ball, players, events);
        self.record_goal_context_events(ball, players, events);
        self.pending_goal_events
            .extend(events.goal_events.iter().cloned().map(|event| {
                PendingGoalEvent {
                    time_after_kickoff: self
                        .active_kickoff_touch_time
                        .map(|kickoff_touch_time| (event.time - kickoff_touch_time).max(0.0)),
                    event,
                }
            }));
        let mut processor_event_counts: HashMap<(PlayerId, TimelineEventKind), i32> =
            HashMap::new();
        for event in &events.player_stat_events {
            let kind = match event.kind {
                PlayerStatEventKind::Shot => TimelineEventKind::Shot,
                PlayerStatEventKind::Save => TimelineEventKind::Save,
                PlayerStatEventKind::Assist => TimelineEventKind::Assist,
            };
            self.timeline.push(TimelineEvent {
                time: event.time,
                kind,
                player_id: Some(event.player.clone()),
                is_team_0: Some(event.is_team_0),
            });
            *processor_event_counts
                .entry((event.player.clone(), kind))
                .or_default() += 1;
        }

        for player in &players.players {
            self.player_teams
                .insert(player.player_id.clone(), player.is_team_0);
            let mut current_stats = CorePlayerStats {
                score: player.match_score.unwrap_or(0),
                goals: player.match_goals.unwrap_or(0),
                assists: player.match_assists.unwrap_or(0),
                saves: player.match_saves.unwrap_or(0),
                shots: player.match_shots.unwrap_or(0),
                scoring_context: self
                    .player_stats
                    .get(&player.player_id)
                    .map(|stats| stats.scoring_context.clone())
                    .unwrap_or_default(),
            };

            let previous_stats = self
                .previous_player_stats
                .get(&player.player_id)
                .cloned()
                .unwrap_or_default();

            let shot_delta = current_stats.shots - previous_stats.shots;
            let save_delta = current_stats.saves - previous_stats.saves;
            let assist_delta = current_stats.assists - previous_stats.assists;
            let goal_delta = current_stats.goals - previous_stats.goals;
            let shot_fallback_delta = shot_delta
                - processor_event_counts
                    .get(&(player.player_id.clone(), TimelineEventKind::Shot))
                    .copied()
                    .unwrap_or(0);
            let save_fallback_delta = save_delta
                - processor_event_counts
                    .get(&(player.player_id.clone(), TimelineEventKind::Save))
                    .copied()
                    .unwrap_or(0);
            let assist_fallback_delta = assist_delta
                - processor_event_counts
                    .get(&(player.player_id.clone(), TimelineEventKind::Assist))
                    .copied()
                    .unwrap_or(0);

            if shot_fallback_delta > 0 {
                self.emit_timeline_events(
                    frame.time,
                    TimelineEventKind::Shot,
                    &player.player_id,
                    player.is_team_0,
                    shot_fallback_delta,
                );
            }
            if save_fallback_delta > 0 {
                self.emit_timeline_events(
                    frame.time,
                    TimelineEventKind::Save,
                    &player.player_id,
                    player.is_team_0,
                    save_fallback_delta,
                );
            }
            if assist_fallback_delta > 0 {
                self.emit_timeline_events(
                    frame.time,
                    TimelineEventKind::Assist,
                    &player.player_id,
                    player.is_team_0,
                    assist_fallback_delta,
                );
            }
            if goal_delta > 0 {
                for _ in 0..goal_delta.max(0) {
                    let pending_goal_event =
                        self.take_pending_goal_event(&player.player_id, player.is_team_0);
                    let goal_time = pending_goal_event
                        .as_ref()
                        .map(|event| event.event.time)
                        .unwrap_or(frame.time);
                    let time_after_kickoff = pending_goal_event
                        .and_then(|event| event.time_after_kickoff)
                        .or_else(|| {
                            self.active_kickoff_touch_time
                                .map(|kickoff_touch_time| (goal_time - kickoff_touch_time).max(0.0))
                        });
                    if let Some(time_after_kickoff) = time_after_kickoff {
                        current_stats
                            .scoring_context
                            .goal_after_kickoff
                            .record_goal(time_after_kickoff);
                    }
                    current_stats
                        .scoring_context
                        .goal_buildup
                        .record(self.classify_goal_buildup(goal_time, player.is_team_0));
                    self.timeline.push(TimelineEvent {
                        time: goal_time,
                        kind: TimelineEventKind::Goal,
                        player_id: Some(player.player_id.clone()),
                        is_team_0: Some(player.is_team_0),
                    });
                }
            }

            self.previous_player_stats
                .insert(player.player_id.clone(), current_stats.clone());
            self.player_stats
                .insert(player.player_id.clone(), current_stats);
        }

        if let (Some(team_zero_score), Some(team_one_score)) =
            (gameplay.team_zero_score, gameplay.team_one_score)
        {
            if let Some((prev_team_zero_score, prev_team_one_score)) = self.previous_team_scores {
                let team_zero_delta = team_zero_score - prev_team_zero_score;
                let team_one_delta = team_one_score - prev_team_one_score;

                if team_zero_delta > 0 {
                    if let Some(last_defender) = self.last_defender(players, false) {
                        if let Some(stats) = self.player_stats.get_mut(&last_defender) {
                            stats.scoring_context.goals_conceded_while_last_defender +=
                                team_zero_delta as u32;
                        }
                    }
                }

                if team_one_delta > 0 {
                    if let Some(last_defender) = self.last_defender(players, true) {
                        if let Some(stats) = self.player_stats.get_mut(&last_defender) {
                            stats.scoring_context.goals_conceded_while_last_defender +=
                                team_one_delta as u32;
                        }
                    }
                }
            }

            self.previous_team_scores = Some((team_zero_score, team_one_score));
        }

        self.timeline.sort_by(|a, b| {
            a.time
                .partial_cmp(&b.time)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Ok(())
    }
}