vsrg 0.3.0

Data structures for vertical scrolling rhythm games
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
use crate::collections::sort_multi;
use crate::{
    math::Easing,
    rhythm::{
        SameUnitTimeVec,
        time::{BeatTime, ClockTime, SameUnitTime, Time},
        track::EventTracks,
    },
};
use std::collections::HashMap;

const INTEGRATE_SAMPES: usize = 1024;

/// Represents tempo of a rhythm.
///
/// The beats per minute value is guaranteed to be finite, positive and not close to 0,
/// with the chosen lower bound arbitrarily being one beat per year (or 1.8973891924711e-6 BPM).
///
/// This restriction guarantees predictable behaviour when counting beats & clock time.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Tempo {
    bpm: f64,
}

impl Tempo {
    /// Creates a new tempo in BPM unit.
    ///
    /// The beats per minute value MUST be at least 1.8973891924711e-06 and finite.
    /// i.e the tempo must be a minimum of one beat per year (where the year is a leap year).
    pub fn from_bpm(bpm: f64) -> Option<Self> {
        (bpm.is_finite() && bpm >= 1.8973891924711e-06).then_some(Self { bpm })
    }

    /// Gets the number of beats per minute.
    pub fn beats_per_min(self) -> f64 {
        self.bpm
    }

    /// Gets duration of a beat in minutes.
    pub fn mins_per_beat(self) -> f64 {
        1.0 / self.bpm
    }

    /// Gets number of beats per second.
    pub fn beats_per_sec(self) -> f64 {
        self.bpm / 60.0
    }

    /// Gets duratinof a beat in seconds.
    pub fn secs_per_beat(self) -> f64 {
        60.0 / self.bpm
    }

    /// Gets duration of a beat in as a [`std::time::Duration`].
    pub fn beat_duration(self) -> std::time::Duration {
        // This can't panic, because bpm is positive and finite, and beat length is maximum 1 year.
        std::time::Duration::from_secs_f64(self.secs_per_beat())
    }

    fn beats_to_clock(&self, beats: BeatTime) -> ClockTime {
        ClockTime::from_seconds(self.secs_per_beat() * beats.beats())
            .expect("secs_per_beat is finite, and beats is not NaN. The product cannot be NaN")
    }

    fn clock_to_beats(&self, clock: ClockTime) -> BeatTime {
        BeatTime::new(self.beats_per_sec() * clock.seconds())
            .expect("beats_per_sec is finite, and clocktime is not NaN. The product cannot be NaN")
    }
}

/// Represents a point in time where tempo changes.
///
/// Tempo can be interpolated with [`Easing`]. Standard non-intepolated tempo change uses
/// [`Easing::InConst`] easing.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TempoChangeEvent {
    pub time: Time,
    pub tempo: Tempo,
    pub ease: Easing,
}

// Precompute total elapsed ClockTime and BeatTime at the start of each tempo change.
// Arbitrary elapsed time calculation at runtime then, only needs to add an offset to a precomputed
// value instead of having to sum up elapsed time from the first tempo change every time.
//
// e.g: beats(t) = (sum of total beats of all tempo change event before `t`) + (elapsed beats from
// last tempo event to `t`). The former is precalculated here.
impl TempoChangeEvent {
    pub fn time(&self) -> Time {
        self.time
    }

    fn initial_cumulate(first_time: Time, event: &Self) -> (ClockTime, BeatTime) {
        match first_time {
            Time::Clock(t) => (t, event.tempo.clock_to_beats(t)),
            Time::Beat(b) => (event.tempo.beats_to_clock(b), b),
        }
    }

