Skip to main content

unbanished_audio/scene/
effects.rs

1//! Sound effects and their cache: loading, preparing and adding effects.
2
3use super::*;
4
5/// A SoundEffect with its decoded buffers (per sound, per variant).
6pub struct Effect {
7    /// The effect's resource reference.
8    pub reference: String,
9    /// The effect: its timeline of sounds, variants, radius and length.
10    pub desc: SoundEffect,
11    /// The decoded sounds, for each sound of the timeline and each variant (`None` when one could
12    /// not be decoded).
13    pub buffers: Vec<Vec<Option<Sound>>>,
14}
15
16/// Loads each effect once.
17#[derive(Default)]
18pub struct EffectCache {
19    effects: HashMap<String, Option<Rc<Effect>>>,
20}
21
22/// Effects read and decoded by [`EffectCache::prepare`], for [`EffectCache::add`].
23pub struct Prepared {
24    keys: Vec<String>,
25    /// Per key: the description, or why it did not load (`None`: not in the packages).
26    descs: Vec<Result<SoundEffect, Option<String>>>,
27    /// Every variant's buffer reference, in order, and its decoded samples.
28    buffers: Vec<Option<String>>,
29    decoded: Vec<Option<Result<(crate::Pcm, bool), String>>>,
30}
31
32impl Effect {
33    /// Max length in microseconds (0 = endless).
34    pub(super) fn max_length(&self) -> i64 {
35        self.desc.max_length
36    }
37}
38
39impl EffectCache {
40    /// An effect by its reference, loaded and decoded the first time it is asked for.
41    pub fn get(
42        &mut self,
43        archive: &unbanished_formats::pkg::Archive,
44        reference: &str,
45    ) -> Option<Rc<Effect>> {
46        let key = reference.replace('/', "\\");
47        if !self.effects.contains_key(&key) {
48            self.preload(archive, &[key.as_str()]);
49        }
50        self.effects[&key].clone()
51    }
52
53    /// Load every effect of `references` that is not loaded yet, as [`EffectCache::get`] would
54    /// one by one.
55    pub fn preload(&mut self, archive: &unbanished_formats::pkg::Archive, references: &[&str]) {
56        let missing = self.missing(references);
57        if !missing.is_empty() {
58            self.add(Self::prepare(archive, &missing));
59        }
60    }
61
62    /// The effects of `references` that are not loaded yet.
63    pub fn missing<'a>(&self, references: &[&'a str]) -> Vec<&'a str> {
64        references
65            .iter()
66            .copied()
67            .filter(|r| !self.effects.contains_key(&r.replace('/', "\\")))
68            .collect()
69    }
70
71    /// Read and decode effects without the cache, so that it can run on another thread while
72    /// the caller loads something else. Each sound buffer decodes on its own (a pure function
73    /// of its data), so all the buffers of all the effects decode in parallel (native).
74    pub fn prepare(archive: &unbanished_formats::pkg::Archive, references: &[&str]) -> Prepared {
75        let mut keys: Vec<String> = Vec::new();
76        for r in references {
77            let key = r.replace('/', "\\");
78            if !keys.contains(&key) {
79                keys.push(key);
80            }
81        }
82        let descs: Vec<Result<SoundEffect, Option<String>>> = keys
83            .iter()
84            .map(|key| {
85                let path = key.replace('\\', "/");
86                let bytes = archive.read_ref(&path).map_err(|_| None)?;
87                unbanished_formats::audio::sound_effect(&bytes).map_err(|e| Some(e.to_string()))
88            })
89            .collect();
90        let buffers: Vec<Option<String>> = descs
91            .iter()
92            .flatten()
93            .flat_map(|d| d.sounds.iter().flat_map(|s| &s.variants))
94            .map(|v| Some(v.buffer.as_deref()?.replace('\\', "/")))
95            .collect();
96        let decoded = unbanished_formats::par::map(&buffers, |r| {
97            r.as_deref().map(|r| crate::load_sound(archive, r))
98        });
99        Prepared {
100            keys,
101            descs,
102            buffers,
103            decoded,
104        }
105    }
106
107    /// Put prepared effects in the cache (an effect already there is kept).
108    pub fn add(&mut self, prepared: Prepared) {
109        let Prepared {
110            keys,
111            descs,
112            buffers,
113            decoded,
114        } = prepared;
115        let mut decoded = buffers.iter().zip(decoded).map(|(r, d)| match d? {
116            Ok((pcm, looping)) => Some(Sound::new(pcm, looping)),
117            Err(e) => {
118                log::warn!("{}: {e}", r.as_deref().unwrap_or_default());
119                None
120            }
121        });
122        for (key, desc) in keys.into_iter().zip(descs) {
123            let desc = desc.map_err(|e| e.map(|e| log::warn!("{key}: {e}"))).ok();
124            let loaded = desc.map(|desc| {
125                let buffers = desc
126                    .sounds
127                    .iter()
128                    .map(|s| decoded.by_ref().take(s.variants.len()).collect())
129                    .collect();
130                Rc::new(Effect {
131                    reference: key.clone(),
132                    desc,
133                    buffers,
134                })
135            });
136            self.effects.entry(key).or_insert(loaded);
137        }
138    }
139}