fyrox_impl/scene/sound/
context.rs

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
//! Sound context.

use crate::{
    core::{
        log::{Log, MessageKind},
        pool::Handle,
        visitor::prelude::*,
    },
    scene::{node::Node, sound::Sound},
};
use fxhash::FxHashSet;
use fyrox_sound::{
    bus::AudioBusGraph,
    context::DistanceModel,
    renderer::Renderer,
    source::{SoundSource, SoundSourceBuilder, Status},
};
use std::{sync::MutexGuard, time::Duration};

/// Sound context.
#[derive(Debug, Visit)]
pub struct SoundContext {
    #[visit(optional)]
    pub(crate) native: fyrox_sound::context::SoundContext,
}

/// Proxy for guarded access to the sound context.
pub struct SoundContextGuard<'a> {
    guard: MutexGuard<'a, fyrox_sound::context::State>,
}

impl<'a> SoundContextGuard<'a> {
    /// Returns a reference to the audio bus graph.
    pub fn bus_graph_ref(&self) -> &AudioBusGraph {
        self.guard.bus_graph_ref()
    }

    /// Returns a reference to the audio bus graph.
    pub fn bus_graph_mut(&mut self) -> &mut AudioBusGraph {
        self.guard.bus_graph_mut()
    }

    /// Pause/unpause the sound context. Paused context won't play any sounds.
    pub fn pause(&mut self, pause: bool) {
        self.guard.pause(pause);
    }

    /// Returns true if the sound context is paused, false - otherwise.
    pub fn is_paused(&self) -> bool {
        self.guard.is_paused()
    }

    /// Sets new distance model.
    pub fn set_distance_model(&mut self, distance_model: DistanceModel) {
        self.guard.set_distance_model(distance_model);
    }

    /// Returns current distance model.
    pub fn distance_model(&self) -> DistanceModel {
        self.guard.distance_model()
    }

    /// Normalizes given frequency using context's sampling rate. Normalized frequency then can be used
    /// to create filters.
    pub fn normalize_frequency(&self, f: f32) -> f32 {
        self.guard.normalize_frequency(f)
    }

    /// Returns amount of time context spent on rendering all sound sources.
    pub fn full_render_duration(&self) -> Duration {
        self.guard.full_render_duration()
    }

    /// Returns current renderer.
    pub fn renderer(&self) -> Renderer {
        self.guard.renderer().clone()
    }

    /// Returns current renderer.
    pub fn renderer_ref(&self) -> &Renderer {
        self.guard.renderer()
    }

    /// Returns current renderer.
    pub fn renderer_ref_mut(&mut self) -> &mut Renderer {
        self.guard.renderer_mut()
    }

    /// Sets new renderer.
    pub fn set_renderer(&mut self, renderer: Renderer) -> Renderer {
        self.guard.set_renderer(renderer)
    }

    /// Destroys all backing sound entities.
    pub fn destroy_sound_sources(&mut self) {
        self.guard.sources_mut().clear();
    }
}

impl Default for SoundContext {
    fn default() -> Self {
        let native = fyrox_sound::context::SoundContext::new();
        let mut state = native.state();
        // There's no need to serialize native sources, because they'll be re-created automatically.
        state.serialization_options.skip_sources = true;
        drop(state);
        Self { native }
    }
}

impl SoundContext {
    pub(crate) fn new() -> Self {
        Default::default()
    }

    /// Creates a full copy of the context, instead of shallow that could be done via [`Clone::clone`]
    pub fn deep_clone(&self) -> Self {
        Self {
            native: self.native.deep_clone(),
        }
    }

    /// Returns locked inner state of the sound context.
    pub fn state(&self) -> SoundContextGuard {
        SoundContextGuard {
            guard: self.native.state(),
        }
    }

    pub(crate) fn remove_sound(&mut self, sound: Handle<SoundSource>, name: &str) {
        let mut state = self.native.state();
        if state.is_valid_handle(sound) {
            state.remove_source(sound);

            Log::info(format!(
                "Native sound source was removed for node: {}",
                name
            ));
        }
    }

    pub(crate) fn set_sound_position(&mut self, sound: &Sound) {
        if let Some(source) = self.native.state().try_get_source_mut(sound.native.get()) {
            source.set_position(sound.global_position());
        }
    }

    pub(crate) fn sync_with_sound(&self, sound: &mut Sound) {
        if let Some(source) = self.native.state().try_get_source_mut(sound.native.get()) {
            // Sync back.
            sound.status.set_value_silent(source.status());
            sound
                .playback_time
                .set_value_silent(source.playback_time().as_secs_f32());
        }
    }

    pub(crate) fn sync_to_sound(
        &mut self,
        sound_handle: Handle<Node>,
        sound: &Sound,
        node_overrides: Option<&FxHashSet<Handle<Node>>>,
    ) {
        if !sound.is_globally_enabled()
            || !node_overrides.map_or(true, |f| f.contains(&sound_handle))
        {
            self.remove_sound(sound.native.get(), &sound.name);
            sound.native.set(Default::default());
            return;
        }

        if sound.native.get().is_some() {
            let mut state = self.native.state();
            let source = state.source_mut(sound.native.get());
            sound.buffer.try_sync_model(|v| {
                Log::verify(source.set_buffer(v));
            });
            sound.max_distance.try_sync_model(|v| {
                source.set_max_distance(v);
            });
            sound.rolloff_factor.try_sync_model(|v| {
                source.set_rolloff_factor(v);
            });
            sound.radius.try_sync_model(|v| {
                source.set_radius(v);
            });
            sound.playback_time.try_sync_model(|v| {
                source.set_playback_time(Duration::from_secs_f32(v));
            });
            sound.pitch.try_sync_model(|v| {
                source.set_pitch(v);
            });
            sound.looping.try_sync_model(|v| {
                source.set_looping(v);
            });
            sound.panning.try_sync_model(|v| {
                source.set_panning(v);
            });
            sound.gain.try_sync_model(|v| {
                source.set_gain(v);
            });
            sound
                .spatial_blend
                .try_sync_model(|v| source.set_spatial_blend(v));
            sound.status.try_sync_model(|v| match v {
                Status::Stopped => {
                    Log::verify(source.stop());
                }
                Status::Playing => {
                    source.play();
                }
                Status::Paused => {
                    source.pause();
                }
            });
            sound.audio_bus.try_sync_model(|audio_bus| {
                source.set_bus(audio_bus);
            });
        } else {
            match SoundSourceBuilder::new()
                .with_gain(sound.gain())
                .with_opt_buffer(sound.buffer())
                .with_looping(sound.is_looping())
                .with_panning(sound.panning())
                .with_pitch(sound.pitch())
                .with_status(sound.status())
                .with_playback_time(Duration::from_secs_f32(sound.playback_time()))
                .with_position(sound.global_position())
                .with_radius(sound.radius())
                .with_max_distance(sound.max_distance())
                .with_bus(sound.audio_bus())
                .with_rolloff_factor(sound.rolloff_factor())
                .build()
            {
                Ok(source) => {
                    sound.native.set(self.native.state().add_source(source));

                    Log::writeln(
                        MessageKind::Information,
                        format!("Native sound source was created for node: {}", sound.name()),
                    );
                }
                Err(err) => {
                    Log::writeln(
                        MessageKind::Error,
                        format!(
                            "Unable to create native sound source for node: {}. Reason: {:?}",
                            sound.name(),
                            err
                        ),
                    );
                }
            }
        }
    }
}