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
//! Engine wide settings that are applicable using the [Settings](crate::settings::Settings) struct.

use derive_builder::Builder;

// audio feature
#[cfg(feature = "audio")]
#[cfg(feature = "client")]
use crate::resources::{
    sounds::{AudioSettings, NoAudioServerError},
    RESOURCES,
};

#[cfg(feature = "client")]
use super::{Window, WindowBuilder};

use super::TickSettings;

use parking_lot::{Condvar, Mutex};
#[cfg(feature = "client")]
use std::{
    sync::{atomic::AtomicBool, Arc, OnceLock},
    time::Duration,
};

/// The initial settings of this engine.
#[derive(Clone, Builder, Default)]
pub struct EngineSettings {
    /// Settings that determines the look of the window.
    #[builder(setter(into, strip_option), default)]
    #[cfg(feature = "client")]
    pub window_settings: WindowBuilder,
    /// The initial settings of the tick system.
    #[builder(setter(into), default)]
    pub tick_settings: TickSettings,
}

/// General in game settings built into the game engine.
pub struct Settings {
    #[cfg(feature = "client")]
    window: Mutex<std::sync::OnceLock<Arc<Window>>>,
    pub tick_system: TickSystem,
    #[cfg(feature = "client")]
    pub graphics: Graphics,
    #[cfg(feature = "audio")]
    pub audio: Audio,
}

impl Settings {
    pub(crate) fn new() -> Self {
        Self {
            #[cfg(feature = "client")]
            window: Mutex::new(std::sync::OnceLock::new()),
            tick_system: TickSystem::new(),
            #[cfg(feature = "client")]
            graphics: Graphics::new(PresentMode::Fifo),
            #[cfg(feature = "audio")]
            audio: Audio::new(),
        }
    }
    #[cfg(feature = "client")]
    pub(crate) fn set_window(&self, window: Arc<Window>) -> Result<(), Arc<Window>> {
        self.window.lock().set(window)?;
        Ok(())
    }
    #[cfg(feature = "client")]
    /// Returns the window of the game in case it is initialized.
    pub fn window(&self) -> Option<Arc<Window>> {
        self.window.lock().get().cloned()
    }
}

/// Engine wide tick system settings.
pub struct TickSystem {
    pub(super) tick_settings: Mutex<TickSettings>,
    pub(super) tick_pause_lock: (Mutex<bool>, Condvar),
}

impl TickSystem {
    pub(crate) fn new() -> Self {
        Self {
            tick_settings: Mutex::new(TickSettings::default()),
            tick_pause_lock: (Mutex::new(false), Condvar::new()),
        }
    }
    /// Returns the engine wide tick settings.
    pub fn get(&self) -> TickSettings {
        self.tick_settings.lock().clone()
    }
    /// Sets and applies the tick settings of the game engine.
    pub fn set(&self, settings: TickSettings) {
        *self.tick_pause_lock.0.lock() = settings.paused;
        *self.tick_settings.lock() = settings;
        self.tick_pause_lock.1.notify_all();
    }
}

/// Engine wide audio settings.
#[cfg(feature = "audio")]
pub struct Audio {
    audio_settings: Mutex<AudioSettings>,
}

#[cfg(feature = "audio")]
impl Audio {
    pub(crate) fn new() -> Self {
        Self {
            audio_settings: Mutex::new(AudioSettings::new()),
        }
    }
    /// Returns the audio settings.
    #[cfg(feature = "audio")]
    pub fn get(&self) -> AudioSettings {
        *self.audio_settings.lock()
    }
    /// Sets and applies the audio settings and therefore refreshes the engine side audio server to use them.
    #[cfg(feature = "audio")]
    pub fn set(&self, settings: AudioSettings) -> Result<(), NoAudioServerError> {
        *self.audio_settings.lock() = settings;
        RESOURCES
            .audio_server
            .send(crate::resources::sounds::AudioUpdate::SettingsChange(
                settings,
            ))
            .ok()
            .ok_or(NoAudioServerError)
    }
}

/// Engine wide Graphics settings.
///
/// By default the present mode is determined by this order based on availability on the device:
///
/// 1. `Mailbox`
/// 2. `Immediate`
/// 3. `Fifo`
///
/// The framerate limit is `None`, so off.
///
/// Only alter settings after the game engine has been initialized. The initialisation of the game engine also
/// initializes the settings.
#[cfg(feature = "client")]
pub struct Graphics {
    /// An option that determines something called "VSync".
    pub(crate) present_mode: Mutex<PresentMode>,
    /// Time waited before each frame.
    framerate_limit: Mutex<Duration>,
    pub(crate) available_present_modes: OnceLock<Vec<PresentMode>>,
    pub(crate) recreate_swapchain: AtomicBool,
}

