use crate::synth::waveguide::{Biquad, Noise};
const LANES: usize = 8;
const MAX_MODE_HZ: f32 = 13_000.0;
const CULL_LEVEL: f32 = 5e-5;
const MF_VELOCITY: f32 = 0.4;
const HIT_SCATTER_DB: f32 = 3.0;
const RING_SCATTER: f32 = 0.3;
const WOBBLE_STEP: f32 = 0.14;
const SPLIT_HZ: (f32, f32) = (0.7, 4.0);
const FLOOR_Q: f32 = 1.6;
const FLOOR_ORDER: usize = 3;
const CHOKE_T60: f32 = 0.05;
const EMPTY: u32 = u32::MAX;
#[derive(Clone, Copy, Debug)]
pub struct CymbalBand {
pub hz: f32,
pub db: f32,
pub bloom: f32,
pub tau: f32,
}
#[derive(Clone, Copy, Debug)]
pub struct CymbalSpec {
pub seed: u32,
pub lo: f32,
pub hi: f32,
pub density: f32,
pub scatter_db: f32,
pub floor_db: f32,
pub bands: &'static [CymbalBand],
pub ring: f32,
pub ring_corner: f32,
pub brightness: f32,
pub noise_hz: f32,
pub stick: f32,
pub stick_tau: f32,
pub sizzle: f32,
pub sizzle_t60: f32,
pub drive: f32,
pub wobble: f32,
}
#[derive(Clone, Copy, Debug)]
struct Mode {
f: f32,
amp: f32,
c: (f32, f32),
c_onset: (f32, f32),
bloom: f32,
}
#[derive(Clone, Debug)]
struct FloorBand {
hz: f32,
bp: [Biquad; FLOOR_ORDER],
gain: f32,
bloom: f32,
ring: f32,
onset: f32,
r: f32,
r_onset: f32,
}
#[derive(Clone, Debug)]
struct RotorBlock {
re: [f32; LANES],
im: [f32; LANES],
cr: [f32; LANES],
ci: [f32; LANES],
tag: [u32; LANES],
}
impl Default for RotorBlock {
fn default() -> Self {
Self {
re: [0.0; LANES],
im: [0.0; LANES],
cr: [0.0; LANES],
ci: [0.0; LANES],
tag: [EMPTY; LANES],
}
}
}
#[derive(Clone, Debug)]
pub struct Cymbal {
spec: CymbalSpec,
sr: f32,
modes: Vec<Mode>,
blocks: Vec<RotorBlock>,
floor: Vec<FloorBand>,
noise: Noise,
hp: Biquad,
stick_env: f32,
stick_coef: f32,
sizzle_env: f32,
sizzle_coef: f32,
wob_from: [f32; LANES],
wob_to: [f32; LANES],
wob_t: f32,
wob_inc: f32,
level: f32,
}
struct Rng(u32);
impl Rng {
fn new(seed: u32) -> Self {
let mut s = seed.wrapping_mul(0x9E37_79B9) ^ 0x85EB_CA6B;
s ^= s >> 16;
Self(s.max(1))
}
fn next(&mut self) -> f32 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
self.0 = x;
(x >> 8) as f32 / 16_777_216.0
}
fn bell(&mut self) -> f32 {
(self.next() + self.next() + self.next()) * (2.0 / 3.0) - 1.0
}
}
fn shape(bands: &[CymbalBand], hz: f32) -> (f32, f32, f32) {
let first = bands[0];
if hz <= first.hz {
return (first.db, first.bloom, first.tau);
}
for w in bands.windows(2) {
let (a, b) = (w[0], w[1]);
if hz <= b.hz {
let t = (hz / a.hz).ln() / (b.hz / a.hz).ln();
let mix = |x: f32, y: f32| x + (y - x) * t;
return (mix(a.db, b.db), mix(a.bloom, b.bloom), mix(a.tau, b.tau));
}
}
let last = bands[bands.len() - 1];
(last.db, last.bloom, last.tau)
}
fn t60_coef(t60: f32, sr: f32) -> f32 {
10f32.powf(-3.0 / (t60.max(0.01) * sr))
}
fn onset_coef(r: f32, tau: f32, sr: f32) -> f32 {
r * (-1.0 / (tau.max(1e-3) * sr)).exp()
}
fn noise_power(bp: &Biquad, sr: f32) -> f32 {
let steps = 1_000;
let (lo, hi) = (10f32, sr * 0.5);
let k = (hi / lo).ln() / steps as f32;
let sum: f32 = (0..steps)
.map(|i| {
let f = lo * ((i as f32 + 0.5) * k).exp();
let (re, im) = bp.response(f, sr);
(re * re + im * im).powi(FLOOR_ORDER as i32) * f * k
})
.sum();
(1.0 / 3.0) * 2.0 / sr * sum
}
fn rotor(r: f32, f: f32, sr: f32) -> (f32, f32) {
let w = std::f32::consts::TAU * f / sr;
(r * w.cos(), r * w.sin())
}
impl Cymbal {
pub fn new(spec: &CymbalSpec, sr: f32) -> Self {
let hi = spec.hi.min(MAX_MODE_HZ).min(sr * 0.45);
let slot = 100.0 / spec.density;
let count = ((hi - spec.lo) / slot).max(0.0) as usize;
let ring_t60 = |f: f32| spec.ring / (1.0 + (f / spec.ring_corner).powi(2));
let mut rng = Rng::new(spec.seed);
let mut modes = Vec::with_capacity(count);
for k in 0..count {
let f = spec.lo + (k as f32 + rng.next()) * slot;
let (db, bloom, tau) = shape(spec.bands, f);
let amp = 10f32.powf((db + spec.scatter_db * rng.bell()) / 20.0);
let r = t60_coef(ring_t60(f) * (1.0 + RING_SCATTER * rng.bell()), sr);
let split = SPLIT_HZ.0 + (SPLIT_HZ.1 - SPLIT_HZ.0) * rng.next();
let partner = 0.4 + 0.6 * rng.next();
for (f, amp) in [(f, amp), (f + split, amp * partner)] {
modes.push(Mode {
f,
amp,
c: rotor(r, f, sr),
c_onset: rotor(onset_coef(r, tau, sr), f, sr),
bloom,
});
}
}
let power: f32 = modes.iter().map(|m| m.amp * m.amp * 0.5).sum();
let norm = 1.0 / power.max(1e-12).sqrt();
for m in &mut modes {
m.amp *= norm;
}
let floor_lin = 10f32.powf(spec.floor_db / 10.0);
let edge = 2f32.powf(0.25);
let mut floor = Vec::new();
let mut hz = spec.lo * edge;
while hz / edge < hi {
let p: f32 = modes
.iter()
.filter(|m| m.f >= hz / edge && m.f < hz * edge)
.map(|m| m.amp * m.amp * 0.5)
.sum();
let bp = [Biquad::bandpass(hz, FLOOR_Q, sr); FLOOR_ORDER];
let unit = noise_power(&bp[0], sr);
let (_, bloom, tau) = shape(spec.bands, hz);
let r = t60_coef(ring_t60(hz), sr);
floor.push(FloorBand {
hz,
bp,
gain: (floor_lin * p / unit).sqrt(),
bloom,
ring: 0.0,
onset: 0.0,
r,
r_onset: onset_coef(r, tau, sr),
});
hz *= edge * edge;
}
Self {
spec: *spec,
sr,
modes,
blocks: Vec::new(),
floor,
noise: Noise::new(spec.seed),
hp: Biquad::highpass(spec.noise_hz, 0.7, sr),
stick_env: 0.0,
stick_coef: (-1.0 / (spec.stick_tau.max(1e-4) * sr)).exp(),
sizzle_env: 0.0,
sizzle_coef: t60_coef(spec.sizzle_t60, sr),
wob_from: [0.0; LANES],
wob_to: [0.0; LANES],
wob_t: 1.0,
wob_inc: 1.0 / (WOBBLE_STEP * sr),
level: 0.0,
}
}
pub fn strike(&mut self, velocity: f32, hit: u64) {
let spec = &self.spec;
let vel_ratio = (velocity.max(0.01) / MF_VELOCITY).sqrt();
let corner = spec.brightness * vel_ratio;
let tilt = |f: f32| {
((1.0 + (f / spec.brightness).powi(2)) / (1.0 + (f / corner).powi(2)))
.sqrt()
};
let bloom = |b: f32| {
if b > 0.0 {
(b * vel_ratio.sqrt()).min(0.9)
} else {
b
}
};
let mut state = vec![(0.0f32, 0.0f32); self.modes.len() * 2];
for blk in &self.blocks {
for j in 0..LANES {
if blk.tag[j] != EMPTY {
state[blk.tag[j] as usize] = (blk.re[j], blk.im[j]);
}
}
}
let mut rng = Rng::new(spec.seed ^ (hit as u32) ^ ((hit >> 32) as u32));
let mut rotors = Vec::with_capacity(self.modes.len() * 2);
for (k, m) in self.modes.iter().enumerate() {
let a = velocity
* m.amp
* tilt(m.f)
* 10f32.powf(HIT_SCATTER_DB * rng.bell() / 20.0);
let (s, c) = (std::f32::consts::TAU * rng.next()).sin_cos();
let (re, im) = state[2 * k];
rotors.push((2 * k as u32, re + a * c, im + a * s, m.c));
let b = bloom(m.bloom);
let (re, im) = state[2 * k + 1];
if b != 0.0 || re != 0.0 || im != 0.0 {
rotors.push((
2 * k as u32 + 1,
re - b * a * c,
im - b * a * s,
m.c_onset,
));
}
}
self.blocks = pack(&rotors);
for band in &mut self.floor {
let a = velocity * band.gain * tilt(band.hz);
band.ring += a;
band.onset -= bloom(band.bloom) * a;
}
self.stick_env += velocity * spec.stick * vel_ratio;
self.sizzle_env += velocity * spec.sizzle * vel_ratio.min(1.5);
self.level = 1.0;
}
#[inline]
pub fn tick(&mut self) -> f32 {
self.wob_t += self.wob_inc;
if self.wob_t >= 1.0 {
self.wob_t -= 1.0;
self.wob_from = self.wob_to;
for w in &mut self.wob_to {
*w = self.spec.wobble * self.noise.tick();
}
}
let k = 0.5 - 0.5 * (std::f32::consts::PI * self.wob_t).cos();
let rot: [(f32, f32); LANES] = std::array::from_fn(|j| {
(self.wob_from[j] + (self.wob_to[j] - self.wob_from[j]) * k).sin_cos()
});
let mut out = step_blocks(&mut self.blocks, &rot);
let white = self.noise.tick();
for b in &mut self.floor {
let y = b.bp.iter_mut().fold(white, |x, f| f.tick(x));
out += y * (b.ring + b.onset);
b.ring *= b.r;
b.onset *= b.r_onset;
}
let env = self.stick_env + self.sizzle_env;
if env > 1e-6 {
out += self.hp.tick(white) * env;
self.stick_env *= self.stick_coef;
self.sizzle_env *= self.sizzle_coef;
}
let d = self.spec.drive;
if d > 0.0 {
out = (out * d).tanh() / d;
}
out
}
pub fn damp(&mut self) {
let d = 10f32.powf(-3.0 / (CHOKE_T60 * self.sr));
for blk in &mut self.blocks {
for j in 0..LANES {
blk.cr[j] *= d;
blk.ci[j] *= d;
}
}
for b in &mut self.floor {
b.r *= d;
b.r_onset *= d;
}
self.stick_coef *= d;
self.sizzle_coef *= d;
}
pub fn cull(&mut self) {
let floor: f32 = self.floor.iter().map(|b| (b.ring + b.onset).abs()).sum();
self.level =
cull_blocks(&mut self.blocks) + floor + self.stick_env + self.sizzle_env;
}
pub fn is_silent(&self) -> bool {
self.level < 1e-4
}
}
#[inline]
#[allow(clippy::needless_range_loop)]
fn step_blocks(blocks: &mut [RotorBlock], rot: &[(f32, f32); LANES]) -> f32 {
let s: [f32; LANES] = std::array::from_fn(|j| rot[j].0);
let c: [f32; LANES] = std::array::from_fn(|j| rot[j].1);
let mut acc = [0.0f32; LANES];
for blk in blocks {
for j in 0..LANES {
let (r, i) = (blk.re[j], blk.im[j]);
blk.re[j] = r * blk.cr[j] - i * blk.ci[j];
blk.im[j] = r * blk.ci[j] + i * blk.cr[j];
acc[j] += blk.im[j] * c[j] + blk.re[j] * s[j];
}
}
acc.iter().sum()
}
fn lane(tag: u32) -> usize {
(tag / 2) as usize % LANES
}
fn pack(rotors: &[(u32, f32, f32, (f32, f32))]) -> Vec<RotorBlock> {
let mut blocks: Vec<RotorBlock> = Vec::new();
let mut fill = [0usize; LANES];
for &(tag, re, im, (cr, ci)) in rotors {
let j = lane(tag);
if fill[j] == blocks.len() {
blocks.push(RotorBlock::default());
}
let blk = &mut blocks[fill[j]];
fill[j] += 1;
blk.tag[j] = tag;
blk.re[j] = re;
blk.im[j] = im;
blk.cr[j] = cr;
blk.ci[j] = ci;
}
blocks
}
fn cull_blocks(blocks: &mut Vec<RotorBlock>) -> f32 {
let mut live = Vec::new();
let mut level = 0.0;
for blk in blocks.iter() {
for j in 0..LANES {
let mag = blk.re[j].hypot(blk.im[j]);
if blk.tag[j] != EMPTY && mag > CULL_LEVEL {
level += mag;
live.push((blk.tag[j], blk.re[j], blk.im[j], (blk.cr[j], blk.ci[j])));
}
}
}
if live.len().div_ceil(LANES) < blocks.len() {
let packed = pack(&live);
if packed.len() < blocks.len() {
*blocks = packed;
}
}
level
}