Fixed a warning and allowed two others
[kaka/rust-sdl-test.git] / src / game / app.rs
CommitLineData
6ba7aef1
TW
1use boll::*;
2use common::{Point2D, Rect};
3use point; // defined in common, but loaded from main...
95e3e10d
TW
4use rand::Rng;
5use sdl2::event::Event;
6ba7aef1
TW
6use sdl2::event::WindowEvent;
7use sdl2::gfx::primitives::DrawRenderer;
95e3e10d 8use sdl2::keyboard::Keycode;
3bfea951 9use sdl2::pixels::Color;
6ba7aef1 10use sdl2::rect::Rect as SDLRect;
3bfea951
TW
11use sdl2::render::BlendMode;
12use sdl2::render::Canvas;
6ba7aef1 13use sdl2::video::FullscreenType;
fea68d56 14use sdl2::video::{SwapInterval, Window};
6ba7aef1 15use sdl2::{EventPump, VideoSubsystem};
3bfea951 16use sprites::SpriteManager;
6ba7aef1
TW
17use std::f32::consts::PI;
18use time::PreciseTime;
19use {SCREEN_HEIGHT, SCREEN_WIDTH};
95e3e10d
TW
20
21pub type Nanoseconds = u64;
3bfea951 22
6ba7aef1
TW
23const FPS: u32 = 60;
24const NS_PER_FRAME: u32 = 1_000_000_000 / FPS;
25
6edafdc0
TW
26#[derive(Default)]
27pub struct AppBuilder {
28 resolution: Rect<u16>,
6edafdc0
TW
29 state: Option<Box<dyn AppState>>,
30 title: Option<String>,
3bfea951
TW
31}
32
6edafdc0
TW
33impl AppBuilder {
34 pub fn with_resolution(mut self, width: u16, height: u16) -> Self {
6ba7aef1
TW
35 self.resolution = Rect { width, height };
36 self
6edafdc0
TW
37 }
38
6edafdc0 39 pub fn with_state(mut self, state: Box<dyn AppState>) -> Self {
6ba7aef1
TW
40 self.state = Some(state);
41 self
6edafdc0
TW
42 }
43
44 pub fn with_title(mut self, title: &str) -> Self {
6ba7aef1
TW
45 self.title = Some(title.to_string());
46 self
6edafdc0
TW
47 }
48
fea68d56 49 pub fn build(self) -> Result<App, String> {
3bfea951 50 let context = sdl2::init().unwrap();
fea68d56 51 sdl2::image::init(sdl2::image::InitFlag::PNG)?;
6ba7aef1 52 let video = context.video()?;
fea68d56 53
6ba7aef1 54 self.print_video_display_modes(&video);
fea68d56
TW
55
56 let window = video
6ba7aef1
TW
57 .window(
58 &self.title.unwrap(),
59 self.resolution.width.into(),
60 self.resolution.height.into(),
61 )
3bfea951 62 .position_centered()
6ba7aef1
TW
63 // .fullscreen()
64 // .fullscreen_desktop()
3bfea951 65 .opengl()
6ba7aef1
TW
66 .build()
67 .unwrap();
3bfea951 68 context.mouse().show_cursor(false);
6edafdc0 69
3bfea951
TW
70 let mut canvas = window.into_canvas().build().unwrap();
71 canvas.set_blend_mode(BlendMode::Add);
72 canvas.set_draw_color(Color::RGB(0, 0, 0));
73 canvas.clear();
74 canvas.present();
6edafdc0 75
6ba7aef1 76 video.gl_set_swap_interval(SwapInterval::VSync)?;
fea68d56
TW
77
78 let event_pump = context.event_pump()?;
3bfea951 79 let sprites = SpriteManager::new(canvas.texture_creator());
6edafdc0 80
fea68d56 81 Ok(App {
3bfea951
TW
82 canvas,
83 event_pump,
84 sprites,
98995f2b 85 state: self.state.unwrap_or_else(|| Box::new(ActiveState::new())),
fea68d56
TW
86 })
87 }
88
89 fn print_video_display_modes(&self, video: &VideoSubsystem) {
6ba7aef1
TW
90 println!("video subsystem: {:?}", video);
91 println!("current_video_driver: {:?}", video.current_video_driver());
92 for display in 0..video.num_video_displays().unwrap() {
93 println!(
94 "=== display {} - {} ===",
95 display,
96 video.display_name(display).unwrap()
97 );
98 println!(
99 " display_bounds: {:?}",
100 video.display_bounds(display).unwrap()
101 );
102 println!(
103 " num_display_modes: {:?}",
104 video.num_display_modes(display).unwrap()
105 );
106 println!(
107 " desktop_display_mode: {:?}",
108 video.desktop_display_mode(display).unwrap()
109 );
110 println!(
111 " current_display_mode: {:?}",
112 video.current_display_mode(display).unwrap()
113 );
114 for mode in 0..video.num_display_modes(display).unwrap() {
115 println!(
116 " {:2}: {:?}",
117 mode,
118 video.display_mode(display, mode).unwrap()
119 );
120 }
121 }
122 println!("swap interval: {:?}", video.gl_get_swap_interval());
3bfea951 123 }
6edafdc0
TW
124}
125
126pub struct App {
127 pub canvas: Canvas<Window>,
128 pub event_pump: EventPump,
129 pub sprites: SpriteManager,
130 pub state: Box<dyn AppState>,
131}
132
133impl App {
98995f2b 134 #[allow(clippy::new_ret_no_self)]
6edafdc0 135 pub fn new() -> AppBuilder {
6ba7aef1 136 Default::default()
6edafdc0 137 }
3bfea951 138
1e322944 139 pub fn load_sprites(&mut self, sprites: &[(&str, &str)]) {
3bfea951
TW
140 for (name, file) in sprites {
141 self.sprites.load(name, file);
142 }
143 }
6ba7aef1
TW
144
145 pub fn start(&mut self) {
146 let mut frame_count: u64 = 0;
147 let mut fps_time = PreciseTime::now();
148 let mut last_time = PreciseTime::now();
149
150 let mut mario_angle = 0.0;
151
152 'running: loop {
153 self.canvas.set_draw_color(Color::RGB(0, 0, 0));
154 self.canvas.clear();
155 {
156 let blocks = 20;
157 let size = 32;
158 let offset = point!(
159 (SCREEN_WIDTH as i32 - (blocks + 1) * size) / 2,
160 (SCREEN_HEIGHT as i32 - (blocks + 1) * size) / 2
161 );
162 let block = self.sprites.get("block");
163 for i in 0..blocks {
164 self.canvas
165 .copy(
166 block,
167 None,
168 SDLRect::new((i) * size + offset.x, offset.y, size as u32, size as u32),
169 )
170 .unwrap();
171 self.canvas
172 .copy(
173 block,
174 None,
175 SDLRect::new(
176 (blocks - i) * size + offset.x,
177 (blocks) * size + offset.y,
178 size as u32,
179 size as u32,
180 ),
181 )
182 .unwrap();
183 self.canvas
184 .copy(
185 block,
186 None,
187 SDLRect::new(
188 offset.x,
189 (blocks - i) * size + offset.y,
190 size as u32,
191 size as u32,
192 ),
193 )
194 .unwrap();
195 self.canvas
196 .copy(
197 block,
198 None,
199 SDLRect::new(
200 (blocks) * size + offset.x,
201 (i) * size + offset.y,
202 size as u32,
203 size as u32,
204 ),
205 )
206 .unwrap();
207 }
208 }
209 {
210 let size = 64;
211 let offset = point!(
212 (SCREEN_WIDTH as i32 - size) / 2,
213 (SCREEN_HEIGHT as i32 - size) / 2
214 );
215 let radius = 110.0 + size as f32 * 0.5;
216 let angle = (mario_angle as f32 - 90.0) * PI / 180.0;
217 let offset2 = point!((angle.cos() * radius) as i32, (angle.sin() * radius) as i32);
218 self.canvas
219 .copy_ex(
220 self.sprites.get("mario"),
221 None,
222 SDLRect::new(
223 offset.x + offset2.x,
224 offset.y + offset2.y,
225 size as u32,
226 size as u32,
227 ),
228 mario_angle,
229 sdl2::rect::Point::new(size / 2, size / 2),
230 false,
231 false,
232 )
233 .unwrap();
234 mario_angle += 1.0;
235 if mario_angle >= 360.0 {
236 mario_angle -= 360.0
237 }
238 }
239 {
240 let p = point!((SCREEN_WIDTH / 2) as i16, (SCREEN_HEIGHT / 2) as i16);
241 self.canvas
242 .circle(p.x, p.y, 100, Color::RGB(255, 255, 255))
243 .unwrap();
244 self.canvas
245 .aa_circle(p.x, p.y, 110, Color::RGB(255, 255, 255))
246 .unwrap();
247 self.canvas
248 .ellipse(p.x, p.y, 50, 100, Color::RGB(255, 255, 255))
249 .unwrap();
250 self.canvas
251 .aa_ellipse(p.x, p.y, 110, 55, Color::RGB(255, 255, 255))
252 .unwrap();
253 }
254
255 // window.gl_swap_window();
256 for event in self.event_pump.poll_iter() {
257 match event {
258 Event::Quit { .. }
259 | Event::KeyDown {
260 keycode: Some(Keycode::Escape),
261 ..
262 } => {
263 break 'running;
264 }
265 Event::KeyDown {
266 keycode: Some(Keycode::F11),
267 ..
268 } => {
269 match self.canvas.window().fullscreen_state() {
270 FullscreenType::Off => self
271 .canvas
272 .window_mut()
273 .set_fullscreen(FullscreenType::Desktop),
274 _ => self.canvas.window_mut().set_fullscreen(FullscreenType::Off),
275 }
276 .unwrap();
277 }
278 Event::Window {
279 win_event: WindowEvent::Resized(x, y),
280 ..
281 } => {
282 println!("window resized({}, {})", x, y)
283 }
284 Event::Window {
285 win_event: WindowEvent::Maximized,
286 ..
287 } => {
288 println!("window maximized")
289 }
290 Event::Window {
291 win_event: WindowEvent::Restored,
292 ..
293 } => {
294 println!("window restored")
295 }
296 Event::Window {
297 win_event: WindowEvent::Enter,
298 ..
299 } => {
300 println!("window enter")
301 }
302 Event::Window {
303 win_event: WindowEvent::Leave,
304 ..
305 } => {
306 println!("window leave")
307 }
308 Event::Window {
309 win_event: WindowEvent::FocusGained,
310 ..
311 } => {
312 println!("window focus gained")
313 }
314 Event::Window {
315 win_event: WindowEvent::FocusLost,
316 ..
317 } => {
318 println!("window focus lost")
319 }
320 _ => self.state.on_event(event),
321 }
322 }
323
324 let duration =
325 last_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as Nanoseconds;
326 last_time = PreciseTime::now();
327 self.state.update(duration);
328 self.state.render(&mut self.canvas);
329 self.canvas.present();
330
331 frame_count += 1;
332 if frame_count == FPS as u64 {
333 let duration = fps_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as f64
334 / 1_000_000_000.0;
335 println!("fps: {}", frame_count as f64 / duration);
336 frame_count = 0;
337 fps_time = PreciseTime::now();
338 }
339 }
340
341 self.state.leave();
342 }
3bfea951 343}
95e3e10d
TW
344
345pub trait AppState {
346 fn update(&mut self, dt: Nanoseconds);
347 fn render(&self, canvas: &mut Canvas<Window>);
348 fn leave(&self);
349 fn on_event(&mut self, event: Event);
350}
351
352type Bollar = Vec<Box<dyn Boll>>;
353
354pub struct ActiveState {
355 bolls: Bollar,
356 boll_size: u32,
357}
358
359impl ActiveState {
6edafdc0 360 pub fn new() -> ActiveState {
95e3e10d
TW
361 ActiveState {
362 bolls: Bollar::new(),
363 boll_size: 1,
364 }
365 }
366
367 fn change_boll_count(&mut self, delta: i32) {
98995f2b 368 #[allow(clippy::comparison_chain)]
95e3e10d
TW
369 if delta > 0 {
370 for _i in 0..delta {
371 self.add_boll();
372 }
373 } else if delta < 0 {
5cbbebbe 374 for _i in 0..(-delta) {
95e3e10d
TW
375 self.bolls.pop();
376 }
377 }
378 }
379
380 fn add_boll(&mut self) {
381 let mut rng = rand::thread_rng();
382 self.bolls.push(Box::new(SquareBoll {
6ba7aef1
TW
383 pos: point!(
384 rng.gen_range(0, SCREEN_WIDTH) as f64,
385 rng.gen_range(0, SCREEN_HEIGHT) as f64
386 ),
95e3e10d
TW
387 vel: point!(rng.gen_range(-2.0, 2.0), rng.gen_range(-2.0, 2.0)),
388 }));
389 }
390}
391
392impl AppState for ActiveState {
393 fn update(&mut self, dt: Nanoseconds) {
93679b27 394 for b in &mut self.bolls {
95e3e10d
TW
395 b.update();
396 }
397
398 match dt {
6ba7aef1
TW
399 ns if ns < (NS_PER_FRAME - 90_0000) as u64 => self.change_boll_count(100),
400 ns if ns > (NS_PER_FRAME + 90_0000) as u64 => self.change_boll_count(-100),
95e3e10d
TW
401 _ => {}
402 }
403 }
404
405 fn render(&self, canvas: &mut Canvas<Window>) {
93679b27 406 for b in &self.bolls {
95e3e10d
TW
407 b.draw(canvas, self.boll_size);
408 }
409 }
410
411 fn leave(&self) {
412 println!("number of bolls: {}", self.bolls.len());
413 }
414
415 fn on_event(&mut self, event: Event) {
416 match event {
6ba7aef1
TW
417 Event::KeyDown {
418 keycode: Some(Keycode::KpPlus),
419 ..
420 } => self.boll_size = std::cmp::min(self.boll_size + 1, 32),
421 Event::KeyDown {
422 keycode: Some(Keycode::KpMinus),
423 ..
424 } => self.boll_size = std::cmp::max(self.boll_size - 1, 1),
425 Event::MouseMotion { x, y, .. } => self.bolls.push(Box::new(CircleBoll::new(
426 point!(x as f64, y as f64),
427 point!(0.0, 0.0),
428 ))),
95e3e10d
TW
429 _ => {}
430 }
431 }
432}