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
// This file is part of Carambolage.

// Carambolage is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Carambolage is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Carambolage.  If not, see <http://www.gnu.org/licenses/>.

/// GameObject, currently only a car.
mod car;
/// User input handling.
mod controller;
/// Environment of a `Scene`.
mod level;
/// Actual runtime data.
mod scene;
/// 3D translation, rotation and scale.
mod transform;

use self::controller::{Controller, ControllerLayout};
use self::scene::Scene;
use glfw::{Action, Context, Glfw, Key, Window};
use grphx::Screen;
use log::{debug, info};
use nalgebra::Perspective3;
use rodio::{Sink, Source};
use time::Duration;
use util::FrameLimiter;

use std::cell::Cell;
use std::fs::File;
use std::io::BufReader;
use std::sync::mpsc::Receiver;
use std::thread::sleep;

type Event = Receiver<(f64, glfw::WindowEvent)>;

pub(crate) struct Game {
    // Glfw and GL
    glfw: Glfw,
    window: Window,
    events: Event,
    frame_limiter: FrameLimiter,

    screen: Screen,

    // Game
    settings: GameSettings,
    scene: Scene,
    controller: Vec<Controller>,
}

pub struct GameSettings {
    pub is_fullscreen: bool,
    pub width: u32,
    pub height: u32,
    pub map: u32,
    pub fps: u32,
}

impl Default for GameSettings {
    fn default() -> GameSettings {
        GameSettings {
            is_fullscreen: false,
            width: 640,
            height: 480,
            map: 1,
            fps: 60,
        }
    }
}

impl Game {
    pub(crate) fn new(settings: GameSettings) -> Game {
        info!("Initializing game");
        let frame_limiter = FrameLimiter::new(settings.fps);

        debug!("Initializing glfw window");
        let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
        glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3));
        glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
        glfw.window_hint(glfw::WindowHint::SRgbCapable(true));
        glfw.set_error_callback(Some(glfw::Callback {
            f: error_callback,
            data: Cell::new(0),
        }));

        let (mut window, events) = glfw
            .with_primary_monitor(|glfw, m| {
                glfw.create_window(settings.width, settings.height, "Carambolage", {
                    if settings.is_fullscreen {
                        m.map_or(glfw::WindowMode::Windowed, |m| glfw::WindowMode::FullScreen(m))
                    } else {
                        glfw::WindowMode::Windowed
                    }
                })
            }).expect("Failed to create GLFW window");

        window.make_current();
        window.set_framebuffer_size_polling(true);
        window.set_cursor_pos_polling(true);
        window.set_scroll_polling(true);
        window.set_cursor_mode(glfw::CursorMode::Normal);

        debug!("Initializing openGL attributes");
        gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
        unsafe {
            gl::Enable(gl::BLEND);
            gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
            gl::Enable(gl::DEPTH_TEST);
            gl::DepthFunc(gl::LESS);
        }

        let screen = Screen::new(settings.width, settings.height);

        let controller = vec![
            Controller::new(true, &ControllerLayout::WASD),
            Controller::new(true, &ControllerLayout::Arrows),
        ];
        let scene = Scene::new(settings.map);

        Game {
            glfw,
            window,
            events,
            frame_limiter,

            screen,

            settings,
            scene,
            controller,
        }
    }

    pub(crate) fn run(&mut self) {
        let device = rodio::default_output_device().unwrap();
        let file = File::open("res/sounds/music/The_Rush.mp3").unwrap();
        let source = rodio::Decoder::new(BufReader::new(file)).unwrap().repeat_infinite();
        let mut sinc = Sink::new(&device);
        sinc.set_volume(0.5);
        sinc.append(source);

        let nano_sec = Duration::nanoseconds(1).to_std().unwrap();

        while !self.window.should_close() {
            let dt = self.frame_limiter.start();
            self.window.make_current();
            self.glfw.poll_events();
            self.process_events();
            self.process_input(dt);

            self.scene.update(dt, &self.controller);

            self.screen.first_step();
            let projection = Perspective3::new(self.settings.width as f32 / self.settings.height as f32, 70., 1.0, 200.).unwrap();
            self.scene.draw(&projection);

            self.screen.second_step();

            self.window.swap_buffers();
            while self.frame_limiter.stop() {
                self.glfw.poll_events();
                sleep(nano_sec);
            }
        }
    }

    #[cfg_attr(feature = "cargo-clippy", allow(single_match))]
    pub fn process_events(&mut self) {
        for (_, event) in glfw::flush_messages(&self.events) {
            match event {
                glfw::WindowEvent::FramebufferSize(width, height) => unsafe {
                    gl::Viewport(0, 0, width, height);
                    self.settings.width = width as u32;
                    self.settings.height = height as u32;
                    self.screen.resize(width as u32, height as u32);
                },
                _ => {}
            }
        }
    }

    pub fn process_input(&mut self, dt: f32) {
        if self.window.get_key(Key::Escape) == Action::Press {
            self.window.set_should_close(true)
        }

        for ctrl in &mut self.controller.iter_mut() {
            ctrl.process_input(&self.window, dt);
        }
    }
}

#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn error_callback(_: glfw::Error, description: String, error_count: &Cell<usize>) {
    println!("GLFW error {}: {}", error_count.get(), description);
    error_count.set(error_count.get() + 1);
}