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
612
613
614
615
616
617
618
619
620
621
622

use crate::input::Input;
use crate::scene::Scene;
use crate::renderer::{Renderer, RendererNewInfo};
#[cfg(feature = "imgui_integration")] use crate::imgui_handler::ImGuiHandler;
#[cfg(feature = "default_logger")] use crate::doglog;

use sdl2::event::Event;
use sdl2::event::WindowEvent;
use sdl2::keyboard::Scancode;
#[cfg(feature = "graphical_panic")]use sdl2::messagebox;

#[cfg(feature = "graphical_panic")] use std::panic::PanicInfo;
#[cfg(feature = "graphical_panic")] use backtrace::Backtrace;

#[cfg(feature = "imgui_integration")] use imgui;

use std::time::{Instant, Duration};

const MILLISECONDS_PER_NANOSECOND : f64 = 0.000001;

#[cfg(feature = "graphical_panic")]
fn panic_hook(info : &PanicInfo)
{
    // Get error message if that's what the payload happens to be
    let message : &str = match info.payload().downcast_ref::<String>()
    {
        Some(s) => s,
        None => match info.payload().downcast_ref::<&str>()
        {
            Some(s) => s,
            None => "No reason was given.",
        }
    };
    // Format with file/line info if available
    let mut message = match info.location()
    {
        Some(location) => format!("A panic error occurred on {}:{}: \n{}",
                                location.file(),
                                location.line(),
                                message),
        None => format!("A panic error occurred: \n{}", message),
    };
    
    let bt = Backtrace::new();
    
    message = format!("{}\n\n{:?}", message, bt);
    
    gui_cli_message(&message, "Panic Error");
    
    std::process::exit(1);
}

#[allow(unused_variables)]
pub fn gui_cli_message(message : &str, title : &str)
{
    // Print to console first in case something weird happens
    println!("{}", message);
    
    #[cfg(feature = "graphical_panic")]
    {
        // Show dialog box with panic
        match messagebox::show_simple_message_box(messagebox::MESSAGEBOX_ERROR, title, &message[..], None)
        {
            Ok(_) => (),
            Err(_) => println!("(Messagebox could not be displayed)"),
        };
    }
}

fn read_options() -> getopts::Matches
{
    let args : Vec<String> = std::env::args().collect();
    let options = getopts::Options::new();
    
    let match_result = options.parse(&args[1..]);
    
    match match_result
    {
        Ok(_) => (),
        Err(fail) =>
        {
            let message = format!("{:?}\n{}",
                                  fail,
                                  options.usage("Command parsing failed. Run without options to use defaults."));
            gui_cli_message(&message, "Commandline Help");
            std::process::exit(1);
        }
    }
    
    match_result.unwrap()
}

pub struct GameloopStopwatch
{
    jiffies : Instant,
    jiffies_this_frame : Duration,
    jiffies_this_second : Duration,
    tics_this_frame : u32,
    tics_this_second : u32,
    frames_this_second : u32,
    in_frame : bool
}

impl GameloopStopwatch
{
    pub fn new() -> GameloopStopwatch
    {
        GameloopStopwatch
        {
            jiffies : Instant::now(),
            jiffies_this_frame : Duration::new(0, 0),
            jiffies_this_second : Duration::new(0, 0),
            tics_this_frame : 0,
            tics_this_second : 0,
            frames_this_second : 0,
            in_frame : false
        }
    }
    
    pub fn begin_frame_timing(&mut self)
    {
        if self.in_frame
        {
            return;
        }
        
        self.in_frame = true;
        
        self.jiffies = Instant::now();
        self.jiffies_this_frame = Duration::new(0, 0);
        self.tics_this_frame = 0;
    }
    
    pub fn end_frame_timing(&mut self)
    {
        if !self.in_frame
        {
            return;
        }
        
        self.in_frame = false;
        
        self.jiffies_this_frame = Instant::now() - self.jiffies;
        self.tics_this_second += self.tics_this_frame;
        self.jiffies_this_second += self.jiffies_this_frame;
        self.frames_this_second += 1;
    }
    
    pub fn tic(&mut self)
    {
        self.tics_this_frame += 1;
    }
    
