-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSongreader.js
69 lines (57 loc) · 2.93 KB
/
Songreader.js
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
// Given a song reader state, move the reader to the new time.
//
// - prev_state: the previous song reader state
// - song: the song being read
//
function f_next_song_reader_state(prev_state, song) {
let next_state = {...prev_state}
// Pattern commands don't transfer from state to state, so we must clear these out
next_state.pattern_commands = []
let prev_pattern = song.patterns[ prev_state.pattern_index ]
let tick_period = 60.0 / (prev_pattern.bpm * prev_pattern.ticks_per_beat)
// At end of pattern? Start next one, or repeat entire song if option provided. Set done
// if not repeating.
let next_pattern_command_index = prev_state.next_pattern_command_index
if (!prev_state.started_playing) {
// Special case: We've just started playing, so we're already on the right tick and pattern.
next_state.started_playing = true
} else if (prev_state.tick_index == prev_pattern.ticks_per_pattern - 1) {
next_state.tick_index = 0
next_state.pattern_index++
next_state.pattern_start_time = prev_state.pattern_start_time + tick_period * prev_pattern.ticks_per_pattern
next_pattern_command_index = 0
if (next_state.pattern_index == song.patterns.length) {
if (prev_state.song_reader_options.repeats) {
next_state.pattern_index = 0
} else {
next_state.done = true
}
}
} else {
// Not done pattern, so move onto next tick.
next_state.tick_index++
}
if (!next_state.done) {
let curr_pattern = song.patterns[ next_state.pattern_index ]
next_state.pattern_commands = []
// Find the patterns that apply to this current tick
while (next_pattern_command_index < curr_pattern.pattern_commands.length
&& curr_pattern.pattern_commands[ next_pattern_command_index].tick_index < next_state.tick_index ) {
next_pattern_command_index++
}
if (next_pattern_command_index < curr_pattern.pattern_commands.length
&& curr_pattern.pattern_commands[ next_pattern_command_index ].tick_index == next_state.tick_index) {
// We found a pattern command that applies to this tick.
next_state.pattern_commands.push(curr_pattern.pattern_commands[ next_pattern_command_index ])
next_pattern_command_index++
// Keep going until we go past the commands with the same index
while (next_pattern_command_index < curr_pattern.pattern_commands.length
&& curr_pattern.pattern_commands[next_pattern_command_index].tick_index == next_state.tick_index ) {
next_state.pattern_commands.push(curr_pattern.pattern_commands[ next_pattern_command_index ])
next_pattern_command_index++
}
}
next_state.next_pattern_command_index = next_pattern_command_index
}
return next_state
}