bms-rs 1.0.0

The BMS format parser.
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
//! Validity checks for BMS data after parsing and/or manual edits.
//!
//! This module provides a set of structural validations that are independent of
//! the parsing process. It can be used after editing `Bms` in-memory to ensure
//! referential integrity and basic invariants required for correct playback.

use std::collections::{HashMap, HashSet};

use thiserror::Error;

use crate::bms::{
    command::{
        ObjId,
        channel::{Key, NoteKind, PlayerSide},
        time::ObjTime,
    },
    model::{Bms, obj::WavObj},
    prelude::{KeyLayoutBeat, KeyLayoutMapper, KeyMapping},
};

/// Missing-related validity entries.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Error)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ValidityMissing {
    /// A note references an [`ObjId`] without a corresponding `#WAV` definition.
    #[error("Missing WAV definition for note object id: {0:?}")]
    WavForNote(ObjId),
    /// A BGM references an [`ObjId`] without a corresponding `#WAV` definition.
    #[error("Missing WAV definition for BGM object id: {0:?}")]
    WavForBgm(ObjId),
    /// A BGA change references an [`ObjId`] without a corresponding `#BMP`/`#EXBMP` definition.
    #[error("Missing BMP definition for BGA object id: {0:?}")]
    BmpForBga(ObjId),
    /// A BPM change references an [`ObjId`] without a corresponding `#BPMxx` definition.
    #[error("Missing BPM change definition for object id: {0:?}")]
    BpmChangeDef(ObjId),
    /// A STOP event references an [`ObjId`] without a corresponding `#STOPxx` definition.
    #[error("Missing STOP definition for object id: {0:?}")]
    StopDef(ObjId),
}

/// Invalid-related validity entries.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Error)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ValidityInvalid {
    /// A playable single note is placed in section 000 (but supported by LR2).
    #[error("Playable note placed in section 000 at {time:?} (side={side:?}, key={key:?})")]
    PlayableNoteInTrackZero {
        /// Player side where the note is placed.
        side: PlayerSide,
        /// Key lane where the note is placed.
        key: Key,
        /// Timestamp of the note.
        time: ObjTime,
    },
    /// Two or more visible single notes overlap at the same time in the same lane.
    #[error("Visible single-note overlap at {time:?} (side={side:?}, key={key:?})")]
    OverlapVisibleSingleWithSingle {
        /// Player side where the note is placed.
        side: PlayerSide,
        /// Key lane where the overlap occurs.
        key: Key,
        /// Timestamp of the overlap.
        time: ObjTime,
    },
    /// A visible single note overlaps an active long note interval in the same lane.
    #[error(
        "Visible single-note overlaps a long note at {time:?} (side={side:?}, key={key:?}; ln=[{ln_start:?}..{ln_end:?}])"
    )]
    OverlapVisibleSingleWithLong {
        /// Player side where the note is placed.
        side: PlayerSide,
        /// Key lane where the overlap occurs.
        key: Key,
        /// Timestamp of the single note.
        time: ObjTime,
        /// Start time of the long note interval.
        ln_start: ObjTime,
        /// End time of the long note interval.
        ln_end: ObjTime,
    },
    /// A landmine note overlaps a long note interval; warn only at the long start point.
    #[error(
        "Landmine overlaps a long note starting at {ln_start:?} (side={side:?}, key={key:?}; ln_end={ln_end:?})"
    )]
    OverlapsLandmineLongAtStart {
        /// Player side where the overlap occurs.
        side: PlayerSide,
        /// Key lane where the overlap occurs.
        key: Key,
        /// Start time of the long note interval.
        ln_start: ObjTime,
        /// End time of the long note interval.
        ln_end: ObjTime,
    },
    /// A landmine note overlaps a visible single note at the same time in the same lane.
    #[error("Landmine overlaps visible single note at {time:?} (side={side:?}, key={key:?})")]
    OverlapLandmineWithSingle {
        /// Player side where the overlap occurs.
        side: PlayerSide,
        /// Key lane where the overlap occurs.
        key: Key,
        /// Timestamp of the overlap.
        time: ObjTime,
    },
}

