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
#![allow(dead_code)]

pub mod renderer;
pub mod types;
pub mod ui;

pub mod overture {
    use crate::renderer::Camera;
    use crate::renderer::Model;
    use crate::renderer::Renderer;
    use crate::types;
    use crate::ui;
    use glutin::config::{Config, ConfigSurfaceTypes, ConfigTemplate, ConfigTemplateBuilder};
    use glutin::context::{ContextApi, ContextAttributesBuilder, NotCurrentContext};
    use glutin::display::{Display, DisplayApiPreference};
    use glutin::prelude::*;
    use glutin::surface::{SurfaceAttributesBuilder, WindowSurface};
    use raw_window_handle::{
        HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle,
    };
    use std::num::NonZeroU32;
    pub use winit::event::{ElementState, MouseButton, TouchPhase, VirtualKeyCode};
    use winit::event::{Event, WindowEvent};
    use winit::event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget};

    struct SurfaceState {
        window: winit::window::Window,
        surface: glutin::surface::Surface<glutin::surface::WindowSurface>,
    }

    pub enum CustomEvent {
        Keyboard(VirtualKeyCode, ElementState, Box<dyn Fn()>),
        Mouse(MouseButton, ElementState, Box<dyn Fn()>),
        Touch(TouchPhase, Box<dyn Fn()>),
    }

    pub struct Scene {
        event_loop: Option<EventLoop<CustomEvent>>,
        winsys_display: Option<RawDisplayHandle>,
        glutin_display: Option<Display>,
        surface_state: Option<SurfaceState>,
        context: Option<glutin::context::PossiblyCurrentContext>,
        render_state: Option<Renderer>,
    }

    impl Scene {
        pub fn new(event_loop: EventLoop<CustomEvent>) -> Self {
            #[cfg(not(target_os = "android"))]
            if std::env::var("MESA_GLES_VERSION_OVERRIDE").is_err() {
                // Fallback to GLES version 2.0 for test runs (mesa drivers particularly)
                std::env::set_var("MESA_GLES_VERSION_OVERRIDE", "2.0");
            }

            let winsys_display = event_loop.raw_display_handle();
            Self {
                event_loop: Some(event_loop),
                winsys_display: Some(winsys_display),
                glutin_display: None,
                surface_state: None,
                context: None,
                render_state: None,
            }
        }

        #[allow(unused_variables)]
        fn create_display(
            raw_display: RawDisplayHandle,
            raw_window_handle: RawWindowHandle,
        ) -> Display {
            #[cfg(target_os = "linux")]
            let preference = DisplayApiPreference::Egl;

            #[cfg(target_os = "android")]
            let preference = DisplayApiPreference::Egl;

            #[cfg(target_os = "macos")]
            let preference = DisplayApiPreference::Cgl;

            #[cfg(target_os = "windows")]
            let preference = DisplayApiPreference::Wgl(Some(raw_window_handle));

            unsafe { Display::new(raw_display, preference).unwrap() }
        }

        fn ensure_glutin_display(&mut self, window: &winit::window::Window) {
            if self.glutin_display.is_none() {
                let raw_window_handle = window.raw_window_handle();
                self.glutin_display = Some(Self::create_display(
                    self.winsys_display.unwrap(),
                    raw_window_handle,
                ));
            }
        }

        fn create_compatible_gl_context(
            glutin_display: &Display,
            raw_window_handle: RawWindowHandle,
            config: &Config,
        ) -> NotCurrentContext {
            let context_attributes = ContextAttributesBuilder::new()
                .with_context_api(ContextApi::Gles(Some(glutin::context::Version::new(2, 0))))
                .with_debug(true)
                .build(Some(raw_window_handle));

            let fallback_context_attributes = ContextAttributesBuilder::new()
                .with_context_api(ContextApi::Gles(None))
                .build(Some(raw_window_handle));
            unsafe {
                glutin_display
                    .create_context(&config, &context_attributes)
                    .unwrap_or_else(|_| {
                        glutin_display
                            .create_context(config, &fallback_context_attributes)
                            .expect("failed to create context")
                    })
            }
        }

        fn config_template(raw_window_handle: RawWindowHandle) -> ConfigTemplate {
            let builder = ConfigTemplateBuilder::new()
                .with_alpha_size(8)
                .compatible_with_native_window(raw_window_handle)
                .with_surface_type(ConfigSurfaceTypes::WINDOW)
                .with_api(glutin::config::Api::GLES2);

            builder.build()
        }

        fn ensure_surface_and_context<T>(&mut self, event_loop: &EventLoopWindowTarget<T>) {
            let window = winit::window::WindowBuilder::new()
                .with_inner_size(winit::dpi::LogicalSize::new(960.0, 640.0))
                .with_min_inner_size(winit::dpi::LogicalSize::new(480.0, 320.0))
                .with_title("TRS_24 Window")
                .build(&event_loop)
                .unwrap();
            let raw_window_handle = window.raw_window_handle();

            self.ensure_glutin_display(&window);
            let glutin_display = self
                .glutin_display
                .as_ref()
                .expect("Can't ensure surface + context without a Glutin Display connection");

            let template = Self::config_template(raw_window_handle);
            let config = unsafe {
                glutin_display
                    .find_configs(template)
                    .unwrap()
                    .reduce(|accum, config| {
                        if config.num_samples() > accum.num_samples() {
                            config
                        } else {
                            accum
                        }
                    })
                    .unwrap()
            };
            println!("Picked a config with {} samples", config.num_samples());

            let (width, height): (u32, u32) = window.inner_size().into();
            let raw_window_handle = window.raw_window_handle();
            let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
                raw_window_handle,
                NonZeroU32::new(width).unwrap(),
                NonZeroU32::new(height).unwrap(),
            );
            let surface = unsafe {
                glutin_display
                    .create_window_surface(&config, &attrs)
                    .unwrap()
            };
            let surface_state = SurfaceState { window, surface };

            let prev_ctx = self.context.take();
            match prev_ctx {
                Some(ctx) => {
                    let not_current_context = ctx
                        .make_not_current()
                        .expect("Failed to make GL context not current");
                    self.context = Some(
                        not_current_context
                            .make_current(&surface_state.surface)
                            .expect("Failed to make GL context current"),
                    );
                }
                None => {
                    let not_current_context = Self::create_compatible_gl_context(
                        glutin_display,
                        raw_window_handle,
                        &config,
                    );
                    self.context = Some(
                        not_current_context
                            .make_current(&surface_state.surface)
                            .expect("Failed to make GL context current"),
                    );
                }
            }

            self.surface_state = Some(surface_state);
        }

        fn ensure_renderer(&mut self, models: &Vec<Model>, ui: &Vec<ui::Element>) {
            let glutin_display = self
                .glutin_display
                .as_ref()
                .expect("Can't ensure renderer without a Glutin Display connection");
            self.render_state
                .get_or_insert_with(|| Renderer::new(glutin_display, models, ui));
        }

        fn queue_redraw(&self) {
            if let Some(surface_state) = &self.surface_state {
                surface_state.window.request_redraw();
            }
        }

        fn resume<T>(
            &mut self,
            event_loop: &EventLoopWindowTarget<T>,
            models: &Vec<Model>,
            ui: &Vec<ui::Element>,
        ) {
            self.ensure_surface_and_context(event_loop);
            self.ensure_renderer(models, ui);
            self.queue_redraw();
        }

        pub fn run(mut self, world_color: types::RGBA, models: Vec<Model>, ui: Vec<ui::Element>) {
            let mut camera: Camera = Camera::new(0.0, 0.0);
            let mut allowed_to_set_camera: bool = true;

            #[cfg(debug_assertions)]
            let mut left_mouse_button_pressed = false;

            let mut key_input_vec: Vec<(VirtualKeyCode, ElementState, Box<dyn Fn()>)> = Vec::new();
            let mut mouse_input_vec: Vec<(MouseButton, ElementState, Box<dyn Fn()>)> = Vec::new();
            let mut touch_input_vec: Vec<(TouchPhase, Box<dyn Fn()>)> = Vec::new();

            let mut previous_frame_time = std::time::Instant::now();
            if let Some(event_loop) = self.event_loop.take() {
                event_loop.run(move |event, event_loop, control_flow| {
                    if let Some(ref surface_state) = self.surface_state {
                        let (width, height): (u32, u32) = surface_state.window.inner_size().into();
                        if allowed_to_set_camera {
                            camera = Camera::new(width as f32, height as f32);
                            allowed_to_set_camera = false;
                        }
                    }

                    *control_flow = ControlFlow::Wait;
                    match event {
                        Event::Resumed => {
                            self.resume(&event_loop, &models, &ui);
                        }
                        Event::Suspended => {
                            self.surface_state = None;
                        }
                        Event::RedrawRequested(_) => {
                            let current_frame_time = std::time::Instant::now();
                            let _timestep = current_frame_time
                                .duration_since(previous_frame_time)
                                .as_secs_f32();
                            previous_frame_time = current_frame_time;

                            //println!("{:?}ms", timestep * 1000.0);

                            if let Some(ref surface_state) = self.surface_state {
                                if let Some(ctx) = &self.context {
                                    if let Some(ref mut renderer) = self.render_state {
                                        renderer.draw(&world_color, &camera);

                                        if let Err(err) = surface_state.surface.swap_buffers(ctx) {
                                            println!(
                                                "Failed to swap buffers after render: {}",
                                                err
                                            );
                                        }
                                    }
                                    self.queue_redraw();
                                }
                            }
                        }
                        Event::UserEvent(custom_event) => match custom_event {
                            CustomEvent::Keyboard(key, state, result) => {
                                key_input_vec.push((key, state, result))
                            }
                            CustomEvent::Touch(touch, result) => {
                                touch_input_vec.push((touch, result))
                            }
                            CustomEvent::Mouse(mouse, state, result) => {
                                mouse_input_vec.push((mouse, state, result))
                            }
                        },
                        Event::WindowEvent {
                            event: WindowEvent::Touch(location),
                            ..
                        } => {
                            for phase in &touch_input_vec {
                                if location.phase == phase.0 {
                                    (phase.1)();
                                }
                            }
                        }
                        Event::WindowEvent { event, .. } => match event {
                            WindowEvent::KeyboardInput { input, .. } => {
                                if let Some(key) = input.virtual_keycode {
                                    #[cfg(debug_assertions)]
                                    match key {
                                        VirtualKeyCode::W => {
                                            camera.position += camera.speed * camera.orientation;
                                        }
                                        VirtualKeyCode::A => {
                                            camera.position += camera.speed
                                                * -nalgebra_glm::normalize(&nalgebra_glm::cross(
                                                    &camera.orientation,
                                                    &camera.up,
                                                ))
                                        }
                                        VirtualKeyCode::S => {
                                            camera.position -= camera.speed * camera.orientation
                                        }
                                        VirtualKeyCode::D => {
                                            camera.position += camera.speed
                                                * nalgebra_glm::normalize(&nalgebra_glm::cross(
                                                    &camera.orientation,
                                                    &camera.up,
                                                ))
                                        }
                                        VirtualKeyCode::Space => {
                                            camera.position += camera.speed * camera.up
                                        }
                                        VirtualKeyCode::LControl => {
                                            camera.position -= camera.speed * camera.up
                                        }
                                        VirtualKeyCode::LShift => {
                                            camera.speed = if input.state == ElementState::Pressed {
                                                0.4
                                            } else {
                                                0.1
                                            };
                                        }
                                        _ => {}
                                    }

                                    for given_key in &key_input_vec {
                                        match (input.state, key) {
                                            (s, b) if s == given_key.1 && b == given_key.0 => {
                                                (given_key.2)();
                                            }
                                            _ => {}
                                        }
                                    }
                                }
                            }
                            WindowEvent::MouseInput { state, button, .. } => {
                                #[cfg(debug_assertions)]
                                match (state, button) {
                                    (ElementState::Pressed, MouseButton::Left) => {
                                        if let Some(ref surface_state) = &self.surface_state {
                                            surface_state.window.set_cursor_visible(false);
                                            if camera.first_click {
                                                surface_state
                                                    .window
                                                    .set_cursor_grab(
                                                        winit::window::CursorGrabMode::Locked,
                                                    )
                                                    .unwrap();

                                                surface_state
                                                    .window
                                                    .set_cursor_position(
                                                        winit::dpi::LogicalPosition::<f64>::from((
                                                            camera.width as f64 / 2.0,
                                                            camera.height as f64 / 2.0,
                                                        )),
                                                    )
                                                    .unwrap();

                                                surface_state
                                                    .window
                                                    .set_cursor_grab(
                                                        winit::window::CursorGrabMode::Confined,
                                                    )
                                                    .unwrap();
                                                camera.first_click = false;

                                                left_mouse_button_pressed = true;
                                            }
                                        }
                                    }
                                    (ElementState::Released, MouseButton::Left) => {
                                        if let Some(ref surface_state) = &self.surface_state {
                                            surface_state
                                                .window
                                                .set_cursor_grab(
                                                    winit::window::CursorGrabMode::Confined,
                                                )
                                                .unwrap();
                                            surface_state.window.set_cursor_visible(true);
                                            camera.first_click = true;
                                            left_mouse_button_pressed = false;
                                        }
                                    }

                                    _ => {}
                                }

                                for given_mouse in &mouse_input_vec {
                                    match (state, button) {
                                        (s, b) if s == given_mouse.1 && b == given_mouse.0 => {
                                            (given_mouse.2)();
                                        }
                                        _ => {}
                                    }
                                }
                            }
                            #[cfg(debug_assertions)]
                            WindowEvent::CursorMoved { position, .. } => {
                                if left_mouse_button_pressed {
                                    if let Some(ref surface_state) = &self.surface_state {
                                        let mouse_x: f32 = position.x as f32;
                                        let mouse_y: f32 = position.y as f32;

                                        let rot_x = camera.sensitivity
                                            * (mouse_y - (camera.height / 2.0))
                                            / camera.height;
                                        let rot_y = camera.sensitivity
                                            * (mouse_x - (camera.width / 2.0))
                                            / camera.width;

                                        let new_orientation = nalgebra_glm::rotate_vec3(
                                            &camera.orientation,
                                            -rot_x as f32,
                                            &nalgebra_glm::normalize(&nalgebra_glm::cross(
                                                &camera.orientation,
                                                &camera.up,
                                            )),
                                        );

                                        if (nalgebra_glm::angle(&new_orientation, &camera.up)
                                            - 90.0)
                                            .abs()
                                            <= 85.0
                                        {
                                            camera.orientation = new_orientation;
                                        }

                                        camera.orientation = nalgebra_glm::rotate_vec3(
                                            &camera.orientation,
                                            -rot_y as f32,
                                            &camera.up,
                                        );

                                        surface_state
                                            .window
                                            .set_cursor_grab(winit::window::CursorGrabMode::Locked)
                                            .unwrap();

                                        surface_state
                                            .window
                                            .set_cursor_position(
                                                winit::dpi::LogicalPosition::<f64>::from((
                                                    camera.width as f64 / 2.0,
                                                    camera.height as f64 / 2.0,
                                                )),
                                            )
                                            .unwrap();

                                        surface_state
                                            .window
                                            .set_cursor_grab(
                                                winit::window::CursorGrabMode::Confined,
                                            )
                                            .unwrap();
                                    }
                                }
                            }
                            WindowEvent::CloseRequested => {
                                *control_flow = ControlFlow::Exit;
                            }
                            _ => {}
                        },
                        _ => {}
                    }
                });
            }
        }
    }

    pub use winit::event_loop::EventLoopBuilder;
    #[cfg(target_os = "android")]
    pub use winit::platform::android::activity::AndroidApp;
    #[cfg(target_os = "android")]
    pub use winit::platform::android::EventLoopBuilderExtAndroid;
}