fmod/core/sound/
defaults.rs

1// Copyright (c) 2024 Lily Lyons
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7use fmod_sys::*;
8use std::ffi::{c_float, c_int, c_uint};
9
10use crate::{Mode, Sound, TimeUnit, Vector};
11
12impl Sound {
13    /// Sets the angles and attenuation levels of a 3D cone shape, for simulated occlusion which is based on direction.
14    ///
15    /// When ChannelControl::set3DConeOrientation is used and a 3D 'cone' is set up,
16    /// attenuation will automatically occur for a sound based on the relative angle of the direction the cone is facing,
17    /// vs the angle between the sound and the listener.
18    /// - If the relative angle is within the `inside_angle`, the sound will not have any attenuation applied.
19    /// - If the relative angle is between the `inside_angle` and `outside_angle`,
20    /// linear volume attenuation (between 1 and `outside_volume`) is applied between the two angles until it reaches the `outside_angle`.
21    /// - If the relative angle is outside of the `outside_angle` the volume does not attenuate any further.
22    pub fn set_3d_cone_settings(
23        &self,
24        inside_angle: c_float,
25        outside_angle: c_float,
26        outside_volume: c_float,
27    ) -> Result<()> {
28        unsafe {
29            FMOD_Sound_Set3DConeSettings(self.inner, inside_angle, outside_angle, outside_volume)
30                .to_result()
31        }
32    }
33
34    /// Retrieves the inside and outside angles of the 3D projection cone and the outside volume.
35    pub fn get_3d_cone_settings(&self) -> Result<(c_float, c_float, c_float)> {
36        let mut inside_angle = 0.0;
37        let mut outside_angle = 0.0;
38        let mut outside_volume = 0.0;
39        unsafe {
40            FMOD_Sound_Get3DConeSettings(
41                self.inner,
42                &mut inside_angle,
43                &mut outside_angle,
44                &mut outside_volume,
45            )
46            .to_result()?;
47        }
48        Ok((inside_angle, outside_angle, outside_volume))
49    }
50
51    /// Sets a custom roll-off shape for 3D distance attenuation.
52    ///
53    /// Must be used in conjunction with [`Mode::CUSTOM_ROLLOFF`] flag to be activated.
54    ///
55    /// If [`Mode::CUSTOM_ROLLOFF`] is set and the roll-off shape is not set, FMOD will revert to [`Mode::INVERSE_ROLLOFF`] roll-off mode.
56    ///
57    /// When a custom roll-off is specified a [`Channel`] or [`ChannelGroup`]'s 3D 'minimum' and 'maximum' distances are ignored.
58    ///
59    /// The distance in-between point values is linearly interpolated until the final point where the last value is held.
60    ///
61    /// If the points are not sorted by distance, an error will result.
62    ///
63    /// # Safety
64    ///
65    /// This function does not duplicate the memory for the points internally.
66    /// The memory you pass to FMOD must remain valid while in use.
67    pub unsafe fn set_3d_custom_rolloff(&self, points: &mut [Vector]) -> Result<()> {
68        // probably doesn't need to be mutable, but more safe to be mutable just in case
69        unsafe {
70            FMOD_Sound_Set3DCustomRolloff(
71                self.inner,
72                points.as_mut_ptr().cast(),
73                points.len() as i32,
74            )
75            .to_result()
76        }
77    }
78
79    /// Retrieves the current custom roll-off shape for 3D distance attenuation.
80    pub fn get_3d_custom_rolloff(&self) -> Result<Vec<Vector>> {
81        let mut points = std::ptr::null_mut();
82        let mut num_points = 0;
83        unsafe {
84            FMOD_Sound_Get3DCustomRolloff(self.inner, &mut points, &mut num_points).to_result()?;
85
86            let points = std::slice::from_raw_parts(points.cast(), num_points as usize).to_vec();
87
88            Ok(points)
89        }
90    }
91
92    /// Sets the minimum and maximum audible distance for a 3D sound.
93    ///
94    /// The distances are meant to simulate the 'size' of a sound. Reducing the min distance will mean the sound appears smaller in the world, and in some modes makes the volume attenuate faster as the listener moves away from the sound.
95    /// Increasing the min distance simulates a larger sound in the world, and in some modes makes the volume attenuate slower as the listener moves away from the sound.
96    ///
97    /// max will affect attenuation differently based on roll-off mode set in the mode parameter of System::createSound, System::createStream, Sound::setMode or ChannelControl::setMode.
98    ///
99    /// For these modes the volume will attenuate to 0 volume (silence), when the distance from the sound is equal to or further than the max distance:
100    /// - FMOD_3D_LINEARROLLOFF
101    /// - FMOD_3D_LINEARSQUAREROLLOFF
102    ///
103    /// For these modes the volume will stop attenuating at the point of the max distance, without affecting the rate of attenuation:
104    /// - FMOD_3D_INVERSEROLLOFF
105    /// - FMOD_3D_INVERSETAPEREDROLLOFF
106    ///
107    /// For this mode the max distance is ignored:
108    /// - FMOD_3D_CUSTOMROLLOFF
109    pub fn set_3d_min_max_distance(&self, min: c_float, max: c_float) -> Result<()> {
110        unsafe { FMOD_Sound_Set3DMinMaxDistance(self.inner, min, max).to_result() }
111    }
112
113    /// Retrieve the minimum and maximum audible distance for a 3D sound.
114    pub fn get_3d_min_max_distance(&self) -> Result<(c_float, c_float)> {
115        let mut min = 0.0;
116        let mut max = 0.0;
117        unsafe {
118            FMOD_Sound_Get3DMinMaxDistance(self.inner, &mut min, &mut max).to_result()?;
119        }
120        Ok((min, max))
121    }
122
123    /// Sets a sound's default playback attributes.
124    ///
125    /// When the Sound is played it will use these values without having to specify them later on a per Channel basis.
126    pub fn set_defaults(&self, frequency: c_float, priority: c_int) -> Result<()> {
127        unsafe { FMOD_Sound_SetDefaults(self.inner, frequency, priority).to_result() }
128    }
129
130    /// Retrieves a sound's default playback attributes.
131    pub fn get_defaults(&self) -> Result<(c_float, c_int)> {
132        let mut frequency = 0.0;
133        let mut priority = 0;
134        unsafe {
135            FMOD_Sound_GetDefaults(self.inner, &mut frequency, &mut priority).to_result()?;
136        }
137        Ok((frequency, priority))
138    }
139
140    /// Sets or alters the mode of a sound.
141    ///
142    /// When calling this function, note that it will only take effect when the sound is played again with System::playSound.
143    /// This is the default for when the sound next plays, not a mode that will suddenly change all currently playing instances of this sound.
144    ///
145    /// Flags supported:
146    /// - [`Mode::LOOP_OFF`]
147    /// - [`Mode::LOOP_NORMAL`]
148    /// - [`Mode::LOOP_BIDI`]
149    /// - [`Mode::HEADRELATIVE_3D`]
150    /// - [`Mode::WORLDRELATIVE_3D`]
151    /// - [`Mode::D2`]
152    /// - [`Mode::D3`]
153    /// - [`Mode::INVERSE_ROLLOFF_3D`]
154    /// - [`Mode::LINEAR_ROLLOFF_3D`]
155    /// - [`Mode::LINEAR_SQUARE_ROLLOFF_3D`]
156    /// - [`Mode::INVERSE_TAPERED_ROLLOFF_3D`]
157    /// - [`Mode::CUSTOM_ROLLOFF_3D`]
158    /// - [`Mode::IGNORE_GEOMETRY_3D`]
159    ///
160    /// If [`Mode::IGNORE_GEOMETRY_3D`] is not specified, the flag will be cleared if it was specified previously.
161    ///
162    /// Changing mode on an already buffered stream may not produced desired output. See Streaming Issues.
163    // FIXME this is pretty unsafe, add safe version
164    pub fn set_mode(&self, mode: Mode) -> Result<()> {
165        unsafe { FMOD_Sound_SetMode(self.inner, mode.bits()).to_result() }
166    }
167
168    /// Retrieves the mode of a sound.
169    ///
170    /// The mode will be dependent on the mode set by a call to System::createSound, System::createStream or [`Sound::set_mode`].
171    pub fn get_mode(&self) -> Result<Mode> {
172        let mut mode = 0;
173        unsafe {
174            FMOD_Sound_GetMode(self.inner, &mut mode).to_result()?;
175        }
176        Ok(Mode::from(mode))
177    }
178
179    /// Sets the sound to loop a specified number of times before stopping if the playback mode is set to looping.
180    ///
181    /// Changing loop count on an already buffered stream may not produced desired output. See Streaming Issues.
182    pub fn set_loop_count(&self, loop_count: c_int) -> Result<()> {
183        unsafe { FMOD_Sound_SetLoopCount(self.inner, loop_count).to_result() }
184    }
185
186    /// Retrieves the sound's loop count.
187    ///
188    /// Unlike the Channel loop count function, this function simply returns the value set with Sound::setLoopCount.
189    /// It does not decrement as it plays (especially seeing as one sound can be played multiple times).
190    pub fn get_loop_count(&self) -> Result<c_int> {
191        let mut loop_count = 0;
192        unsafe {
193            FMOD_Sound_GetLoopCount(self.inner, &mut loop_count).to_result()?;
194        }
195        Ok(loop_count)
196    }
197
198    /// Sets the loop points within a sound.
199    ///
200    /// The values used for `loop_start` and loopend are inclusive, which means these positions will be played.
201    ///
202    /// If a `loop_end` is smaller or equal to loopstart an error will be returned.
203    /// The same will happen for any values that are equal or greater than the length of the sound.
204    ///
205    /// Changing loop points on an already buffered stream may not produced desired output. See Streaming Issues.
206    ///
207    /// The Sound's mode must be set to [`Mode::LOOP_NORMAL`] or [`Mode::LOOP_BIDI`] for loop points to affect playback.
208    pub fn set_loop_points(
209        &self,
210        loop_start: c_uint,
211        start_type: TimeUnit,
212        loop_end: c_uint,
213        end_type: TimeUnit,
214    ) -> Result<()> {
215        unsafe {
216            FMOD_Sound_SetLoopPoints(
217                self.inner,
218                loop_start,
219                start_type.into(),
220                loop_end,
221                end_type.into(),
222            )
223            .to_result()
224        }
225    }
226
227    /// Retrieves the loop points for a sound.
228    ///
229    /// The values returned are inclusive, which means these positions will be played.
230    pub fn get_loop_points(
231        &self,
232        start_type: TimeUnit,
233        end_type: TimeUnit,
234    ) -> Result<(c_uint, c_uint)> {
235        let mut loop_start = 0;
236        let mut loop_end = 0;
237        unsafe {
238            FMOD_Sound_GetLoopPoints(
239                self.inner,
240                &mut loop_start,
241                start_type.into(),
242                &mut loop_end,
243                end_type.into(),
244            )
245            .to_result()?;
246        }
247        Ok((loop_start, loop_end))
248    }
249}