use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParamDef {
pub name: &'static str,
pub min: u16,
pub max: u16,
}
pub mod id {
pub const WAVE: usize = 0;
pub const FREQ: usize = 1;
pub const SLIDE: usize = 2;
pub const DSLIDE: usize = 3;
pub const MIN_FREQ: usize = 4;
pub const VIB_DEPTH: usize = 5;
pub const VIB_SPEED: usize = 6;
pub const ARP: usize = 7;
pub const ARP_TIME: usize = 8;
pub const ATTACK: usize = 9;
pub const SUSTAIN: usize = 10;
pub const PUNCH: usize = 11;
pub const DECAY: usize = 12;
pub const DUTY: usize = 13;
pub const DUTY_SWEEP: usize = 14;
pub const REPEAT: usize = 15;
pub const LPF: usize = 16;
pub const LPF_SWEEP: usize = 17;
pub const LPF_RES: usize = 18;
pub const HPF: usize = 19;
pub const HPF_SWEEP: usize = 20;
pub const FLANGE: usize = 21;
pub const FLANGE_SWEEP: usize = 22;
pub const VOL: usize = 23;
pub const PAN: usize = 24;
pub const COUNT: usize = 25;
}
pub mod wave {
pub const SQUARE: u16 = 0;
pub const SAW: u16 = 1;
pub const SINE: u16 = 2;
pub const NOISE: u16 = 3;
pub const TRIANGLE: u16 = 4;
}
pub const CENTER: u16 = 100;
const fn d(name: &'static str, min: u16, max: u16) -> ParamDef {
ParamDef { name, min, max }
}
pub const PARAMS: [ParamDef; id::COUNT] = [
d("wave", 0, 4),
d("freq", 0, 127),
d("slide", 0, 200),
d("dslide", 0, 200),
d("min_freq", 0, 127),
d("vib_depth", 0, 100),
d("vib_speed", 0, 100),
d("arp", 0, 96),
d("arp_time", 0, 255),
d("attack", 0, 300),
d("sustain", 0, 300),
d("punch", 0, 100),
d("decay", 1, 300),
d("duty", 1, 99),
d("duty_sweep", 0, 200),
d("repeat", 0, 255),
d("lpf", 0, 100),
d("lpf_sweep", 0, 200),
d("lpf_res", 0, 100),
d("hpf", 0, 100),
d("hpf_sweep", 0, 200),
d("flange", 0, 100),
d("flange_sweep", 0, 200),
d("vol", 0, 100),
d("pan", 0, 16),
];
pub fn param_index(name: &str) -> Option<usize> {
PARAMS.iter().position(|p| p.name == name)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Category {
Coin = 0,
Laser = 1,
Explosion = 2,
Powerup = 3,
Hit = 4,
Jump = 5,
Select = 6,
Tone = 7,
}
impl Category {
pub const ALL: [Category; 8] = [
Category::Coin,
Category::Laser,
Category::Explosion,
Category::Powerup,
Category::Hit,
Category::Jump,
Category::Select,
Category::Tone,
];
pub fn from_index(n: u8) -> Option<Category> {
Self::ALL.get(n as usize).copied()
}
pub fn name(self) -> &'static str {
match self {
Category::Coin => "coin",
Category::Laser => "laser",
Category::Explosion => "explosion",
Category::Powerup => "powerup",
Category::Hit => "hit",
Category::Jump => "jump",
Category::Select => "select",
Category::Tone => "tone",
}
}
pub fn from_name(name: &str) -> Option<Category> {
Self::ALL.iter().copied().find(|c| c.name() == name)
}
pub const fn preset(self) -> SfxParams {
PRESETS[self as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SfxParams {
values: [u16; id::COUNT],
}
const fn preset(v: [u16; id::COUNT]) -> SfxParams {
SfxParams { values: v }
}
const PRESETS: [SfxParams; 8] = [
preset([
0, 84, 100, 100, 0, 0, 0, 53, 6, 0, 4, 45, 26, 50, 100, 0, 100, 100, 0, 0, 100, 0, 100, 50,
8,
]),
preset([
0, 100, 52, 100, 40, 0, 0, 48, 0, 0, 12, 20, 18, 30, 120, 0, 100, 100, 0, 20, 100, 0, 100,
45, 8,
]),
preset([
3, 50, 80, 100, 0, 0, 0, 48, 0, 0, 20, 70, 60, 50, 100, 0, 90, 70, 10, 0, 100, 0, 100, 60,
8,
]),
preset([
0, 64, 128, 100, 0, 10, 30, 48, 0, 0, 25, 0, 30, 40, 100, 9, 100, 100, 0, 0, 100, 0, 100,
45, 8,
]),
preset([
1, 76, 40, 100, 0, 0, 0, 48, 0, 0, 3, 30, 14, 50, 100, 0, 100, 100, 0, 30, 100, 0, 100, 50,
8,
]),
preset([
0, 62, 140, 100, 0, 0, 0, 48, 0, 0, 10, 0, 20, 35, 100, 0, 85, 100, 0, 20, 100, 0, 100, 45,
8,
]),
preset([
0, 88, 100, 100, 0, 0, 0, 48, 0, 0, 3, 0, 5, 50, 100, 0, 100, 100, 0, 10, 100, 0, 100, 45,
8,
]),
preset([
0, 60, 100, 100, 0, 0, 0, 48, 0, 0, 15, 0, 10, 50, 100, 0, 100, 100, 0, 0, 100, 0, 100, 50,
8,
]),
];
impl Default for SfxParams {
fn default() -> Self {
Category::Coin.preset()
}
}
impl SfxParams {
pub fn get(&self, i: usize) -> u16 {
self.values.get(i).copied().unwrap_or(0)
}
pub fn set(&mut self, i: usize, v: u32) {
if let (Some(slot), Some(def)) = (self.values.get_mut(i), PARAMS.get(i)) {
*slot = v.clamp(def.min as u32, def.max as u32) as u16;
}
}
pub fn set_by_name(&mut self, name: &str, v: u32) -> bool {
match param_index(name) {
Some(i) => {
self.set(i, v);
true
}
None => false,
}
}
pub const fn values_const(&self) -> [u16; id::COUNT] {
self.values
}
pub fn values(&self) -> &[u16; id::COUNT] {
&self.values
}
pub fn length_samples(&self, sample_rate: u32) -> u32 {
let t =
self.get(id::ATTACK) as u64 + self.get(id::SUSTAIN) as u64 + self.get(id::DECAY) as u64;
(t * sample_rate as u64 / 100).max(1) as u32
}
pub fn write_text(&self, base: Category, w: &mut impl fmt::Write) -> fmt::Result {
write!(w, "@{}", base as u8)?;
let b = base.preset();
for (i, def) in PARAMS.iter().enumerate() {
if self.values[i] != b.values[i] {
write!(w, " %{}={}", def.name, self.values[i])?;
}
}
Ok(())
}
pub fn write_text_auto(&self, w: &mut impl fmt::Write) -> fmt::Result {
self.write_text(self.nearest_category(), w)
}
pub fn nearest_category(&self) -> Category {
let mut best = Category::Coin;
let mut best_n = usize::MAX;
for c in Category::ALL {
let p = c.preset();
let n = (0..id::COUNT)
.filter(|&i| p.values[i] != self.values[i])
.count();
if n < best_n {
best = c;
best_n = n;
}
}
best
}
pub fn parse(text: &str) -> Result<SfxParams, ParseError<'_>> {
let mut p = SfxParams::default();
for tok in text.split_whitespace() {
if let Some(n) = tok.strip_prefix('@') {
let c = n
.parse::<u8>()
.ok()
.and_then(Category::from_index)
.ok_or(ParseError::BadTone(tok))?;
p = c.preset();
} else if let Some(kv) = tok.strip_prefix('%') {
let (k, v) = kv.split_once('=').ok_or(ParseError::BadToken(tok))?;
let i = param_index(k).ok_or(ParseError::UnknownParam(tok))?;
let v: u32 = v.parse().map_err(|_| ParseError::BadValue(tok))?;
let def = PARAMS[i];
if v < def.min as u32 || v > def.max as u32 {
return Err(ParseError::OutOfRange(tok));
}
p.values[i] = v as u16;
} else {
return Err(ParseError::BadToken(tok));
}
}
Ok(p)
}
#[cfg(feature = "alloc")]
pub fn to_text(&self) -> alloc::string::String {
let mut s = alloc::string::String::new();
let _ = self.write_text_auto(&mut s);
s
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError<'a> {
BadTone(&'a str),
UnknownParam(&'a str),
BadValue(&'a str),
OutOfRange(&'a str),
BadToken(&'a str),
}
impl crate::text::Localized for ParseError<'_> {
fn text_key(&self) -> &'static str {
match self {
ParseError::BadTone(_) => "err-params-bad-tone",
ParseError::UnknownParam(_) => "err-params-unknown-param",
ParseError::BadValue(_) => "err-params-bad-value",
ParseError::OutOfRange(_) => "err-params-out-of-range",
ParseError::BadToken(_) => "err-params-bad-token",
}
}
fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
let (ParseError::BadTone(t)
| ParseError::UnknownParam(t)
| ParseError::BadValue(t)
| ParseError::OutOfRange(t)
| ParseError::BadToken(t)) = self;
f("word", crate::text::TextArg::Str(t));
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::text::table::CATALOGS
}
}
impl core::fmt::Display for ParseError<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presets_are_in_range() {
for c in Category::ALL {
let p = c.preset();
for (i, def) in PARAMS.iter().enumerate() {
let v = p.get(i);
assert!(
v >= def.min && v <= def.max,
"{} {}={v}",
c.name(),
def.name
);
}
}
}
#[test]
fn names_are_unique() {
for (i, a) in PARAMS.iter().enumerate() {
assert_eq!(param_index(a.name), Some(i));
}
}
#[test]
fn text_round_trips() {
struct Buf([u8; 512], usize);
impl fmt::Write for Buf {
fn write_str(&mut self, s: &str) -> fmt::Result {
let b = s.as_bytes();
self.0[self.1..self.1 + b.len()].copy_from_slice(b);
self.1 += b.len();
Ok(())
}
}
let mut p = Category::Laser.preset();
p.set(id::FREQ, 90);
p.set(id::FLANGE, 30);
let mut b = Buf([0; 512], 0);
p.write_text_auto(&mut b).unwrap();
let s = core::str::from_utf8(&b.0[..b.1]).unwrap();
assert_eq!(s, "@1 %freq=90 %flange=30");
assert_eq!(SfxParams::parse(s).unwrap(), p);
}
#[test]
fn parse_reports_errors() {
assert_eq!(SfxParams::parse("@9"), Err(ParseError::BadTone("@9")));
assert_eq!(
SfxParams::parse("%nope=1"),
Err(ParseError::UnknownParam("%nope=1"))
);
assert_eq!(
SfxParams::parse("%freq=200"),
Err(ParseError::OutOfRange("%freq=200"))
);
assert_eq!(SfxParams::parse("c4"), Err(ParseError::BadToken("c4")));
assert_eq!(SfxParams::parse("").unwrap(), SfxParams::default());
}
}