    pub fn new_second(&mut self)
    {
        self.jiffies_this_second = Duration::new(0, 0);
        self.tics_this_second = 0;
        self.frames_this_second = 0;
    }
    
    pub fn jiffies_this_frame(&self) -> Duration
    {
        if self.in_frame
        {
            return Instant::now() - self.jiffies;
        }
        
        self.jiffies_this_frame
    }
    
    pub fn jiffies_this_second(&self) -> Duration
    {
        self.jiffies_this_second
    }
    
    pub fn tics_this_frame(&self) -> u32
    {
        self.tics_this_frame
    }
    
    pub fn tics_this_second(&self) -> u32
    {
        self.tics_this_second
    }
    
    pub fn frames_this_second(&self) -> u32
    {
        self.frames_this_second
    }
    
    pub fn average_ms(&self) -> f64
    {
        self.jiffies_this_second.as_nanos() as f64 * MILLISECONDS_PER_NANOSECOND / self.frames_this_second as f64
    }
}

pub struct GameloopControl
{
    target_framerate : f64,
    frame_interpolation : bool,
    input : Input,
    next_scene : Box<Scene>,
    next_scene_waiting : bool,
    #[cfg(feature = "imgui_integration")]
    imgui_handler : ImGuiHandler
}

impl GameloopControl
{
    pub fn new() -> Result<GameloopControl, String>
    {
        #[cfg(feature = "imgui_integration")]
        let imgui_handler = unwrap_result_or_return_error!(ImGuiHandler::new(), "Could not create imgui");
        
        Ok(GameloopControl
        {
            target_framerate : 60.0,
            frame_interpolation : false,
            input : Input::new(),
            next_scene : Box::new(Scene::new()),
            next_scene_waiting : false,
            #[cfg(feature = "imgui_integration")]
            imgui_handler
        })
    }
    
    pub fn target_framerate(&self) -> f64
    {
        self.target_framerate
    }
    
    pub fn set_target_framerate(&mut self, new_framerate : f64)
    {
        if new_framerate < 1.0 || new_framerate >= 1000.0
        {
            panic!("Target framerate must be between 1 and 1000.");
        }
        
        self.target_framerate = new_framerate;
    }
    
    pub fn frame_interpolation(&self) -> bool
    {
        self.frame_interpolation
    }
    
    pub fn set_frame_interpolation(&mut self, enabled : bool)
    {
        self.frame_interpolation = enabled;
    }
    
    pub fn input(&self) -> &Input
    {
        &self.input
    }
    
    pub fn input_mut(&mut self) -> &mut Input
    {
        &mut self.input
    }
    
    #[cfg(feature = "imgui_integration")]
    pub fn imgui(&self) -> &imgui::ImGui
    {
        self.imgui_handler.imgui()
    }
    
    #[cfg(feature = "imgui_integration")]
    pub fn imgui_mut(&mut self) -> &mut imgui::ImGui
    {
        self.imgui_handler.imgui_mut()
    }
    
    pub fn goto_constructed_scene(&mut self, next_scene : Box<Scene>)
    {
        self.next_scene = next_scene;
        self.next_scene_waiting = true;
    }
}

struct GameloopTimeState
{
    jiffies : Instant,
    last_jiffies : Instant,
    last_fps_jiffies : Instant,
    jiffy_queue : Duration,
    target_frametime : Duration,
    lag_this_second : u32,
    thought_yet : bool,
    think_timer : GameloopStopwatch,
    draw_timer : GameloopStopwatch,
    wait_timer : GameloopStopwatch,
    present_timer : GameloopStopwatch
}

impl GameloopTimeState
{
    fn new() -> GameloopTimeState
    {
        let jiffies = Instant::now();
        let last_jiffies = jiffies;
        let last_fps_jiffies = Instant::now();
        let jiffy_queue = Duration::new(0, 0);
        let target_frametime = Duration::new(0, 0);
        
        GameloopTimeState
        {
            jiffies,
            last_jiffies,
            last_fps_jiffies,
            jiffy_queue,
            target_frametime,
            lag_this_second : 0,
            thought_yet : false,
            think_timer : GameloopStopwatch::new(),
            draw_timer : GameloopStopwatch::new(),
            wait_timer : GameloopStopwatch::new(),
            present_timer : GameloopStopwatch::new()
        }
    }
    
