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
use std::ops::{Add, Div, Sub};

use crate::{
    math::Easing,
    rhythm::{
        ClockTime, TempoTracks, Time, TrackId,
        track::{EventTrack, EventTracks, TrackEvent},
    },
};

/// Defines scrolling speed change at a point in time.
///
/// The speed must not be NaN.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ScrollSpeedChangeEvent {
    /// The time at which the speed change starts
    pub time: Time,
    /// The speed is in unit of [`ScrollPosition`] per second.
    speed: f64,
    /// The easing of the speed change, taking effect until the next event's time.
    pub ease: Easing,
}

impl ScrollSpeedChangeEvent {
    /// Creates a new event.
    ///
    /// # Returns
    /// [`None`] if the speed is NaN.
    pub fn new(time: Time, speed: f64, ease: Easing) -> Option<ScrollSpeedChangeEvent> {
        if speed.is_finite() {
            Some(Self { time, speed, ease })
        } else {
            None
        }
    }

    /// The speed is in unit of [`ScrollPosition`] per second.
    pub fn speed(&self) -> f64 {
        self.speed
    }

    /// Creates a new event with the provided scroll speed.
    ///
    /// # Returns
    /// [`None`] if the speed is NaN.
    pub fn with_speed(self, speed: f64) -> Option<Self> {
        Self::new(self.time, speed, self.ease)
    }
}

impl TrackEvent for ScrollSpeedChangeEvent {
    type Cumulated = ScrollPosition;

    fn time(&self) -> Time {
        self.time
    }

    fn cumulate<'id>(
        current_cumulated: Self::Cumulated,
        delta: ClockTime,
        full_duration: ClockTime,
        current: &Self,
        next: &Self,
    ) -> Self::Cumulated {
        if full_duration.seconds() <= 1e-6 {
            return current_cumulated;
        }

        let p = delta / full_duration;
        let val = current_cumulated.0
            + current.ease.integrate(current.speed, next.speed, p) * full_duration.seconds();
        if !val.is_finite() {
            return ScrollPosition(f64::INFINITY);
        }
        // integrate result should be finite because current, next speed and p are all finite.
        ScrollPosition(val)
    }

    fn initial_cumulate(first_time: ClockTime, event: &Self) -> Self::Cumulated {
        ScrollPosition(first_time.seconds() * event.speed)
    }
}

pub type ScrollSpeedTracks = EventTracks<ScrollSpeedTrack>;

/// Position on the [`ScrollSpeedTrack`] where scrolling speed might change.
///
/// Calculated as integral of scrolling speed over time.
/// The scroll position is newtype of [`f64`] that is not NaN.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ScrollPosition(f64);

impl ScrollPosition {
    pub const ZERO: Self = Self(0.);
    pub const INF: Self = Self(f64::INFINITY);

    /// Creates a scroll position.
    ///
    /// # Returns
    /// [`None`] if `position` is NaN.
    pub fn new(position: f64) -> Option<Self> {
        (!position.is_nan()).then_some(Self(position))
    }

    /// Gets the position.
    pub fn pos(self) -> f64 {
        self.0
    }

    /// Scale the position by a factor.
    ///
    /// # Returns
    /// [`None`] if the result of this multiplcation is NaN.
    pub fn scale(self, s: f64) -> Option<Self> {
        let v = self.0 * s;
        v.is_nan().then_some(Self(v))
    }
}

impl Eq for ScrollPosition {}

impl PartialOrd for ScrollPosition {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ScrollPosition {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0
            .partial_cmp(&other.0)
            .expect("Scroll position is never NaN")
    }
}

impl Add for ScrollPosition {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        let v = self.0 + rhs.0;
        if v.is_nan() {
            Self(f64::INFINITY)
        } else {
            Self(v)
        }
    }
}

impl Sub for ScrollPosition {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        let v = self.0 - rhs.0;
        if v.is_nan() {
            Self(f64::INFINITY)
        } else {
            Self(v)
        }
    }
}

impl Div for ScrollPosition {
    type Output = f64;

    fn div(self, rhs: Self) -> Self::Output {
        self.0 / rhs.0
    }
}

/// A scroll track which can have different scrolling speed at different point in time.
#[derive(Debug, Clone)]
pub struct ScrollSpeedTrack(EventTrack<ScrollSpeedChangeEvent>);

