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
use crate::instruments::drums::DrumType;
use crate::track::Track;
/// A trait for types that can be converted into drum step positions.
///
/// This allows `DrumGrid` methods to accept either:
/// - Index arrays: `&[0, 4, 8, 12]`
/// - String patterns: `"x--- x--- x--- x---"`
///
/// # String Pattern Syntax
/// - Hit characters: `x`, `X`, `1`, `*`
/// - Rest characters: `-`, `_`, `.`, `~`, `0`, space (and any other character)
pub trait DrumPattern {
/// Convert to a list of step indices where hits occur
fn into_steps(&self) -> Vec<usize>;
}
impl DrumPattern for [usize] {
fn into_steps(&self) -> Vec<usize> {
self.to_vec()
}
}
// Implement for fixed-size arrays using const generics
impl<const N: usize> DrumPattern for [usize; N] {
fn into_steps(&self) -> Vec<usize> {
self.to_vec()
}
}
// Implement for Vec<usize>
impl DrumPattern for Vec<usize> {
fn into_steps(&self) -> Vec<usize> {
self.clone()
}
}
impl DrumPattern for str {
fn into_steps(&self) -> Vec<usize> {
self.chars()
.enumerate()
.filter_map(|(i, c)| {
if matches!(c, 'x' | 'X' | '1' | '*') {
Some(i)
} else {
None
}
})
.collect()
}
}
/// A step sequencer-style drum grid for easy drum pattern programming
pub struct DrumGrid<'a> {
track: &'a mut Track,
start_time: f32,
steps: usize,
step_duration: f32,
}
impl<'a> DrumGrid<'a> {
/// Create a new drum grid
///
/// # Arguments
/// * `track` - The track to add drum events to
/// * `start_time` - When the grid starts (in seconds)
/// * `steps` - Number of steps in the grid (e.g., 16 for a bar of 16th notes)
/// * `step_duration` - Duration of each step (e.g., 0.125 for 16th notes at 120bpm)
pub fn new(track: &'a mut Track, start_time: f32, steps: usize, step_duration: f32) -> Self {
Self {
track,
start_time,
steps,
step_duration,
}
}
/// Add a drum sound at specific step positions
///
/// Accepts either an array of step indices or a string pattern:
/// - Array: `&[0, 4, 8, 12]` - explicit step positions
/// - String: `"x---x---x---x---"` - pattern notation where `x`/`X`/`1`/`*` are hits
///
/// All 90+ drum sounds from `DrumType` are available.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .sound(DrumType::Kick, "x---x---x---x---")
/// .sound(DrumType::Snare, "----x-------x---")
/// .sound(DrumType::HiHatClosed, "x-x-x-x-x-x-x-x-"));
/// ```
pub fn sound<P: DrumPattern + ?Sized>(self, drum_type: DrumType, pattern: &P) -> Self {
for step in pattern.into_steps() {
if step < self.steps {
let time = self.start_time + (step as f32 * self.step_duration);
self.track.add_drum(drum_type, time, None);
}
}
self
}
/// Get the total duration of the grid
pub fn duration(&self) -> f32 {
self.steps as f32 * self.step_duration
}
/// Apply an accent pattern to all drums in the grid
///
/// Accented steps get high velocity (1.0), unaccented steps get lower velocity (0.5).
/// Use `accent_with_levels` for custom velocity levels.
///
/// # Pattern Syntax
/// - Accent characters: `x`, `X`, `1`, `*` (velocity 1.0)
/// - Unaccented: `-`, `_`, `.`, `~`, `0`, space (velocity 0.5)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .sound(DrumType::HiHatClosed, "x-x-x-x-x-x-x-x-")
/// .accent("x---x---x---x---")); // Accent every 4th hi-hat
/// ```
pub fn accent<P: DrumPattern + ?Sized>(self, pattern: &P) -> Self {
self.accent_with_levels(pattern, 1.0, 0.5)
}
/// Apply an accent pattern with custom high/low velocity levels
///
/// # Arguments
/// * `pattern` - Pattern where hits are accented, rests are unaccented
/// * `high_velocity` - Velocity for accented steps (0.0-1.0)
/// * `low_velocity` - Velocity for unaccented steps (0.0-1.0)
pub fn accent_with_levels<P: DrumPattern + ?Sized>(
self,
pattern: &P,
high_velocity: f32,
low_velocity: f32,
) -> Self {
let accent_steps: std::collections::HashSet<usize> =
pattern.into_steps().into_iter().collect();
let grid_end_time = self.start_time + self.duration();
for event in &mut self.track.events {
if let crate::track::AudioEvent::Drum(drum) = event {
if drum.start_time >= self.start_time && drum.start_time < grid_end_time {
// Calculate which step this drum lands on
let relative_time = drum.start_time - self.start_time;
let step = (relative_time / self.step_duration).round() as usize;
if accent_steps.contains(&step) {
drum.velocity = high_velocity.clamp(0.0, 1.0);
} else {
drum.velocity = low_velocity.clamp(0.0, 1.0);
}
}
}
}
self
}
/// Apply explicit per-step velocity values to all drums
///
/// Each velocity value corresponds to a step. Drums landing on that step
/// get the specified velocity. Steps beyond the velocity slice use 1.0.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(8, 0.125, |g| g
/// .sound(DrumType::HiHatClosed, "xxxxxxxx")
/// .velocity(&[1.0, 0.5, 0.7, 0.5, 1.0, 0.5, 0.7, 0.5])); // Swung velocity
/// ```
pub fn velocity(self, velocities: &[f32]) -> Self {
let grid_end_time = self.start_time + self.duration();
for event in &mut self.track.events {
if let crate::track::AudioEvent::Drum(drum) = event {
if drum.start_time >= self.start_time && drum.start_time < grid_end_time {
let relative_time = drum.start_time - self.start_time;
let step = (relative_time / self.step_duration).round() as usize;
if step < velocities.len() {
drum.velocity = velocities[step].clamp(0.0, 1.0);
}
}
}
}
self
}
/// Add probabilistic drum hits - each hit has a chance to be played
///
/// # Arguments
/// * `drum_type` - The drum sound to add
/// * `pattern` - Step pattern (same as `sound`)
/// * `probability` - Chance of each hit occurring (0.0 = never, 1.0 = always)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .sound(DrumType::Kick, "x---x---x---x---")
/// .maybe(DrumType::HiHatOpen, "x-x-x-x-x-x-x-x-", 0.3)); // 30% chance per step
/// ```
pub fn maybe<P: DrumPattern + ?Sized>(
self,
drum_type: DrumType,
pattern: &P,
probability: f32,
) -> Self {
use rand::Rng;
let mut rng = rand::rng();
let prob = probability.clamp(0.0, 1.0);
for step in pattern.into_steps() {
if step < self.steps && rng.random::<f32>() < prob {
let time = self.start_time + (step as f32 * self.step_duration);
self.track.add_drum(drum_type, time, None);
}
}
self
}
/// Add ghost notes - quieter hits that add groove
///
/// Ghost notes are typically played at lower velocity to add subtle texture.
///
/// # Arguments
/// * `drum_type` - The drum sound for ghost notes
/// * `pattern` - Step pattern for ghost note positions
/// * `velocity` - Ghost note velocity (typically 0.2-0.4)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .sound(DrumType::Snare, "----x-------x---")
/// .ghost(DrumType::Snare, "-x----x--x----x-", 0.3)); // Ghost notes between hits
/// ```
pub fn ghost<P: DrumPattern + ?Sized>(
self,
drum_type: DrumType,
pattern: &P,
velocity: f32,
) -> Self {
let vel = velocity.clamp(0.0, 1.0);
for step in pattern.into_steps() {
if step < self.steps {
let time = self.start_time + (step as f32 * self.step_duration);
self.track.add_drum_with_velocity(drum_type, time, vel, None);
}
}
self
}
/// Add a flam - two quick hits, the first quieter (grace note)
///
/// A flam is a rudiment where a grace note precedes the main hit.
/// The grace note is typically 20-40ms before the main hit.
///
/// # Arguments
/// * `drum_type` - The drum sound
/// * `pattern` - Step pattern for flam positions
/// * `grace_offset` - Time before main hit for grace note (in seconds, e.g., 0.03)
/// * `grace_velocity` - Velocity of the grace note (typically 0.3-0.5)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .flam(DrumType::Snare, "----x-------x---", 0.03, 0.4));
/// ```
pub fn flam<P: DrumPattern + ?Sized>(
self,
drum_type: DrumType,
pattern: &P,
grace_offset: f32,
grace_velocity: f32,
) -> Self {
let grace_vel = grace_velocity.clamp(0.0, 1.0);
for step in pattern.into_steps() {
if step < self.steps {
let main_time = self.start_time + (step as f32 * self.step_duration);
let grace_time = (main_time - grace_offset).max(0.0);
// Add grace note (quieter, slightly before)
self.track.add_drum_with_velocity(drum_type, grace_time, grace_vel, None);
// Add main hit
self.track.add_drum(drum_type, main_time, None);
}
}
self
}
/// Add a drum roll - rapid repeated hits
///
/// Creates multiple hits spread evenly across the step duration.
///
/// # Arguments
/// * `drum_type` - The drum sound
/// * `pattern` - Step pattern for roll positions
/// * `subdivisions` - Number of hits per step (e.g., 4 for a quick roll)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .roll(DrumType::Snare, "---------------x", 8)); // Roll on last step
/// ```
pub fn roll<P: DrumPattern + ?Sized>(
self,
drum_type: DrumType,
pattern: &P,
subdivisions: usize,
) -> Self {
if subdivisions == 0 {
return self;
}
let sub_duration = self.step_duration / subdivisions as f32;
for step in pattern.into_steps() {
if step < self.steps {
let step_start = self.start_time + (step as f32 * self.step_duration);
for i in 0..subdivisions {
let time = step_start + (i as f32 * sub_duration);
self.track.add_drum(drum_type, time, None);
}
}
}
self
}
/// Repeat the drum grid pattern N times
///
/// This will duplicate all drum events that were added to the grid,
/// placing copies sequentially after the original pattern.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::instruments::drums::DrumType;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .sound(DrumType::Kick, &[0, 4, 8, 12])
/// .sound(DrumType::Snare, &[4, 12])
/// .repeat(3)); // Plays the pattern 4 times total (original + 3 repeats)
/// ```
pub fn repeat(self, times: usize) -> Self {
if times == 0 {
return self;
}
let grid_duration = self.duration();
let grid_end_time = self.start_time + grid_duration;
// Collect all drum events in this grid's time range
let pattern_events: Vec<_> = self
.track
.events
.iter()
.filter_map(|event| match event {
crate::track::AudioEvent::Drum(drum) => {
if drum.start_time >= self.start_time && drum.start_time < grid_end_time {
Some((drum.drum_type, drum.start_time - self.start_time))
} else {
None
}
}
_ => None,
})
.collect();
// Repeat the pattern
for i in 0..times {
let offset = grid_duration * (i + 1) as f32;
for &(drum_type, relative_time) in &pattern_events {
self.track
.add_drum(drum_type, self.start_time + relative_time + offset, None);
}
}
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::track::AudioEvent;
#[test]
fn test_drum_grid_creation() {
let mut track = Track::new();
let grid = DrumGrid::new(&mut track, 0.0, 16, 0.125);
assert_eq!(grid.start_time, 0.0);
assert_eq!(grid.steps, 16);
assert_eq!(grid.step_duration, 0.125);
}
#[test]
fn test_drum_grid_duration() {
let mut track = Track::new();
let grid = DrumGrid::new(&mut track, 0.0, 16, 0.125);
assert_eq!(grid.duration(), 2.0); // 16 steps * 0.125 = 2.0 seconds
}
#[test]
fn test_drum_grid_sound_basic() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, &[0, 4, 8, 12]);
assert_eq!(track.events.len(), 4);
// Verify first hit
if let AudioEvent::Drum(drum) = &track.events[0] {
assert!(matches!(drum.drum_type, DrumType::Kick));
assert_eq!(drum.start_time, 0.0);
}
// Verify last hit
if let AudioEvent::Drum(drum) = &track.events[3] {
assert!(matches!(drum.drum_type, DrumType::Kick));
assert_eq!(drum.start_time, 1.5); // step 12 * 0.125
}
}
#[test]
fn test_drum_grid_sound_with_offset() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 2.0, 8, 0.25).sound(DrumType::Snare, &[2, 6]);
assert_eq!(track.events.len(), 2);
if let AudioEvent::Drum(drum) = &track.events[0] {
assert_eq!(drum.start_time, 2.5); // 2.0 start + (2 * 0.25)
}
if let AudioEvent::Drum(drum) = &track.events[1] {
assert_eq!(drum.start_time, 3.5); // 2.0 start + (6 * 0.25)
}
}
#[test]
fn test_drum_grid_out_of_bounds_steps() {
let mut track = Track::new();
let _grid =
DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, &[0, 8, 16, 20, 100]); // 16, 20, 100 are out of bounds
// Should only add hits for valid steps (0, 8)
assert_eq!(track.events.len(), 2);
}
#[test]
fn test_drum_grid_chaining() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125)
.sound(DrumType::Kick, &[0, 4, 8, 12])
.sound(DrumType::Snare, &[4, 12])
.sound(DrumType::HiHatClosed, &[0, 2, 4, 6, 8, 10, 12, 14]);
// Should have 4 kicks + 2 snares + 8 hihats = 14 events
assert_eq!(track.events.len(), 14);
}
#[test]
fn test_drum_grid_empty_pattern() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, &[]);
assert_eq!(track.events.len(), 0);
}
#[test]
fn test_drum_grid_repeat() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.5) // 2 second pattern
.sound(DrumType::Kick, &[0, 2])
.repeat(2); // Repeat 2 more times
// Original 2 kicks + 2 repeats * 2 kicks = 6 total
assert_eq!(track.events.len(), 6);
// Verify timing of repeats
if let AudioEvent::Drum(drum) = &track.events[0] {
assert_eq!(drum.start_time, 0.0); // Original
}
if let AudioEvent::Drum(drum) = &track.events[2] {
assert_eq!(drum.start_time, 2.0); // First repeat
}
if let AudioEvent::Drum(drum) = &track.events[4] {
assert_eq!(drum.start_time, 4.0); // Second repeat
}
}
#[test]
fn test_drum_grid_repeat_zero_times() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.5)
.sound(DrumType::Kick, &[0, 2])
.repeat(0);
// Repeating 0 times should leave pattern unchanged
assert_eq!(track.events.len(), 2);
}
#[test]
fn test_drum_grid_repeat_with_chained_patterns() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.25)
.sound(DrumType::Kick, &[0, 4])
.sound(DrumType::Snare, &[2, 6])
.repeat(1);
// 2 kicks + 2 snares = 4 original, repeated once = 8 total
assert_eq!(track.events.len(), 8);
}
#[test]
fn test_drum_grid_many_drum_types() {
// Test that sound() works with various drum types
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 10, 0.1)
.sound(DrumType::Kick, &[0])
.sound(DrumType::Kick808, &[1])
.sound(DrumType::Snare, &[2])
.sound(DrumType::HiHatClosed, &[3])
.sound(DrumType::Clap, &[4])
.sound(DrumType::Tom, &[5])
.sound(DrumType::Crash, &[6])
.sound(DrumType::Cowbell, &[7])
.sound(DrumType::Djembe, &[8])
.sound(DrumType::LaserZap, &[9]);
assert_eq!(track.events.len(), 10, "Should have one of each drum type");
}
#[test]
fn test_drum_grid_duplicate_steps() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, &[0, 4, 4, 8]); // Step 4 is duplicated
// Should add all 4 events (including duplicate)
assert_eq!(track.events.len(), 4);
}
#[test]
fn test_drum_grid_overlapping_drums() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125)
.sound(DrumType::Kick, &[0])
.sound(DrumType::Snare, &[0]); // Same step as kick
// Both should be added at the same time
assert_eq!(track.events.len(), 2);
if let AudioEvent::Drum(drum1) = &track.events[0] {
if let AudioEvent::Drum(drum2) = &track.events[1] {
assert_eq!(drum1.start_time, drum2.start_time);
}
}
}
#[test]
fn test_drum_grid_fine_step_resolution() {
let mut track = Track::new();
// 32nd note grid
let _grid = DrumGrid::new(&mut track, 0.0, 32, 0.0625)
.sound(DrumType::HiHatClosed, &[0, 1, 2, 3, 4, 5, 6, 7]);
assert_eq!(track.events.len(), 8);
// Verify tight spacing
if let AudioEvent::Drum(drum1) = &track.events[0] {
if let AudioEvent::Drum(drum2) = &track.events[1] {
assert_eq!(drum2.start_time - drum1.start_time, 0.0625);
}
}
}
// ===== String Pattern Tests =====
#[test]
fn test_string_pattern_basic() {
let mut track = Track::new();
let _grid =
DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, "x---x---x---x---");
assert_eq!(track.events.len(), 4);
// Verify timing: hits at positions 0, 4, 8, 12
if let AudioEvent::Drum(drum) = &track.events[0] {
assert_eq!(drum.start_time, 0.0);
}
if let AudioEvent::Drum(drum) = &track.events[1] {
assert_eq!(drum.start_time, 0.5); // 4 * 0.125
}
if let AudioEvent::Drum(drum) = &track.events[2] {
assert_eq!(drum.start_time, 1.0); // 8 * 0.125
}
if let AudioEvent::Drum(drum) = &track.events[3] {
assert_eq!(drum.start_time, 1.5); // 12 * 0.125
}
}
#[test]
fn test_string_pattern_with_spaces() {
let mut track = Track::new();
let _grid =
DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, "x--- x--- x--- x---");
// Spaces count as steps (rests), so pattern is 19 chars
// Hits at positions 0, 5, 10, 15
assert_eq!(track.events.len(), 4);
}
#[test]
fn test_string_pattern_different_hit_chars() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.125).sound(DrumType::Snare, "xX1*----");
// All four hit markers should work
assert_eq!(track.events.len(), 4);
}
#[test]
fn test_string_pattern_different_rest_chars() {
let mut track = Track::new();
let _grid =
DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::HiHatClosed, "x-x_x.x~x0x x");
// Hits at positions: 0, 2, 4, 6, 8, 10, 12 = 7 hits
assert_eq!(track.events.len(), 7);
}
#[test]
fn test_string_pattern_all_hits() {
let mut track = Track::new();
let _grid =
DrumGrid::new(&mut track, 0.0, 8, 0.125).sound(DrumType::HiHatClosed, "xxxxxxxx");
assert_eq!(track.events.len(), 8);
}
#[test]
fn test_string_pattern_all_rests() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.125).sound(DrumType::Kick, "--------");
assert_eq!(track.events.len(), 0);
}
#[test]
fn test_string_pattern_empty() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125).sound(DrumType::Kick, "");
assert_eq!(track.events.len(), 0);
}
#[test]
fn test_string_pattern_mixed_with_array() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125)
.sound(DrumType::Kick, &[0, 4, 8, 12]) // Array syntax
.sound(DrumType::Snare, "----x-------x---") // String syntax
.sound(DrumType::HiHatClosed, "x-x-x-x-x-x-x-x-"); // String syntax
// 4 kicks + 2 snares + 8 hihats = 14
assert_eq!(track.events.len(), 14);
// Count each type
let mut kicks = 0;
let mut snares = 0;
let mut hihats = 0;
for event in &track.events {
if let AudioEvent::Drum(drum) = event {
match drum.drum_type {
DrumType::Kick => kicks += 1,
DrumType::Snare => snares += 1,
DrumType::HiHatClosed => hihats += 1,
_ => {}
}
}
}
assert_eq!(kicks, 4);
assert_eq!(snares, 2);
assert_eq!(hihats, 8);
}
#[test]
fn test_string_pattern_out_of_bounds() {
let mut track = Track::new();
// Grid is only 8 steps, but pattern is 16 chars
let _grid =
DrumGrid::new(&mut track, 0.0, 8, 0.125).sound(DrumType::Kick, "x---x---x---x---");
// Only first 2 hits should be added (positions 0 and 4)
// Positions 8 and 12 are out of bounds
assert_eq!(track.events.len(), 2);
}
#[test]
fn test_string_pattern_repeat() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.25)
.sound(DrumType::Kick, "x---x---")
.sound(DrumType::Snare, "--x---x-")
.repeat(1);
// 2 kicks + 2 snares = 4, repeated once = 8
assert_eq!(track.events.len(), 8);
}
#[test]
fn test_string_pattern_classic_rock_beat() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 16, 0.125)
.sound(DrumType::Kick, "x---x---x---x---") // Four on the floor
.sound(DrumType::Snare, "----x-------x---") // Backbeat
.sound(DrumType::HiHatClosed, "x-x-x-x-x-x-x-x-"); // Eighth notes
// 4 kicks + 2 snares + 8 hihats = 14
assert_eq!(track.events.len(), 14);
}
#[test]
fn test_string_pattern_numeric_notation() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.125).sound(DrumType::Cowbell, "10011001");
// Hits at 0, 3, 4, 7 = 4 hits
assert_eq!(track.events.len(), 4);
}
#[test]
fn test_drum_pattern_trait_into_steps() {
// Test the trait directly
let array: &[usize] = &[0, 4, 8, 12];
assert_eq!(array.into_steps(), vec![0, 4, 8, 12]);
let pattern = "x---x---";
assert_eq!(pattern.into_steps(), vec![0, 4]);
let pattern2 = "xXx1*";
assert_eq!(pattern2.into_steps(), vec![0, 1, 2, 3, 4]);
let empty = "";
assert_eq!(empty.into_steps(), Vec::<usize>::new());
let all_rests = "----";
assert_eq!(all_rests.into_steps(), Vec::<usize>::new());
}
// ===== Accent and Velocity Tests =====
#[test]
fn test_accent_basic() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.125)
.sound(DrumType::HiHatClosed, "xxxxxxxx")
.accent("x---x---"); // Accent steps 0 and 4
assert_eq!(track.events.len(), 8);
// Check velocities
for (i, event) in track.events.iter().enumerate() {
if let AudioEvent::Drum(drum) = event {
if i == 0 || i == 4 {
assert_eq!(drum.velocity, 1.0, "Step {} should be accented", i);
} else {
assert_eq!(drum.velocity, 0.5, "Step {} should be unaccented", i);
}
}
}
}
#[test]
fn test_accent_with_levels() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.125)
.sound(DrumType::HiHatClosed, "xxxx")
.accent_with_levels("x-x-", 0.9, 0.3);
// Check custom velocity levels
if let AudioEvent::Drum(drum) = &track.events[0] {
assert_eq!(drum.velocity, 0.9); // Accented
}
if let AudioEvent::Drum(drum) = &track.events[1] {
assert_eq!(drum.velocity, 0.3); // Unaccented
}
}
#[test]
fn test_velocity_explicit() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.125)
.sound(DrumType::HiHatClosed, "xxxx")
.velocity(&[1.0, 0.5, 0.7, 0.3]);
let velocities: Vec<f32> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::Drum(d) = e {
Some(d.velocity)
} else {
None
}
})
.collect();
assert_eq!(velocities, vec![1.0, 0.5, 0.7, 0.3]);
}
#[test]
fn test_ghost_notes() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 8, 0.125)
.sound(DrumType::Snare, "----x---") // Main hit at step 4
.ghost(DrumType::Snare, "-x-x----", 0.3); // Ghost notes at steps 1 and 3
assert_eq!(track.events.len(), 3);
// Count velocities
let mut full_hits = 0;
let mut ghost_hits = 0;
for event in &track.events {
if let AudioEvent::Drum(drum) = event {
if drum.velocity == 1.0 {
full_hits += 1;
} else if (drum.velocity - 0.3).abs() < 0.01 {
ghost_hits += 1;
}
}
}
assert_eq!(full_hits, 1, "Should have 1 main hit");
assert_eq!(ghost_hits, 2, "Should have 2 ghost notes");
}
#[test]
fn test_flam() {
let mut track = Track::new();
// Use step 2 so there's room for the grace note before the main hit
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.5)
.flam(DrumType::Snare, "--x-", 0.03, 0.4);
assert_eq!(track.events.len(), 2); // Grace note + main hit
// Sort events by time to check order
let mut times: Vec<(f32, f32)> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::Drum(d) = e {
Some((d.start_time, d.velocity))
} else {
None
}
})
.collect();
times.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
// Main hit should be at step 2 = 1.0s
// Grace note should be at 1.0 - 0.03 = 0.97s
assert!(times[0].0 < times[1].0, "Grace note should be before main hit");
assert!((times[0].0 - 0.97).abs() < 0.01, "Grace note at 0.97s");
assert_eq!(times[0].1, 0.4, "Grace note velocity");
assert_eq!(times[1].0, 1.0, "Main hit at 1.0s");
assert_eq!(times[1].1, 1.0, "Main hit velocity");
}
#[test]
fn test_roll() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.5)
.roll(DrumType::Snare, "x---", 4); // 4 subdivisions
assert_eq!(track.events.len(), 4); // 4 hits in the roll
// Check timing spacing
let times: Vec<f32> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::Drum(d) = e {
Some(d.start_time)
} else {
None
}
})
.collect();
// All should be within step 0 (0.0 to 0.5)
assert_eq!(times[0], 0.0);
assert_eq!(times[1], 0.125); // 0.5 / 4
assert_eq!(times[2], 0.25);
assert_eq!(times[3], 0.375);
}
#[test]
fn test_roll_zero_subdivisions() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.5)
.roll(DrumType::Snare, "x---", 0);
assert_eq!(track.events.len(), 0, "Zero subdivisions should add nothing");
}
#[test]
fn test_maybe_always() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.125)
.maybe(DrumType::Kick, "xxxx", 1.0); // 100% probability
assert_eq!(track.events.len(), 4, "All hits should be added with probability 1.0");
}
#[test]
fn test_maybe_never() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.125)
.maybe(DrumType::Kick, "xxxx", 0.0); // 0% probability
assert_eq!(track.events.len(), 0, "No hits should be added with probability 0.0");
}
#[test]
fn test_accent_multiple_drums_same_step() {
let mut track = Track::new();
let _grid = DrumGrid::new(&mut track, 0.0, 4, 0.125)
.sound(DrumType::Kick, "x---")
.sound(DrumType::HiHatClosed, "x-x-")
.accent("x---"); // Only step 0 is accented
// All drums at step 0 should be accented
for event in &track.events {
if let AudioEvent::Drum(drum) = event {
let step = (drum.start_time / 0.125).round() as usize;
if step == 0 {
assert_eq!(drum.velocity, 1.0, "Step 0 drums should be accented");
} else {
assert_eq!(drum.velocity, 0.5, "Other steps should be unaccented");
}
}
}
}
}