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