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
//! This module contains the struct `Core` and the trait `GameLoop`
//! This module will change in the near future, so no documentation for you.
//!
//! `GameLoop` is required for a struct if it should be used by the `game_loop()` method of `Core`.

use sdl2;
use sdl2::render::TextureCreator;
use sdl2::pixels::Color;
use sdl2::video::WindowContext;

use std::time::{Duration, Instant};
use std::thread::sleep;
use std::rc::Rc;


use graphic::TextureManager;


/// The main struct of the engine, this struct manages the gameloop and sets up [`SDL2`]
/// # Examples
///
///[`SDL2`]:https://crates.io/crates/sdl2
pub struct Core {
    _sdl_context: sdl2::Sdl,
    _video_subsystem: sdl2::VideoSubsystem,

    canvas: sdl2::render::WindowCanvas,
    event_pump: sdl2::EventPump,
    texture_creator: Rc<TextureCreator<WindowContext>>,

    game_h: u32,
    game_w: u32,
    _scale: u32,

    fps: u32,
    frame_count: u32,
}

impl Core {
    /// Creates a new `Core`.
    ///
    /// # Panics
    ///
    /// * If SDL2 is not setup correctly, this method should `panic!`,
    ///         Right now, only **SDL2** and **SDL2_image** is required.
    ///         Go to the [SDL2 Crate][1] to see how to setup SDL2.
    ///
    /// # Examples
    ///
    /// ```
    /// use crow_engine::core;
    ///
    /// let core = core::Core::new()
    /// ```
    /// [1]: https://crates.io/crates/sdl2
    pub fn new(game_w: u32, game_h: u32, scale: u32, window_title: &str, fps: u32) -> Self {
        let sdl_context = sdl2::init().unwrap();
        let video_subsystem = sdl_context.video().unwrap();

        let mut canvas = video_subsystem
            .window(window_title,game_w*scale,game_h*scale)
            .build().unwrap()
            .into_canvas()
            .target_texture()
            //.present_vsync() // Deactivated for manual framerate adjustments!
            .build().unwrap();
        canvas.set_draw_color(Color::RGB(0, 0, 0));

        let texture_creator = Rc::new(canvas.texture_creator());
        let event_pump = sdl_context.event_pump().unwrap();

        Core {
            _sdl_context: sdl_context,
            _video_subsystem: video_subsystem,

            canvas: canvas,
            event_pump: event_pump,
            texture_creator: texture_creator,

            game_w: game_w,
            game_h: game_h,
            _scale: scale,

            fps: fps,
            frame_count: 0,
        }
    }

    pub fn texture_manager(&self)-> TextureManager {
        TextureManager::new(self.texture_creator.clone())
    }

    pub fn game_loop<T: GameLoop>(&mut self,item: &mut T) {
        let mut running: bool = true;
        let mut render_texture = self.texture_creator.create_texture_target(None, self.game_w, self.game_h).unwrap();
        let time_per_frame = Duration::new(0,1_000_000_000/self.fps);
        let mut now = Instant::now();
        while running {
            item.manage_input(&mut self.event_pump);

            self.canvas.with_texture_canvas(&mut render_texture, |texture_canvas| {
                    //texture_canvas.set_draw_color(Color::RGB(0, 0, 40)); // Should not be needed as the whole screen should be filled every frame
                    //texture_canvas.clear(); // Should not be needed as the whole screen should be filled every frame
                    running = item.frame(texture_canvas);
                }).unwrap();
            self.canvas.copy_ex(&render_texture,
                                None,
                                None,
                                0.0,
                                None,
                                false,
                                true).unwrap();
            self.canvas.present();

            self.frame_count += 1;
            let elapsed_time = now.elapsed();
            if elapsed_time < time_per_frame*self.frame_count {
                sleep(time_per_frame* self.frame_count - elapsed_time);
            }
            else {
                now = Instant::now();
                self.frame_count = 0;
                println!("Could not catch up, dropped a frame!");
            }
        }
    }
}

pub trait GameLoop {
    fn frame<T: sdl2::render::RenderTarget>(&mut self,texture_canvas:&mut sdl2::render::Canvas<T>) -> bool;

    fn manage_input(&mut self, event_pump: &mut sdl2::EventPump);
}