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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
use std::result;

use crate::graphics::{self, GraphicsContext};
use crate::input::{self, InputContext};
use crate::platform::{self, GraphicsDevice, Window};
use crate::time::{self, TimeContext, Timestep};
use crate::{Result, State, TetraError};

#[cfg(feature = "audio")]
use crate::audio::AudioDevice;

/// A struct containing all of the 'global' state within the framework.
pub struct Context {
    pub(crate) window: Window,
    pub(crate) device: GraphicsDevice,
    #[cfg(feature = "audio")]
    pub(crate) audio: AudioDevice,
    pub(crate) graphics: GraphicsContext,
    pub(crate) input: InputContext,
    pub(crate) time: TimeContext,

    pub(crate) running: bool,
    pub(crate) quit_on_escape: bool,
}

impl Context {
    pub(crate) fn new(settings: &ContextBuilder) -> Result<Context> {
        // This needs to be initialized ASAP to avoid https://github.com/tomaka/rodio/issues/214
        #[cfg(feature = "audio")]
        let audio = AudioDevice::new();

        let (window, gl_context, window_width, window_height) = Window::new(settings)?;
        let mut device = GraphicsDevice::new(gl_context)?;

        if settings.debug_info {
            println!("OpenGL Vendor: {}", device.get_vendor());
            println!("OpenGL Renderer: {}", device.get_renderer());
            println!("OpenGL Version: {}", device.get_version());
            println!("GLSL Version: {}", device.get_shading_language_version());
        }

        let graphics = GraphicsContext::new(&mut device, window_width, window_height)?;
        let input = InputContext::new();
        let time = TimeContext::new(settings.timestep);

        Ok(Context {
            window,
            device,

            #[cfg(feature = "audio")]
            audio,
            graphics,
            input,
            time,

            running: false,
            quit_on_escape: settings.quit_on_escape,
        })
    }

    /// Runs the game.
    ///
    /// The `init` parameter takes a function or closure that creates a
    /// `State` implementation. A common pattern is to use method references
    /// to pass in your state's constructor directly - see the example below
    /// for how this works.
    ///
    /// The error type returned by your `init` closure currently must match the error
    /// type returned by your [`State`] methods. This limitation may be lifted
    /// in the future.
    ///
    /// # Errors
    ///
    /// If the [`State`] returns an error from [`update`](State::update), [`draw`](State::draw)
    /// or [`event`](State::event), the game will stop running and this method will
    /// return the error.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tetra::{Context, ContextBuilder, State};
    ///
    /// struct GameState;
    ///
    /// impl GameState {
    ///     fn new(ctx: &mut Context) -> tetra::Result<GameState> {
    ///         Ok(GameState)
    ///     }
    /// }
    ///
    /// impl State for GameState { }
    ///
    /// fn main() -> tetra::Result {
    ///     // Because GameState::new takes `&mut Context` and returns a `State` implementation
    ///     // wrapped in a `Result`, you can use it without a closure wrapper:
    ///     ContextBuilder::new("Hello, world!", 1280, 720)
    ///         .build()?
    ///         .run(GameState::new)
    /// }
    /// ```
    ///
    pub fn run<S, F, E>(&mut self, init: F) -> result::Result<(), E>
    where
        S: State<E>,
        F: FnOnce(&mut Context) -> result::Result<S, E>,
        E: From<TetraError>,
    {
        let state = &mut init(self)?;

        time::reset(self);

        self.running = true;
        self.window.set_visible(true);

        let mut output = Ok(());

        while self.running {
            if let Err(e) = self.tick(state) {
                output = Err(e);
                self.running = false;
            }
        }

        self.window.set_visible(false);

        output
    }

    pub(crate) fn tick<S, E>(&mut self, state: &mut S) -> result::Result<(), E>
    where
        S: State<E>,
        E: From<TetraError>,
    {
        time::tick(self);

        platform::handle_events(self, state)?;

        match time::get_timestep(self) {
            Timestep::Fixed(_) => {
                while time::is_fixed_update_ready(self) {
                    state.update(self)?;
                    input::clear(self);
                }
            }
            Timestep::Variable => {
                state.update(self)?;
                input::clear(self);
            }
        }

        state.draw(self)?;

        graphics::present(self);

        std::thread::yield_now();

        Ok(())
    }
}

/// Settings that can be configured when starting up a game.
///
/// # Serde
///
/// Serialization and deserialization of this type (via [Serde](https://serde.rs/))
/// can be enabled via the `serde_support` feature.
///
/// Note that the available settings could change between releases of
/// Tetra (semver permitting). If you need a config file schema that will
/// be stable in the long term, consider making your own and then mapping
/// it to Tetra's API, rather than relying on `ContextBuilder` to not
/// change.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct ContextBuilder {
    pub(crate) title: String,
    pub(crate) window_width: i32,
    pub(crate) window_height: i32,
    pub(crate) vsync: bool,
    pub(crate) timestep: Timestep,
    pub(crate) fullscreen: bool,
    pub(crate) maximized: bool,
    pub(crate) minimized: bool,
    pub(crate) resizable: bool,
    pub(crate) borderless: bool,
    pub(crate) high_dpi: bool,
    pub(crate) show_mouse: bool,
    pub(crate) grab_mouse: bool,
    pub(crate) relative_mouse_mode: bool,
    pub(crate) quit_on_escape: bool,
    pub(crate) debug_info: bool,
}

impl ContextBuilder {
    /// Create a new `ContextBuilder`, with a title and window size.
    pub fn new<S>(title: S, window_width: i32, window_height: i32) -> ContextBuilder
    where
        S: Into<String>,
    {
        ContextBuilder {
            title: title.into(),
            window_width,
            window_height,

            ..ContextBuilder::default()
        }
    }