impl ScrollSpeedTrack {
    /// Calculates the scroll position at a point in time.
    ///
    /// # Returns
    /// [`ScrollPosition::INF`] if the calculation result in overflow or NaN.
    pub fn calculate_scroll_position(&self, clock_time: ClockTime) -> ScrollPosition {
        if self.is_empty() {
            return ScrollPosition(clock_time.seconds());
        }

        // Index of the first tempo change whose cumulative beat exceed the query beat.
        let index = self
            .change_clock_times()
            .partition_point(|t| *t <= clock_time);

        // The query comes before any event
        if index == 0 {
            let first = self.0.content()[0];
            let val = self.0.cumulated()[0].0
                - (self.0.clock_times()[0] - clock_time).seconds() * first.speed;
            if !val.is_finite() {
                return ScrollPosition(f64::INFINITY);
            } else {
                return ScrollPosition(val);
            }
        }

        if index == self.len() {
            let last_index = self.len() - 1;
            let last_ev = self.0.content()[last_index];
            let val = self.0.cumulated()[last_index].0
                + (clock_time - self.0.clock_times()[last_index]).seconds() * last_ev.speed;
            if !val.is_finite() {
                return ScrollPosition(f64::INFINITY);
            } else {
                return ScrollPosition(val);
            }
        }

        let base = self.0.cumulated()[index - 1].0;
        let elapsed_time_since = clock_time - self.0.clock_times()[index - 1];
        let full_elapsed_time = self.0.clock_times()[index] - self.0.clock_times()[index - 1];
        let sp0 = self.0.content()[index - 1].speed;
        let sp1 = self.0.content()[index].speed;
        let ease = self.0.content()[index - 1].ease;

        let p = elapsed_time_since / full_elapsed_time;
        let val = base + ease.integrate(sp0, sp1, p) * full_elapsed_time.seconds();
        if !val.is_finite() {
            return ScrollPosition(f64::INFINITY);
        }

        ScrollPosition(val)
    }

    /// Create a new empty track with the given id.
    pub fn new(tempo_track_id: TrackId) -> Self {
        Self(EventTrack::new(tempo_track_id))
    }

    /// Create a tempo track from a list of tempo change events.
    pub fn with_events(
        tempo_track_id: TrackId,
        events: Vec<ScrollSpeedChangeEvent>,
        tempo_tracks: &TempoTracks,
    ) -> Self {
        Self(EventTrack::with_events(
            tempo_track_id,
            events,
            tempo_tracks,
        ))
    }

    /// Add an event.
    pub fn add_event(&mut self, event: ScrollSpeedChangeEvent, tempo_tracks: &TempoTracks) {
        self.0.add_event(event, tempo_tracks)
    }

    /// Add multiple events.
    pub fn add_events(
        &mut self,
        events: impl Iterator<Item = ScrollSpeedChangeEvent>,
        tempo_tracks: &TempoTracks,
    ) {
        self.0.add_events(events, tempo_tracks)
    }

    /// Remove an event from the track.
    pub fn remove_event(&mut self, id: u64) {
        self.0.remove_event(id)
    }

    /// Remove multiple events from the track.
    pub fn remove_events(&mut self, ids: impl IntoIterator<Item = u64>) {
        self.0.remove_events(ids)
    }

    /// Replace an event in the track.
    pub fn replace_event(
        &mut self,
        id: u64,
        replace_with: ScrollSpeedChangeEvent,
        tempo_tracks: &TempoTracks,
    ) {
        self.0.replace_event(id, replace_with, tempo_tracks)
    }

    /// Replace multiple events in the track.
    pub fn replace_events(
        &mut self,
        events: impl Iterator<Item = (u64, ScrollSpeedChangeEvent)>,
        tempo_tracks: &TempoTracks,
    ) {
        self.0.replace_events(events, tempo_tracks);
    }

    /// Rebuild the event list after changes in tempo.
    ///
    /// # Remarks
    /// After changes in tempo, events with beat time may now have different clock time,
    /// requiring event tracks to reindex.
    pub fn rebuild_after_tempo_change(&mut self, tempo_tracks: &TempoTracks) {
        self.0.rebuild_after_tempo_change(tempo_tracks);
    }

    /// Change the tempo track that this event track follow then rebuild.
    pub fn change_tempo_track(&mut self, tempo_track_id: TrackId, tempo_tracks: &TempoTracks) {
        self.0.change_tempo_track(tempo_track_id, tempo_tracks);
    }

    #[inline]
    pub fn change_times(&self) -> &[Time] {
        self.0.times()
    }

    #[inline]
    pub fn change_clock_times(&self) -> &[ClockTime] {
        self.0.clock_times()
    }

    #[inline]
    pub fn speed_changes(&self) -> &[ScrollSpeedChangeEvent] {
        self.0.content()
    }

    #[inline]
    pub fn cumulative_scroll_position(&self) -> &[ScrollPosition] {
        self.0.cumulated()
    }

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

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

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

    use super::*;

