use std::{fmt::Debug, sync::Arc}; use glam::Vec2; use wgpu::util::DeviceExt; use winit::{ application::ApplicationHandler, event::*, event_loop::{ActiveEventLoop, EventLoop}, keyboard::{KeyCode, PhysicalKey}, window::Window, }; #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] struct Vertex { position: [f32; 3], color: [f32; 3], } impl Vertex { fn desc() -> wgpu::VertexBufferLayout<'static> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &[ //position wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x3, }, //color wgpu::VertexAttribute { offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, format: wgpu::VertexFormat::Float32x3, }, ], } } } const GAME_SIZE: glam::Vec2 = glam::Vec2::new(800.0, 450.0); const PADDLE_SPEED: f32 = 0.5; const BALL_SPEED: f32 = 0.2; pub struct Ball { position: glam::Vec2, size: glam::Vec2, velocity: glam::Vec2, } pub struct Paddle { position: glam::Vec2, size: glam::Vec2, velocity_y: f32, } impl Ball { fn collides_with(&self, p: &Paddle) -> bool { let pos = self.position; let size = self.size; pos.x + size.x > p.position.x && pos.x < p.position.x + p.size.x && pos.y + size.y > p.position.y && pos.y < p.position.y + p.size.y } } #[rustfmt::skip] const INDICES: &[u16] = &[ 0, 2, 1, 1, 2, 3, 4, 6, 5, 5, 6, 7, 8, 10, 9, 9, 10, 11, ]; pub struct State { surface: wgpu::Surface<'static>, device: wgpu::Device, queue: wgpu::Queue, config: wgpu::SurfaceConfiguration, is_surface_configured: bool, window: Arc, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, index_buffer: wgpu::Buffer, num_indices: u32, ball: Ball, p1: Paddle, p2: Paddle, } impl State { pub async fn new(window: Arc) -> anyhow::Result { let size = window.inner_size(); println!("Window size: {}x{}", size.width, size.height); let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends: wgpu::Backends::PRIMARY, flags: Default::default(), memory_budget_thresholds: Default::default(), backend_options: Default::default(), display: None, }); let surface = instance.create_surface(window.clone()).unwrap(); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: Some(&surface), force_fallback_adapter: false, apply_limit_buckets: true, }) .await?; let (device, queue) = adapter .request_device(&wgpu::wgt::DeviceDescriptor { label: None, required_features: wgpu::Features::empty(), experimental_features: wgpu::ExperimentalFeatures::disabled(), required_limits: wgpu::Limits::default(), memory_hints: Default::default(), trace: wgpu::Trace::Off, }) .await?; let surface_caps = surface.get_capabilities(&adapter); let surface_format = surface_caps .formats .iter() .find(|f| f.is_srgb()) .copied() .unwrap_or(surface_caps.formats[0]); let config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: surface_format, width: size.width, height: size.height, present_mode: surface_caps.present_modes[0], alpha_mode: surface_caps.alpha_modes[0], view_formats: vec![], desired_maximum_frame_latency: 2, color_space: wgpu::SurfaceColorSpace::Auto, }; let shader = device.create_shader_module(wgpu::include_wgsl!("shader.wgsl")); let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Render Pipeline Layout"), bind_group_layouts: &[], immediate_size: 0, }); let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(&render_pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[Some(Vertex::desc())], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(wgpu::ColorTargetState { format: config.format, blend: Some(wgpu::BlendState::REPLACE), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: Some(wgpu::Face::Back), polygon_mode: wgpu::PolygonMode::Fill, unclipped_depth: false, conservative: false, }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, multiview_mask: None, cache: None, }); let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Index Buffer"), contents: bytemuck::cast_slice(INDICES), usage: wgpu::BufferUsages::INDEX, }); let num_indices = INDICES.len() as u32; let ball = Ball { position: Vec2::new(GAME_SIZE.x / 2.0 - 4.0, GAME_SIZE.y / 2.0 - 4.0), size: Vec2::new(8.0, 8.0), velocity: Vec2::ZERO, }; let p1 = Paddle { position: Vec2::new(50.0, GAME_SIZE.y / 2.0 - 32.0), size: Vec2::new(8.0, 64.0), velocity_y: 0.0, }; let p2 = Paddle { position: Vec2::new(GAME_SIZE.x - 50.0, GAME_SIZE.y / 2.0 - 32.0), size: Vec2::new(8.0, 64.0), velocity_y: 0.0, }; let vertices = &[ // Ball Vertex { position: [ball.position.x, ball.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [ball.position.x + ball.size.x, ball.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [ball.position.x, ball.position.y + ball.size.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [ ball.position.x + ball.size.x, ball.position.y + ball.size.y, 0.0, ], color: [1.0, 1.0, 1.0], }, // Paddle 1 Vertex { position: [p1.position.x, p1.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p1.position.x + p1.size.x, p1.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p1.position.x, p1.position.y + p1.size.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p1.position.x + p1.size.x, p1.position.y + p1.size.y, 0.0], color: [1.0, 1.0, 1.0], }, // Paddle 2 Vertex { position: [p2.position.x, p2.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p2.position.x + p2.size.x, p2.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p2.position.x, p2.position.y + p2.size.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p2.position.x + p2.size.x, p2.position.y + p2.size.y, 0.0], color: [1.0, 1.0, 1.0], }, ]; let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Vertex Buffer"), contents: bytemuck::cast_slice(vertices), usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, }); Ok(Self { surface, device, queue, config, is_surface_configured: false, render_pipeline, window, vertex_buffer, index_buffer, num_indices, ball, p1, p2, }) } pub fn resize(&mut self, width: u32, height: u32) { if width > 0 && height > 0 { self.config.width = width; self.config.height = height; self.surface.configure(&self.device, &self.config); self.is_surface_configured = true; } } pub fn handle_key(&mut self, event_loop: &ActiveEventLoop, code: KeyCode, is_pressed: bool) { match (code, is_pressed) { (KeyCode::Escape, true) => event_loop.exit(), (KeyCode::KeyW, pressed) => { self.p1.velocity_y = if pressed { -PADDLE_SPEED } else { 0.0 }; } (KeyCode::KeyS, pressed) => { self.p1.velocity_y = if pressed { PADDLE_SPEED } else { 0.0 }; } (KeyCode::ArrowUp, pressed) => { self.p2.velocity_y = if pressed { -PADDLE_SPEED } else { 0.0 }; } (KeyCode::ArrowDown, pressed) => { self.p2.velocity_y = if pressed { PADDLE_SPEED } else { 0.0 }; } (KeyCode::Space, true) => { if self.ball.velocity.x == 0.0 { self.ball.velocity.x = BALL_SPEED; self.ball.velocity.y = BALL_SPEED; } } _ => {} } } pub fn update(&mut self) { self.p1.position.y = (self.p1.position.y + self.p1.velocity_y).clamp(0.0, GAME_SIZE.y - self.p1.size.y); self.p2.position.y = (self.p2.position.y + self.p2.velocity_y).clamp(0.0, GAME_SIZE.y - self.p2.size.y); let ball = &mut self.ball; ball.position += ball.velocity; if ball.position.y < 0.0 || ball.position.y + ball.size.y > GAME_SIZE.y { ball.velocity.y = -ball.velocity.y; } if ball.collides_with(&self.p1) || ball.collides_with(&self.p2) { ball.velocity.x = -ball.velocity.x; } if ball.position.x < 0.0 || ball.position.x > GAME_SIZE.x { ball.velocity = glam::Vec2::ZERO; ball.position = glam::Vec2::new( (GAME_SIZE.x - ball.size.x) / 2.0, (GAME_SIZE.y - ball.size.y) / 2.0, ); println!("Hit"); } } pub fn render(&mut self) -> anyhow::Result<()> { self.window.request_redraw(); if !self.is_surface_configured { return Ok(()); } let output = match self.surface.get_current_texture() { wgpu::CurrentSurfaceTexture::Success(surface_texture) => surface_texture, wgpu::CurrentSurfaceTexture::Suboptimal(surface_texture) => surface_texture, wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Validation => { return Ok(()); } wgpu::CurrentSurfaceTexture::Outdated => { self.surface.configure(&self.device, &self.config); return Ok(()); } wgpu::CurrentSurfaceTexture::Lost => { anyhow::bail!("Lost device"); } }; let view = output .texture .create_view(&wgpu::wgt::TextureViewDescriptor::default()); let mut encoder = self.device .create_command_encoder(&wgpu::wgt::CommandEncoderDescriptor { label: Some("Render Encoder"), }); let ball = &self.ball; let p1 = &self.p1; let p2 = &self.p2; let vertices = &[ // Ball Vertex { position: [ball.position.x, ball.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [ball.position.x + ball.size.x, ball.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [ball.position.x, ball.position.y + ball.size.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [ ball.position.x + ball.size.x, ball.position.y + ball.size.y, 0.0, ], color: [1.0, 1.0, 1.0], }, // Paddle 1 Vertex { position: [p1.position.x, p1.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p1.position.x + p1.size.x, p1.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p1.position.x, p1.position.y + p1.size.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p1.position.x + p1.size.x, p1.position.y + p1.size.y, 0.0], color: [1.0, 1.0, 1.0], }, // Paddle 2 Vertex { position: [p2.position.x, p2.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p2.position.x + p2.size.x, p2.position.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p2.position.x, p2.position.y + p2.size.y, 0.0], color: [1.0, 1.0, 1.0], }, Vertex { position: [p2.position.x + p2.size.x, p2.position.y + p2.size.y, 0.0], color: [1.0, 1.0, 1.0], }, ]; { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, depth_slice: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, occlusion_query_set: None, timestamp_writes: None, multiview_mask: None, }); render_pass.set_pipeline(&self.render_pipeline); render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16); self.queue .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(vertices)); render_pass.draw_indexed(0..self.num_indices, 0, 0..1); } self.queue.submit(std::iter::once(encoder.finish())); self.queue.present(output); Ok(()) } } 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.update(); match state.render() { Ok(_) => {} Err(e) => { log::error!("{e}"); event_loop.exit(); } } } WindowEvent::KeyboardInput { event: KeyEvent { physical_key: PhysicalKey::Code(code), state: key_state, .. }, .. } => state.handle_key(event_loop, code, key_state.is_pressed()), _ => {} } } } 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(); }