    /// Sets the title of the window.
    ///
    /// Defaults to `"Tetra"`.
    pub fn title<S>(&mut self, title: S) -> &mut ContextBuilder
    where
        S: Into<String>,
    {
        self.title = title.into();
        self
    }

    /// Sets the size of the window.
    ///
    /// Defaults to `1280` by `720`.
    pub fn size(&mut self, width: i32, height: i32) -> &mut ContextBuilder {
        self.window_width = width;
        self.window_height = height;
        self
    }

    /// Enables or disables vsync.
    ///
    /// Defaults to `true`.
    pub fn vsync(&mut self, vsync: bool) -> &mut ContextBuilder {
        self.vsync = vsync;
        self
    }

    /// Sets the game's timestep.
    ///
    /// Defaults to `Timestep::Fixed(60.0)`.
    pub fn timestep(&mut self, timestep: Timestep) -> &mut ContextBuilder {
        self.timestep = timestep;
        self
    }

    /// Sets whether or not the window should start in fullscreen.
    ///
    /// Defaults to `false`.
    pub fn fullscreen(&mut self, fullscreen: bool) -> &mut ContextBuilder {
        self.fullscreen = fullscreen;
        self
    }

    /// Sets whether or not the window should start maximized.
    ///
    /// Defaults to `false`.
    pub fn maximized(&mut self, maximized: bool) -> &mut ContextBuilder {
        self.maximized = maximized;
        self
    }

    /// Sets whether or not the window should start minimized.
    ///
    /// Defaults to `false`.
    pub fn minimized(&mut self, minimized: bool) -> &mut ContextBuilder {
        self.minimized = minimized;
        self
    }

    /// Sets whether or not the window should be resizable.
    ///
    /// Defaults to `false`.
    pub fn resizable(&mut self, resizable: bool) -> &mut ContextBuilder {
        self.resizable = resizable;
        self
    }

    /// Sets whether or not the window should be borderless.
    ///
    /// Defaults to `false`.
    pub fn borderless(&mut self, borderless: bool) -> &mut ContextBuilder {
        self.borderless = borderless;
        self
    }

    /// Sets whether or not the window should use a high-DPI backbuffer, on platforms
    /// that support it (e.g. MacOS with a retina display).
    ///
    /// Note that you may also need to configure your game's packaging to allow for
    /// high-DPI rendering:
    ///
    /// * On Windows, you will need to set the 'DPI Awareness' setting in a
    ///   [manifest resource](https://github.com/rust-lang/rust/issues/11207#issuecomment-573424095)
    ///   or call into the `SetProcessDpiAwareness` function in the Windows API.
    /// * On Mac, you will need to set `NSHighResolutionCapable` to `true` in your Info.plist. This is the
    ///   default on Catalina and higher.
    ///
    /// Defaults to `false`.
    pub fn high_dpi(&mut self, high_dpi: bool) -> &mut ContextBuilder {
        self.high_dpi = high_dpi;
        self
    }

    /// Sets whether or not the mouse cursor should be visible when it is within the
    /// game window.
    ///
    /// Defaults to `false`.
    pub fn show_mouse(&mut self, show_mouse: bool) -> &mut ContextBuilder {
        self.show_mouse = show_mouse;
        self
    }

    /// Sets whether or not the mouse cursor should be grabbed by the game window
    /// at startup.
    ///
    /// Defaults to `false`.
    pub fn grab_mouse(&mut self, grab_mouse: bool) -> &mut ContextBuilder {
        self.grab_mouse = grab_mouse;
        self
    }

    /// Sets whether or not relative mouse mode should be enabled.
    ///
    /// While the mouse is in relative mode, the cursor is hidden and can move beyond the
    /// bounds of the window. The `delta` field of [`Event::MouseMoved`](crate::lifecycle::Event::MouseMoved)
    /// can then be used to track the cursor's changes in position. This is useful
    /// when implementing control schemes that require the mouse to be able to
    /// move infinitely in any direction (for example, FPS-style movement).
    ///
    /// While this mode is enabled, the absolute position of the mouse may not be updated -
    /// as such, you should not rely on it.
    ///
    /// Defaults to `false`.
    pub fn relative_mouse_mode(&mut self, relative_mouse_mode: bool) -> &mut ContextBuilder {
        self.relative_mouse_mode = relative_mouse_mode;
        self
    }

    /// Sets whether or not the game should close when the Escape key is pressed.
    ///
    /// Defaults to `false`.
    pub fn quit_on_escape(&mut self, quit_on_escape: bool) -> &mut ContextBuilder {
        self.quit_on_escape = quit_on_escape;
        self
    }

    /// Sets whether or not the game should print out debug info at startup.
    /// Please include this if you're submitting a bug report!
    pub fn debug_info(&mut self, debug_info: bool) -> &mut ContextBuilder {
        self.debug_info = debug_info;
        self
    }

    /// Builds the context.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`] will be returned if the context cannot be initialized.
    pub fn build(&self) -> Result<Context> {
        Context::new(self)
    }
}

impl Default for ContextBuilder {
    fn default() -> ContextBuilder {
        ContextBuilder {
            title: "Tetra".into(),
            window_width: 1280,
            window_height: 720,
            vsync: true,
            timestep: Timestep::Fixed(60.0),
            fullscreen: false,
            maximized: false,
            minimized: false,
            resizable: false,
            borderless: false,
            high_dpi: false,
            show_mouse: false,
            grab_mouse: false,
            relative_mouse_mode: false,
            quit_on_escape: false,
            debug_info: false,
        }
    }
}