    fn cumulate<'id>(
        current_clock: ClockTime,
        current_beat: BeatTime,
        delta: SameUnitTime<'id>,
        full_duration: SameUnitTime<'id>,
        current: &Self,
        next: &Self,
    ) -> (ClockTime, BeatTime) {
        // Full duration in either beats or seconds, either case we know it matches the expected
        // unit due to SameUnitTime's guarantee.
        let full_duration_f64 = match full_duration.as_time() {
            Time::Clock(clock_time) => clock_time.seconds(),
            Time::Beat(beat_time) => beat_time.beats(),
        };

        if full_duration_f64 <= 1e-6 {
            return (current_clock, current_beat);
        }
        let p = delta / full_duration;
        if !p.is_finite() {
            return (ClockTime::INF, BeatTime::INF);
        }

        match Time::from(delta) {
            Time::Clock(t) => {
                // Time-parameterized: p = Δs / D_sec.
                // Δbeats = D_sec * ∫₀ᵖ bps(t) dt
                let delta_beats = current.ease.integrate(
                    current.tempo.beats_per_sec(),
                    next.tempo.beats_per_sec(),
                    p,
                ) * full_duration_f64;
                (
                    current_clock + t,
                    current_beat
                        + BeatTime::new(delta_beats)
                            .expect("Integration with finite input can't be NaN"),
                )
            }
            Time::Beat(t) => {
                // Beat-parameterized: p = Δb / D_beats.
                // Δseconds = D_beats * ∫₀ᵖ 1/bps(b) db
                let delta_secs = full_duration_f64
                    * current
                        .ease
                        .integrate_reciprocal(
                            current.tempo.beats_per_sec(),
                            next.tempo.beats_per_sec(),
                            p,
                            INTEGRATE_SAMPES, // TODO: more samples for bigger interval
                        )
                        .expect("All input is finite, and both tempo must be positive");
                (
                    current_clock
                        + ClockTime::from_seconds(delta_secs)
                            .expect("integrate_reciprocal never returns non-finite float"),
                    current_beat + t,
                )
            }
        }
    }
}

pub type TempoTracks = EventTracks<TempoTrack>;

/// A list of [`TempoChangeEvent`], defining tempo change over time of a song.
///
/// All events are required to have the same [`Time`] unit (either [`ClockTime`] or [`BeatTime`]).
/// After the track is setup, it allows converting between [`Time`] unit, via the methods:
/// [`Self::beat_to_clock`] and [`Self::clock_to_beats`]
#[derive(Default, Debug, Clone)]
pub struct TempoTrack {
    id_counter: u64,
    id_lookup: HashMap<u64, usize>,

    ids: Vec<u64>,
    time: SameUnitTimeVec,
    content: Vec<TempoChangeEvent>,
    cumulated: Vec<(ClockTime, BeatTime)>,
}

impl TempoTrack {
    /// Create a new empty track.
    pub fn new() -> Self {
        Self {
            id_counter: 0,
            id_lookup: Default::default(),
            ids: Default::default(),
            time: Default::default(),
            content: Default::default(),
            cumulated: Default::default(),
        }
    }

    /// Create a track from a list of events with the same time unit.
    ///
    /// # Returns
    /// None if events' timing do not have the same unit. Otherwise returns an EventTrack.
    pub fn with_events(mut events: Vec<TempoChangeEvent>) -> Option<Self> {
        let len = events.len();

        let mut time = SameUnitTimeVec::try_from_iter(events.iter().map(|event| event.time()))?;
        match &mut time {
            SameUnitTimeVec::Clock(times) => {
                sort_multi(times, |i, j| events.swap(i, j));
            }
            SameUnitTimeVec::Beat(times) => {
                sort_multi(times, |i, j| events.swap(i, j));
            }
        }

        let mut s = Self {
            id_counter: len as u64,
            ids: (0..len as u64).collect(),
            time,
            content: events,
            id_lookup: Default::default(),
            cumulated: Default::default(),
        };
        s.recalc_cumulative_and_lookup();
        Some(s)
    }

