pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! 現代系の効果音のパラメータ:4 つの層を持つパッチと、全体の処理。カテゴリのプリセットと、
//! テキスト(`@n %名前=値 …`)との相互変換。
//!
//! パラメータはすべて整数で、MML の `%名前=値` と同じ名前・同じ値を使う。層のパラメータは
//! `l1_src` のように `l層の番号_` を前に付ける。

use std::fmt;

/// 層の数。
pub const LAYERS: usize = 4;
/// 1 つの層のパラメータの数。
pub const LAYER_PARAMS: usize = 12;
/// パラメータの総数。
pub const COUNT: usize = LAYERS * LAYER_PARAMS + 6;

/// パラメータの説明。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParamDef {
    /// `%` の後ろに書く名前。
    pub name: &'static str,
    pub min: u16,
    pub max: u16,
    /// 既定値(どの層も鳴らない、素の状態)。
    pub default: u16,
}

/// 層の中のパラメータの並び(`層の番号 × LAYER_PARAMS + これ` が番号)。
pub mod layer {
    pub const SRC: usize = 0;
    pub const LEVEL: usize = 1;
    pub const PITCH: usize = 2;
    pub const PEND: usize = 3;
    pub const PTIME: usize = 4;
    pub const ATTACK: usize = 5;
    pub const DECAY: usize = 6;
    pub const DELAY: usize = 7;
    pub const FTYPE: usize = 8;
    pub const CUT: usize = 9;
    pub const CEND: usize = 10;
    pub const RES: usize = 11;
}

/// 全体のパラメータの番号。
pub mod master {
    use super::{LAYERS, LAYER_PARAMS};
    pub const DRIVE: usize = LAYERS * LAYER_PARAMS;
    pub const REV: usize = DRIVE + 1;
    pub const REV_SIZE: usize = DRIVE + 2;
    pub const LENGTH: usize = DRIVE + 3;
    pub const VOL: usize = DRIVE + 4;
    pub const PAN: usize = DRIVE + 5;
}

/// 層の音源(`%lN_src` の値)。
pub mod source {
    pub const OFF: u16 = 0;
    pub const SINE: u16 = 1;
    pub const TRIANGLE: u16 = 2;
    pub const SAW: u16 = 3;
    pub const SQUARE: u16 = 4;
    pub const NOISE: u16 = 5;
    pub const METAL: u16 = 6;
}

/// 層 `l`(0〜3)のパラメータ `p`([`layer`])の番号。
pub const fn layer_param(l: usize, p: usize) -> usize {
    l * LAYER_PARAMS + p
}

const fn d(name: &'static str, min: u16, max: u16, default: u16) -> ParamDef {
    ParamDef {
        name,
        min,
        max,
        default,
    }
}

/// すべてのパラメータ(層 1〜4 の 12 個ずつと、全体の 6 個)。`(名前, 最小, 最大, 既定, 説明)`。
pub const PARAMS: [ParamDef; COUNT] = [
    d("l1_src", 0, 6, 0),
    d("l1_level", 0, 100, 80),
    d("l1_pitch", 0, 127, 60),
    d("l1_pend", 0, 127, 60),
    d("l1_ptime", 1, 2000, 100),
    d("l1_attack", 0, 1000, 0),
    d("l1_decay", 1, 5000, 300),
    d("l1_delay", 0, 1000, 0),
    d("l1_ftype", 0, 2, 0),
    d("l1_cut", 0, 135, 135),
    d("l1_cend", 0, 135, 135),
    d("l1_res", 0, 100, 0),
    d("l2_src", 0, 6, 0),
    d("l2_level", 0, 100, 80),
    d("l2_pitch", 0, 127, 60),
    d("l2_pend", 0, 127, 60),
    d("l2_ptime", 1, 2000, 100),
    d("l2_attack", 0, 1000, 0),
    d("l2_decay", 1, 5000, 300),
    d("l2_delay", 0, 1000, 0),
    d("l2_ftype", 0, 2, 0),
    d("l2_cut", 0, 135, 135),
    d("l2_cend", 0, 135, 135),
    d("l2_res", 0, 100, 0),
    d("l3_src", 0, 6, 0),
    d("l3_level", 0, 100, 80),
    d("l3_pitch", 0, 127, 60),
    d("l3_pend", 0, 127, 60),
    d("l3_ptime", 1, 2000, 100),
    d("l3_attack", 0, 1000, 0),
    d("l3_decay", 1, 5000, 300),
    d("l3_delay", 0, 1000, 0),
    d("l3_ftype", 0, 2, 0),
    d("l3_cut", 0, 135, 135),
    d("l3_cend", 0, 135, 135),
    d("l3_res", 0, 100, 0),
    d("l4_src", 0, 6, 0),
    d("l4_level", 0, 100, 80),
    d("l4_pitch", 0, 127, 60),
    d("l4_pend", 0, 127, 60),
    d("l4_ptime", 1, 2000, 100),
    d("l4_attack", 0, 1000, 0),
    d("l4_decay", 1, 5000, 300),
    d("l4_delay", 0, 1000, 0),
    d("l4_ftype", 0, 2, 0),
    d("l4_cut", 0, 135, 135),
    d("l4_cend", 0, 135, 135),
    d("l4_res", 0, 100, 0),
    d("drive", 0, 100, 0),
    d("rev", 0, 100, 0),
    d("rev_size", 0, 100, 50),
    d("length", 10, 400, 100),
    d("vol", 0, 100, 70),
    d("pan", 0, 16, 8),
];

