subtr-actor 1.1.0

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
use super::*;

/// Ball gravity (Unreal units / s²) used to remove the gravitational component
/// when estimating the velocity change a touch imparted to the ball.
const BALL_GRAVITY_Z: f32 = -650.0;

/// How long after a flick-candidate touch the detector keeps measuring the
/// ball's velocity change. A flick's power is not delivered in the single frame
/// the touch is first detected: when a car carries/drags the ball through the
/// dodge (e.g. a 180 flick) the ball keeps accelerating for a few frames after
/// contact. Measuring the *peak* gravity-compensated impulse over this window —
/// instead of one frame — is what lets those flicks clear the impulse gate.
const FLICK_IMPULSE_WINDOW_SECONDS: f32 = 0.15;

const FLICK_MAX_DODGE_TO_TOUCH_SECONDS: f32 = 0.32;
/// How far *before* the recorded dodge transition the flick contact may register.
/// The ball can start accelerating well before the dodge-active byte flips — the
/// launch touch has been observed up to ~0.23s ahead of the byte on downsampled
/// replays — so the touch that the pending flick anchors to sometimes precedes
/// the recorded dodge start. Allow a negative `time_since_dodge` down to the
/// shared dodge-byte lag tolerance rather than rejecting these as "touch before
/// dodge". See [`DODGE_ACTIVE_BYTE_LAG_TOLERANCE_SECONDS`].
const FLICK_DODGE_LEAD_TOLERANCE_SECONDS: f32 = DODGE_ACTIVE_BYTE_LAG_TOLERANCE_SECONDS;
/// How long a pending flick is kept alive waiting to be confirmed. Impulse is
/// only *measured* over [`FLICK_IMPULSE_WINDOW_SECONDS`], but the entry must
/// outlive that window so a dodge byte that replicates late (see
/// [`FLICK_DODGE_LEAD_TOLERANCE_SECONDS`]) can still attach to the launch touch
/// and emit the flick. Must be at least the impulse window.
const FLICK_PENDING_RETENTION_SECONDS: f32 = FLICK_DODGE_LEAD_TOLERANCE_SECONDS;
const _: () = assert!(FLICK_PENDING_RETENTION_SECONDS >= FLICK_IMPULSE_WINDOW_SECONDS);
const FLICK_MAX_CONTROL_TO_DODGE_SECONDS: f32 = 0.08;
const FLICK_MAX_SETUP_STALE_SECONDS: f32 = 0.35;
/// How long a control setup survives without a fresh control observation before
/// it is finished. A real carry/dribble lets the ball wobble in and out of the
/// tight control volume (the ball briefly exceeds the gap thresholds), so
/// finishing the setup on the first dropped frame fragments one ~0.5s carry into
/// sub-`FLICK_MIN_SETUP_SECONDS` pieces that never qualify. Bridging brief gaps
/// keeps the setup continuous while still ending it when the carry truly stops.
const FLICK_SETUP_GAP_GRACE_SECONDS: f32 = 0.12;
const FLICK_MIN_PENDING_DODGE_SETUP_SECONDS: f32 = 0.10;
const FLICK_MIN_SETUP_SECONDS: f32 = 0.20;
const FLICK_MIN_BALL_SPEED_CHANGE: f32 = 325.0;
const FLICK_MIN_CONFIDENCE: f32 = 0.55;
const FLICK_MAX_CONTROL_BALL_Z: f32 = 700.0;
const FLICK_MAX_CONTROL_HORIZONTAL_GAP: f32 = BALL_RADIUS_Z * 1.7;
const FLICK_MIN_CONTROL_VERTICAL_GAP: f32 = 35.0;
const FLICK_MAX_CONTROL_VERTICAL_GAP: f32 = 280.0;
/// Carry evidence threshold: the *minimum* horizontal speed difference between
/// the ball and the car observed across a flick setup must fall at or below this
/// for the setup to count as a genuine carry/dribble. A real flick rides the
/// ball on the car, so at some point during the setup their horizontal
/// velocities track within tens of uu/s (observed minima ~24–46). A loose ball
/// the car is merely driving at keeps its own velocity, so the difference never
/// drops — its setup-minimum stays ~600+. Taking the minimum over the whole
/// setup (rather than gating per frame) keeps the high relative velocity at the
/// instant of the dodge from causing a false negative.
const FLICK_MAX_CARRY_REL_HORIZONTAL_SPEED: f32 = 300.0;
const FLICK_MIN_LOCAL_Z: f32 = 20.0;
const FLICK_MAX_LOCAL_X_BEHIND: f32 = 95.0;
const FLICK_MAX_LOCAL_X_FRONT: f32 = 210.0;
const FLICK_MAX_LOCAL_Y: f32 = 170.0;
const FLICK_MIN_IMPULSE_AWAY_ALIGNMENT: f32 = 0.15;
const REVERSE_FLICK_MIN_BACKFLIP_PITCH_RATE: f32 = 2.5;
const REVERSE_FLICK_MIN_FORWARD_IMPULSE: f32 = 450.0;
const REVERSE_FLICK_MIN_FORWARD_IMPULSE_ALIGNMENT: f32 = 0.55;
const REVERSE_FLICK_MIN_ROTATION_UNDER_BALL_DEGREES: f32 = 15.0;