    /// Convert a [`BeatTime`] to a [`ClockTime`].
    ///
    /// # Returns
    /// This returns [`ClockTime::INF`] if the [`BeatTime`] is already infinite, or if there's an
    /// overflow in the calculation. All systems downstream should already filters out infinite
    /// gracefully.
    pub fn beat_to_clock(&self, source: BeatTime) -> ClockTime {
        if self.is_empty() {
            return ClockTime::default();
        }
        if source == BeatTime::INF {
            return ClockTime::INF;
        }

        // Index of the first tempo change whose cumulative beat exceed the query beat.
        let index = self
            .cumulated
            .partition_point(|(_, cbeat)| cbeat <= &source);

        // The query comes before any event
        if index == 0 {
            let first = self.content[0];
            return match first.time {
                Time::Clock(t) => t - first.tempo.beats_to_clock(self.cumulated[0].1 - source),
                Time::Beat(b) => self.cumulated[0].0 - first.tempo.beats_to_clock(b - source),
            };
        }

        // The query comes after any event
        if index == self.len() {
            let last_index = self.len() - 1;
            let last = self.content[last_index];
            let last_cumulated = self.cumulated[last_index];
            return match last.time {
                Time::Clock(t) => t + last.tempo.beats_to_clock(source - last_cumulated.1),
                Time::Beat(b) => last_cumulated.0 + last.tempo.beats_to_clock(source - b),
            };
        }

        let base = self.cumulated[index - 1].0;
        let elapsed_beats_since = source - self.cumulated[index - 1].1;
        let bps0 = self.content[index - 1].tempo.beats_per_sec();
        let bps1 = self.content[index].tempo.beats_per_sec();
        let ease = self.content[index - 1].ease;

        match self.content[index - 1].time {
            Time::Clock(_) => {
                // Clock-parameterized: Δbeats = D_sec * integrate(bps0, bps1, Δs/D_sec).
                // Invert: solve integrate(bps0, bps1, p) = Δbeats / D_sec, then Δs = D_sec * p.
                let segment_clock = self.cumulated[index].0 - self.cumulated[index - 1].0;
                let val = elapsed_beats_since.beats() / segment_clock.seconds();
                // This should only happen if there's an overflow somewhere, in which case
                // returning INF is a good default.
                if !val.is_finite() {
                    return ClockTime::INF;
                }
                let t = ease
                    .solve_integrate(bps0, bps1, val)
                    .expect("All input are finite, and bpms are positive, so this can't be None");
                base + segment_clock
                    .scale(t)
                    .expect("solve_integrate can't return NaN")
            }
            Time::Beat(_) => {
                // Beat-parameterized: Δsecs = D_beats * integrate_reciprocal(bps0, bps1, Δb/D_beats).
                // Δb / D_beats is known directly, so no inversion is needed.
                let segment_beats = self.cumulated[index].1 - self.cumulated[index - 1].1;
                let beats_total = segment_beats.beats();
                if !beats_total.is_finite() || beats_total == 0.0 {
                    return ClockTime::INF;
                }
                let p_b = elapsed_beats_since.beats() / beats_total;
                // This should only happen if there's an overflow somewhere, in which case
                // returning INF is a good default.
                if !p_b.is_finite() {
                    return ClockTime::INF;
                }
                let delta_secs = ease
                    .integrate_reciprocal(bps0, bps1, p_b, INTEGRATE_SAMPES) // TODO: more samples for bigger interval
                    .expect("Both bps are positive, so no pole")
                    * beats_total;
                base + ClockTime::from_seconds(delta_secs)
                    .expect("integrate_reciprocal with finite input can't be NaN")
            }
        }
    }