/// 名前でパラメータの番号を探す。
pub fn param_index(name: &str) -> Option<usize> {
    PARAMS.iter().position(|p| p.name == name)
}

/// 効果音のカテゴリ。MML の音色番号 `@n` と同じ順。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Category {
    /// レーザー。
    Laser = 0,
    /// 銃・ブラスターの発射音。
    Blaster = 1,
    /// 爆発。
    Explosion = 2,
    /// 打撃・当たった音。
    Impact = 3,
    /// アイテムを取る音。
    Pickup = 4,
    /// UI のクリック音。
    Click = 5,
    /// UI の決定音。
    Confirm = 6,
    /// 風切り音(ウーッシュ)。
    Whoosh = 7,
    /// チャージ(ためる音)。
    Charge = 8,
    /// 電撃(ザップ)。
    Zap = 9,
}

/// プリセットの中身(素の状態からの差)。並びは [`Category`] と同じ。
const PRESET_TEXT: [&str; 10] = [
    // レーザー:鋸歯状波と矩形波が下がり、頭にノイズ
    "%l1_src=3 %l1_level=80 %l1_pitch=100 %l1_pend=64 %l1_ptime=180 %l1_decay=220 %l1_cut=120 %l1_cend=82 %l1_res=30 \
     %l2_src=4 %l2_level=45 %l2_pitch=112 %l2_pend=76 %l2_ptime=150 %l2_decay=160 \
     %l3_src=5 %l3_level=25 %l3_decay=40 %l3_ftype=1 %l3_cut=100 %l3_cend=100 \
     %drive=20 %rev=20",
    // ブラスター:ノイズの破裂と、低い胴鳴り
    "%l1_src=5 %l1_level=90 %l1_decay=120 %l1_cut=110 %l1_cend=80 \
     %l2_src=1 %l2_level=90 %l2_pitch=76 %l2_pend=40 %l2_ptime=60 %l2_decay=150 \
     %l3_src=4 %l3_level=40 %l3_pitch=96 %l3_pend=60 %l3_ptime=40 %l3_decay=50 \
     %drive=40 %rev=25",
    // 爆発:長いノイズ、沈むサブの爆音、頭の破裂音、遅れて降る破片
    "%l1_src=5 %l1_level=100 %l1_attack=5 %l1_decay=1800 %l1_cut=100 %l1_cend=60 %l1_res=10 \
     %l2_src=1 %l2_level=100 %l2_pitch=48 %l2_pend=28 %l2_ptime=400 %l2_decay=900 \
     %l3_src=5 %l3_level=60 %l3_decay=150 %l3_ftype=2 %l3_cut=105 %l3_cend=105 %l3_res=20 \
     %l4_src=5 %l4_level=35 %l4_delay=120 %l4_decay=1200 %l4_ftype=2 %l4_cut=90 %l4_cend=70 \
     %drive=50 %rev=40 %rev_size=70",
    // 打撃:沈む胴鳴り、乾いた破裂音、金属の響き
    "%l1_src=1 %l1_level=100 %l1_pitch=60 %l1_pend=36 %l1_ptime=50 %l1_decay=250 \
     %l2_src=5 %l2_level=70 %l2_decay=60 %l2_ftype=2 %l2_cut=100 %l2_cend=100 %l2_res=20 \
     %l3_src=6 %l3_level=25 %l3_pitch=84 %l3_pend=84 %l3_decay=120 %l3_ftype=1 %l3_cut=96 %l3_cend=96 \
     %drive=30 %rev=15",
    // アイテム:2 音の上がる和音にきらめきを重ねる
    "%l1_src=2 %l1_level=70 %l1_pitch=84 %l1_pend=84 %l1_decay=250 \
     %l2_src=1 %l2_level=80 %l2_pitch=91 %l2_pend=91 %l2_delay=70 %l2_decay=400 \
     %l3_src=1 %l3_level=30 %l3_pitch=103 %l3_pend=103 %l3_delay=70 %l3_decay=300 \
     %rev=35",
    // クリック:ごく短い帯域のノイズと高い正弦波
    "%l1_src=5 %l1_level=70 %l1_decay=15 %l1_ftype=2 %l1_cut=108 %l1_cend=108 %l1_res=30 \
     %l2_src=1 %l2_level=50 %l2_pitch=96 %l2_pend=96 %l2_decay=30 \
     %rev=5 %vol=100",
    // 決定音:5 度上がる 2 音と、オクターブ上の層
    "%l1_src=1 %l1_level=80 %l1_pitch=79 %l1_pend=79 %l1_decay=180 \
     %l2_src=1 %l2_level=80 %l2_pitch=86 %l2_pend=86 %l2_delay=80 %l2_decay=300 \
     %l3_src=2 %l3_level=30 %l3_pitch=98 %l3_pend=98 %l3_delay=80 %l3_decay=200 \
     %rev=20",
    // 風切り音:帯域のノイズがふくらみ、周波数が上がる
    "%l1_src=5 %l1_level=100 %l1_attack=250 %l1_decay=300 %l1_ftype=2 %l1_cut=70 %l1_cend=110 %l1_res=40 \
     %l2_src=5 %l2_level=50 %l2_attack=200 %l2_decay=250 %l2_delay=40 %l2_ftype=2 %l2_cut=60 %l2_cend=100 %l2_res=30 \
     %rev=30 %vol=100",
    // チャージ:3 つの層が 1 秒かけて上がる
    "%l1_src=3 %l1_level=70 %l1_pitch=48 %l1_pend=84 %l1_ptime=1200 %l1_attack=900 %l1_decay=400 %l1_cut=80 %l1_cend=125 \
     %l2_src=4 %l2_level=40 %l2_pitch=55 %l2_pend=91 %l2_ptime=1200 %l2_attack=900 %l2_decay=400 \
     %l3_src=1 %l3_level=60 %l3_pitch=36 %l3_pend=60 %l3_ptime=1200 %l3_attack=800 %l3_decay=400 \
     %drive=15 %rev=30",
    // 電撃:急に下がる矩形波、金属音、共振の強いノイズ
    "%l1_src=4 %l1_level=70 %l1_pitch=108 %l1_pend=60 %l1_ptime=80 %l1_decay=140 \
     %l2_src=6 %l2_level=50 %l2_pitch=90 %l2_pend=90 %l2_decay=100 %l2_ftype=1 %l2_cut=100 %l2_cend=100 \
     %l3_src=5 %l3_level=40 %l3_decay=70 %l3_ftype=2 %l3_cut=110 %l3_cend=110 %l3_res=60 \
     %drive=35",
];