    fn new_second(&mut self)
    {
        self.think_timer.new_second();
        self.draw_timer.new_second();
        self.wait_timer.new_second();
        self.present_timer.new_second();
        
        self.last_fps_jiffies += Duration::from_secs(1);
        self.lag_this_second = 0;
    }
    
    fn update_jiffies(&mut self)
    {
        self.jiffies = Instant::now();
        self.jiffy_queue += self.jiffies - self.last_jiffies;
        self.last_jiffies = self.jiffies;
    }
    
    fn sleep(&mut self, wait_duration : Duration)
    {
        while self.jiffy_queue <= wait_duration
        {
            self.update_jiffies();
            
            if self.jiffy_queue <= wait_duration - Duration::from_millis(1)
            {
                std::thread::sleep(Duration::from_millis(1));
            }
        }
    }
}

pub struct Gameloop
{
    #[allow(dead_code)] // Only used by the imgui integration feature
    sdl_context : sdl2::Sdl,
    event_pump : sdl2::EventPump,
    renderer : Renderer,
    control : GameloopControl,
    current_scene : Box<Scene>,
    time : GameloopTimeState
}

impl Gameloop
{
    pub fn new(package_name : &str, friendly_name : &str) -> Result<Gameloop, String>
    {
        #[cfg(feature = "default_logger")]
        {
            let mut logger = doglog::DogLog::new();
            logger.add_package_filter(String::from(package_name));
            
            if let Err(_) = doglog::DogLog::init(logger, log::LevelFilter::Debug)
            {
                eprintln!("Could not initialize default logger.");
            }
        }
        
        info!("🐶 KEESHOND Game Engine 🐶");
        
        // Messagebox panic handler
        #[cfg(feature = "graphical_panic")]
        std::panic::set_hook(Box::new(panic_hook));
        
        // Get commandline options
        let _matches = read_options();
        
        let version = sdl2::version::version();
        info!("Starting SDL version {}", version);
        
        // Subsystems init
        let sdl_context = unwrap_result_or_return_error!(sdl2::init(), "Could not initialize SDL");
        let event_pump = unwrap_result_or_return_error!(sdl_context.event_pump(), "Could not initialize SDL event pump");
        let video_subsystem = unwrap_result_or_return_error!(sdl_context.video(), "Could not initialize SDL video subsystem");
        
        #[allow(unused_mut)] // mut used only by imgui feature
        let mut control = unwrap_result_or_return_error!(GameloopControl::new(), "Could not initialize gameloop control");
        
        let renderer_new_info = RendererNewInfo
        {
            video_subsystem,
            window_title : friendly_name,
            #[cfg(feature = "imgui_integration")]
            imgui : control.imgui_mut()
        };
        
        let renderer = unwrap_result_or_return_error!(Renderer::new(renderer_new_info), "Could not initialize renderer");
        
        Ok(Gameloop
        {
            sdl_context,
            event_pump, renderer,
            control,
            current_scene : Box::new(Scene::new()),
            time : GameloopTimeState::new()
        })
    }
    
    pub fn control(&self) -> &GameloopControl
    {
        &self.control
    }
    
    pub fn control_mut(&mut self) -> &mut GameloopControl
    {
        &mut self.control
    }
    
    pub fn set_power_management_enabled(&mut self, enabled : bool)
    {
        self.renderer.set_power_management_enabled(enabled);
    }
    
    fn update_input(&mut self)
    {
        let event_pump = &self.event_pump;
        
        let mut callback = | key : &str |
        {
            let scancode = unwrap_option_or_return!(Scancode::from_name(key), false);
            
            event_pump.keyboard_state().is_scancode_pressed(scancode)
        };
        
        self.control.input_mut().check_and_update_state(&mut callback);
    }
    
    fn think(&mut self)
    {
        self.time.think_timer.begin_frame_timing();
        
        let target_ms = 1000.0 / self.control.target_framerate();
        self.time.target_frametime = Duration::from_nanos((target_ms * 1_000_000.0) as u64);
        
        while self.time.jiffy_queue > self.time.target_frametime
        {
            // Prevent overflow if CPU cannot process all the frames
            if (self.time.think_timer.jiffies_this_frame()) > self.time.target_frametime
            {
                while self.time.jiffy_queue > self.time.target_frametime
                {
                    self.time.jiffy_queue -= self.time.target_frametime;
                    self.time.lag_this_second += 1;
                }
                break;
            }
            
            self.update_input();
            self.current_scene.think(&mut self.control);
            
            self.time.think_timer.tic();
            
            self.time.jiffy_queue -= self.time.target_frametime;
            self.time.thought_yet = true;
        }
        
        self.time.think_timer.end_frame_timing();
    }
    
