From d5ae9d13648bea021cfd6e37505b95707e72ba6b Mon Sep 17 00:00:00 2001 From: Dominik Kaiser Date: Fri, 27 Nov 2026 13:10:19 +0100 Subject: Dependencies and the window --- games/00_triangle/Cargo.toml | 12 ++++++ games/00_triangle/src/main.rs | 93 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 games/00_triangle/Cargo.toml create mode 100644 games/00_triangle/src/main.rs (limited to 'games') diff --git a/games/00_triangle/Cargo.toml b/games/00_triangle/Cargo.toml new file mode 100644 index 0000000..6e183e5 --- /dev/null +++ b/games/00_triangle/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_triangle" +version = "0.1.0" +edition = "2024" + +[dependencies] +anyhow = "1.0" +winit = { version = "0.30", features = ["android-native-activity"] } +env_logger = "0.10" +log = "0.4" +wgpu = "30.0" +pollster = "0.3" \ No newline at end of file diff --git a/games/00_triangle/src/main.rs b/games/00_triangle/src/main.rs new file mode 100644 index 0000000..da9d249 --- /dev/null +++ b/games/00_triangle/src/main.rs @@ -0,0 +1,93 @@ +use std::sync::Arc; + +use winit::{ + application::ApplicationHandler, + event::*, + event_loop::{ActiveEventLoop, EventLoop}, + keyboard::{KeyCode, PhysicalKey}, + window::Window, +}; + +pub struct State { + window: Arc, +} + +impl State { + pub async fn new(window: Arc) -> anyhow::Result { + Ok(Self { window }) + } + + pub fn resize(&mut self, _width: u32, _height: u32) {} + + pub fn render(&mut self) { + self.window.request_redraw(); + } +} + +pub struct App { + state: Option, +} + +impl App { + pub fn new() -> Self { + Self { state: None } + } +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window_attributes = Window::default_attributes(); + let window = Arc::new(event_loop.create_window(window_attributes).unwrap()); + self.state = Some(pollster::block_on(State::new(window)).unwrap()); + } + + fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: State) { + self.state = Some(event); + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: winit::window::WindowId, + event: WindowEvent, + ) { + let state = match &mut self.state { + Some(canvas) => canvas, + None => return, + }; + + match event { + WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::Resized(size) => state.resize(size.width, size.height), + WindowEvent::RedrawRequested => { + state.render(); + } + WindowEvent::KeyboardInput { + event: + KeyEvent { + physical_key: PhysicalKey::Code(code), + state: key_state, + .. + }, + .. + } => match (code, key_state.is_pressed()) { + (KeyCode::Escape, true) => event_loop.exit(), + _ => {} + }, + _ => {} + } + } +} + +pub fn run() -> anyhow::Result<()> { + env_logger::init(); + + let event_loop = EventLoop::with_user_event().build()?; + let mut app = App::new(); + event_loop.run_app(&mut app)?; + Ok(()) +} + +pub fn main() { + run().unwrap(); +} -- cgit v1.2.3