impl Category {
    /// すべてのカテゴリ(音色番号の順)。
    pub const ALL: [Category; 10] = [
        Category::Laser,
        Category::Blaster,
        Category::Explosion,
        Category::Impact,
        Category::Pickup,
        Category::Click,
        Category::Confirm,
        Category::Whoosh,
        Category::Charge,
        Category::Zap,
    ];

    /// 音色番号 `@n` から。
    pub fn from_index(n: u8) -> Option<Category> {
        Self::ALL.get(n as usize).copied()
    }

    /// 英語の名前(`laser` など)。
    pub fn name(self) -> &'static str {
        match self {
            Category::Laser => "laser",
            Category::Blaster => "blaster",
            Category::Explosion => "explosion",
            Category::Impact => "impact",
            Category::Pickup => "pickup",
            Category::Click => "click",
            Category::Confirm => "confirm",
            Category::Whoosh => "whoosh",
            Category::Charge => "charge",
            Category::Zap => "zap",
        }
    }

    /// 名前から。
    pub fn from_name(name: &str) -> Option<Category> {
        Self::ALL.iter().copied().find(|c| c.name() == name)
    }

    /// このカテゴリのプリセット(MML で `@n` を書いたときの値)。
    pub fn preset(self) -> HdParams {
        let mut p = HdParams::neutral();
        p.apply(PRESET_TEXT[self as usize])
            .expect("プリセットの中身は正しい");
        p
    }
}

/// 効果音のパラメータ 1 組(パッチ)。値は [`PARAMS`] の範囲に収まっている。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HdParams {
    values: [u16; COUNT],
}

impl Default for HdParams {
    /// [`Category::Laser`] のプリセット(MML の既定の音色 `@0`)。
    fn default() -> Self {
        Category::Laser.preset()
    }
}