    fn draw(&mut self)
    {
        self.time.draw_timer.begin_frame_timing();
        
        if self.time.thought_yet
        {
            let mut interpolation_amount = 0.0;
        
            if self.control.frame_interpolation
            {
                interpolation_amount = (self.time.jiffy_queue.as_nanos() as f64
                    / self.time.target_frametime.as_nanos() as f64) - 1.0;
            }
            
            self.renderer.draw(&mut self.current_scene, interpolation_amount as f32);
        }
        self.renderer.flush();
        
        #[cfg(feature = "imgui_integration")]
        {
            self.update_imgui();
            self.renderer.flush();
        }
        
        self.time.draw_timer.end_frame_timing();
    }
    
    #[cfg(feature = "imgui_integration")]
    fn update_imgui(&mut self)
    {
        let frametime = self.time.target_frametime * self.time.think_timer.tics_this_frame();
        self.control.imgui_handler.update_cursor(&mut self.sdl_context.mouse());
        
        let frame_delta = frametime.as_nanos() as f64 * MILLISECONDS_PER_NANOSECOND / 1000.0;
        let (width, height) = self.renderer.window_size();
        let ui = self.control.imgui_mut().frame(imgui::FrameSize::new(width as f64, height as f64, 1.0), frame_delta as f32);
        
        self.current_scene.imgui_think(&ui);
        
        self.renderer.control().draw_imgui(ui);
    }
    
    fn wait(&mut self)
    {
        self.time.wait_timer.begin_frame_timing();
        
        if !self.control.frame_interpolation
        {
            // Spin until it's time for the next frame
            self.time.sleep(self.time.target_frametime);
        }
        else
        {
            self.time.update_jiffies();
        }
        
        self.time.wait_timer.end_frame_timing();
    }
    
    fn present(&mut self)
    {
        self.time.present_timer.begin_frame_timing();
        
        self.renderer.present();
        
        self.time.present_timer.end_frame_timing();
    }
    
    fn update_fps(&mut self)
    {
        if self.time.jiffies < self.time.last_fps_jiffies + Duration::from_secs(1)
        {
            return;
        }
        
        debug!("{} ents  |  FPS: {} / {}  |  avg ms:  think {:.2}  draw {:.2}  present {:.2}  wait {:.2}",
        self.current_scene.entity_count(),
            self.time.draw_timer.frames_this_second(),
            self.time.think_timer.tics_this_second(),
            self.time.think_timer.average_ms(),
            self.time.draw_timer.average_ms(),
            self.time.present_timer.average_ms(),
            self.time.wait_timer.average_ms());
        
        if self.time.lag_this_second > 0
        {
            warn!("Too much CPU work, game is slowing down!");
        }
        
        self.time.new_second();
    }

    pub fn run(&mut self)
    {
        self.time = GameloopTimeState::new();
        
        'runloop: loop
        {
            // Consume events
            for event in self.event_pump.poll_iter()
            {
                match event
                {
                    Event::Quit {..} =>
                    {
                        break 'runloop;
                    },
                    Event::Window { win_event, .. } => match win_event
                    {
                        WindowEvent::SizeChanged {..} =>
                        {
                            self.renderer.update_view();
                        }
                        _ => ()
                    }
                    _ => ()
                }
                
                #[cfg(feature = "imgui_integration")]
                self.control.imgui_handler.handle_event(event);
            }
            
            self.think();
            self.draw();
            self.wait();
            self.present();
            
            self.update_fps();
            
            // Go to next scene if one is requested
            if self.control.next_scene_waiting
            {
                std::mem::swap(&mut self.current_scene, &mut self.control.next_scene);
                
                // Reset jiffy queue
                self.time = GameloopTimeState::new();
                self.control.next_scene_waiting = false;
            }
        }
    }
}