/// The kind of flick detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlickKind {
    Other,
    Reverse,
}

/// Rotation direction of the car during the flick setup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlickSetupRotationDirection {
    Unknown,
    Left,
    Right,
}

pub(crate) const FLICK_KIND_LABELS: [StatLabel; 2] = [
    StatLabel::new("kind", "other"),
    StatLabel::new("kind", "reverse"),
];

pub(crate) const FLICK_SETUP_ROTATION_DIRECTION_LABELS: [StatLabel; 3] = [
    StatLabel::new("setup_rotation_direction", "unknown"),
    StatLabel::new("setup_rotation_direction", "left"),
    StatLabel::new("setup_rotation_direction", "right"),
];

impl FlickKind {
    pub fn as_label_value(self) -> &'static str {
        match self {
            Self::Other => "other",
            Self::Reverse => "reverse",
        }
    }

    pub fn as_label(self) -> StatLabel {
        flick_kind_label(self.as_label_value())
    }
}

impl FlickSetupRotationDirection {
    pub fn as_label_value(self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::Left => "left",
            Self::Right => "right",
        }
    }
}

pub(crate) fn flick_kind_label(value: &str) -> StatLabel {
    match value {
        "reverse" => StatLabel::new("kind", "reverse"),
        _ => StatLabel::new("kind", "other"),
    }
}

pub(crate) fn flick_setup_rotation_direction_label(value: &str) -> StatLabel {
    match value {
        "left" => StatLabel::new("setup_rotation_direction", "left"),
        "right" => StatLabel::new("setup_rotation_direction", "right"),
        _ => StatLabel::new("setup_rotation_direction", "unknown"),
    }
}