    /// Convert a [`ClockTime`] to a [`BeatTime`].
    ///
    /// # Returns
    /// This returns [`ClockTime::INF`] if the [`BeatTime`] is already infinite, or if there's an
    /// overflow in the calculation. All systems downstream should already filters out infinite
    /// gracefully.
    pub fn clock_to_beats(&self, source: ClockTime) -> BeatTime {
        if self.is_empty() {
            return BeatTime::default();
        }
        if source == ClockTime::INF {
            return BeatTime::INF;
        }

        // Index of the first tempo change whose cumulative time exceed the query time.
        let index = self.cumulated.partition_point(|(cms, _)| cms <= &source);

        // The query comes before any event
        if index == 0 {
            let first = self.content[0];
            return match first.time {
                Time::Clock(t) => self.cumulated[0].1 - first.tempo.clock_to_beats(t - source),
                Time::Beat(b) => b - first.tempo.clock_to_beats(self.cumulated[0].0 - source),
            };
        }
        // The query comes after any event
        if index == self.len() {
            let last_index = self.len() - 1;
            let last = self.content[last_index];
            let last_cumulated = self.cumulated[last_index];
            return match last.time {
                Time::Clock(t) => last_cumulated.1 + last.tempo.clock_to_beats(source - t),
                Time::Beat(b) => b + last.tempo.clock_to_beats(source - last_cumulated.0),
            };
        }

        let base = self.cumulated[index - 1].1;
        let elapsed_ms_since = source - self.cumulated[index - 1].0;
        let bps0 = self.content[index - 1].tempo.beats_per_sec();
        let bps1 = self.content[index].tempo.beats_per_sec();
        let ease = self.content[index - 1].ease;

        match self.content[index - 1].time {
            Time::Clock(_) => {
                // Clock-parameterized: Δbeats = D_sec * integrate(bps0, bps1, Δs/D_sec).
                let segment_clock = self.cumulated[index].0 - self.cumulated[index - 1].0;
                let p = elapsed_ms_since / segment_clock;
                // This should only happen if there's an overflow somewhere, in which case
                // returning INF is a good default.
                if !p.is_finite() {
                    return BeatTime::INF;
                }
                let delta_beats = ease.integrate(bps0, bps1, p) * segment_clock.seconds();
                base + BeatTime::new(delta_beats)
                    .expect("All input to integrate is finite, so this can't be NaN")
            }
            Time::Beat(_) => {
                // Beat-parameterized: Δsecs = D_beats * integrate_reciprocal(bps0, bps1, Δb/D_beats).
                // Invert: solve integrate_reciprocal(bps0, bps1, p_b) = Δs / D_beats,
                // then Δb = D_beats * p_b.
                let segment_beats = self.cumulated[index].1 - self.cumulated[index - 1].1;
                let beats_total = segment_beats.beats();
                if !beats_total.is_finite() || beats_total == 0.0 {
                    return BeatTime::INF;
                }
                let val = elapsed_ms_since.seconds() / beats_total;
                // This should only happen if there's an overflow somewhere, in which case
                // returning INF is a good default.
                if !val.is_finite() {
                    return BeatTime::INF;
                }
                let p_b = ease
                    .solve_integrate_reciprocal(bps0, bps1, val, 1024)
                    .expect("Both bps are positive, so no pole and monotonic");
                let delta_beats = p_b * beats_total;
                base + BeatTime::new(delta_beats)
                    .expect("solve_integrate_reciprocal returns finite value in [0,1]")
            }
        }
    }

    /// Add an event.
    ///
    /// If its timing unit doesn't match the track's timing unit, then nothing is done and false is
    /// returned.
    pub fn add_event(&mut self, event: TempoChangeEvent) -> bool {
        if !self.time.unit_match(event.time()) {
            return false;
        }

        self.add_event_impl(event);
        self.recalc_cumulative_and_lookup();
        self.health_check();
        true
    }

    /// Add multiple events.
    ///
    /// If any event has timing unit that doesn't match the track's timing unit, then nothing is done
    /// and false is returned.
    pub fn add_events(&mut self, events: impl Iterator<Item = TempoChangeEvent> + Clone) -> bool {
        if events.clone().any(|ev| !self.time.unit_match(ev.time())) {
            return false;
        }

        for ev in events {
            self.add_event_impl(ev);
        }
        self.recalc_cumulative_and_lookup();
        self.health_check();
        true
    }