/// Output of validity checks.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[must_use]
pub struct ValidityCheckOutput {
    /// Missing-related findings.
    pub missing: Vec<ValidityMissing>,
    /// Invalid-related findings.
    pub invalid: Vec<ValidityInvalid>,
}

impl Bms {
    /// Validate the internal consistency of `Bms` after parsing or manual edits.
    ///
    /// This performs basic referential integrity checks and data invariants that
    /// are required for correct playback, separate from parse-time checks.
    pub fn check_validity(&self) -> ValidityCheckOutput {
        let missing = self.check_missing();
        let invalid = self.check_invalid();
        ValidityCheckOutput { missing, invalid }
    }

    fn check_missing(&self) -> Vec<ValidityMissing> {
        let mut missing = vec![];
        // 1) Check notes reference valid WAV ids.
        for obj_id in self.wav.notes.all_notes().map(|obj| &obj.wav_id) {
            if !self.wav.wav_files.contains_key(obj_id) {
                missing.push(ValidityMissing::WavForNote(*obj_id));
            }
        }

        // 2) Check BGAs reference valid BMP ids.
        for bga_obj in self.bmp.bga_changes.values() {
            if !self.bmp.bmp_files.contains_key(&bga_obj.id) {
                missing.push(ValidityMissing::BmpForBga(bga_obj.id));
            }
        }

        // 3) Check BPM change ids used in messages have corresponding #BPMxx definitions.
        for id in &self.bpm.bpm_change_ids_used {
            if !self.bpm.bpm_defs.contains_key(id) {
                missing.push(ValidityMissing::BpmChangeDef(*id));
            }
        }

        // 4) Check STOP ids used in messages have corresponding #STOPxx definitions.
        for id in &self.stop.stop_ids_used {
            if !self.stop.stop_defs.contains_key(id) {
                missing.push(ValidityMissing::StopDef(*id));
            }
        }
        missing
    }

