Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
466 lines (422 loc) · 13.3 KB
/
Copy pathlib.rs
File metadata and controls
466 lines (422 loc) · 13.3 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Tetra is a simple 2D game framework written in Rust. It uses SDL2 for event handling and OpenGL 3.2+ for rendering.
//!
//! * [Website/Tutorial](https://tetra.seventeencups.net)
//! * [API Docs](https://docs.rs/tetra)
//! * [FAQ](https://tetra.seventeencups.net/FAQ)
//!
//! ## Features
//!
//! * XNA/MonoGame-inspired API
//! * Efficient 2D rendering, with draw call batching by default
//! * Simple input handling
//! * Animations/spritesheets
//! * TTF font rendering
//! * Multiple screen scaling algorithms, including pixel-perfect variants (for those chunky retro pixels)
//! * Deterministic game loop, à la [Fix Your Timestep](https://gafferongames.com/post/fix_your_timestep/)
//!
//! ## Installation
//!
//! To add Tetra to your project, add the following line to your `Cargo.toml` file:
//!
//! ```toml
//! tetra = "0.2"
//! ```
//!
//! Tetra currently requires Rust 1.32 or higher.
//!
//! You will also need to install the SDL2 native libraries, as described [here](https://github.com/Rust-SDL2/rust-sdl2#user-content-requirements). The 'bundled' and 'static linking' features described can be activated using the `sdl2_bundled` and `sdl2_static_link` Cargo features in Tetra.
//!
//! ## Examples
//!
//! To get a simple window displayed on screen, the following code can be used:
//!
//! ```no_run
//! use tetra::graphics::{self, Color};
//! use tetra::{Context, Settings, State};
//!
//! struct GameState;
//!
//! impl State for GameState {
//! fn draw(&mut self, ctx: &mut Context, _dt: f64) -> tetra::Result {
//! // Cornflower blue, as is tradition
//! graphics::clear(ctx, Color::rgb(0.392, 0.584, 0.929));
//! Ok(())
//! }
//! }
//!
//! fn main() {
//! tetra::run(&Settings::new("Hello, world!", 1280, 720), |_| {
//! Ok(GameState)
//! });
//! }
//! ```
//!
//! You can see this example in action by running `cargo run --example hello_world`.
//!
//! The full list of examples is available [here](https://github.com/17cupsofcoffee/tetra/tree/master/examples).
//!
//! ## Support/Feedback
//!
//! Tetra is fairly early in development, so you might run into bugs/flaky docs/general weirdness. Please feel free to open an issue/PR if you find something! You can also contact me via [Twitter](https://twitter.com/17cupsofcoffee), or find me lurking in the #games-and-graphics channel on the [Rust Community Discord](https://bit.ly/rust-community).
#![warn(missing_docs)]
pub mod audio;
pub mod error;
mod fs;
pub mod graphics;
pub mod input;
pub mod math;
mod platform;
pub mod time;
pub mod window;
pub use crate::error::{Result, TetraError};
use crate::graphics::opengl::GLDevice;
use crate::graphics::GraphicsContext;
use crate::input::InputContext;
use crate::platform::Platform;
use crate::time::TimeContext;
/// A trait representing a type that contains game state and provides logic for updating it
/// and drawing it to the screen. This is where you'll write your game logic!
///
/// The methods on `State` allow you to return a `Result`, either explicitly or via the `?`
/// operator. If an error is returned, the game will close and the error will be returned from
/// the `run` function that was used to start it.
#[allow(unused_variables)]
pub trait State {
/// Called when it is time for the game to update, at the interval specified by the context's
/// tick rate.
///
/// The game will update at a fixed time step (defaulting to 60fps), and draw as fast as it is
/// allowed to (depending on CPU/vsync settings). This allows for deterministic updates even at
/// varying framerates, but may require you to do some interpolation in the `draw` method in
/// order to make things look smooth.
///
/// See [Fix Your Timestep](https://gafferongames.com/post/fix_your_timestep/) for more info.
fn update(&mut self, ctx: &mut Context) -> Result {
Ok(())
}
/// Called when it is time for the game to be drawn.
///
/// As drawing will not necessarily be in step with updating, the `dt` argument is provided -
/// this will be a number between 0 and 1, specifying how far through the current tick you are.
///
/// For example, if the player is meant to move 16 pixels per frame, and the current `dt` is 0.5,
/// you should draw them 8 pixels along.
fn draw(&mut self, ctx: &mut Context, dt: f64) -> Result {
Ok(())
}
/// Called when an error is returned from one of the other `State` methods.
///
/// This method does not provide any way to recover from the error - it exists so that you can
/// log/report any fatal errors before exiting the game. Non-fatal errors should be handled at
/// the point where they were thrown.
fn error(error: TetraError) {
platform::log_error(error)
}
}
/// A struct containing all of the 'global' state within the framework.
pub struct Context {
platform: Platform,
gl: GLDevice,
graphics: GraphicsContext,
input: InputContext,
time: TimeContext,
running: bool,
quit_on_escape: bool,
}
impl Context {
/// Creates a new `Context`, using the provided settings.
///
/// Unless you're writing a custom game loop, you probably don't need to call this!
pub fn new(settings: &Settings) -> Result<Context> {
let (platform, gl_context, width, height) = Platform::new(settings)?;
let mut gl = GLDevice::new(gl_context)?;
if settings.debug_info {
platform::log_info(&format!("OpenGL Vendor: {}", gl.get_vendor()));
platform::log_info(&format!("OpenGL Renderer: {}", gl.get_renderer()));
platform::log_info(&format!("OpenGL Version: {}", gl.get_version()));
platform::log_info(&format!(
"GLSL Version: {}",
gl.get_shading_language_version()
));
}
let graphics = GraphicsContext::new(&mut gl, width, height)?;
let input = InputContext::new();
let time = TimeContext::new(settings.tick_rate);
Ok(Context {
platform,
gl,
graphics,
input,
time,
running: false,
quit_on_escape: settings.quit_on_escape,
})
}
}
/// Settings that can be configured when starting up a game.
#[derive(Debug, Clone)]
pub struct Settings {
title: String,
window_width: i32,
window_height: i32,
canvas_id: String,
vsync: bool,
tick_rate: f64,
fullscreen: bool,
maximized: bool,
minimized: bool,
resizable: bool,
borderless: bool,
show_mouse: bool,
quit_on_escape: bool,
debug_info: bool,
}
impl Settings {
/// Create a new `Settings` struct, with a title and window size.
pub fn new<S>(title: S, window_width: i32, window_height: i32) -> Settings
where
S: Into<String>,
{
Settings {
title: title.into(),
window_width,
window_height,
..Settings::default()
}
}
/// Sets the title of the window.
///
/// Defaults to `"Tetra"`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms.
pub fn title<S>(&mut self, title: S) -> &mut Settings
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 Settings {
self.window_width = width;
self.window_height = height;
self
}
/// Specifies the ID of the `canvas` element that should be used for
/// rendering, when running in a browser.
///
/// Defaults to `"canvas"`.
///
/// # Platform-specific Behaviour
///
/// Ignored on desktop platforms.
pub fn canvas_id<S>(&mut self, id: S) -> &mut Settings
where
S: Into<String>,
{
self.canvas_id = id.into();
self
}
/// Enables or disables vsync.
///
/// Defaults to `true`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms, as vsync cannot be disabled there.
pub fn vsync(&mut self, vsync: bool) -> &mut Settings {
self.vsync = vsync;
self
}
/// Sets the game's update tick rate, in ticks per second.
///
/// Defaults to `60.0`.
pub fn tick_rate(&mut self, tick_rate: f64) -> &mut Settings {
self.tick_rate = 1.0 / tick_rate;
self
}
/// Sets whether or not the window should start in fullscreen.
///
/// Defaults to `false`.
pub fn fullscreen(&mut self, fullscreen: bool) -> &mut Settings {
self.fullscreen = fullscreen;
self
}
/// Sets whether or not the window should start maximized.
///
/// Defaults to `false`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms.
pub fn maximized(&mut self, maximized: bool) -> &mut Settings {
self.maximized = maximized;
self
}
/// Sets whether or not the window should start minimized.
///
/// Defaults to `false`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms.
pub fn minimized(&mut self, minimized: bool) -> &mut Settings {
self.minimized = minimized;
self
}
/// Sets whether or not the window should be resizable.
///
/// Defaults to `false`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms.
pub fn resizable(&mut self, resizable: bool) -> &mut Settings {
self.resizable = resizable;
self
}
/// Sets whether or not the window should be borderless.
///
/// Defaults to `false`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms.
pub fn borderless(&mut self, borderless: bool) -> &mut Settings {
self.borderless = borderless;
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 Settings {
self.show_mouse = show_mouse;
self
}
/// Sets whether or not the game should close when the Escape key is pressed.
///
/// Defaults to `false`.
///
/// # Platform-specific Behaviour
///
/// Ignored on web platforms.
pub fn quit_on_escape(&mut self, quit_on_escape: bool) -> &mut Settings {
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 Settings {
self.debug_info = debug_info;
self
}
}
impl Default for Settings {
fn default() -> Settings {
Settings {
title: "Tetra".into(),
window_width: 1280,
window_height: 720,
canvas_id: "canvas".into(),
vsync: true,
tick_rate: 1.0 / 60.0,
fullscreen: false,
maximized: false,
minimized: false,
resizable: false,
borderless: false,
show_mouse: false,
quit_on_escape: false,
debug_info: false,
}
}
}
/// Runs the game, using the provided settings.
///
/// 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.
///
/// # Examples
///
/// ```no_run
/// use tetra::{Context, Settings, State};
///
/// struct GameState;
///
/// impl GameState {
/// fn new(ctx: &mut Context) -> tetra::Result<GameState> {
/// Ok(GameState)
/// }
/// }
///
/// impl State for GameState { }
///
/// fn main() {
/// // Because the signature of GameState::new is
/// // (&mut Context) -> tetra::Result<GameState>, you can pass it
/// // into tetra::run directly.
/// tetra::run(&Settings::new("Hello, world!", 1280, 720), GameState::new);
/// }
/// ```
///
/// # Platform-specific Behaviour
///
/// This function blocks the main thread on desktop platforms, but returns
/// immediately on web platforms.
pub fn run<S, F>(settings: &Settings, init: F)
where
S: State + 'static,
F: FnOnce(&mut Context) -> Result<S>,
{
let mut ctx = match Context::new(settings) {
Ok(ctx) => ctx,
Err(e) => {
S::error(e);
return;
}
};
let state = match init(&mut ctx) {
Ok(state) => state,
Err(e) => {
S::error(e);
return;
}
};
time::reset(&mut ctx);
ctx.running = true;
platform::run_loop(ctx, state, run_frame);
}
fn run_frame<S>(ctx: &mut Context, state: &mut S)
where
S: State,
{
time::tick(ctx);
if let Err(e) = platform::handle_events(ctx) {
ctx.running = false;
S::error(e);
return;
}
while time::is_tick_ready(ctx) {
if let Err(e) = state.update(ctx) {
ctx.running = false;
S::error(e);
return;
}
input::cleanup_after_state_update(ctx);
time::consume_tick(ctx);
}
if let Err(e) = state.draw(ctx, time::get_alpha(ctx)) {
ctx.running = false;
S::error(e);
return;
}
graphics::present(ctx);
std::thread::yield_now();
}