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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use audio;
use audio::cpal;
use draw;
use find_folder;
use frame::Frame;
use geom;
use glium::glutin;
use state;
use std;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use std::sync::atomic::{self, AtomicBool};
use std::thread;
use std::time::Duration;
use window::{self, Window};
use ui;
pub struct App {
pub(crate) events_loop: glutin::EventsLoop,
pub(crate) windows: RefCell<HashMap<window::Id, Window>>,
config: RefCell<Config>,
pub(crate) ui: ui::Arrangement,
draw_state: DrawState,
pub(crate) focused_window: RefCell<Option<window::Id>>,
pub(crate) elapsed_frames: u64,
pub(crate) events_loop_is_asleep: Arc<AtomicBool>,
pub audio: Audio,
pub mouse: state::Mouse,
pub keys: state::Keys,
pub duration: state::Time,
pub time: DrawScalar,
}
#[derive(Debug)]
struct Config {
loop_mode: LoopMode,
exit_on_escape: bool,
fullscreen_on_shortcut: bool,
}
#[derive(Debug)]
pub struct Draw<'a> {
window_id: window::Id,
draw: RefMut<'a, draw::Draw<DrawScalar>>,
renderer: RefMut<'a, RefCell<draw::backend::glium::Renderer>>,
}
#[derive(Debug)]
struct DrawState {
draw: RefCell<draw::Draw<DrawScalar>>,
renderer: RefCell<Option<RefCell<draw::backend::glium::Renderer>>>,
}
pub type DrawScalar = geom::DefaultScalar;
pub struct Audio {
event_loop: Arc<cpal::EventLoop>,
process_fn_tx: RefCell<Option<mpsc::Sender<audio::stream::ProcessFnMsg>>>,
}
pub struct Proxy {
events_loop_proxy: glutin::EventsLoopProxy,
events_loop_is_asleep: Arc<AtomicBool>,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum LoopMode {
Rate {
update_interval: Duration,
},
Wait {
updates_following_event: usize,
update_interval: Duration,
},
}
fn update_interval(fps: f64) -> Duration {
assert!(fps > 0.0);
const NANOSEC_PER_SEC: f64 = 1_000_000_000.0;
let interval_nanosecs = NANOSEC_PER_SEC / fps;
let secs = (interval_nanosecs / NANOSEC_PER_SEC) as u64;
let nanosecs = (interval_nanosecs % NANOSEC_PER_SEC) as u32;
Duration::new(secs, nanosecs)
}
impl LoopMode {
pub const DEFAULT_RATE_FPS: f64 = 60.0;
pub const DEFAULT_UPDATES_FOLLOWING_EVENT: usize = 3;
pub fn rate_fps(fps: f64) -> Self {
let update_interval = update_interval(fps);
LoopMode::Rate { update_interval }
}
pub fn wait(updates_following_event: usize) -> Self {
let update_interval = update_interval(Self::DEFAULT_RATE_FPS);
LoopMode::Wait {
updates_following_event,
update_interval,
}
}
pub fn wait_with_max_fps(updates_following_event: usize, max_fps: f64) -> Self {
let update_interval = update_interval(max_fps);
LoopMode::Wait {
updates_following_event,
update_interval,
}
}
pub fn wait_with_interval(updates_following_event: usize, update_interval: Duration) -> Self {
LoopMode::Wait {
updates_following_event,
update_interval,
}
}
}
impl Default for LoopMode {
fn default() -> Self {
LoopMode::rate_fps(Self::DEFAULT_RATE_FPS)
}
}
impl Default for Config {
fn default() -> Self {
let loop_mode = Default::default();
let exit_on_escape = App::DEFAULT_EXIT_ON_ESCAPE;
let fullscreen_on_shortcut = App::DEFAULT_FULLSCREEN_ON_SHORTCUT;
Config {
loop_mode,
exit_on_escape,
fullscreen_on_shortcut,
}
}
}
impl App {
pub const ASSETS_DIRECTORY_NAME: &'static str = "assets";
pub const DEFAULT_EXIT_ON_ESCAPE: bool = true;
pub const DEFAULT_FULLSCREEN_ON_SHORTCUT: bool = true;
pub(super) fn new(events_loop: glutin::EventsLoop) -> Self {
let windows = RefCell::new(HashMap::new());
let draw = RefCell::new(draw::Draw::default());
let config = RefCell::new(Default::default());
let renderer = RefCell::new(None);
let draw_state = DrawState { draw, renderer };
let cpal_event_loop = Arc::new(cpal::EventLoop::new());
let process_fn_tx = RefCell::new(None);
let audio = Audio {
event_loop: cpal_event_loop,
process_fn_tx,
};
let focused_window = RefCell::new(None);
let ui = ui::Arrangement::new();
let mouse = state::Mouse::new();
let keys = state::Keys::default();
let duration = state::Time::default();
let time = duration.since_start.secs() as _;
let events_loop_is_asleep = Arc::new(AtomicBool::new(false));
let elapsed_frames = 0;
App {
events_loop,
events_loop_is_asleep,
focused_window,
elapsed_frames,
windows,
config,
draw_state,
audio,
ui,
mouse,
keys,
duration,
time,
}
}
pub fn assets_path(&self) -> Result<PathBuf, find_folder::Error> {
let exe_path = std::env::current_exe()?;
find_folder::Search::ParentsThenKids(5, 3)
.of(exe_path
.parent()
.expect("executable has no parent directory to search")
.into())
.for_folder(Self::ASSETS_DIRECTORY_NAME)
}
pub fn new_window<'a>(&'a self) -> window::Builder<'a, 'static> {
window::Builder::new(self)
}
pub fn window_count(&self) -> usize {
self.windows.borrow().len()
}
pub fn window(&self, id: window::Id) -> Option<std::cell::Ref<Window>> {
let windows = self.windows.borrow();
if !windows.contains_key(&id) {
None
} else {
Some(std::cell::Ref::map(windows, |ws| &ws[&id]))
}
}
pub fn window_id(&self) -> window::Id {
self.focused_window
.borrow()
.expect("called `App::window_id` but there is no window currently in focus")
}
pub fn window_rect(&self) -> geom::Rect<DrawScalar> {
let (w, h) = self.main_window().inner_size_points();
geom::Rect::from_w_h(w as _, h as _)
}
pub fn main_window(&self) -> std::cell::Ref<Window> {
self.window(self.window_id()).expect("no window for focused id")
}
pub fn exit_on_escape(&self) -> bool {
self.config.borrow().exit_on_escape
}
pub fn set_exit_on_escape(&self, b: bool) {
self.config.borrow_mut().exit_on_escape = b;
}
pub fn fullscreen_on_shortcut(&self) -> bool {
self.config.borrow().fullscreen_on_shortcut
}
pub fn set_fullscreen_on_shortcut(&self, b: bool) {
self.config.borrow_mut().fullscreen_on_shortcut = b;
}
pub fn loop_mode(&self) -> LoopMode {
self.config.borrow().loop_mode
}
pub fn set_loop_mode(&self, mode: LoopMode) {
self.config.borrow_mut().loop_mode = mode;
}
pub fn create_proxy(&self) -> Proxy {
let events_loop_proxy = self.events_loop.create_proxy();
let events_loop_is_asleep = self.events_loop_is_asleep.clone();
Proxy { events_loop_proxy, events_loop_is_asleep }
}
pub fn new_ui(&self) -> ui::Builder {
ui::Builder::new(self)
}
pub fn draw_for_window(&self, window_id: window::Id) -> Option<Draw> {
let window = match self.window(window_id) {
None => return None,
Some(window) => window,
};
let facade = window.inner_glium_display();
let draw = self.draw_state.draw.borrow_mut();
draw.reset();
if self.draw_state.renderer.borrow().is_none() {
let renderer = draw::backend::glium::Renderer::new(facade)
.expect("failed to create `Draw` renderer for glium backend");
*self.draw_state.renderer.borrow_mut() = Some(RefCell::new(renderer));
}
let renderer = self.draw_state.renderer.borrow_mut();
let renderer = RefMut::map(renderer, |r| r.as_mut().unwrap());
Some(Draw {
window_id,
draw,
renderer,
})
}
pub fn draw(&self) -> Draw {
self.draw_for_window(self.window_id())
.expect("no window open for `app.window_id`")
}
pub fn elapsed_frames(&self) -> u64 {
self.elapsed_frames
}
}
impl Audio {
pub fn devices(&self) -> audio::Devices {
let devices = cpal::devices();
audio::Devices { devices }
}
pub fn input_devices(&self) -> audio::stream::input::Devices {
let devices = cpal::input_devices();
audio::stream::input::Devices { devices }
}
pub fn output_devices(&self) -> audio::stream::output::Devices {
let devices = cpal::output_devices();
audio::stream::output::Devices { devices }
}
pub fn default_input_device(&self) -> Option<audio::Device> {
cpal::default_input_device().map(|device| audio::Device { device })
}
pub fn default_output_device(&self) -> Option<audio::Device> {
cpal::default_output_device().map(|device| audio::Device { device })
}
pub fn new_input_stream<M, F, S>(
&self,
model: M,
capture: F,
) -> audio::stream::input::Builder<M, F, S> {
audio::stream::input::Builder {
capture,
builder: self.new_stream(model),
}
}
pub fn new_output_stream<M, F, S>(
&self,
model: M,
render: F,
) -> audio::stream::output::Builder<M, F, S> {
audio::stream::output::Builder {
render,
builder: self.new_stream(model),
}
}
fn new_stream<M, S>(&self, model: M) -> audio::stream::Builder<M, S> {
let process_fn_tx = if self.process_fn_tx.borrow().is_none() {
let event_loop = self.event_loop.clone();
let (tx, rx) = mpsc::channel();
let mut loop_context = audio::stream::LoopContext::new(rx);
thread::Builder::new()
.name("cpal::EventLoop::run thread".into())
.spawn(move || event_loop.run(move |id, data| loop_context.process(id, data)))
.expect("failed to spawn cpal::EventLoop::run thread");
*self.process_fn_tx.borrow_mut() = Some(tx.clone());
tx
} else {
self.process_fn_tx.borrow().as_ref().unwrap().clone()
};
audio::stream::Builder {
event_loop: self.event_loop.clone(),
process_fn_tx: process_fn_tx,
model,
sample_rate: None,
channels: None,
frames_per_buffer: None,
device: None,
sample_format: PhantomData,
}
}
}
impl Proxy {
pub fn wakeup(&self) -> Result<(), glutin::EventsLoopClosed> {
if self.events_loop_is_asleep.load(atomic::Ordering::Relaxed) {
self.events_loop_proxy.wakeup()?;
self.events_loop_is_asleep.store(false, atomic::Ordering::Relaxed);
}
Ok(())
}
}
impl<'a> Draw<'a> {
pub fn to_frame(
&self,
app: &App,
frame: &Frame,
) -> Result<(), draw::backend::glium::RendererDrawError> {
let window = app.window(self.window_id)
.expect("no window to draw to for `app::Draw`'s window_id");
let dpi_factor = window.hidpi_factor();
let facade = window.inner_glium_display();
let mut renderer = self.renderer.borrow_mut();
let mut window_frame = frame
.window(self.window_id)
.expect("no frame to draw to for `app::Draw`'s window_id");
renderer.draw(&self.draw, facade, dpi_factor, &mut (**window_frame).frame)
}
}
impl<'a> Deref for Draw<'a> {
type Target = RefMut<'a, draw::Draw<DrawScalar>>;
fn deref(&self) -> &Self::Target {
&self.draw
}
}
impl<'a> DerefMut for Draw<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.draw
}
}