    fn check_invalid(&self) -> Vec<ValidityInvalid> {
        let mut invalid = vec![];

        // Placement/overlap checks for notes on lanes.
        //      - Playable notes in section 000
        //      - Overlap: visible single vs single (same time, same lane)
        //      - Overlap: visible single within long interval (same lane)
        //      - Overlap: landmine vs single (same time, same lane)
        //      - Overlap: landmine within long interval -> warn once at long start
        let mut lane_to_notes: HashMap<Key, Vec<&WavObj>> = HashMap::new();
        for obj in self.wav.notes.all_notes() {
            // Visible note in section 000 (track index 0)
            let Some(map) = KeyLayoutBeat::from_channel_id(obj.channel_id) else {
                continue;
            };
            if map.kind().is_playable() && obj.offset.track().0 == 0 {
                invalid.push(ValidityInvalid::PlayableNoteInTrackZero {
                    side: map.side(),
                    key: map.key(),
                    time: obj.offset,
                });
            }
            lane_to_notes.entry(map.key()).or_default().push(obj);
        }
        for (key, objs) in lane_to_notes {
            if objs.is_empty() {
                continue;
            }
            // Sort by time
            let mut lane_objs = objs;
            lane_objs.sort_unstable_by_key(|o| o.offset);

            // Build LN intervals by pairing consecutive Long notes
            let long_times: Vec<ObjTime> = lane_objs
                .iter()
                .filter_map(|o| {
                    let map = KeyLayoutBeat::from_channel_id(o.channel_id)?;
                    (map.kind() == NoteKind::Long).then_some(o.offset)
                })
                .collect();

            // Overlap single vs single at the same time
            let mut single_offsets = HashSet::new();
            for (single_obj, map) in lane_objs
                .iter()
                .filter_map(|obj| {
                    KeyLayoutBeat::from_channel_id(obj.channel_id).map(|map| (obj, map))
                })
                .filter(|(_, map)| map.kind() == NoteKind::Visible)
            {
                if !single_offsets.insert(single_obj.offset) {
                    invalid.push(ValidityInvalid::OverlapVisibleSingleWithSingle {
                        side: map.side(),
                        key,
                        time: single_obj.offset,
                    });
                }
            }

            // Overlap landmine vs single at the same time
            for (landmine_obj, map) in lane_objs
                .iter()
                .filter_map(|obj| {
                    KeyLayoutBeat::from_channel_id(obj.channel_id).map(|map| (obj, map))
                })
                .filter(|(_, map)| map.kind() == NoteKind::Landmine)
            {
                if single_offsets.contains(&landmine_obj.offset) {
                    invalid.push(ValidityInvalid::OverlapLandmineWithSingle {
                        side: map.side(),
                        key,
                        time: landmine_obj.offset,
                    });
                }
            }

            // Helper: check if a time is within [s, e]
            let time_overlaps_any_ln = |t: ObjTime| -> Option<(ObjTime, ObjTime)> {
                // Early return if no long notes exist
                if long_times.is_empty() {
                    return None;
                }
                // Use binary search on sorted long_times to find the insertion point for t
                let pos = long_times.partition_point(|&x| x < t);

                // Check if we're exactly at a long note time
                if long_times.get(pos).copied() == Some(t) {
                    if pos % 2 == 0 {
                        let end = long_times.get(pos + 1).copied()?;
                        return Some((t, end));
                    }

                    if pos > 0 {
                        let start = long_times.get(pos - 1).copied()?;
                        if start == t {
                            return Some((start, t));
                        }
                    }
                    return None;
                }

                if pos % 2 == 1 {
                    let start = long_times.get(pos - 1).copied()?;
                    let end = long_times.get(pos).copied()?;
                    if start <= t {
                        return Some((start, end));
                    }
                }

                None
            };

            // Overlap single vs long: any visible single inside any LN interval
            for (single_obj, map) in lane_objs
                .iter()
                .filter_map(|obj| {
                    KeyLayoutBeat::from_channel_id(obj.channel_id).map(|map| (obj, map))
                })
                .filter(|(_, map)| map.kind() == NoteKind::Visible)
            {
                if let Some((start, end)) = time_overlaps_any_ln(single_obj.offset) {
                    invalid.push(ValidityInvalid::OverlapVisibleSingleWithLong {
                        side: map.side(),
                        key,
                        time: single_obj.offset,
                        ln_start: start,
                        ln_end: end,
                    });
                }
            }

            // Landmine vs long: warn once per LN interval at the long start
            // if any landmine appears inside that interval (including at start).
            let mut warned_ln_intervals: HashSet<(ObjTime, ObjTime)> = HashSet::new();
            for (landmine_obj, map) in lane_objs
                .iter()
                .filter_map(|obj| {
                    KeyLayoutBeat::from_channel_id(obj.channel_id).map(|map| (obj, map))
                })
                .filter(|(_, map)| map.kind() == NoteKind::Landmine)
            {
                if let Some((start, end)) = time_overlaps_any_ln(landmine_obj.offset)
                    && warned_ln_intervals.insert((start, end))
                {
                    invalid.push(ValidityInvalid::OverlapsLandmineLongAtStart {
                        side: map.side(),
                        key,
                        ln_start: start,
                        ln_end: end,
                    });
                }
            }
        }
        invalid
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::bms::{
        command::{
            ObjId,
            channel::{Key, NoteKind, PlayerSide},
            time::ObjTime,
        },
        model::{
            Notes,
            obj::{BgaLayer, BgaObj, WavObj},
        },
    };

    fn t(track: u64, num: u64, den: u64) -> ObjTime {
        ObjTime::new(track, num, den).expect("denominator should be non-zero")
    }

    #[test]
    fn test_missing_wav_for_note() {
        let mut bms = Bms::default();
        let id = ObjId::try_from("0A", false).unwrap();
        let time = t(1, 0, 4);
        // Insert note via push_note to keep ids_by_key consistent
        let mut notes = Notes::default();
        notes.push_note(WavObj {
            offset: time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id,
        });
        bms.wav.notes = notes;
        // No WAV defined for id
        let out = bms.check_validity();
        assert!(out.missing.contains(&ValidityMissing::WavForNote(id)));
    }

    #[test]
    fn test_missing_bmp_for_bga() {
        let mut bms = Bms::default();
        let id = ObjId::try_from("0B", false).unwrap();
        let time = t(1, 0, 4);
        bms.bmp.bga_changes.insert(
            time,
            BgaObj {
                time,
                id,
                layer: BgaLayer::Base,
            },
        );
        let out = bms.check_validity();
        assert!(out.missing.contains(&ValidityMissing::BmpForBga(id)));
    }

    #[test]
    fn test_visible_note_in_track_zero() {
        let mut bms = Bms::default();
        let id = ObjId::try_from("10", false).unwrap();
        let time = t(0, 0, 4);
        let mut notes = Notes::default();
        notes.push_note(WavObj {
            offset: time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id,
        });
        bms.wav.notes = notes;

        let out = bms.check_validity();
        assert!(out.invalid.iter().any(|e| matches!(
            e,
            ValidityInvalid::PlayableNoteInTrackZero { time: t0, side: PlayerSide::Player1, key: Key::Key(1) } if *t0 == time
        )));
    }

    #[test]
    fn test_overlap_visible_single_with_single() {
        let mut bms = Bms::default();
        let id1 = ObjId::try_from("01", false).unwrap();
        let id2 = ObjId::try_from("02", false).unwrap();
        let time = t(1, 0, 4);
        let mut notes = Notes::default();
        notes.push_note(WavObj {
            offset: time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id1,
        });
        notes.push_note(WavObj {
            offset: time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id2,
        });
        bms.wav.notes = notes;

        let out = bms.check_validity();
        assert!(out.invalid.iter().any(|e| matches!(
            e,
            ValidityInvalid::OverlapVisibleSingleWithSingle { time: t0, side: PlayerSide::Player1, key: Key::Key(1) } if *t0 == time
        )));
    }

    #[test]
    fn test_overlap_visible_single_with_long() {
        let mut bms = Bms::default();
        let id_ln_s = ObjId::try_from("0E", false).unwrap();
        let id_ln_e = ObjId::try_from("0F", false).unwrap();
        let id_vis = ObjId::try_from("03", false).unwrap();
        let ln_start = t(2, 0, 4);
        let ln_end = t(2, 2, 4);
        let vis_time = t(2, 1, 4);
        let mut notes = Notes::default();
        // LN start
        notes.push_note(WavObj {
            offset: ln_start,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Long, Key::Key(1))
                .to_channel_id(),
            wav_id: id_ln_s,
        });
        // LN end
        notes.push_note(WavObj {
            offset: ln_end,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Long, Key::Key(1))
                .to_channel_id(),
            wav_id: id_ln_e,
        });
        // Visible inside LN interval
        notes.push_note(WavObj {
            offset: vis_time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id_vis,
        });
        bms.wav.notes = notes;