/// A dodge-powered touch following a short controlled carry setup.
#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
#[ts(export)]
pub struct FlickEvent {
    pub time: f32,
    pub frame: usize,
    pub sample_time: f32,
    pub sample_frame: usize,
    #[ts(as = "crate::interop::ts_bindings::RemoteIdTs")]
    pub player: PlayerId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub player_position: Option<[f32; 3]>,
    pub is_team_0: bool,
    pub dodge_time: f32,
    pub dodge_frame: usize,
    pub time_since_dodge: f32,
    pub setup_start_time: f32,
    pub setup_start_frame: usize,
    pub setup_duration: f32,
    pub setup_touch_count: u32,
    pub average_horizontal_gap: f32,
    pub average_vertical_gap: f32,
    pub ball_speed_change: f32,
    pub ball_impulse: [f32; 3],
    pub impulse_away_alignment: f32,
    pub vertical_impulse: f32,
    pub kind: String,
    pub local_ball_position: [f32; 3],
    pub local_ball_impulse: [f32; 3],
    pub backflip_pitch_rate: f32,
    pub rotation_under_ball_degrees: f32,
    pub setup_rotation_degrees: f32,
    pub setup_rotation_direction: String,
    pub confidence: f32,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct FlickControlObservation {
    horizontal_gap: f32,
    vertical_gap: f32,
    /// Horizontal speed difference between ball and car this frame, or `None`
    /// when velocity data is unavailable. See [`FLICK_MAX_CARRY_REL_HORIZONTAL_SPEED`].
    relative_horizontal_speed: Option<f32>,
}

#[derive(Debug, Clone, PartialEq)]
struct ActiveFlickSetup {
    is_team_0: bool,
    start_time: f32,
    start_frame: usize,
    last_time: f32,
    last_frame: usize,
    duration: f32,
    horizontal_gap_integral: f32,
    vertical_gap_integral: f32,
    touch_count: u32,
    start_forward: Option<glam::Vec3>,
    max_horizontal_rotation_degrees: f32,
    signed_horizontal_rotation_degrees: f32,
    /// Smallest ball-vs-car horizontal speed difference seen during a *non-dodge*
    /// frame of the setup, or `f32::INFINITY` if none. See
    /// [`FLICK_MAX_CARRY_REL_HORIZONTAL_SPEED`].
    min_relative_horizontal_speed: f32,
    /// Whether any frame of the setup carried ball+car velocity data. Lets the
    /// carry check stay lenient on replays without velocities while still
    /// rejecting a setup that *has* velocity data but no non-dodge carry.
    observed_velocity: bool,
}

#[derive(Debug, Clone, PartialEq)]
struct FlickSetupSummary {
    is_team_0: bool,
    start_time: f32,
    start_frame: usize,
    last_time: f32,
    last_frame: usize,
    duration: f32,
    average_horizontal_gap: f32,
    average_vertical_gap: f32,
    touch_count: u32,
    rotation_under_ball_degrees: f32,
    setup_rotation_degrees: f32,
    min_relative_horizontal_speed: f32,
    observed_velocity: bool,
}

#[derive(Debug, Clone, PartialEq)]
struct RecentDodgeStart {
    time: f32,
    frame: usize,
    setup: FlickSetupSummary,
    rotation_at_dodge: Option<glam::Quat>,
}

/// A touch that looks like it could be a flick, kept alive for a short window so
/// the detector can watch the ball's full velocity change (see
/// [`FLICK_IMPULSE_WINDOW_SECONDS`]). `peak_impulse` is the largest
/// gravity-compensated change observed since just before the touch; `ball` and
/// `player` are snapshotted at the touch so the flick geometry is measured at
/// contact while its power is measured across the window.
#[derive(Debug, Clone)]
struct PendingFlick {
    touch_event: TouchEvent,
    ball: BallFrameState,
    player: PlayerSample,
    /// Dodge start recorded by a genuine dodge-active transition, when present.
    real_dodge_start: Option<RecentDodgeStart>,
    /// Whether the touch was classified as a dodge contact downstream.
    classified_dodge: bool,
    /// Ball velocity in the frame just before the touch.
    pre_velocity: glam::Vec3,
    peak_impulse: glam::Vec3,
    peak_magnitude: f32,
}

impl PartialEq for PendingFlick {
    fn eq(&self, other: &Self) -> bool {
        self.touch_event.touch_id == other.touch_event.touch_id
            && self.touch_event.player == other.touch_event.player
            && self.touch_event.frame == other.touch_event.frame
    }
}

/// Detects flicks from ball/player state and touches.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FlickCalculator {
    events: EventStream<FlickEvent>,
    active_setups: HashMap<PlayerId, ActiveFlickSetup>,
    recent_setups: HashMap<PlayerId, FlickSetupSummary>,
    recent_dodge_starts: HashMap<PlayerId, RecentDodgeStart>,
    pending_flicks: Vec<PendingFlick>,
    previous_dodge_active: HashMap<PlayerId, bool>,
    previous_ball_velocity: Option<glam::Vec3>,
    /// Frame of the dodge start behind the most recent flick emitted for each
    /// player, used to enforce one flick per dodge. Frame numbers are monotonic,
    /// so a stored frame never collides with a later dodge.
    last_emitted_dodge_frame: HashMap<PlayerId, usize>,
}

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

    pub fn events(&self) -> &[FlickEvent] {
        self.events.all()
    }

    pub fn new_events(&self) -> &[FlickEvent] {
        self.events.new_events()
    }

    fn normalize_score(value: f32, min_value: f32, max_value: f32) -> f32 {
        if max_value <= min_value {
            return 0.0;
        }

        ((value - min_value) / (max_value - min_value)).clamp(0.0, 1.0)
    }

    /// Velocity change imparted to the ball between `reference_velocity` and
    /// `current_velocity`, with gravity over `elapsed` removed. With
    /// `elapsed == dt` and the previous frame's velocity this is the
    /// single-frame impulse; with a longer `elapsed` it measures the change
    /// accumulated across a flick's contact window.
    fn gravity_compensated_impulse(
        current_velocity: glam::Vec3,
        reference_velocity: glam::Vec3,
        elapsed: f32,
    ) -> glam::Vec3 {
        let expected_linear_delta = glam::Vec3::new(0.0, 0.0, BALL_GRAVITY_Z * elapsed.max(0.0));
        current_velocity - reference_velocity - expected_linear_delta
    }

    fn control_observation(
        ball: &BallSample,
        player: &PlayerSample,
        controlling_player: Option<&PlayerId>,
    ) -> Option<FlickControlObservation> {
        if controlling_player != Some(&player.player_id) {
            return None;
        }

        let player_rigid_body = player.rigid_body.as_ref()?;
        let player_position = player.position()?;
        let ball_position = ball.position();
        if !(BALL_CARRY_MIN_BALL_Z..=FLICK_MAX_CONTROL_BALL_Z).contains(&ball_position.z) {
            return None;
        }

        let horizontal_gap = player_position
            .truncate()
            .distance(ball_position.truncate());
        if horizontal_gap > FLICK_MAX_CONTROL_HORIZONTAL_GAP {
            return None;
        }

        let vertical_gap = ball_position.z - player_position.z;
        if !(FLICK_MIN_CONTROL_VERTICAL_GAP..=FLICK_MAX_CONTROL_VERTICAL_GAP)
            .contains(&vertical_gap)
        {
            return None;
        }

        // How closely the ball tracks the car horizontally this frame. A real
        // flick is set up by a carry/dribble where the ball rides the car, so
        // this stays small; a loose ball the car is merely driving at keeps its
        // own velocity. `None` when velocity data is unavailable so the carry
        // check downstream stays lenient on such replays.
        let relative_horizontal_speed = match (
            ball.rigid_body.linear_velocity.as_ref().map(vec_to_glam),
            player.velocity(),
        ) {
            (Some(ball_velocity), Some(player_velocity)) => {
                Some((ball_velocity.truncate() - player_velocity.truncate()).length())
            }
            _ => None,
        };

        let local_ball_position =
            quat_to_glam(&player_rigid_body.rotation).inverse() * (ball_position - player_position);
        if local_ball_position.x < -FLICK_MAX_LOCAL_X_BEHIND
            || local_ball_position.x > FLICK_MAX_LOCAL_X_FRONT
            || local_ball_position.y.abs() > FLICK_MAX_LOCAL_Y
            || local_ball_position.z < FLICK_MIN_LOCAL_Z
        {
            return None;
        }

        Some(FlickControlObservation {
            horizontal_gap,
            vertical_gap,
            relative_horizontal_speed,
        })
    }

    fn setup_summary(setup: &ActiveFlickSetup) -> FlickSetupSummary {
        FlickSetupSummary {
            is_team_0: setup.is_team_0,
            start_time: setup.start_time,
            start_frame: setup.start_frame,
            last_time: setup.last_time,
            last_frame: setup.last_frame,
            duration: setup.duration,
            average_horizontal_gap: setup.horizontal_gap_integral
                / setup.duration.max(f32::EPSILON),
            average_vertical_gap: setup.vertical_gap_integral / setup.duration.max(f32::EPSILON),
            touch_count: setup.touch_count,
            rotation_under_ball_degrees: setup.max_horizontal_rotation_degrees,
            setup_rotation_degrees: setup.signed_horizontal_rotation_degrees,
            min_relative_horizontal_speed: setup.min_relative_horizontal_speed,
            observed_velocity: setup.observed_velocity,
        }
    }

    /// Whether a setup shows genuine carry/dribble evidence: at some non-dodge
    /// frame the ball tracked the car closely. Lenient when no velocity data was
    /// available at all (replays without velocities keep prior behavior), but a
    /// setup that *has* velocity data yet never shows a non-dodge carry — a car
    /// that drove into a loose ball while already dodging — is rejected. This is
    /// what separates a flick off a dribble from a dodge into a loose ball that
    /// merely passed through the control volume.
    fn setup_shows_carry(setup: &FlickSetupSummary) -> bool {
        !setup.observed_velocity
            || setup.min_relative_horizontal_speed <= FLICK_MAX_CARRY_REL_HORIZONTAL_SPEED
    }

    fn setup_qualifies(setup: &FlickSetupSummary) -> bool {
        setup.duration >= FLICK_MIN_SETUP_SECONDS
    }

    fn classify_kind(
        player_rotation: glam::Quat,
        player_angular_velocity: glam::Vec3,
        rotation_at_dodge: Option<glam::Quat>,
        rotation_under_ball_degrees: f32,
        relative_ball_position: glam::Vec3,
        ball_impulse: glam::Vec3,
    ) -> (FlickKind, glam::Vec3, glam::Vec3, f32) {
        let local_ball_position = player_rotation.inverse() * relative_ball_position;
        let impulse_reference_rotation = rotation_at_dodge.unwrap_or(player_rotation);
        let local_ball_impulse = impulse_reference_rotation.inverse() * ball_impulse;
        let local_angular_velocity = player_rotation.inverse() * player_angular_velocity;
        let backflip_pitch_rate = (-local_angular_velocity.y).max(0.0);
        let forward_impulse_alignment = ball_impulse
            .normalize_or_zero()
            .dot(impulse_reference_rotation * glam::Vec3::X);
        let kind = if backflip_pitch_rate >= REVERSE_FLICK_MIN_BACKFLIP_PITCH_RATE
            && local_ball_impulse.x >= REVERSE_FLICK_MIN_FORWARD_IMPULSE
            && forward_impulse_alignment >= REVERSE_FLICK_MIN_FORWARD_IMPULSE_ALIGNMENT
            && rotation_under_ball_degrees >= REVERSE_FLICK_MIN_ROTATION_UNDER_BALL_DEGREES
        {
            FlickKind::Reverse
        } else {
            FlickKind::Other
        };

        (
            kind,
            local_ball_position,
            local_ball_impulse,
            backflip_pitch_rate,
        )
    }

    fn signed_horizontal_rotation_degrees(
        start_forward: Option<glam::Vec3>,
        current_forward: Option<glam::Vec3>,
    ) -> Option<f32> {
        let start = start_forward?.truncate().normalize_or_zero();
        let current = current_forward?.truncate().normalize_or_zero();
        if start.length_squared() <= f32::EPSILON || current.length_squared() <= f32::EPSILON {
            return None;
        }

        let cross_z = start.x * current.y - start.y * current.x;
        Some(cross_z.atan2(start.dot(current)).to_degrees())
    }

    fn setup_rotation_direction(signed_degrees: f32) -> FlickSetupRotationDirection {
        if signed_degrees.abs() < REVERSE_FLICK_MIN_ROTATION_UNDER_BALL_DEGREES {
            FlickSetupRotationDirection::Unknown
        } else if signed_degrees > 0.0 {
            FlickSetupRotationDirection::Right
        } else {
            FlickSetupRotationDirection::Left
        }
    }

    fn store_recent_setup(&mut self, player_id: PlayerId, setup: FlickSetupSummary) {
        if Self::setup_qualifies(&setup) {
            self.recent_setups.insert(player_id, setup);
        }
    }

    fn finish_setup(&mut self, player_id: &PlayerId) {
        let Some(setup) = self.active_setups.remove(player_id) else {
            return;
        };
        self.store_recent_setup(player_id.clone(), Self::setup_summary(&setup));
    }

    fn recent_setup_for_player(
        &self,
        player_id: &PlayerId,
        current_time: f32,
    ) -> Option<FlickSetupSummary> {
        if let Some(active) = self.active_setups.get(player_id) {
            return Some(Self::setup_summary(active));
        }

        self.recent_setups
            .get(player_id)
            .filter(|setup| current_time - setup.last_time <= FLICK_MAX_SETUP_STALE_SECONDS)
            .cloned()
    }

    fn update_control_setups(
        &mut self,
        frame: &FrameInfo,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        touch_events: &[TouchEvent],
        controlling_player: Option<&PlayerId>,
    ) {
        let Some(ball) = ball.sample() else {
            let player_ids: Vec<_> = self.active_setups.keys().cloned().collect();
            for player_id in player_ids {
                self.finish_setup(&player_id);
            }
            return;
        };

        let mut observed_players = HashSet::new();
        for player in &players.players {
            let Some(observation) = Self::control_observation(ball, player, controlling_player)
            else {
                continue;
            };
            observed_players.insert(player.player_id.clone());
            let current_forward = player
                .rigid_body
                .as_ref()
                .map(|rigid_body| quat_to_glam(&rigid_body.rotation) * glam::Vec3::X);
            let setup = self
                .active_setups
                .entry(player.player_id.clone())
                .or_insert_with(|| ActiveFlickSetup {
                    is_team_0: player.is_team_0,
                    start_time: (frame.time - frame.dt).max(0.0),
                    start_frame: frame.frame_number.saturating_sub(1),
                    last_time: frame.time,
                    last_frame: frame.frame_number,
                    duration: frame.dt.max(0.0),
                    horizontal_gap_integral: observation.horizontal_gap * frame.dt.max(0.0),
                    vertical_gap_integral: observation.vertical_gap * frame.dt.max(0.0),
                    touch_count: 0,
                    start_forward: current_forward,
                    max_horizontal_rotation_degrees: 0.0,
                    signed_horizontal_rotation_degrees: 0.0,
                    min_relative_horizontal_speed: f32::INFINITY,
                    observed_velocity: false,
                });

            // Carry evidence is the dribble *before* the flick. Once the player
            // is dodging, the ball is being struck, and its post-contact velocity
            // can transiently align with the car — so only frames where the
            // player is not dodging count toward the carry minimum.
            if let Some(relative_horizontal_speed) = observation.relative_horizontal_speed {
                setup.observed_velocity = true;
                // Carry evidence is the dribble *before* the flick. Once the
                // player is dodging the ball is being struck, and its
                // post-contact velocity can transiently align with the car — so
                // only frames where the player is not dodging count toward the
                // carry minimum. A setup whose control frames are *all* during a
                // dodge (a car that drove into a loose ball while already
                // flicking) therefore shows no carry and is rejected below.
                if !player.dodge_active {
                    setup.min_relative_horizontal_speed = setup
                        .min_relative_horizontal_speed
                        .min(relative_horizontal_speed);
                }
            }

            if setup.last_frame != frame.frame_number {
                setup.last_time = frame.time;
                setup.last_frame = frame.frame_number;
                setup.duration += frame.dt.max(0.0);
                setup.horizontal_gap_integral += observation.horizontal_gap * frame.dt.max(0.0);
                setup.vertical_gap_integral += observation.vertical_gap * frame.dt.max(0.0);
                if let Some(signed_degrees) =
                    Self::signed_horizontal_rotation_degrees(setup.start_forward, current_forward)
                {
                    let degrees = signed_degrees.abs();
                    if degrees > setup.max_horizontal_rotation_degrees {
                        setup.max_horizontal_rotation_degrees = degrees;
                        setup.signed_horizontal_rotation_degrees = signed_degrees;
                    }
                }
            }
        }

        for touch_event in touch_events {
            let Some(player_id) = touch_event.player.as_ref() else {
                continue;
            };
            if let Some(setup) = self.active_setups.get_mut(player_id) {
                setup.touch_count += 1;
            }
        }

        let active_ids: Vec<_> = self.active_setups.keys().cloned().collect();
        for player_id in active_ids {
            if observed_players.contains(&player_id) {
                continue;
            }
            // Keep the setup alive across brief observation gaps; only finish it
            // once the ball has been out of the control volume long enough that
            // the carry is genuinely over.
            let gap_elapsed = self
                .active_setups
                .get(&player_id)
                .map(|setup| frame.time - setup.last_time > FLICK_SETUP_GAP_GRACE_SECONDS)
                .unwrap_or(true);
            if gap_elapsed {
                self.finish_setup(&player_id);
            }
        }
    }

    fn track_dodge_starts(&mut self, frame: &FrameInfo, players: &PlayerFrameState) {
        for player in &players.players {
            let was_dodge_active = self
                .previous_dodge_active
                .insert(player.player_id.clone(), player.dodge_active)
                .unwrap_or(false);
            if !player.dodge_active || was_dodge_active {
                continue;
            }

            let Some(setup) = self.recent_setup_for_player(&player.player_id, frame.time) else {
                continue;
            };
            if !Self::setup_qualifies(&setup) {
                continue;
            }
            if !Self::setup_shows_carry(&setup) {
                continue;
            }
            if frame.time - setup.last_time > FLICK_MAX_CONTROL_TO_DODGE_SECONDS {
                continue;
            }

            self.recent_dodge_starts.insert(
                player.player_id.clone(),
                RecentDodgeStart {
                    time: frame.time,
                    frame: frame.frame_number,
                    setup,
                    rotation_at_dodge: player
                        .rigid_body
                        .as_ref()
                        .map(|rigid_body| quat_to_glam(&rigid_body.rotation)),
                },
            );
        }
    }

    fn prune_recent_state(&mut self, current_time: f32) {
        self.recent_setups
            .retain(|_, setup| current_time - setup.last_time <= FLICK_MAX_SETUP_STALE_SECONDS);
        self.recent_dodge_starts
            .retain(|_, dodge| current_time - dodge.time <= FLICK_MAX_DODGE_TO_TOUCH_SECONDS);
    }

    fn candidate_event(
        &self,
        ball: &BallFrameState,
        player: &PlayerSample,
        touch_event: &TouchEvent,
        dodge_start: &RecentDodgeStart,
        ball_impulse: glam::Vec3,
    ) -> Option<FlickEvent> {
        let ball = ball.sample()?;
        let player_rigid_body = player.rigid_body.as_ref()?;
        let player_position = player.position()?;
        let time_since_dodge = touch_event.time - dodge_start.time;
        if !(-FLICK_DODGE_LEAD_TOLERANCE_SECONDS..=FLICK_MAX_DODGE_TO_TOUCH_SECONDS)
            .contains(&time_since_dodge)
        {
            return None;
        }

        let ball_speed_change = ball_impulse.length();
        if ball_speed_change < FLICK_MIN_BALL_SPEED_CHANGE {
            return None;
        }

        let to_ball = (ball.position() - player_position).normalize_or_zero();
        let impulse_direction = ball_impulse.normalize_or_zero();
        if to_ball.length_squared() <= f32::EPSILON
            || impulse_direction.length_squared() <= f32::EPSILON
        {
            return None;
        }

        let impulse_away_alignment = impulse_direction.dot(to_ball);
        if impulse_away_alignment < FLICK_MIN_IMPULSE_AWAY_ALIGNMENT {
            return None;
        }

        let vertical_impulse = ball_impulse.z.max(0.0);
        let player_rotation = quat_to_glam(&player_rigid_body.rotation);
        let player_angular_velocity = player_rigid_body
            .angular_velocity
            .as_ref()
            .map(vec_to_glam)
            .unwrap_or(glam::Vec3::ZERO);
        let (kind, local_ball_position, local_ball_impulse, backflip_pitch_rate) =
            Self::classify_kind(
                player_rotation,
                player_angular_velocity,
                dodge_start.rotation_at_dodge,
                dodge_start.setup.rotation_under_ball_degrees,
                ball.position() - player_position,
                ball_impulse,
            );
        let setup = &dodge_start.setup;
        let setup_rotation_direction = Self::setup_rotation_direction(setup.setup_rotation_degrees);
        let timing_score =
            1.0 - (time_since_dodge / FLICK_MAX_DODGE_TO_TOUCH_SECONDS).clamp(0.0, 1.0);
        let setup_duration_score =
            Self::normalize_score(setup.duration, FLICK_MIN_SETUP_SECONDS, 0.75);
        let horizontal_control_score =
            1.0 - (setup.average_horizontal_gap / FLICK_MAX_CONTROL_HORIZONTAL_GAP).clamp(0.0, 1.0);
        let vertical_control_score = 1.0
            - ((setup.average_vertical_gap - 110.0).abs() / FLICK_MAX_CONTROL_VERTICAL_GAP)
                .clamp(0.0, 1.0);
        let impulse_score =
            Self::normalize_score(ball_speed_change, FLICK_MIN_BALL_SPEED_CHANGE, 1450.0);
        let away_score = Self::normalize_score(
            impulse_away_alignment,
            FLICK_MIN_IMPULSE_AWAY_ALIGNMENT,
            0.85,
        );
        let vertical_score = Self::normalize_score(vertical_impulse, 100.0, 750.0);

        let confidence = 0.16 * timing_score
            + 0.19 * setup_duration_score
            + 0.12 * horizontal_control_score
            + 0.10 * vertical_control_score
            + 0.22 * impulse_score
            + 0.15 * away_score
            + 0.06 * vertical_score;
        if confidence < FLICK_MIN_CONFIDENCE {
            return None;
        }

        Some(FlickEvent {
            time: touch_event.time,
            frame: touch_event.frame,
            sample_time: touch_event.time,
            sample_frame: touch_event.frame,
            player: player.player_id.clone(),
            player_position: Some(player_position.to_array()),
            is_team_0: player.is_team_0,
            dodge_time: dodge_start.time,
            dodge_frame: dodge_start.frame,
            time_since_dodge,
            setup_start_time: setup.start_time,
            setup_start_frame: setup.start_frame,
            setup_duration: setup.duration,
            setup_touch_count: setup.touch_count,
            average_horizontal_gap: setup.average_horizontal_gap,
            average_vertical_gap: setup.average_vertical_gap,
            ball_speed_change,
            ball_impulse: ball_impulse.to_array(),
            impulse_away_alignment,
            vertical_impulse,
            kind: kind.as_label_value().to_owned(),
            local_ball_position: local_ball_position.to_array(),
            local_ball_impulse: local_ball_impulse.to_array(),
            backflip_pitch_rate,
            rotation_under_ball_degrees: setup.rotation_under_ball_degrees,
            setup_rotation_degrees: setup.setup_rotation_degrees,
            setup_rotation_direction: setup_rotation_direction.as_label_value().to_owned(),
            confidence,
        })
    }

    fn apply_event(&mut self, frame: &FrameInfo, mut event: FlickEvent) {
        event.sample_time = frame.time;
        event.sample_frame = frame.frame_number;
        self.events.push(event);
    }

    fn dodge_start_for_touch(&self, player: &PlayerSample) -> Option<RecentDodgeStart> {
        if let Some(dodge_start) = self.recent_dodge_starts.get(&player.player_id) {
            return Some(dodge_start.clone());
        }
        None
    }

    fn classified_as_dodge_touch(
        touch_event: &TouchEvent,
        touch_classification_events: &[TouchClassificationEvent],
    ) -> bool {
        let Some(touch_player) = touch_event.player.as_ref() else {
            return false;
        };
        touch_classification_events.iter().any(|event| {
            let same_touch = match (event.touch_id, touch_event.touch_id) {
                (Some(event_id), Some(touch_id)) => event_id == touch_id,
                _ => event.player == *touch_player && event.frame == touch_event.frame,
            };
            same_touch && event.has_tag("dodge_state", "dodge")
        })
    }

    fn pending_dodge_start_for_touch(
        &self,
        player: &PlayerSample,
        touch_event: &TouchEvent,
    ) -> Option<RecentDodgeStart> {
        let setup = self.recent_setup_for_player(&player.player_id, touch_event.time)?;
        if setup.duration < FLICK_MIN_PENDING_DODGE_SETUP_SECONDS {
            return None;
        }
        if !Self::setup_shows_carry(&setup) {
            return None;
        }
        Some(RecentDodgeStart {
            time: touch_event.time,
            frame: touch_event.frame,
            setup,
            rotation_at_dodge: player
                .rigid_body
                .as_ref()
                .map(|rigid_body| quat_to_glam(&rigid_body.rotation)),
        })
    }

    /// Open (or refresh) a pending flick for a touch by a player who has a
    /// recent control setup (i.e. was dribbling/carrying). The pending entry is
    /// what lets the detector watch the ball's velocity change across the
    /// [`FLICK_IMPULSE_WINDOW_SECONDS`] window rather than only at the touch
    /// frame.
    fn store_pending_flick(
        &mut self,
        ball: &BallFrameState,
        player: &PlayerSample,
        touch_event: &TouchEvent,
        pre_velocity: glam::Vec3,
    ) {
        let already_tracked = self.pending_flicks.iter().any(|pending| {
            pending.touch_event.touch_id == touch_event.touch_id
                && pending.touch_event.player == touch_event.player
                && pending.touch_event.frame == touch_event.frame
        });
        if already_tracked {
            // Same touch reappearing on a later frame: keep accumulating into
            // its existing window rather than resetting it.
            return;
        }
        // Require at least the loose pending-setup threshold; the stricter
        // dodge/confidence gates are enforced when the window resolves.
        let has_setup = self
            .recent_setup_for_player(&player.player_id, touch_event.time)
            .is_some_and(|setup| setup.duration >= FLICK_MIN_PENDING_DODGE_SETUP_SECONDS);
        if !has_setup {
            return;
        }
        // One flick per dodge: a newer touch by the same player supersedes its
        // earlier window so a single dribble cannot emit multiple flicks when
        // its control touches fall within one impulse window of each other.
        self.pending_flicks
            .retain(|pending| pending.player.player_id != player.player_id);
        self.pending_flicks.push(PendingFlick {
            touch_event: touch_event.clone(),
            ball: ball.clone(),
            player: player.clone(),
            real_dodge_start: self.dodge_start_for_touch(player),
            classified_dodge: false,
            pre_velocity,
            peak_impulse: glam::Vec3::ZERO,
            peak_magnitude: 0.0,
        });
    }

    /// Per-frame step: grow each pending flick's peak impulse from the live ball
    /// velocity, refresh its dodge evidence, and emit as soon as the peak clears
    /// the gates. Entries that never qualify are dropped once the window closes.
    fn update_and_resolve_pending_flicks(
        &mut self,
        frame: &FrameInfo,
        ball: &BallFrameState,
        touch_classification_events: &[TouchClassificationEvent],
    ) {
        let current_velocity = ball.velocity();
        let mut pending = std::mem::take(&mut self.pending_flicks);
        let mut emitted = Vec::new();
        pending.retain_mut(|flick| {
            let elapsed = (frame.time - flick.touch_event.time).max(0.0);
            if elapsed > FLICK_PENDING_RETENTION_SECONDS {
                return false;
            }

            // Measure the impulse only over the (shorter) impulse window; the
            // entry is kept alive past it purely so a late-replicating dodge byte
            // can still confirm the launch touch.
            if elapsed <= FLICK_IMPULSE_WINDOW_SECONDS {
                if let Some(velocity) = current_velocity {
                    let impulse =
                        Self::gravity_compensated_impulse(velocity, flick.pre_velocity, elapsed);
                    let magnitude = impulse.length();
                    if magnitude > flick.peak_magnitude {
                        flick.peak_magnitude = magnitude;
                        flick.peak_impulse = impulse;
                    }
                }
            }

            if flick.real_dodge_start.is_none() {
                flick.real_dodge_start = self.dodge_start_for_touch(&flick.player);
            }
            if !flick.classified_dodge {
                flick.classified_dodge = Self::classified_as_dodge_touch(
                    &flick.touch_event,
                    touch_classification_events,
                );
            }

            // A genuine dodge transition stands on its own; otherwise the touch
            // must have been classified as a dodge contact (the old pending
            // path) and have a recent control setup to synthesize a start from.
            let dodge_start = flick.real_dodge_start.clone().or_else(|| {
                if flick.classified_dodge {
                    self.pending_dodge_start_for_touch(&flick.player, &flick.touch_event)
                } else {
                    None
                }
            });
            let Some(dodge_start) = dodge_start else {
                return true;
            };

            // One flick per dodge. Extending the pending window so a late dodge
            // byte can confirm an earlier launch touch means several touches that
            // bracket a single dodge (a pre-dodge carry contact and the launch)
            // can each resolve against the same dodge start. Drop any candidate
            // for a dodge that already produced a flick — whether emitted on an
            // earlier frame or earlier in this same frame's batch — so the first
            // qualifying touch wins and the dodge is not double-counted.
            let already_emitted = self.last_emitted_dodge_frame.get(&flick.player.player_id)
                == Some(&dodge_start.frame)
                || emitted.iter().any(|event: &FlickEvent| {
                    event.player == flick.player.player_id && event.dodge_frame == dodge_start.frame
                });
            if already_emitted {
                return false;
            }

            if let Some(event) = self.candidate_event(
                &flick.ball,
                &flick.player,
                &flick.touch_event,
                &dodge_start,
                flick.peak_impulse,
            ) {
                emitted.push(event);
                return false;
            }
            true
        });
        self.pending_flicks = pending;
        for event in emitted {
            self.last_emitted_dodge_frame
                .insert(event.player.clone(), event.dodge_frame);
            self.apply_event(frame, event);
        }
    }

    fn apply_touch_events(
        &mut self,
        _frame: &FrameInfo,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        touch_events: &[TouchEvent],
    ) {
        let pre_velocity = self
            .previous_ball_velocity
            .or_else(|| ball.velocity())
            .unwrap_or(glam::Vec3::ZERO);

        for touch_event in touch_events {
            let Some(player_id) = touch_event.player.as_ref() else {
                continue;
            };
            let Some(player) = players
                .players
                .iter()
                .find(|player| &player.player_id == player_id)
            else {
                continue;
            };
            // Open a measurement window for any touch by a dribbling player; the
            // impulse, dodge, and confidence gates resolve over the window in
            // `update_and_resolve_pending_flicks`.
            self.store_pending_flick(ball, player, touch_event, pre_velocity);
        }
    }

    fn reset_live_play_state(&mut self, ball: &BallFrameState) {
        self.active_setups.clear();
        self.recent_setups.clear();
        self.recent_dodge_starts.clear();
        self.pending_flicks.clear();
        self.previous_dodge_active.clear();
        self.last_emitted_dodge_frame.clear();
        self.previous_ball_velocity = ball.velocity();
    }

    fn update_with_touch_classification_events(
        &mut self,
        frame: &FrameInfo,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        touch_state: &TouchState,
        touch_classification_events: &[TouchClassificationEvent],
        live_play_state: &LivePlayState,
    ) -> SubtrActorResult<()> {
        self.events.begin_update();
        if !live_play_state.is_live_play {
            self.reset_live_play_state(ball);
            return Ok(());
        }
        self.prune_recent_state(frame.time);
        self.update_control_setups(
            frame,
            ball,
            players,
            &touch_state.touch_events,
            touch_state.last_touch_player.as_ref(),
        );
        self.track_dodge_starts(frame, players);
        self.apply_touch_events(frame, ball, players, &touch_state.touch_events);
        self.update_and_resolve_pending_flicks(frame, ball, touch_classification_events);
        self.previous_ball_velocity = ball.velocity();
        Ok(())
    }

    pub fn update(
        &mut self,
        frame: &FrameInfo,
        ball: &BallFrameState,
        players: &PlayerFrameState,
        touch_state: &TouchState,
        touch: &TouchCalculator,
        live_play_state: &LivePlayState,
    ) -> SubtrActorResult<()> {
        self.update_with_touch_classification_events(
            frame,
            ball,
            players,
            touch_state,
            touch.events(),
            live_play_state,
        )
    }
}

#[cfg(test)]
#[path = "flick_tests.rs"]
mod tests;