    /// Remove an event from the track.
    pub fn remove_event(&mut self, id: u64) {
        let Some(&index) = self.id_lookup.get(&id) else {
            return;
        };

        self.ids.remove(index);
        self.time.remove(index);
        self.content.remove(index);
        self.recalc_cumulative_and_lookup();
        self.health_check();
    }

    /// Remove multiple events from the track.
    pub fn remove_events(&mut self, ids: impl IntoIterator<Item = u64>) {
        let mut removing_indices = ids
            .into_iter()
            .flat_map(|id| self.id_lookup.get(&id))
            .copied()
            .collect::<Vec<_>>();
        removing_indices.sort_unstable();
        removing_indices.dedup();
        for i in removing_indices.into_iter().rev() {
            self.ids.remove(i);
            self.time.remove(i);
            self.content.remove(i);
        }
        self.recalc_cumulative_and_lookup();
        self.health_check();
    }

    /// Replace an event in the track.
    ///
    /// If its timing unit doesn't match the track's timing unit, then nothing is done and false is
    /// returned.
    pub fn replace_event(&mut self, id: u64, replace_with: TempoChangeEvent) -> bool {
        let time = replace_with.time();
        if !self.time.unit_match(time) {
            return false;
        }

        let Some(&index) = self.id_lookup.get(&id) else {
            return false;
        };

        let old_time = self.time.index(index);
        self.time
            .try_set(index, time)
            .expect("Checked that unit matches");
        self.content[index] = replace_with;

        let len = self.ids.len();
        let mut j = index;
        if self.time.index(j) > old_time {
            while j + 1 < len && self.time.index(j) > self.time.index(j + 1) {
                self.ids.swap(j, j + 1);
                self.time.swap(j, j + 1);
                self.content.swap(j, j + 1);
                j += 1;
            }
        } else {
            while j > 0 && self.time.index(j - 1) > self.time.index(j) {
                self.ids.swap(j - 1, j);
                self.time.swap(j - 1, j);
                self.content.swap(j - 1, j);
                j -= 1;
            }
        }
        self.recalc_cumulative_and_lookup();
        self.health_check();
        true
    }

    /// Replace multiple events in the track.
    ///
    /// If any event has timing unit that doesn't match the track's timing unit, then nothing is done
    /// and false is returned.
    pub fn replace_events(
        &mut self,
        events: impl Iterator<Item = (u64, TempoChangeEvent)> + Clone,
    ) -> bool {
        if events
            .clone()
            .any(|(_, ev)| !self.time.unit_match(ev.time()))
        {
            return false;
        }

        for (id, ev) in events {
            let Some(&index) = self.id_lookup.get(&id) else {
                continue;
            };
            self.time
                .try_set(index, ev.time())
                .expect("Checked that unit matches");
            self.content[index] = ev;
        }
        let swap = |i, j| {
            self.ids.swap(i, j);
            self.content.swap(i, j);
        };
        match &mut self.time {
            SameUnitTimeVec::Clock(times) => {
                sort_multi(times, swap);
            }
            SameUnitTimeVec::Beat(times) => {
                sort_multi(times, swap);
            }
        }
        self.recalc_cumulative_and_lookup();
        self.health_check();
        true
    }

    #[inline]
    pub fn change_times(&self) -> &SameUnitTimeVec {
        &self.time
    }

    #[inline]
    pub fn tempo_changes(&self) -> &[TempoChangeEvent] {
        &self.content
    }

