use super::*;
pub(super) const SHOT_SLOTS: usize = MAX_SHOT_VOICES + 2;
pub(super) const MAX_SHOT_RENDER_SECS: u32 = 20;
#[derive(Debug, Clone, Copy)]
pub(super) struct ShotVoice {
pub(super) id: Option<u8>,
pub(super) pos: u32,
pub(super) gain: f32,
pub(super) track: u8,
pub(super) order: u32,
pub(super) fade: u32,
}
impl ShotVoice {
pub(super) const EMPTY: Self = ShotVoice {
id: None,
pos: 0,
gain: 0.0,
track: 0,
order: 0,
fade: 0,
};
}
pub(super) fn render_shots(song: &Song, sample_rate: u32) -> Vec<Arc<[[f32; 2]]>> {
let max = (sample_rate as usize).saturating_mul(MAX_SHOT_RENDER_SECS as usize);
song.shots
.iter()
.map(|shot| {
let s = &shot.song;
let Some(spec) = synth::find(synth::all(), &s.synth.name) else {
return Arc::from(Vec::new());
};
let synth = (spec.create)(&s.synth, sample_rate, s.tracks.len());
let mut pcm = render_inner(s, sample_rate, synth, 0);
pcm.truncate(max);
Arc::from(pcm)
})
.collect()
}
impl Player {
pub(super) fn shots_active(&self) -> bool {
self.shot_voices.iter().any(|v| v.id.is_some())
}
pub(super) fn stop_shots(&mut self) {
self.shot_voices = [ShotVoice::EMPTY; SHOT_SLOTS];
}
pub(super) fn start_shot(&mut self, id: u8, vel: u8, track: u8) {
if self.shot_pcm.get(id as usize).is_none_or(|p| p.is_empty()) {
return;
}
let active = self
.shot_voices
.iter()
.filter(|v| v.id.is_some() && v.fade == 0)
.count();
if active >= MAX_SHOT_VOICES {
if let Some(old) = self
.shot_voices
.iter_mut()
.filter(|v| v.id.is_some() && v.fade == 0)
.min_by_key(|v| v.order)
{
old.fade = self.shot_fade;
}
}
let slot = match self.shot_voices.iter().position(|v| v.id.is_none()) {
Some(i) => i,
None => self
.shot_voices
.iter()
.enumerate()
.min_by_key(|(_, v)| (v.fade == 0, v.order))
.map_or(0, |(i, _)| i),
};
self.shot_order = self.shot_order.wrapping_add(1);
self.shot_voices[slot] = ShotVoice {
id: Some(id),
pos: 0,
gain: vel.min(15) as f32 / 15.0,
track,
order: self.shot_order,
fade: 0,
};
if self.song.shots.get(id as usize).is_some_and(|s| s.duck) {
self.synth.shot_duck();
}
}
pub(super) fn mix_shots(&mut self, audible: u32) -> [f32; 2] {
let mut out = [0.0f32; 2];
let fade_len = self.shot_fade as f32;
for v in self.shot_voices.iter_mut() {
let Some(id) = v.id else {
continue;
};
let Some(pcm) = self.shot_pcm.get(id as usize) else {
*v = ShotVoice::EMPTY;
continue;
};
let Some(&[l, r]) = pcm.get(v.pos as usize) else {
*v = ShotVoice::EMPTY;
continue;
};
let mut g = v.gain;
if v.fade > 0 {
g *= v.fade as f32 / fade_len;
v.fade -= 1;
if v.fade == 0 {
*v = ShotVoice::EMPTY;
continue;
}
}
if v.track < 32 && audible & (1 << v.track) != 0 {
out[0] += l * g;
out[1] += r * g;
}
v.pos += 1;
}
out
}
}