pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 曲が使う音源の設定(`#synth` のオプションと `#sample` の録音)。

use super::{SynthSpec, BASIC};

/// 曲が使う音源と、そのオプション(既定値を補った完全な形)。
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SynthConfig {
    /// 音源の正式名(別名ではなく [`SynthSpec::name`])。
    pub name: String,
    pub options: Vec<(String, String)>,
    /// `#sample` で読み込んだ録音(WAV のバイト列)。音源を作るときに、その音源が使う(`va` のサンプラー)。
    /// 直列化(`serde`)の対象ではない(バイト列を持たない形に戻る)。
    #[cfg_attr(feature = "serde", serde(skip))]
    pub samples: Vec<SampleAsset>,
}

/// `#sample スロット "パス" [元の高さ]` で読み込んだ録音。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SampleAsset {
    /// 登録先のスロット(0〜[`SAMPLE_SLOTS`] 未満)。
    pub slot: u8,
    /// 曲に書いたパス(表示用)。
    pub path: String,
    /// 録音の元の高さ(MIDI ノート番号。`o4 c` = 60)。書かなければ音源の既定。
    pub root_key: Option<u8>,
    /// WAV ファイルの中身。
    pub data: std::sync::Arc<[u8]>,
    /// `#sample` の位置(診断に使う)。
    pub span: crate::compiler::diagnostic::Span,
}

/// `#sample` で使えるスロットの数(0〜7)。
pub const SAMPLE_SLOTS: u8 = 8;

impl SynthConfig {
    pub fn get(&self, key: &str) -> Option<&str> {
        self.options
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }

    pub fn get_u32(&self, key: &str) -> Option<u32> {
        self.get(key).and_then(|v| v.parse().ok())
    }

    /// 既定のオプションで設定を作る。
    pub fn defaults(spec: &SynthSpec) -> Self {
        SynthConfig {
            name: spec.name.to_string(),
            options: spec
                .options
                .iter()
                .map(|o| (o.name.to_string(), o.default.to_string()))
                .collect(),
            samples: Vec::new(),
        }
    }
}

impl Default for SynthConfig {
    fn default() -> Self {
        SynthConfig::defaults(&BASIC)
    }
}