    fn test_tempo_tracks() -> TempoTracks {
        TempoTracks::with_tracks(
            crate::rhythm::TempoTrack::with_events(vec![crate::rhythm::TempoChangeEvent {
                time: Time::Clock(ClockTime::ZERO),
                tempo: crate::rhythm::Tempo::from_bpm(60.0).unwrap(),
                ease: crate::math::Easing::InConst,
            }])
            .unwrap(),
            std::iter::empty(),
        )
    }

    fn clock_time(s: f64) -> Time {
        Time::Clock(ClockTime::from_seconds(s).unwrap())
    }

    #[test]
    fn query_empty_track() {
        let scroll_track = ScrollSpeedTrack::new(TrackId::Main);
        let timing = ClockTime::from_seconds(10.0).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(10.0)
        );
    }

    #[test]
    fn query_with_speed_change() {
        let ease = Easing::InConst;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![
                ScrollSpeedChangeEvent::new(clock_time(0.), 2., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(1.), 1., ease).unwrap(),
            ],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(2.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(3.)
        );
    }

    #[test]
    fn query_with_multiple_speed_change() {
        let ease = Easing::InConst;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![
                ScrollSpeedChangeEvent::new(clock_time(0.), 1., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(1.), 2., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(2.), 3., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(3.), 4., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(4.), 5., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(5.), 6., ease).unwrap(),
            ],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(3.5).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(1.0 + 2.0 + 3.0 + 4.0 * 0.5)
        );
    }

    #[test]
    fn query_before_first_point() {
        let ease = Easing::InConst;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![ScrollSpeedChangeEvent::new(clock_time(0.), 1., ease).unwrap()],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(-5.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(-5.)
        );
    }

    #[test]
    fn query_after_last_point() {
        let ease = Easing::InConst;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![ScrollSpeedChangeEvent::new(clock_time(10.), 1., ease).unwrap()],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(20.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(20.)
        );
    }

    #[test]
    fn query_speed_changes_at_same_timing() {
        let ease = Easing::InConst;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![
                ScrollSpeedChangeEvent::new(clock_time(0.), 1., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(10.), 1., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(10.), 2., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(10.), 3., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(10.), 4., ease).unwrap(),
            ],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(20.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(10. + 4. * 10.)
        );
    }

    #[test]
    fn query_with_linear_speed_change() {
        let ease = Easing::Linear;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![
                ScrollSpeedChangeEvent::new(clock_time(0.), 2., ease).unwrap(),
                ScrollSpeedChangeEvent::new(clock_time(1.), 1., ease).unwrap(),
            ],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(2.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(1.0 + ease.integrate(2.0, 1.0, 1.0))
        );
    }

    #[test]
    fn query_with_non_zero_start_time() {
        let ease = Easing::Linear;
        let scroll_track = ScrollSpeedTrack::with_events(
            TrackId::Main,
            vec![ScrollSpeedChangeEvent::new(clock_time(10.), 1., ease).unwrap()],
            &test_tempo_tracks(),
        );
        let timing = ClockTime::from_seconds(5.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(5.0)
        );

        let timing = ClockTime::from_seconds(0.).unwrap();
        assert_eq!(
            scroll_track.calculate_scroll_position(timing),
            ScrollPosition(0.0)
        );
    }

    use proptest::prelude::*;

    fn arb_time() -> impl Strategy<Value = Time> {
        let non_nan = prop::num::f64::POSITIVE | prop::num::f64::NEGATIVE;
        (non_nan).prop_map(|t| Time::Clock(ClockTime::from_seconds(t).unwrap()))
    }

    fn arb_event() -> impl Strategy<Value = ScrollSpeedChangeEvent> {
        let non_nan = prop::num::f64::POSITIVE | prop::num::f64::NEGATIVE;
        (non_nan, non_nan).prop_map(|(t, s)| ScrollSpeedChangeEvent {
            time: Time::Clock(ClockTime::from_seconds(t).unwrap()),
            speed: s,
            ease: Easing::Linear,
        })
    }

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

    fn arb_clock_track(max_len: usize) -> impl Strategy<Value = ScrollSpeedTrack> {
        arb_clock_events(max_len)
            .prop_map(|v| ScrollSpeedTrack::with_events(TrackId::Main, v, &test_tempo_tracks()))
    }

    proptest! {
        #[test]
        fn query_never_triggers_nan(track in arb_clock_track(100), time in arb_time()) {
            let Time::Clock(clock_time) = time else {
                panic!("Test input must be clock time")
            };
            let scroll_pos = track.calculate_scroll_position(clock_time);
            assert!(!scroll_pos.0.is_nan())
        }
    }
}