    #[inline]
    pub fn cumulative_times(&self) -> &[(ClockTime, BeatTime)] {
        &self.cumulated
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    /// Resizes and recalculate cumulated values, should be called after every edit to the event list.
    fn recalc_cumulative_and_lookup(&mut self) {
        self.id_lookup.clear();
        while self.cumulated.len() > self.ids.len() {
            self.cumulated.pop();
        }
        while self.cumulated.len() < self.ids.len() {
            self.cumulated.push((ClockTime::ZERO, BeatTime::ZERO));
        }
        if self.ids.is_empty() {
            return;
        }

        let mut cumulated =
            TempoChangeEvent::initial_cumulate(self.time.index(0), &self.content[0]);
        self.cumulated[0] = cumulated;
        self.id_lookup.insert(self.ids[0], 0);
        for i in 1..self.ids.len() {
            self.id_lookup.insert(self.ids[i], i);
            generativity::make_guard!(g);
            let v = self.time.read_with_guard(g);
            let delta = v.index(i) - v.index(i - 1);
            let current = &self.content[i - 1];
            let next = &self.content[i];
            cumulated = TempoChangeEvent::cumulate(
                cumulated.0,
                cumulated.1,
                delta,
                v.index(i) - v.index(i - 1),
                current,
                next,
            );
            self.cumulated[i] = cumulated;
        }
    }

    fn add_event_impl(&mut self, event: TempoChangeEvent) {
        let time = event.time();
        assert!(self.time.unit_match(time));

        let insert_index = {
            match &self.time {
                SameUnitTimeVec::Clock(times) => times.partition_point(|x| Time::Clock(*x) <= time),
                SameUnitTimeVec::Beat(times) => times.partition_point(|x| Time::Beat(*x) <= time),
            }
        };
        let id = self.id_counter;
        self.id_counter += 1;
        self.ids.insert(insert_index, id);
        self.time
            .try_insert(insert_index, time)
            .expect("Checked that unit matches");
        self.content.insert(insert_index, event);
    }

    /// Check if all invariants are intact, but only in debug mode.
    ///
    /// Does nothing in release mode.
    pub(crate) fn health_check(&self) {
        match &self.time {
            SameUnitTimeVec::Clock(l) => debug_assert!(l.is_sorted()),
            SameUnitTimeVec::Beat(l) => debug_assert!(l.is_sorted()),
        }
        let len = self.ids.len();
        debug_assert_eq!(self.time.len(), len);
        debug_assert_eq!(self.content.len(), len);
        debug_assert_eq!(self.cumulated.len(), len);
        debug_assert_eq!(self.id_lookup.len(), len);
        for i in 0..len {
            if i == 0 {
                debug_assert_eq!(
                    self.cumulated[0],
                    TempoChangeEvent::initial_cumulate(self.time.index(0), &self.content[0])
                );
            } else {
                generativity::make_guard!(g);
                let v = self.time.read_with_guard(g);
                let delta = v.index(i) - v.index(i - 1);
                let expected = TempoChangeEvent::cumulate(
                    self.cumulated[i - 1].0,
                    self.cumulated[i - 1].1,
                    delta,
                    v.index(i) - v.index(i - 1),
                    &self.content[i - 1],
                    &self.content[i],
                );
                debug_assert_eq!(self.cumulated[i], expected);
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::rhythm::ClockTime;
    use proptest::prelude::*;

    use super::*;

    fn arb_clock_event() -> impl Strategy<Value = TempoChangeEvent> {
        (any::<u16>(), any::<u32>()).prop_map(|(t, s)| TempoChangeEvent {
            time: Time::Clock(ClockTime::from_seconds(t as f64 / 1000.0).unwrap()),
            tempo: Tempo::from_bpm(s as f64 / 1000.0).unwrap(),
            ease: Easing::Linear,
        })
    }

    fn arb_clock_events(max_len: usize) -> impl Strategy<Value = Vec<TempoChangeEvent>> {
        prop::collection::vec(arb_clock_event(), 0..=max_len)
    }

    fn arb_clock_track(max_len: usize) -> impl Strategy<Value = TempoTrack> {
        arb_clock_events(max_len).prop_map(|v| TempoTrack::with_events(v).expect("Same unit"))
    }

    fn arb_clock_track_select(max_len: usize) -> impl Strategy<Value = (TempoTrack, u64)> {
        prop::collection::vec(arb_clock_event(), 1..=max_len)
            .prop_map(|events| TempoTrack::with_events(events).expect("Same unit"))
            .prop_flat_map(|track| {
                let len = track.ids.len();
                let ids = track.ids.clone();
                (Just(track), (0..len).prop_map(move |index| ids[index]))
            })
    }

    fn arb_clock_track_select_multi(
        max_len: usize,
        max_select_len: usize,
    ) -> impl Strategy<Value = (TempoTrack, Vec<u64>)> {
        prop::collection::vec(arb_clock_event(), 1..=max_len)
            .prop_map(|events| TempoTrack::with_events(events).expect("Same unit"))
            .prop_flat_map(move |track| {
                let len = track.ids.len();
                let ids = track.ids.clone();
                (
                    Just(track),
                    proptest::collection::hash_set(0..len, 0..=(max_select_len.min(len)))
                        .prop_map(move |indices| indices.into_iter().map(|i| ids[i]).collect()),
                )
            })
    }

    fn arb_clock_track_replace_multi(
        max_len: usize,
        max_replace_len: usize,
    ) -> impl Strategy<Value = (TempoTrack, Vec<u64>, Vec<TempoChangeEvent>)> {
        arb_clock_track_select_multi(max_len, max_replace_len).prop_flat_map(|(track, ids)| {
            let len = ids.len();
            (
                Just(track),
                Just(ids),
                proptest::collection::vec(arb_clock_event(), len),
            )
        })
    }

    proptest! {
        #[test]
        fn add_track_stays_consistent(mut track in arb_clock_track(100), event in arb_clock_event()) {
            let len = track.ids.len();
            track.add_event(event);
            assert_eq!(track.ids.len(), len + 1);
        }
    }

    proptest! {
        #[test]
        fn add_multi_track_stays_consistent(mut track in arb_clock_track(100), events in arb_clock_events(100)) {
            let len = track.ids.len();
            let add_len = events.len();
            track.add_events(events.into_iter());
            assert_eq!(track.ids.len(), len + add_len);
        }
    }

    proptest! {
        #[test]
        fn remove_track_stays_consistent((mut track, index) in arb_clock_track_select(100)) {
            let len = track.ids.len();
            track.remove_event(index);
            assert_eq!(track.ids.len(), len - 1);
        }
    }

    proptest! {
        #[test]
        fn remove_multi_track_stays_consistent((mut track, ids) in arb_clock_track_select_multi(100, 50)) {
            let len = track.ids.len();
            let remove_len = ids.len();
            track.remove_events(ids);
            assert_eq!(track.ids.len(), len - remove_len);
        }
    }

    proptest! {
        #[test]
        fn replace_track_stays_consistent((mut track, index) in arb_clock_track_select(100), repl in arb_clock_event()) {
            let len = track.ids.len();
            track.replace_event(index, repl);
            assert_eq!(track.ids.len(), len);
        }
    }

    proptest! {
        #[test]
        fn replace_multi_track_stays_consistent((mut track, ids, events) in arb_clock_track_replace_multi(100, 50)) {
            let len = track.ids.len();
            track.replace_events(std::iter::zip(ids, events));
            assert_eq!(track.ids.len(), len);
        }
    }

    fn approx_eq(a: f64, b: f64, tol: f64) -> bool {
        (a - b).abs() <= tol
    }

    #[test]
    fn convert_from_const_tempo_clock_time() {
        let tempo = Tempo::from_bpm(120.0).unwrap();
        let tempo_track = TempoTrack::with_events(vec![TempoChangeEvent {
            time: Time::Clock(ClockTime::from_seconds(0.0).unwrap()),
            tempo,
            ease: Easing::InConst,
        }])
        .unwrap();

        assert_eq!(
            tempo_track.beat_to_clock(BeatTime::new(6.0).unwrap()),
            ClockTime::from_seconds(3.0).unwrap()
        );
        assert_eq!(
            tempo_track.clock_to_beats(ClockTime::from_seconds(3.0).unwrap()),
            BeatTime::new(6.0).unwrap()
        );
    }

    #[test]
    fn convert_from_const_tempo_beat_time() {
        let tempo = Tempo::from_bpm(120.0).unwrap();
        let tempo_track = TempoTrack::with_events(vec![TempoChangeEvent {
            time: Time::Beat(BeatTime::new(0.0).unwrap()),
            tempo,
            ease: Easing::InConst,
        }])
        .unwrap();

        assert_eq!(
            tempo_track.beat_to_clock(BeatTime::new(6.0).unwrap()),
            ClockTime::from_seconds(3.0).unwrap()
        );
        assert_eq!(
            tempo_track.clock_to_beats(ClockTime::from_seconds(3.0).unwrap()),
            BeatTime::new(6.0).unwrap()
        );
    }

    #[test]
    fn convert_from_linear_tempo_clock_time() {
        let t120 = Tempo::from_bpm(120.0).unwrap();
        let t240 = Tempo::from_bpm(240.0).unwrap();
        let tempo_track = TempoTrack::with_events(vec![
            TempoChangeEvent {
                time: Time::Clock(ClockTime::from_seconds(0.0).unwrap()),
                tempo: t120,
                ease: Easing::Linear,
            },
            TempoChangeEvent {
                time: Time::Clock(ClockTime::from_seconds(4.0).unwrap()),
                tempo: t240,
                ease: Easing::Linear,
            },
            TempoChangeEvent {
                time: Time::Clock(ClockTime::from_seconds(8.0).unwrap()),
                tempo: t120,
                ease: Easing::Linear,
            },
            TempoChangeEvent {
                time: Time::Clock(ClockTime::from_seconds(12.0).unwrap()),
                tempo: t240,
                ease: Easing::Linear,
            },
        ])
        .unwrap();

        assert_eq!(
            tempo_track.beat_to_clock(BeatTime::new(5.0).unwrap()),
            ClockTime::from_seconds(2.0).unwrap()
        );
        assert_eq!(
            tempo_track.clock_to_beats(ClockTime::from_seconds(2.0).unwrap()),
            BeatTime::new(5.0).unwrap()
        );
    }

    #[test]
    fn convert_from_linear_tempo_beat_time() {
        let t120 = Tempo::from_bpm(120.0).unwrap();
        let t240 = Tempo::from_bpm(240.0).unwrap();
        let tempo_track = TempoTrack::with_events(vec![
            TempoChangeEvent {
                time: Time::Beat(BeatTime::new(0.0).unwrap()),
                tempo: t120,
                ease: Easing::Linear,
            },
            TempoChangeEvent {
                time: Time::Beat(BeatTime::new(12.0).unwrap()),
                tempo: t240,
                ease: Easing::Linear,
            },
            TempoChangeEvent {
                time: Time::Beat(BeatTime::new(24.0).unwrap()),
                tempo: t120,
                ease: Easing::Linear,
            },
            TempoChangeEvent {
                time: Time::Beat(BeatTime::new(36.0).unwrap()),
                tempo: t240,
                ease: Easing::Linear,
            },
        ])
        .unwrap();

        // Forward: 6 beats -> 6 * ln(1.5) seconds. Both the implementation and the expected
        // value evaluate `ln(3.0 / 2.0)`, so they match to floating point precision.
        let expected_secs = 6.0 * f64::ln(3.0 / 2.0);
        let clock = tempo_track.beat_to_clock(BeatTime::new(6.0).unwrap());
        assert!(
            approx_eq(clock.seconds(), expected_secs, 1e-9),
            "beat_to_clock(6) = {}, expected {}",
            clock.seconds(),
            expected_secs
        );

        // Inverse round-trip: 6 * ln(1.5) seconds -> 6 beats.
        let beats = tempo_track.clock_to_beats(ClockTime::from_seconds(expected_secs).unwrap());
        assert!(
            approx_eq(beats.beats(), 6.0, 1e-9),
            "clock_to_beats({}) = {}, expected 6.0",
            expected_secs,
            beats.beats()
        );
    }
}