#[cfg(feature = "client")]
impl Graphics {
    pub(crate) fn new(present_mode: PresentMode) -> Self {
        Self {
            present_mode: Mutex::new(present_mode),
            framerate_limit: Mutex::new(Duration::from_secs(0)),
            available_present_modes: OnceLock::new(),
            recreate_swapchain: false.into(),
        }
    }

    /// Returns the present mode of the game.
    pub fn present_mode(&self) -> PresentMode {
        *self.present_mode.lock()
    }

    /// Sets and applies the present mode of the game.
    pub fn set_present_mode(&self, mode: PresentMode) -> anyhow::Result<()> {
        if self.get_supported_present_modes().contains(&mode) {
            *self.present_mode.lock() = mode;
            self.recreate_swapchain
                .store(true, std::sync::atomic::Ordering::Release);
            Ok(())
        } else {
            Err(anyhow::Error::msg(format!(
                "This present mode \"{:?}\" is not available on this device.\nAvailable modes on this device are {:?}",
                mode, self.get_supported_present_modes()
            )))
        }
    }

    /// Returns waiting time between frames to wait.
    pub fn framerate_limit(&self) -> Duration {
        *self.framerate_limit.lock()
    }

    /// Sets the framerate limit as waiting time between frames.
    ///
    /// This should be able to be changed by the user in case they have a device with limited power capacity like a laptop with a battery.
    ///
    /// Setting the duration to no wait time at all will turn off the limit.
    pub fn set_framerate_limit(&self, limit: Duration) {
        *self.framerate_limit.lock() = limit;
    }

    /// Sets the cap for the max frames per second the game should be able to output.
    ///
    /// This method is the same as setting the `set_framerate_limit` of this setting to `1.0 / cap` in seconds.
    ///
    /// Turns off the framerate cap if 0 was given.
    pub fn set_fps_cap(&self, cap: u64) {
        if cap == 0 {
            self.set_framerate_limit(Duration::from_secs(cap));
            return;
        }
        self.set_framerate_limit(Duration::from_secs_f64(1.0 / cap as f64));
    }

    /// Returns all the present modes this device supports.
    ///
    /// If the vec is empty the engine has not been initialized and the settings should not be changed at this state.
    pub fn get_supported_present_modes(&self) -> Vec<PresentMode> {
        self.available_present_modes
            .get()
            .cloned()
            .unwrap_or(vec![])
    }
}

/// The presentation action to take when presenting images to the window.
///
/// In game engine terms this affects "VSync".
///
/// `Immediate` mode is the only one that does not have "VSync".
///
/// When designing in game graphics settings this is the setting that gets changed when users select the VSync option.
///
/// The vsync options may include higher latency than the other ones.
///
/// It is not recommended dynamically switching between those during the game, as they may cause visual artifacts or noticable changes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg(feature = "client")]
pub enum PresentMode {
    /// This one has no vsync and presents the image as soon as it is available.
    ///
    /// This may happen while the image is presenting, so it may cause tearing.
    ///
    /// This present mode has the lowest latency compared to every other mode, so this is the option for most fast paced games where latency matters.
    ///
    /// This present mode may not be available on every device.
    Immediate,
    /// This present mode has a waiting slot for the next image to be presented after the current one has finished presenting.
    /// This mode also does not block the drawing thread, drawing images, even when they will not get presented.
    ///
    /// This means there is no tearing and with just one waiting slot also not that much latency.
    ///
    /// This option is recommended if `Immediate` is not available and also for games that focus visual experience over latency, as this one does not have tearing.
    ///
    /// It may also not be available on every device.
    Mailbox,
    /// Means first in first out.
    ///
    /// This present mode is also known as "vsync on". It blocks the thread and only draws and presents images if the present buffer is finished drawing to the screen.
    ///
    /// It is guaranteed to be available on every device.
    Fifo,
}

#[cfg(feature = "client")]
impl From<PresentMode> for vulkano::swapchain::PresentMode {
    fn from(value: PresentMode) -> vulkano::swapchain::PresentMode {
        use vulkano::swapchain::PresentMode as Pm;
        match value {
            PresentMode::Immediate => Pm::Immediate,
            PresentMode::Mailbox => Pm::Mailbox,
            PresentMode::Fifo => Pm::Fifo,
        }
    }
}

#[cfg(feature = "client")]
impl From<vulkano::swapchain::PresentMode> for PresentMode {
    fn from(value: vulkano::swapchain::PresentMode) -> PresentMode {
        use vulkano::swapchain::PresentMode as Pm;
        match value {
            Pm::Immediate => PresentMode::Immediate,
            Pm::Mailbox => PresentMode::Mailbox,
            _ => PresentMode::Fifo,
        }
    }
}