From df13db5270aee4e953fafab03513a901e581a383 Mon Sep 17 00:00:00 2001 From: mitchellhansen Date: Tue, 2 Feb 2021 00:46:47 -0800 Subject: [PATCH] ECS'ing it up, lost rendering though, bummer --- src/geometry.rs | 2 +- src/main.rs | 213 +++++++++------------------- src/render.rs | 358 ++++++++++++++++++++++++++++++++++++++++-------- src/runtime.rs | 37 ++--- 4 files changed, 386 insertions(+), 224 deletions(-) diff --git a/src/geometry.rs b/src/geometry.rs index 74ea472..f9ac72e 100644 --- a/src/geometry.rs +++ b/src/geometry.rs @@ -68,7 +68,7 @@ pub fn import_mesh(mesh_path: &str) -> (Vec, Vec) { )); } } - println!("{:?}\n\n\n\n\n {:?}", vertex_data, index_data); + //println!("{:?}\n\n\n\n\n {:?}", vertex_data, index_data); (vertex_data.to_vec(), index_data.to_vec()) } diff --git a/src/main.rs b/src/main.rs index 904c45c..d07c805 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,7 @@ use std::rc::Rc; use wgpu::Buffer; use winit::platform::unix::x11::ffi::Time; use legion::*; +use std::sync::Arc; mod framework; mod geometry; @@ -118,8 +119,8 @@ struct DirectionalLight { #[derive(Clone, Debug)] struct Mesh { - index_buffer: Rc, - vertex_buffer: Rc, + index_buffer: Arc, + vertex_buffer: Arc, } fn main() { @@ -138,31 +139,6 @@ fn main() { use legion::*; let mut world = World::default(); - // This could be used for relationships between entities...??? - let entity: Entity = world.push(( - cgmath::Point3 { - x: -5.0, - y: 7.0, - z: 10.0, - }, - DirectionalLight { - color: wgpu::Color { - r: 1.0, - g: 0.5, - b: 0.5, - a: 1.0, - }, - fov: 45.0, - depth: RangeCopy { start: 1.0, end: 20.0 }, - } - )); - - let entities: &[Entity] = world.extend(vec![ - (Position { x: 0.0, y: 0.0 }, Velocity { dx: 0.0, dy: 0.0 }), - (Position { x: 1.0, y: 1.0 }, Velocity { dx: 0.0, dy: 0.0 }), - (Position { x: 2.0, y: 2.0 }, Velocity { dx: 0.0, dy: 0.0 }), - ]); - /* Querying entities by their handle @@ -180,8 +156,14 @@ fn main() { } */ - // construct a schedule (you should do this on init) - let mut schedule = Schedule::builder() + #[cfg(not(target_arch = "wasm32"))] + let (mut pool, spawner) = { + let local_pool = futures::executor::LocalPool::new(); + let spawner = local_pool.spawner(); + (local_pool, spawner) + }; + + let mut render_schedule = Schedule::builder() .add_system(render::render_test_system()) .build(); @@ -193,7 +175,7 @@ fn main() { // you can then iterate through the components found in the world for position in query.iter(&world) { - println!("{:?}", position); + //println!("{:?}", position); } let event_loop = EventLoop::new(); @@ -207,109 +189,10 @@ fn main() { builder = builder.with_no_redirection_bitmap(true); } - let window = builder.build(&event_loop).unwrap(); - - log::info!("Initializing the surface..."); - - // Grab the GPU instance, and query its features - let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); - let (size, surface) = unsafe { - let size = window.inner_size(); - let surface = instance.create_surface(&window); - (size, surface) - }; - let adapter = - instance - .request_adapter(&wgpu::RequestAdapterOptions { - power_preference: wgpu::PowerPreference::HighPerformance, - compatible_surface: Some(&surface), - }); - - let adapter = futures::executor::block_on(adapter).unwrap(); - - let optional_features = Renderer::optional_features(); - let required_features = Renderer::required_features(); - let adapter_features = adapter.features(); - // assert!( - // adapter_features.contains(required_features), - // "Adapter does not support required features for this example: {:?}", - // required_features - adapter_features - // ); - - let needed_limits = wgpu::Limits::default();//Renderer::required_limits(); - - // Maybe for debug tracing??? - let trace_dir = std::env::var("WGPU_TRACE"); - - // And then get the device we want - let device = adapter - .request_device( - &wgpu::DeviceDescriptor { - features: (optional_features & adapter_features) | required_features, - limits: needed_limits, - shader_validation: true, - }, - trace_dir.ok().as_ref().map(std::path::Path::new), - ); - - let (device, queue) = futures::executor::block_on(device).unwrap(); - - let device = Rc::new(device); - #[cfg(not(target_arch = "wasm32"))] - let (mut pool, spawner) = { - let local_pool = futures::executor::LocalPool::new(); - let spawner = local_pool.spawner(); - (local_pool, spawner) - }; - - // This is some gross-ass web shit - /*#[cfg(target_arch = "wasm32")] - let spawner = { - use futures::{future::LocalFutureObj, task::SpawnError}; - use winit::platform::web::WindowExtWebSys; - - struct WebSpawner {} - impl LocalSpawn for WebSpawner { - fn spawn_local_obj( - &self, - future: LocalFutureObj<'static, ()>, - ) -> Result<(), SpawnError> { - Ok(wasm_bindgen_futures::spawn_local(future)) - } - } - - std::panic::set_hook(Box::new(console_error_panic_hook::hook)); - - // On wasm, append the canvas to the document body - web_sys::window() - .and_then(|win| win.document()) - .and_then(|doc| doc.body()) - .and_then(|body| { - body.append_child(&web_sys::Element::from(window.canvas())) - .ok() - }) - .expect("couldn't append canvas to document body"); - - WebSpawner {} - };*/ + // I think right here is where I can start pulling everything into the renderer + let window = builder.build(&event_loop).unwrap(); - let mut sc_desc = wgpu::SwapChainDescriptor { - // Allows a texture to be a output attachment of a renderpass. - usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, - format: if cfg!(target_arch = "wasm32") { - wgpu::TextureFormat::Bgra8Unorm - } else { - wgpu::TextureFormat::Bgra8UnormSrgb - }, - width: size.width, - height: size.height, - // The presentation engine waits for the next vertical blanking period to update - present_mode: wgpu::PresentMode::Mailbox, - }; - - let mut swap_chain = device.create_swap_chain(&surface, &sc_desc); - log::info!("Done doing the loading part..."); // Not sure why this is guarded, maybe we don't handle the event loop timing? #[cfg(not(target_arch = "wasm32"))] @@ -318,12 +201,49 @@ fn main() { log::info!("Entering render loop..."); // Load up the renderer (and the resources) - let mut renderer = render::Renderer::init(device.clone(), &sc_desc); + let mut renderer = render::Renderer::init(window); + + let (plane_vertex_buffer, plane_index_buffer) = renderer.load_mesh_to_buffer("./resources/untitled.obj"); + + // This could be used for relationships between entities...??? + let light_entity: Entity = world.push(( + cgmath::Point3 { + x: -5.0, + y: 7.0, + z: 10.0, + }, + DirectionalLight { + color: wgpu::Color { + r: 1.0, + g: 0.5, + b: 0.5, + a: 1.0, + }, + fov: 45.0, + depth: RangeCopy { start: 1.0, end: 20.0 }, + } + )); + + let mesh_entity: Entity = world.push(( + cgmath::Point3 { + x: -5.0, + y: 7.0, + z: 10.0, + }, + Mesh { + index_buffer: plane_index_buffer, + vertex_buffer: plane_vertex_buffer, + } + )); - let (plane_vertex_buffer, plane_index_buffer) = Renderer::load_mesh_to_buffer(device.clone(), "./resources/untitled.obj"); + let entities: &[Entity] = world.extend(vec![ + (Position { x: 0.0, y: 0.0 }, Velocity { dx: 0.0, dy: 0.0 }), + (Position { x: 1.0, y: 1.0 }, Velocity { dx: 0.0, dy: 0.0 }), + (Position { x: 2.0, y: 2.0 }, Velocity { dx: 0.0, dy: 0.0 }), + ]); // Init, this wants the references to the buffers... - let mut runtime = runtime::Runtime::init(&sc_desc, &device, &queue); + let mut runtime = runtime::Runtime::init(); let mut resources = Resources::default(); resources.insert(runtime); @@ -331,7 +251,7 @@ fn main() { // This is just an winit event loop event_loop.run(move |event, _, control_flow| { - let _ = (&instance, &adapter); // force ownership by the closure (wtf??) + //let _ = (&instance, &adapter); // force ownership by the closure (wtf??) // Override the control flow behaviour based on our system *control_flow = if cfg!(feature = "metal-auto-capture") { @@ -355,8 +275,8 @@ fn main() { { // ask for a redraw every 20 millis if last_update_inst.elapsed() > Duration::from_millis(20) { - schedule.execute(&mut world, &mut resources); - window.request_redraw(); + render_schedule.execute(&mut world, &mut resources); + //window.request_redraw(); last_update_inst = Instant::now(); } @@ -373,12 +293,12 @@ fn main() { .. } => { log::info!("Resizing to {:?}", size); - sc_desc.width = size.width; - sc_desc.height = size.height; + let width = size.width; + let height = size.height; - resources.get_mut::().unwrap().resize(&sc_desc, &device, &queue); + resources.get_mut::().unwrap().resize(width, height); - swap_chain = device.create_swap_chain(&surface, &sc_desc); + //swap_chain = device.create_swap_chain(&surface, &sc_desc); } event::Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { @@ -398,17 +318,8 @@ fn main() { } }, event::Event::RedrawRequested(_) => { - let frame = match swap_chain.get_current_frame() { - Ok(frame) => frame, - Err(_) => { - swap_chain = device.create_swap_chain(&surface, &sc_desc); - swap_chain - .get_current_frame() - .expect("Failed to acquire next swap chain texture!") - } - }; - resources.get_mut::().unwrap().render(&frame.output, &device, &queue, &spawner); + //resources.get_mut::().unwrap().render(); } _ => {} } diff --git a/src/render.rs b/src/render.rs index 157f5c2..2d7834c 100644 --- a/src/render.rs +++ b/src/render.rs @@ -1,14 +1,19 @@ -use bytemuck::{Pod, Zeroable}; +use std::sync::Arc; +use std::{iter, num::NonZeroU32, ops::Range, rc::Rc}; + use bytemuck::__core::mem; +use bytemuck::{Pod, Zeroable}; +use legion::*; use wgpu::util::DeviceExt; -use std::{iter, num::NonZeroU32, ops::Range, rc::Rc}; -use crate::{OPENGL_TO_WGPU_MATRIX, Velocity}; -use crate::light::LightRaw; -use crate::geometry::{Vertex, import_mesh, create_plane}; -use wgpu::{Buffer, Device}; -use winit::dpi::Position; +use wgpu::{Buffer, Device, SwapChain, Queue, SwapChainFrame, Surface, SwapChainDescriptor, Instance}; +use winit::dpi::{Position, PhysicalSize}; use winit::platform::unix::x11::ffi::Time; -use legion::*; +use winit::window::Window; + +use crate::geometry::{create_plane, import_mesh, Vertex}; +use crate::light::LightRaw; +use crate::{Velocity, OPENGL_TO_WGPU_MATRIX}; +use futures::executor::LocalPool; #[repr(C)] #[derive(Clone, Copy)] @@ -44,7 +49,16 @@ pub struct Pass { } pub struct Renderer { - device: Rc, + window: Window, + swapchain: SwapChain, + swapchain_description: Arc, + instance: Arc, + device: Arc, + queue: Arc, + + size: PhysicalSize, + surface: Arc, + lights_are_dirty: bool, shadow_pass: Pass, forward_pass: Pass, @@ -79,38 +93,178 @@ impl Renderer { } #[system(for_each)] -pub fn render_test(pos: &mut Position, vel: &Velocity) { +pub fn render_test(pos: &mut Position, vel: &Velocity, #[resource] renderer: &mut Renderer) { + + let frame = renderer.get_current_frame(); //pos.x += vel.dx * time.elapsed_seconds; //pos.y += vel.dy * time.elapsed_seconds; -} -impl Renderer { + // frame: &wgpu::SwapChainTexture, + // device: &wgpu::Device, + // queue: &wgpu::Queue, + // _spawner: &impl futures::task::LocalSpawn, + // ) + // { + // update uniforms + // for entity in self.entities.iter_mut() { + // + // // Revolve the entity by the rotation speed, only if it is non-zero + // if entity.rotation_speed != 0.0 { + // let rotation = cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed)); + // entity.mx_world = entity.mx_world * rotation; + // } + // + // let data = EntityUniforms { + // model: entity.mx_world.into(), + // color: [ + // entity.color.r as f32, + // entity.color.g as f32, + // entity.color.b as f32, + // entity.color.a as f32, + // ], + // }; + // queue.write_buffer(&entity.uniform_buf, 0, bytemuck::bytes_of(&data)); + // } + + // if self.lights_are_dirty { + // self.lights_are_dirty = false; + // for (i, light) in self.lights.iter().enumerate() { + // queue.write_buffer( + // &self.light_uniform_buf, + // (i * mem::size_of::()) as wgpu::BufferAddress, + // bytemuck::bytes_of(&light.to_raw()), + // ); + // } + // } + + let mut encoder = renderer + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + + encoder.push_debug_group("shadow passes"); + /*for (i, light) in self.lights.iter().enumerate() { + encoder.push_debug_group(&format!( + "shadow pass {} (light at position {:?})", + i, light.pos + )); + // The light uniform buffer already has the projection, + // let's just copy it over to the shadow uniform buffer. + encoder.copy_buffer_to_buffer( + &self.light_uniform_buf, + (i * mem::size_of::()) as wgpu::BufferAddress, + &self.shadow_pass.uniform_buf, + 0, + 64, + ); + encoder.insert_debug_marker("render entities"); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[], + depth_stencil_attachment: Some( + wgpu::RenderPassDepthStencilAttachmentDescriptor { + attachment: &light.target_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: true, + }), + stencil_ops: None, + }, + ), + }); + pass.set_pipeline(&self.shadow_pass.pipeline); + pass.set_bind_group(0, &self.shadow_pass.bind_group, &[]); + + for entity in &self.entities { + pass.set_bind_group(1, &entity.bind_group, &[]); + pass.set_index_buffer(entity.index_buf.slice(..)); + pass.set_vertex_buffer(0, entity.vertex_buf.slice(..)); + pass.draw_indexed(0..entity.index_count as u32, 0, 0..1); + } + } + + encoder.pop_debug_group(); + }*/ + encoder.pop_debug_group(); + + // forward pass + encoder.push_debug_group("forward rendering pass"); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { + attachment: &frame.output.view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }), + store: true, + }, + }], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor { + attachment: &renderer.forward_depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: false, + }), + stencil_ops: None, + }), + }); + pass.set_pipeline(&renderer.forward_pass.pipeline); + pass.set_bind_group(0, &renderer.forward_pass.bind_group, &[]); + + // for entity in &self.entities { + // pass.set_bind_group(1, &entity.bind_group, &[]); + // pass.set_index_buffer(entity.index_buf.slice(..)); + // pass.set_vertex_buffer(0, entity.vertex_buf.slice(..)); + // pass.draw_indexed(0..entity.index_count as u32, 0, 0..1); + // } + } + encoder.pop_debug_group(); - pub fn create_buffer(device: &wgpu::Device, - indices: Vec, - vertices: Vec) -> (Rc, Rc) { + renderer.queue.submit(iter::once(encoder.finish())); + renderer.window.request_redraw(); +} + +impl Renderer { + + pub fn get_current_frame(&mut self) -> SwapChainFrame { + // Update the renderers swapchain state + match self.swapchain.get_current_frame() { + Ok(frame) => frame, + Err(_) => { + self.swapchain = self.device.create_swap_chain(&self.surface, &self.swapchain_description); + self.swapchain + .get_current_frame() + .expect("Failed to acquire next swap chain texture!") + } + } + } + + pub fn create_buffer( + device: &wgpu::Device, + indices: Vec, + vertices: Vec, + ) -> (Arc, Arc) { // Creates the vertex and index buffers for the cube let vertex_size = mem::size_of::(); //import_mesh("/home/mrh/source/3d-min-viable-eng/resources/my_tree.obj"); - let vertex_buf = Rc::new(device.create_buffer_init( - &wgpu::util::BufferInitDescriptor { + let vertex_buf = Arc::new( + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("vertex-buffer"), contents: bytemuck::cast_slice(&vertices), usage: wgpu::BufferUsage::VERTEX, - }, - )); + }), + ); - let index_buf = Rc::new(device.create_buffer_init( - &wgpu::util::BufferInitDescriptor { + let index_buf = Arc::new( + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("index-buffer"), contents: bytemuck::cast_slice(&indices), usage: wgpu::BufferUsage::INDEX, - }, - )); + }), + ); // // Creates the vertex and index buffers for the plane // let (plane_vertex_data, plane_index_data) = create_plane(7.0); @@ -131,16 +285,110 @@ impl Renderer { (vertex_buf, index_buf) } - - pub fn load_mesh_to_buffer(device: Rc, filepath: &str) -> (Rc, Rc) { + pub fn load_mesh_to_buffer(&self, filepath: &str) -> (Arc, Arc) { let (vertices, indices) = import_mesh(filepath); - Renderer::create_buffer(&device, indices, vertices) + Renderer::create_buffer(&self.device, indices, vertices) } + pub fn init(window: Window) -> Renderer { + log::info!("Initializing the surface..."); + + // Grab the GPU instance, and query its features + let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); + let (size, surface) = unsafe { + let size = window.inner_size(); + let surface = instance.create_surface(&window); + (size, surface) + }; + let surface = Arc::new(surface); + + let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: Some(&surface), + }); + + let adapter = futures::executor::block_on(adapter).unwrap(); + + let optional_features = Renderer::optional_features(); + let required_features = Renderer::required_features(); + let adapter_features = adapter.features(); + // assert!( + // adapter_features.contains(required_features), + // "Adapter does not support required features for this example: {:?}", + // required_features - adapter_features + // ); + + let needed_limits = wgpu::Limits::default(); //Renderer::required_limits(); + + // Maybe for debug tracing??? + let trace_dir = std::env::var("WGPU_TRACE"); + + // And then get the device we want + let device = adapter.request_device( + &wgpu::DeviceDescriptor { + features: (optional_features & adapter_features) | required_features, + limits: needed_limits, + shader_validation: true, + }, + trace_dir.ok().as_ref().map(std::path::Path::new), + ); + + let (device, queue) = futures::executor::block_on(device).unwrap(); + + let queue = Arc::new(queue); + let device = Arc::new(device); - pub fn init(device: Rc, sc_desc: &wgpu::SwapChainDescriptor) -> Renderer { + // This is some gross-ass web shit + /*#[cfg(target_arch = "wasm32")] + let spawner = { + use futures::{future::LocalFutureObj, task::SpawnError}; + use winit::platform::web::WindowExtWebSys; + + struct WebSpawner {} + impl LocalSpawn for WebSpawner { + fn spawn_local_obj( + &self, + future: LocalFutureObj<'static, ()>, + ) -> Result<(), SpawnError> { + Ok(wasm_bindgen_futures::spawn_local(future)) + } + } + + std::panic::set_hook(Box::new(console_error_panic_hook::hook)); + + // On wasm, append the canvas to the document body + web_sys::window() + .and_then(|win| win.document()) + .and_then(|doc| doc.body()) + .and_then(|body| { + body.append_child(&web_sys::Element::from(window.canvas())) + .ok() + }) + .expect("couldn't append canvas to document body"); + + WebSpawner {} + };*/ + + log::info!("Done doing the loading part..."); + + let mut sc_desc = Arc::new(wgpu::SwapChainDescriptor { + // Allows a texture to be a output attachment of a renderpass. + usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, + format: if cfg!(target_arch = "wasm32") { + wgpu::TextureFormat::Bgra8Unorm + } else { + wgpu::TextureFormat::Bgra8UnormSrgb + }, + width: size.width, + height: size.height, + // The presentation engine waits for the next vertical blanking period to update + present_mode: wgpu::PresentMode::Mailbox, + }); + + let mut swap_chain = device.create_swap_chain(&surface, &sc_desc); + let entity_uniform_size = mem::size_of::() as wgpu::BufferAddress; let plane_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { label: None, @@ -239,8 +487,10 @@ impl Renderer { }); // Create the render pipeline - let vs_module = device.create_shader_module(wgpu::include_spirv!("../resources/bake.vert.spv")); - let fs_module = device.create_shader_module(wgpu::include_spirv!("../resources/bake.frag.spv")); + let vs_module = + device.create_shader_module(wgpu::include_spirv!("../resources/bake.vert.spv")); + let fs_module = + device.create_shader_module(wgpu::include_spirv!("../resources/bake.frag.spv")); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("shadow"), @@ -297,7 +547,8 @@ impl Renderer { dynamic: false, min_binding_size: wgpu::BufferSize::new(mem::size_of::< ForwardUniforms, - >() + >( + ) as _), }, count: None, @@ -346,7 +597,6 @@ impl Renderer { num_lights: [1 as u32, 0, 0, 0], }; - let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Uniform Buffer"), contents: bytemuck::bytes_of(&forward_uniforms), @@ -380,7 +630,6 @@ impl Renderer { // shadow_target_views[0].take().unwrap(), // pub(crate) target_view: wgpu::TextureView, - let shadow_view = shadow_texture.create_view(&wgpu::TextureViewDescriptor::default()); let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -395,7 +644,6 @@ impl Renderer { ..Default::default() }); - // Create bind group let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &bind_group_layout, @@ -421,8 +669,10 @@ impl Renderer { }); // Create the render pipeline - let vs_module = device.create_shader_module(wgpu::include_spirv!("../resources/forward.vert.spv")); - let fs_module = device.create_shader_module(wgpu::include_spirv!("../resources/forward.frag.spv")); + let vs_module = + device.create_shader_module(wgpu::include_spirv!("../resources/forward.vert.spv")); + let fs_module = + device.create_shader_module(wgpu::include_spirv!("../resources/forward.frag.spv")); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("main"), @@ -479,18 +729,25 @@ impl Renderer { }); Renderer { + window, + swapchain: swap_chain, + queue: queue, + size, device: device, lights_are_dirty: false, shadow_pass, forward_pass, forward_depth: depth_texture.create_view(&wgpu::TextureViewDescriptor::default()), light_uniform_buf, - // plane_uniform_buf, - // plane_vertex_buf: (), - // plane_index_buf: () + // plane_uniform_buf, + // plane_vertex_buf: (), + // plane_index_buf: () + + swapchain_description: sc_desc, + surface, + instance: Arc::new(instance) } } - // pub fn render( @@ -499,8 +756,7 @@ impl Renderer { device: &wgpu::Device, queue: &wgpu::Queue, _spawner: &impl futures::task::LocalSpawn, - ) - { + ) { // update uniforms // for entity in self.entities.iter_mut() { // @@ -622,6 +878,7 @@ impl Renderer { encoder.pop_debug_group(); queue.submit(iter::once(encoder.finish())); + } pub(crate) fn required_features() -> wgpu::Features { @@ -632,26 +889,20 @@ impl Renderer { wgpu::Features::DEPTH_CLAMPING } - pub fn resize( - &mut self, - sc_desc: &wgpu::SwapChainDescriptor, - device: &wgpu::Device, - queue: &wgpu::Queue, - ) - { + pub fn resize(&mut self, width: u32, height: u32) { // update view-projection matrix - let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); + let mx_total = Self::generate_matrix(width as f32 / height as f32); let mx_ref: &[f32; 16] = mx_total.as_ref(); - queue.write_buffer( + self.queue.write_buffer( &self.forward_pass.uniform_buf, 0, bytemuck::cast_slice(mx_ref), ); - let depth_texture = device.create_texture(&wgpu::TextureDescriptor { + let depth_texture = self.device.create_texture(&wgpu::TextureDescriptor { size: wgpu::Extent3d { - width: sc_desc.width, - height: sc_desc.height, + width: width, + height: height, depth: 1, }, mip_level_count: 1, @@ -664,4 +915,3 @@ impl Renderer { self.forward_depth = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); } } - diff --git a/src/runtime.rs b/src/runtime.rs index 460784d..0658ba7 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -39,9 +39,10 @@ pub struct Runtime { impl Runtime { pub fn init( - sc_desc: &wgpu::SwapChainDescriptor, - device: &wgpu::Device, - _queue: &wgpu::Queue, ) -> Self + // sc_desc: &wgpu::SwapChainDescriptor, + // device: &wgpu::Device, + // _queue: &wgpu::Queue, + ) -> Self { // https://sotrh.github.io/learn-wgpu/beginner/tutorial5-textures/#the-bindgroup @@ -72,21 +73,21 @@ impl Runtime { */ // Defines the Uniform buffer for the Vertex and Fragment shaders - let local_bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, - ty: wgpu::BindingType::UniformBuffer { - dynamic: false, - min_binding_size: wgpu::BufferSize::new( - mem::size_of::() as _ - ), - }, - count: None, - }], - label: None, - }); + // let local_bind_group_layout = + // device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + // entries: &[wgpu::BindGroupLayoutEntry { + // binding: 0, + // visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, + // ty: wgpu::BindingType::UniformBuffer { + // dynamic: false, + // min_binding_size: wgpu::BufferSize::new( + // mem::size_of::() as _ + // ), + // }, + // count: None, + // }], + // label: None, + // }); let mut entities = Vec::default();