        let out = bms.check_validity();
        assert!(out.invalid.iter().any(|e| matches!(
            e,
            ValidityInvalid::OverlapVisibleSingleWithLong { side: PlayerSide::Player1, key: Key::Key(1), time: t0, ln_start: s, ln_end: e } if *t0 == vis_time && *s == ln_start && *e == ln_end
        )));
    }

    #[test]
    fn test_landmine_overlap_long_warn_at_start() {
        let mut bms = Bms::default();
        let id_ln_s = ObjId::try_from("1A", false).unwrap();
        let id_ln_e = ObjId::try_from("1B", false).unwrap();
        let id_mine = ObjId::try_from("1C", false).unwrap();
        let ln_start = t(3, 0, 4);
        let ln_end = t(3, 2, 4);
        let mine_time = t(3, 0, 4);
        let mut notes = Notes::default();
        // LN interval
        notes.push_note(WavObj {
            offset: ln_start,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Long, Key::Key(1))
                .to_channel_id(),
            wav_id: id_ln_s,
        });
        notes.push_note(WavObj {
            offset: ln_end,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Long, Key::Key(1))
                .to_channel_id(),
            wav_id: id_ln_e,
        });
        // Landmine inside the LN
        notes.push_note(WavObj {
            offset: mine_time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Landmine, Key::Key(1))
                .to_channel_id(),
            wav_id: id_mine,
        });
        bms.wav.notes = notes;

        let out = bms.check_validity();
        assert!(out.invalid.iter().any(|e| matches!(
            e,
            ValidityInvalid::OverlapsLandmineLongAtStart { side: PlayerSide::Player1, key: Key::Key(1), ln_start: s, ln_end: e } if *s == ln_start && *e == ln_end
        )));
    }

    #[test]
    fn test_overlap_landmine_with_single() {
        let mut bms = Bms::default();
        let id_vis = ObjId::try_from("04", false).unwrap();
        let id_mine = ObjId::try_from("05", false).unwrap();
        let time = t(1, 0, 4);
        let mut notes = Notes::default();
        notes.push_note(WavObj {
            offset: time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id_vis,
        });
        notes.push_note(WavObj {
            offset: time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Landmine, Key::Key(1))
                .to_channel_id(),
            wav_id: id_mine,
        });
        bms.wav.notes = notes;

        let out = bms.check_validity();
        assert!(out.invalid.iter().any(|e| matches!(
            e,
            ValidityInvalid::OverlapLandmineWithSingle { time: t0, side: PlayerSide::Player1, key: Key::Key(1) } if *t0 == time
        )));
    }

    #[test]
    fn test_zero_length_long_note_overlap() {
        let mut bms = Bms::default();
        let id_ln_start = ObjId::try_from("20", false).unwrap();
        let id_ln_end = ObjId::try_from("21", false).unwrap();
        let id_vis = ObjId::try_from("22", false).unwrap();
        let zero_length_time = t(2, 0, 4);
        let vis_time = t(2, 0, 4); // Same time as zero-length LN
        let mut notes = Notes::default();

        // Zero-length long note: start and end at same time
        notes.push_note(WavObj {
            offset: zero_length_time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Long, Key::Key(1))
                .to_channel_id(),
            wav_id: id_ln_start,
        });
        notes.push_note(WavObj {
            offset: zero_length_time, // Same time - zero length
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Long, Key::Key(1))
                .to_channel_id(),
            wav_id: id_ln_end,
        });

        // Visible note at the same time as zero-length LN
        notes.push_note(WavObj {
            offset: vis_time,
            channel_id: KeyLayoutBeat::new(PlayerSide::Player1, NoteKind::Visible, Key::Key(1))
                .to_channel_id(),
            wav_id: id_vis,
        });

        bms.wav.notes = notes;

        let out = bms.check_validity();
        // This should detect the overlap, but currently fails due to the bug
        assert!(
            out.invalid.iter().any(|e| matches!(
                e,
                ValidityInvalid::OverlapVisibleSingleWithLong {
                    side: PlayerSide::Player1,
                    key: Key::Key(1),
                    time: t0,
                    ln_start: s,
                    ln_end: e
                } if *t0 == vis_time && *s == zero_length_time && *e == zero_length_time
            )),
            "Failed to detect overlap with zero-length long note. Current output: {:?}",
            out.invalid
        );
    }
}