desc:Trance Kick
// A kick drum from first principles:
//   1. a sine wave whose PITCH starts high and falls fast (the "thump")
//   2. multiplied by a VOLUME envelope that decays away
//   3. optionally squashed by a soft clipper for extra harmonics
// Every incoming MIDI note-on triggers the drum; the note number is ignored.

slider1:150<40,400,1>Start pitch (Hz)
slider2:55<30,80,0.5>End pitch (Hz)
slider3:35<5,200,1>Pitch fall time (ms)
slider4:300<80,800,1>Decay time (ms)
slider5:6<0,24,0.5>Drive (dB)
slider6:-3<-24,0,0.5>Output (dB)

in_pin:none
out_pin:Left
out_pin:Right

@init
// Runs once when the effect loads: set up variables and helper functions.
ev_off = 0;      // event queue: up to 16 note-ons per audio block
ev_vel = 16;
function tanh_(x) local(e) (
  x = min(max(x, -20), 20);
  e = exp(2 * x);
  (e - 1) / (e + 1);
);

playing = 0;
t = 0;
phase = 0;

@slider
// Runs whenever a slider moves: turn slider values into ready-to-use numbers.
pitch_tau = slider3 * 0.001;
amp_tau = slider4 * 0.001 / 6.9;   // 6.9 time-constants = 60 dB drop
drive = 10 ^ (slider5 / 20);
outgain = 10 ^ (slider6 / 20);
drive_norm = 1 / tanh_(drive);

@block
// Runs before each chunk of audio: read the incoming MIDI notes here.
blk_pos = 0;
ev_n = 0;
ev_i = 0;
while (midirecv(offs, m1, m2, m3)) (
  (m1 & 0xF0) == 0x90 && m3 > 0 && ev_n < 16 ? (
    ev_off[ev_n] = offs;
    ev_vel[ev_n] = m3 / 127;
    ev_n += 1;
  );
);

@sample
// Runs once for EVERY audio sample (44,100+ times a second): make the sound here.
while (ev_i < ev_n && ev_off[ev_i] <= blk_pos) (
  vel = ev_vel[ev_i];
  playing = 1;
  t = 0;
  phase = 0;
  ev_i += 1;
);

s = 0;
playing ? (
  freq = slider2 + (slider1 - slider2) * exp(-t / pitch_tau);
  phase += 2 * $pi * freq / srate;
  phase > 2 * $pi ? phase -= 2 * $pi;
  s = sin(phase) * exp(-t / amp_tau);
  s = tanh_(s * drive) * drive_norm;
  s *= vel * outgain;
  t += 1 / srate;
  t > slider4 * 0.001 * 1.5 ? playing = 0;
);
spl0 = s;
spl1 = s;
blk_pos += 1;