impl HdParams {
    /// 素の状態(どの層も鳴らない。[`ParamDef::default`] の値)。
    pub const fn neutral() -> Self {
        let mut values = [0u16; COUNT];
        let mut i = 0;
        while i < COUNT {
            values[i] = PARAMS[i].default;
            i += 1;
        }
        HdParams { values }
    }

    /// 番号 `i` のパラメータの値。範囲外の番号は 0。
    pub fn get(&self, i: usize) -> u16 {
        self.values.get(i).copied().unwrap_or(0)
    }

    /// 層 `l`(0〜3)のパラメータ `p`([`layer`])の値。
    pub fn layer(&self, l: usize, p: usize) -> u16 {
        self.get(layer_param(l, p))
    }

    /// 番号 `i` のパラメータを `v` にする(範囲に丸める)。範囲外の番号は何もしない。
    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;
        }
    }

    /// 名前でパラメータを設定する。名前が無ければ `false`。
    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 fn values(&self) -> &[u16; COUNT] {
        &self.values
    }

    /// 鳴る長さの上限(サンプル数)。リバーブの余韻は含まない。
    pub fn length_samples(&self, sample_rate: u32) -> u32 {
        let mut ms = 0u64;
        for l in 0..LAYERS {
            if self.layer(l, layer::SRC) == source::OFF || self.layer(l, layer::LEVEL) == 0 {
                continue;
            }
            let t = self.layer(l, layer::DELAY) as u64
                + self.layer(l, layer::ATTACK) as u64
                + self.layer(l, layer::DECAY) as u64;
            ms = ms.max(t);
        }
        // 立ち上がりの最短 1ms と丸めの分の余裕を 2ms 足す
        let ms = ms * self.get(master::LENGTH) as u64 / 100 + 2;
        (ms * sample_rate as u64 / 1000).max(1) as u32
    }

    /// `@n` と `%名前=値` の並びを、今の値に上書きする(`@n` はそのカテゴリのプリセットに戻す)。
    fn apply<'a>(&mut self, text: &'a str) -> Result<(), ParseError<'a>> {
        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))?;
                *self = 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));
                }
                self.values[i] = v as u16;
            } else {
                return Err(ParseError::BadToken(tok));
            }
        }
        Ok(())
    }

    /// テキストから読む。空白で区切った `@n`(カテゴリのプリセットから始める)と
    /// `%名前=値` を受け付ける。`@n` が無ければ `@0` から始める。後に書いたものが勝つ。
    pub fn parse(text: &str) -> Result<HdParams, ParseError<'_>> {
        let mut p = HdParams::default();
        p.apply(text)?;
        Ok(p)
    }

    /// テキスト(`@n %名前=値 …`)に書く。`base` のプリセットとの差だけを `%` で書く。
    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 nearest_category(&self) -> Category {
        let mut best = Category::Laser;
        let mut best_n = usize::MAX;
        for c in Category::ALL {
            let p = c.preset();
            let n = (0..COUNT)
                .filter(|&i| p.values[i] != self.values[i])
                .count();
            if n < best_n {
                best = c;
                best_n = n;
            }
        }
        best
    }

    /// 差が一番少ないプリセットを基準にしたテキスト。[`HdParams::parse`] で読み戻すと同じ値になる。
    pub fn to_text(&self) -> String {
        let mut s = String::new();
        let _ = self.write_text(self.nearest_category(), &mut s);
        s
    }
}

/// [`HdParams::parse`] の誤り。中身は問題のあった語。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError<'a> {
    /// `@n` の番号がカテゴリに無い。
    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-hd-params-bad-tone",
            ParseError::UnknownParam(_) => "err-hd-params-unknown-param",
            ParseError::BadValue(_) => "err-hd-params-bad-value",
            ParseError::OutOfRange(_) => "err-hd-params-out-of-range",
            ParseError::BadToken(_) => "err-hd-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::synth::sfx_hd::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)
    }
}

impl std::error::Error for ParseError<'_> {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn presets_parse_and_names_are_unique() {
        for c in Category::ALL {
            let _ = c.preset();
        }
        for (i, a) in PARAMS.iter().enumerate() {
            assert_eq!(param_index(a.name), Some(i));
            assert!(a.default >= a.min && a.default <= a.max, "{}", a.name);
        }
        assert_eq!(PARAMS[master::DRIVE].name, "drive");
        assert_eq!(PARAMS[layer_param(3, layer::RES)].name, "l4_res");
    }

    #[test]
    fn text_round_trips() {
        let mut p = Category::Impact.preset();
        p.set(layer_param(1, layer::DECAY), 90);
        assert_eq!(p.to_text(), "@3 %l2_decay=90");
        assert_eq!(HdParams::parse(&p.to_text()).unwrap(), p);
        assert_eq!(HdParams::parse("@0 x"), Err(ParseError::BadToken("x")));
    }
}