From 1fe59e71dbb41f6b8922dc8c0aaf248db9b6b16a Mon Sep 17 00:00:00 2001 From: Tristam MacDonald Date: Tue, 5 Mar 2019 20:41:24 -0800 Subject: [PATCH] run cargo fmt --- examples/hello_triangle_rust/main.rs | 60 +-- gfx-examples/src/cube.rs | 154 ++++---- gfx-examples/src/framework.rs | 58 ++- gfx-examples/src/shadow.rs | 358 +++++++++-------- wgpu-native/src/binding_model.rs | 6 +- wgpu-native/src/command/allocator.rs | 5 +- wgpu-native/src/command/bind.rs | 28 +- wgpu-native/src/command/compute.rs | 32 +- wgpu-native/src/command/mod.rs | 118 +++--- wgpu-native/src/command/render.rs | 83 ++-- wgpu-native/src/command/transfer.rs | 107 ++--- wgpu-native/src/conv.rs | 80 ++-- wgpu-native/src/device.rs | 559 +++++++++++++-------------- wgpu-native/src/hub.rs | 25 +- wgpu-native/src/instance.rs | 45 +-- wgpu-native/src/lib.rs | 6 +- wgpu-native/src/pipeline.rs | 8 +- wgpu-native/src/resource.rs | 14 +- wgpu-native/src/swap_chain.rs | 67 ++-- wgpu-native/src/track.rs | 59 ++- wgpu-remote/src/lib.rs | 16 +- wgpu-rs/src/lib.rs | 146 ++++--- 22 files changed, 1030 insertions(+), 1004 deletions(-) diff --git a/examples/hello_triangle_rust/main.rs b/examples/hello_triangle_rust/main.rs index 5362fe033..56a9b3e74 100644 --- a/examples/hello_triangle_rust/main.rs +++ b/examples/hello_triangle_rust/main.rs @@ -43,21 +43,22 @@ fn main() { depth_bias_clamp: 0.0, }, primitive_topology: wgpu::PrimitiveTopology::TriangleList, - color_states: &[ - wgpu::ColorStateDescriptor { - format: wgpu::TextureFormat::Bgra8Unorm, - color: wgpu::BlendDescriptor::REPLACE, - alpha: wgpu::BlendDescriptor::REPLACE, - write_mask: wgpu::ColorWriteFlags::ALL, - }, - ], + color_states: &[wgpu::ColorStateDescriptor { + format: wgpu::TextureFormat::Bgra8Unorm, + color: wgpu::BlendDescriptor::REPLACE, + alpha: wgpu::BlendDescriptor::REPLACE, + write_mask: wgpu::ColorWriteFlags::ALL, + }], depth_stencil_state: None, index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[], sample_count: 1, }); - use wgpu::winit::{ControlFlow, Event, ElementState, EventsLoop, KeyboardInput, Window, WindowEvent, VirtualKeyCode}; + use wgpu::winit::{ + ControlFlow, ElementState, Event, EventsLoop, KeyboardInput, VirtualKeyCode, Window, + WindowEvent, + }; let mut events_loop = EventsLoop::new(); let window = Window::new(&events_loop).unwrap(); @@ -67,35 +68,40 @@ fn main() { .to_physical(window.get_hidpi_factor()); let surface = instance.create_surface(&window); - let mut swap_chain = device.create_swap_chain(&surface, &wgpu::SwapChainDescriptor { - usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT, - format: wgpu::TextureFormat::Bgra8Unorm, - width: size.width as u32, - height: size.height as u32, - }); + let mut swap_chain = device.create_swap_chain( + &surface, + &wgpu::SwapChainDescriptor { + usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8Unorm, + width: size.width as u32, + height: size.height as u32, + }, + ); events_loop.run_forever(|event| { match event { Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { - input: KeyboardInput { virtual_keycode: Some(code), state: ElementState::Pressed, .. }, + input: + KeyboardInput { + virtual_keycode: Some(code), + state: ElementState::Pressed, + .. + }, .. } => match code { - VirtualKeyCode::Escape => { - return ControlFlow::Break - } + VirtualKeyCode::Escape => return ControlFlow::Break, _ => {} - } - WindowEvent::CloseRequested => { - return ControlFlow::Break - } + }, + WindowEvent::CloseRequested => return ControlFlow::Break, _ => {} - } + }, _ => {} } let frame = swap_chain.get_next_texture(); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { @@ -110,9 +116,7 @@ fn main() { rpass.draw(0..3, 0..1); } - device - .get_queue() - .submit(&[encoder.finish()]); + device.get_queue().submit(&[encoder.finish()]); ControlFlow::Continue }); diff --git a/gfx-examples/src/cube.rs b/gfx-examples/src/cube.rs index cd9e5ea3e..a8de95d9e 100644 --- a/gfx-examples/src/cube.rs +++ b/gfx-examples/src/cube.rs @@ -1,6 +1,5 @@ mod framework; - #[derive(Clone, Copy)] struct Vertex { _pos: [f32; 4], @@ -17,41 +16,41 @@ fn vertex(pos: [i8; 3], tc: [i8; 2]) -> Vertex { fn create_vertices() -> (Vec, Vec) { let vertex_data = [ // top (0, 0, 1) - vertex([-1, -1, 1], [0, 0]), - vertex([ 1, -1, 1], [1, 0]), - vertex([ 1, 1, 1], [1, 1]), - vertex([-1, 1, 1], [0, 1]), + vertex([-1, -1, 1], [0, 0]), + vertex([1, -1, 1], [1, 0]), + vertex([1, 1, 1], [1, 1]), + vertex([-1, 1, 1], [0, 1]), // bottom (0, 0, -1) - vertex([-1, 1, -1], [1, 0]), - vertex([ 1, 1, -1], [0, 0]), - vertex([ 1, -1, -1], [0, 1]), + vertex([-1, 1, -1], [1, 0]), + vertex([1, 1, -1], [0, 0]), + vertex([1, -1, -1], [0, 1]), vertex([-1, -1, -1], [1, 1]), // right (1, 0, 0) - vertex([ 1, -1, -1], [0, 0]), - vertex([ 1, 1, -1], [1, 0]), - vertex([ 1, 1, 1], [1, 1]), - vertex([ 1, -1, 1], [0, 1]), + vertex([1, -1, -1], [0, 0]), + vertex([1, 1, -1], [1, 0]), + vertex([1, 1, 1], [1, 1]), + vertex([1, -1, 1], [0, 1]), // left (-1, 0, 0) - vertex([-1, -1, 1], [1, 0]), - vertex([-1, 1, 1], [0, 0]), - vertex([-1, 1, -1], [0, 1]), + vertex([-1, -1, 1], [1, 0]), + vertex([-1, 1, 1], [0, 0]), + vertex([-1, 1, -1], [0, 1]), vertex([-1, -1, -1], [1, 1]), // front (0, 1, 0) - vertex([ 1, 1, -1], [1, 0]), - vertex([-1, 1, -1], [0, 0]), - vertex([-1, 1, 1], [0, 1]), - vertex([ 1, 1, 1], [1, 1]), + vertex([1, 1, -1], [1, 0]), + vertex([-1, 1, -1], [0, 0]), + vertex([-1, 1, 1], [0, 1]), + vertex([1, 1, 1], [1, 1]), // back (0, -1, 0) - vertex([ 1, -1, 1], [0, 0]), - vertex([-1, -1, 1], [1, 0]), + vertex([1, -1, 1], [0, 0]), + vertex([-1, -1, 1], [1, 0]), vertex([-1, -1, -1], [1, 1]), - vertex([ 1, -1, -1], [0, 1]), + vertex([1, -1, -1], [0, 1]), ]; let index_data: &[u16] = &[ - 0, 1, 2, 2, 3, 0, // top - 4, 5, 6, 6, 7, 4, // bottom - 8, 9, 10, 10, 11, 8, // right + 0, 1, 2, 2, 3, 0, // top + 4, 5, 6, 6, 7, 4, // bottom + 8, 9, 10, 10, 11, 8, // right 12, 13, 14, 14, 15, 12, // left 16, 17, 18, 18, 19, 16, // front 20, 21, 22, 22, 23, 20, // back @@ -63,13 +62,13 @@ fn create_vertices() -> (Vec, Vec) { fn create_texels(size: usize) -> Vec { use std::iter; - (0 .. size * size) + (0..size * size) .flat_map(|id| { // get high five for recognizing this ;) - let cx = 3.0*(id % size) as f32 / (size - 1) as f32 - 2.0; - let cy = 2.0*(id / size) as f32 / (size - 1) as f32 - 1.0; + let cx = 3.0 * (id % size) as f32 / (size - 1) as f32 - 2.0; + let cy = 2.0 * (id / size) as f32 / (size - 1) as f32 - 1.0; let (mut x, mut y, mut count) = (cx, cy, 0); - while count < 0xFF && x*x + y*y < 4.0 { + while count < 0xFF && x * x + y * y < 4.0 { let old_x = x; x = x * x - y * y + cx; y = 2.0 * old_x * y + cy; @@ -108,19 +107,18 @@ impl framework::Example for Example { fn init(sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) -> Self { use std::mem; - let mut init_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - todo: 0, - }); + let mut init_encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); // Create the vertex and index buffers let vertex_size = mem::size_of::(); let (vertex_data, index_data) = create_vertices(); - let vertex_buf = - device.create_buffer_mapped(vertex_data.len(), wgpu::BufferUsageFlags::VERTEX) + let vertex_buf = device + .create_buffer_mapped(vertex_data.len(), wgpu::BufferUsageFlags::VERTEX) .fill_from_slice(&vertex_data); - let index_buf = - device.create_buffer_mapped(index_data.len(), wgpu::BufferUsageFlags::INDEX) + let index_buf = device + .create_buffer_mapped(index_data.len(), wgpu::BufferUsageFlags::INDEX) .fill_from_slice(&index_data); // Create pipeline layout @@ -163,8 +161,8 @@ impl framework::Example for Example { usage: wgpu::TextureUsageFlags::SAMPLED | wgpu::TextureUsageFlags::TRANSFER_DST, }); let texture_view = texture.create_default_view(); - let temp_buf = - device.create_buffer_mapped(texels.len(), wgpu::BufferUsageFlags::TRANSFER_SRC) + let temp_buf = device + .create_buffer_mapped(texels.len(), wgpu::BufferUsageFlags::TRANSFER_SRC) .fill_from_slice(&texels); init_encoder.copy_buffer_to_texture( wgpu::BufferCopyView { @@ -202,8 +200,11 @@ impl framework::Example for Example { }); let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); let mx_ref: &[f32; 16] = mx_total.as_ref(); - let uniform_buf = - device.create_buffer_mapped(16, wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST) + let uniform_buf = device + .create_buffer_mapped( + 16, + wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST, + ) .fill_from_slice(mx_ref); // Create bind group @@ -214,7 +215,7 @@ impl framework::Example for Example { binding: 0, resource: wgpu::BindingResource::Buffer { buffer: &uniform_buf, - range: 0 .. 64, + range: 0..64, }, }, wgpu::Binding { @@ -252,34 +253,30 @@ impl framework::Example for Example { depth_bias_clamp: 0.0, }, primitive_topology: wgpu::PrimitiveTopology::TriangleList, - color_states: &[ - wgpu::ColorStateDescriptor { - format: sc_desc.format, - color: wgpu::BlendDescriptor::REPLACE, - alpha: wgpu::BlendDescriptor::REPLACE, - write_mask: wgpu::ColorWriteFlags::ALL, - }, - ], + color_states: &[wgpu::ColorStateDescriptor { + format: sc_desc.format, + color: wgpu::BlendDescriptor::REPLACE, + alpha: wgpu::BlendDescriptor::REPLACE, + write_mask: wgpu::ColorWriteFlags::ALL, + }], depth_stencil_state: None, index_format: wgpu::IndexFormat::Uint16, - vertex_buffers: &[ - wgpu::VertexBufferDescriptor { - stride: vertex_size as u32, - step_mode: wgpu::InputStepMode::Vertex, - attributes: &[ - wgpu::VertexAttributeDescriptor { - attribute_index: 0, - format: wgpu::VertexFormat::Float4, - offset: 0, - }, - wgpu::VertexAttributeDescriptor { - attribute_index: 1, - format: wgpu::VertexFormat::Float2, - offset: 4 * 4, - }, - ], - }, - ], + vertex_buffers: &[wgpu::VertexBufferDescriptor { + stride: vertex_size as u32, + step_mode: wgpu::InputStepMode::Vertex, + attributes: &[ + wgpu::VertexAttributeDescriptor { + attribute_index: 0, + format: wgpu::VertexFormat::Float4, + offset: 0, + }, + wgpu::VertexAttributeDescriptor { + attribute_index: 1, + format: wgpu::VertexFormat::Float2, + offset: 4 * 4, + }, + ], + }], sample_count: 1, }); @@ -304,24 +301,31 @@ impl framework::Example for Example { let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); let mx_ref: &[f32; 16] = mx_total.as_ref(); - let temp_buf = - device.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC) + let temp_buf = device + .create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC) .fill_from_slice(mx_ref); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); encoder.copy_buffer_to_buffer(&temp_buf, 0, &self.uniform_buf, 0, 64); device.get_queue().submit(&[encoder.finish()]); } fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device) { - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, load_op: wgpu::LoadOp::Clear, store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }, + clear_color: wgpu::Color { + r: 0.1, + g: 0.2, + b: 0.3, + a: 1.0, + }, }], depth_stencil_attachment: None, }); @@ -329,12 +333,10 @@ impl framework::Example for Example { rpass.set_bind_group(0, &self.bind_group); rpass.set_index_buffer(&self.index_buf, 0); rpass.set_vertex_buffers(&[(&self.vertex_buf, 0)]); - rpass.draw_indexed(0 .. self.index_count as u32, 0, 0..1); + rpass.draw_indexed(0..self.index_count as u32, 0, 0..1); } - device - .get_queue() - .submit(&[encoder.finish()]); + device.get_queue().submit(&[encoder.finish()]); } } diff --git a/gfx-examples/src/framework.rs b/gfx-examples/src/framework.rs index 3457ec7f3..59b86c3f5 100644 --- a/gfx-examples/src/framework.rs +++ b/gfx-examples/src/framework.rs @@ -1,14 +1,11 @@ use log::info; - #[allow(dead_code)] pub fn cast_slice(data: &[T]) -> &[u8] { use std::mem::size_of; use std::slice::from_raw_parts; - unsafe { - from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::()) - } + unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::()) } } #[allow(dead_code)] @@ -51,7 +48,7 @@ pub trait Example { pub fn run(title: &str) { use wgpu::winit::{ - Event, ElementState, EventsLoop, KeyboardInput, Window, WindowEvent, VirtualKeyCode + ElementState, Event, EventsLoop, KeyboardInput, VirtualKeyCode, Window, WindowEvent, }; info!("Initializing the device..."); @@ -90,37 +87,36 @@ pub fn run(title: &str) { info!("Entering render loop..."); let mut running = true; while running { - events_loop.poll_events(|event| { - match event { - Event::WindowEvent { - event: WindowEvent::Resized(size), - .. - } => { - let physical = size.to_physical(window.get_hidpi_factor()); - info!("Resizing to {:?}", physical); - sc_desc.width = physical.width as u32; - sc_desc.height = physical.height as u32; - swap_chain = device.create_swap_chain(&surface, &sc_desc); - example.resize(&sc_desc, &mut device); - } - Event::WindowEvent { event, .. } => match event { - WindowEvent::KeyboardInput { - input: KeyboardInput { + events_loop.poll_events(|event| match event { + Event::WindowEvent { + event: WindowEvent::Resized(size), + .. + } => { + let physical = size.to_physical(window.get_hidpi_factor()); + info!("Resizing to {:?}", physical); + sc_desc.width = physical.width as u32; + sc_desc.height = physical.height as u32; + swap_chain = device.create_swap_chain(&surface, &sc_desc); + example.resize(&sc_desc, &mut device); + } + Event::WindowEvent { event, .. } => match event { + WindowEvent::KeyboardInput { + input: + KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), state: ElementState::Pressed, .. }, - .. - } | - WindowEvent::CloseRequested => { - running = false; - } - _ => { - example.update(event); - } + .. } - _ => () - } + | WindowEvent::CloseRequested => { + running = false; + } + _ => { + example.update(event); + } + }, + _ => (), }); let frame = swap_chain.get_next_texture(); diff --git a/gfx-examples/src/shadow.rs b/gfx-examples/src/shadow.rs index 3a818fecc..323963cc3 100644 --- a/gfx-examples/src/shadow.rs +++ b/gfx-examples/src/shadow.rs @@ -4,7 +4,6 @@ use std::rc::Rc; mod framework; - #[derive(Clone, Copy)] struct Vertex { _pos: [i8; 4], @@ -21,41 +20,41 @@ fn vertex(pos: [i8; 3], nor: [i8; 3]) -> Vertex { fn create_cube() -> (Vec, Vec) { let vertex_data = [ // top (0, 0, 1) - vertex([-1, -1, 1], [0, 0, 1]), - vertex([ 1, -1, 1], [0, 0, 1]), - vertex([ 1, 1, 1], [0, 0, 1]), - vertex([-1, 1, 1], [0, 0, 1]), + vertex([-1, -1, 1], [0, 0, 1]), + vertex([1, -1, 1], [0, 0, 1]), + vertex([1, 1, 1], [0, 0, 1]), + vertex([-1, 1, 1], [0, 0, 1]), // bottom (0, 0, -1) - vertex([-1, 1, -1], [0, 0, -1]), - vertex([ 1, 1, -1], [0, 0, -1]), - vertex([ 1, -1, -1], [0, 0, -1]), + vertex([-1, 1, -1], [0, 0, -1]), + vertex([1, 1, -1], [0, 0, -1]), + vertex([1, -1, -1], [0, 0, -1]), vertex([-1, -1, -1], [0, 0, -1]), // right (1, 0, 0) - vertex([ 1, -1, -1], [1, 0, 0]), - vertex([ 1, 1, -1], [1, 0, 0]), - vertex([ 1, 1, 1], [1, 0, 0]), - vertex([ 1, -1, 1], [1, 0, 0]), + vertex([1, -1, -1], [1, 0, 0]), + vertex([1, 1, -1], [1, 0, 0]), + vertex([1, 1, 1], [1, 0, 0]), + vertex([1, -1, 1], [1, 0, 0]), // left (-1, 0, 0) - vertex([-1, -1, 1], [-1, 0, 0]), - vertex([-1, 1, 1], [-1, 0, 0]), - vertex([-1, 1, -1], [-1, 0, 0]), + vertex([-1, -1, 1], [-1, 0, 0]), + vertex([-1, 1, 1], [-1, 0, 0]), + vertex([-1, 1, -1], [-1, 0, 0]), vertex([-1, -1, -1], [-1, 0, 0]), // front (0, 1, 0) - vertex([ 1, 1, -1], [0, 1, 0]), - vertex([-1, 1, -1], [0, 1, 0]), - vertex([-1, 1, 1], [0, 1, 0]), - vertex([ 1, 1, 1], [0, 1, 0]), + vertex([1, 1, -1], [0, 1, 0]), + vertex([-1, 1, -1], [0, 1, 0]), + vertex([-1, 1, 1], [0, 1, 0]), + vertex([1, 1, 1], [0, 1, 0]), // back (0, -1, 0) - vertex([ 1, -1, 1], [0, -1, 0]), - vertex([-1, -1, 1], [0, -1, 0]), + vertex([1, -1, 1], [0, -1, 0]), + vertex([-1, -1, 1], [0, -1, 0]), vertex([-1, -1, -1], [0, -1, 0]), - vertex([ 1, -1, -1], [0, -1, 0]), + vertex([1, -1, -1], [0, -1, 0]), ]; let index_data: &[u16] = &[ - 0, 1, 2, 2, 3, 0, // top - 4, 5, 6, 6, 7, 4, // bottom - 8, 9, 10, 10, 11, 8, // right + 0, 1, 2, 2, 3, 0, // top + 4, 5, 6, 6, 7, 4, // bottom + 8, 9, 10, 10, 11, 8, // right 12, 13, 14, 14, 15, 12, // left 16, 17, 18, 18, 19, 16, // front 20, 21, 22, 22, 23, 20, // back @@ -66,21 +65,17 @@ fn create_cube() -> (Vec, Vec) { fn create_plane(size: i8) -> (Vec, Vec) { let vertex_data = [ - vertex([ size, -size, 0], [0, 0, 1]), - vertex([ size, size, 0], [0, 0, 1]), - vertex([-size, -size, 0], [0, 0, 1]), - vertex([-size, size, 0], [0, 0, 1]), + vertex([size, -size, 0], [0, 0, 1]), + vertex([size, size, 0], [0, 0, 1]), + vertex([-size, -size, 0], [0, 0, 1]), + vertex([-size, size, 0], [0, 0, 1]), ]; - let index_data: &[u16] = &[ - 0, 1, 2, - 2, 1, 3 - ]; + let index_data: &[u16] = &[0, 1, 2, 2, 1, 3]; (vertex_data.to_vec(), index_data.to_vec()) } - struct Entity { mx_world: cgmath::Matrix4, rotation_speed: f32, @@ -110,13 +105,9 @@ struct LightRaw { impl Light { fn to_raw(&self) -> LightRaw { - use cgmath::{EuclideanSpace, Deg, Point3, Vector3, Matrix4, PerspectiveFov}; + use cgmath::{Deg, EuclideanSpace, Matrix4, PerspectiveFov, Point3, Vector3}; - let mx_view = Matrix4::look_at( - self.pos, - Point3::origin(), - -Vector3::unit_z(), - ); + let mx_view = Matrix4::look_at(self.pos, Point3::origin(), -Vector3::unit_z()); let projection = PerspectiveFov { fovy: Deg(self.fov).into(), aspect: 1.0, @@ -194,22 +185,24 @@ impl framework::Example for Example { let vertex_size = mem::size_of::(); let (cube_vertex_data, cube_index_data) = create_cube(); let cube_vertex_buf = Rc::new( - device.create_buffer_mapped(cube_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX) - .fill_from_slice(&cube_vertex_data) + device + .create_buffer_mapped(cube_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX) + .fill_from_slice(&cube_vertex_data), ); let cube_index_buf = Rc::new( - device.create_buffer_mapped(cube_index_data.len(), wgpu::BufferUsageFlags::INDEX) - .fill_from_slice(&cube_index_data) + device + .create_buffer_mapped(cube_index_data.len(), wgpu::BufferUsageFlags::INDEX) + .fill_from_slice(&cube_index_data), ); let (plane_vertex_data, plane_index_data) = create_plane(7); - let plane_vertex_buf = - device.create_buffer_mapped(plane_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX) + let plane_vertex_buf = device + .create_buffer_mapped(plane_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX) .fill_from_slice(&plane_vertex_data); - let plane_index_buf = - device.create_buffer_mapped(plane_index_data.len(), wgpu::BufferUsageFlags::INDEX) + let plane_index_buf = device + .create_buffer_mapped(plane_index_data.len(), wgpu::BufferUsageFlags::INDEX) .fill_from_slice(&plane_index_data); let entity_uniform_size = mem::size_of::() as u32; @@ -218,30 +211,27 @@ impl framework::Example for Example { usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST, }); - let local_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - bindings: &[ - wgpu::BindGroupLayoutBinding { + let local_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + bindings: &[wgpu::BindGroupLayoutBinding { binding: 0, visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT, ty: wgpu::BindingType::UniformBuffer, - }, - ], - }); + }], + }); let mut entities = vec![{ use cgmath::SquareMatrix; let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &local_bind_group_layout, - bindings: &[ - wgpu::Binding { - binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &plane_uniform_buf, - range: 0 .. entity_uniform_size, - }, + bindings: &[wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::Buffer { + buffer: &plane_uniform_buf, + range: 0..entity_uniform_size, }, - ], + }], }); Entity { mx_world: cgmath::Matrix4::identity(), @@ -289,14 +279,11 @@ impl framework::Example for Example { ]; for cube in &cube_descs { - use cgmath::{Deg, Decomposed, Quaternion, Rotation3, InnerSpace}; + use cgmath::{Decomposed, Deg, InnerSpace, Quaternion, Rotation3}; let transform = Decomposed { disp: cube.offset.clone(), - rot: Quaternion::from_axis_angle( - cube.offset.normalize(), - Deg(cube.angle), - ), + rot: Quaternion::from_axis_angle(cube.offset.normalize(), Deg(cube.angle)), scale: cube.scale, }; let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { @@ -312,15 +299,13 @@ impl framework::Example for Example { index_count: cube_index_data.len(), bind_group: device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &local_bind_group_layout, - bindings: &[ - wgpu::Binding { - binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &uniform_buf, - range: 0 .. entity_uniform_size, - }, + bindings: &[wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::Buffer { + buffer: &uniform_buf, + range: 0..entity_uniform_size, }, - ], + }], }), uniform_buf, }); @@ -351,36 +336,50 @@ impl framework::Example for Example { let shadow_view = shadow_texture.create_default_view(); let mut shadow_target_views = (0..2) - .map(|i| Some(shadow_texture.create_view(&wgpu::TextureViewDescriptor { - format: Self::SHADOW_FORMAT, - dimension: wgpu::TextureViewDimension::D2, - aspect: wgpu::TextureAspectFlags::DEPTH, - base_mip_level: 0, - level_count: 1, - base_array_layer: i as u32, - array_count: 1, - }))) + .map(|i| { + Some(shadow_texture.create_view(&wgpu::TextureViewDescriptor { + format: Self::SHADOW_FORMAT, + dimension: wgpu::TextureViewDimension::D2, + aspect: wgpu::TextureAspectFlags::DEPTH, + base_mip_level: 0, + level_count: 1, + base_array_layer: i as u32, + array_count: 1, + })) + }) .collect::>(); let lights = vec![ Light { pos: cgmath::Point3::new(7.0, -5.0, 10.0), - color: wgpu::Color { r: 0.5, g: 1.0, b: 0.5, a: 1.0 }, + color: wgpu::Color { + r: 0.5, + g: 1.0, + b: 0.5, + a: 1.0, + }, fov: 60.0, - depth: 1.0 .. 20.0, + depth: 1.0..20.0, target_view: shadow_target_views[0].take().unwrap(), }, Light { pos: cgmath::Point3::new(-5.0, 7.0, 10.0), - color: wgpu::Color { r: 1.0, g: 0.5, b: 0.5, a: 1.0 }, + color: wgpu::Color { + r: 1.0, + g: 0.5, + b: 0.5, + a: 1.0, + }, fov: 45.0, - depth: 1.0 .. 20.0, + depth: 1.0..20.0, target_view: shadow_target_views[1].take().unwrap(), }, ]; let light_uniform_size = (Self::MAX_LIGHTS * mem::size_of::()) as u32; let light_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { size: light_uniform_size, - usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_SRC | wgpu::BufferUsageFlags::TRANSFER_DST, + usage: wgpu::BufferUsageFlags::UNIFORM + | wgpu::BufferUsageFlags::TRANSFER_SRC + | wgpu::BufferUsageFlags::TRANSFER_DST, }); let vb_desc = wgpu::VertexBufferDescriptor { @@ -402,20 +401,16 @@ impl framework::Example for Example { let shadow_pass = { // Create pipeline layout - let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - bindings: &[ - wgpu::BindGroupLayoutBinding { + let bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + bindings: &[wgpu::BindGroupLayoutBinding { binding: 0, // global visibility: wgpu::ShaderStageFlags::VERTEX, ty: wgpu::BindingType::UniformBuffer, - }, - ], - }); + }], + }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - bind_group_layouts: &[ - &bind_group_layout, - &local_bind_group_layout, - ], + bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout], }); let uniform_size = mem::size_of::() as u32; @@ -427,20 +422,19 @@ impl framework::Example for Example { // Create bind group let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &bind_group_layout, - bindings: &[ - wgpu::Binding { - binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &uniform_buf, - range: 0 .. uniform_size, - }, + bindings: &[wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::Buffer { + buffer: &uniform_buf, + range: 0..uniform_size, }, - ], + }], }); // Create the render pipeline let vs_bytes = framework::load_glsl("shadow-bake.vert", framework::ShaderStage::Vertex); - let fs_bytes = framework::load_glsl("shadow-bake.frag", framework::ShaderStage::Fragment); + let fs_bytes = + framework::load_glsl("shadow-bake.frag", framework::ShaderStage::Fragment); let vs_module = device.create_shader_module(&vs_bytes); let fs_module = device.create_shader_module(&fs_bytes); @@ -486,35 +480,35 @@ impl framework::Example for Example { let forward_pass = { // Create pipeline layout - let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - bindings: &[ - wgpu::BindGroupLayoutBinding { - binding: 0, // global - visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT, - ty: wgpu::BindingType::UniformBuffer, - }, - wgpu::BindGroupLayoutBinding { - binding: 1, // lights - visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT, - ty: wgpu::BindingType::UniformBuffer, - }, - wgpu::BindGroupLayoutBinding { - binding: 2, - visibility: wgpu::ShaderStageFlags::FRAGMENT, - ty: wgpu::BindingType::SampledTexture, - }, - wgpu::BindGroupLayoutBinding { - binding: 3, - visibility: wgpu::ShaderStageFlags::FRAGMENT, - ty: wgpu::BindingType::Sampler, - }, - ], - }); + let bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + bindings: &[ + wgpu::BindGroupLayoutBinding { + binding: 0, // global + visibility: wgpu::ShaderStageFlags::VERTEX + | wgpu::ShaderStageFlags::FRAGMENT, + ty: wgpu::BindingType::UniformBuffer, + }, + wgpu::BindGroupLayoutBinding { + binding: 1, // lights + visibility: wgpu::ShaderStageFlags::VERTEX + | wgpu::ShaderStageFlags::FRAGMENT, + ty: wgpu::BindingType::UniformBuffer, + }, + wgpu::BindGroupLayoutBinding { + binding: 2, + visibility: wgpu::ShaderStageFlags::FRAGMENT, + ty: wgpu::BindingType::SampledTexture, + }, + wgpu::BindGroupLayoutBinding { + binding: 3, + visibility: wgpu::ShaderStageFlags::FRAGMENT, + ty: wgpu::BindingType::Sampler, + }, + ], + }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - bind_group_layouts: &[ - &bind_group_layout, - &local_bind_group_layout, - ], + bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout], }); let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); @@ -523,8 +517,11 @@ impl framework::Example for Example { num_lights: [lights.len() as u32, 0, 0, 0], }; let uniform_size = mem::size_of::() as u32; - let uniform_buf = - device.create_buffer_mapped(1, wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST) + let uniform_buf = device + .create_buffer_mapped( + 1, + wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST, + ) .fill_from_slice(&[forward_uniforms]); // Create bind group @@ -535,14 +532,14 @@ impl framework::Example for Example { binding: 0, resource: wgpu::BindingResource::Buffer { buffer: &uniform_buf, - range: 0 .. uniform_size, + range: 0..uniform_size, }, }, wgpu::Binding { binding: 1, resource: wgpu::BindingResource::Buffer { buffer: &light_uniform_buf, - range: 0 .. light_uniform_size, + range: 0..light_uniform_size, }, }, wgpu::Binding { @@ -557,8 +554,10 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_bytes = framework::load_glsl("shadow-forward.vert", framework::ShaderStage::Vertex); - let fs_bytes = framework::load_glsl("shadow-forward.frag", framework::ShaderStage::Fragment); + let vs_bytes = + framework::load_glsl("shadow-forward.vert", framework::ShaderStage::Vertex); + let fs_bytes = + framework::load_glsl("shadow-forward.frag", framework::ShaderStage::Fragment); let vs_module = device.create_shader_module(&vs_bytes); let fs_module = device.create_shader_module(&fs_bytes); @@ -580,14 +579,12 @@ impl framework::Example for Example { depth_bias_clamp: 0.0, }, primitive_topology: wgpu::PrimitiveTopology::TriangleList, - color_states: &[ - wgpu::ColorStateDescriptor { - format: sc_desc.format, - color: wgpu::BlendDescriptor::REPLACE, - alpha: wgpu::BlendDescriptor::REPLACE, - write_mask: wgpu::ColorWriteFlags::ALL, - }, - ], + color_states: &[wgpu::ColorStateDescriptor { + format: sc_desc.format, + color: wgpu::BlendDescriptor::REPLACE, + alpha: wgpu::BlendDescriptor::REPLACE, + write_mask: wgpu::ColorWriteFlags::ALL, + }], depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor { format: Self::DEPTH_FORMAT, depth_write_enabled: true, @@ -640,11 +637,12 @@ impl framework::Example for Example { { let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); let mx_ref: &[f32; 16] = mx_total.as_ref(); - let temp_buf = - device.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC) + let temp_buf = device + .create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC) .fill_from_slice(mx_ref); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); encoder.copy_buffer_to_buffer(&temp_buf, 0, &self.forward_pass.uniform_buf, 0, 64); device.get_queue().submit(&[encoder.finish()]); } @@ -664,42 +662,61 @@ impl framework::Example for Example { } fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device) { - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); { let size = mem::size_of::() as u32; - let temp_buf_data = - device.create_buffer_mapped(self.entities.len(), wgpu::BufferUsageFlags::TRANSFER_SRC); + let temp_buf_data = device + .create_buffer_mapped(self.entities.len(), wgpu::BufferUsageFlags::TRANSFER_SRC); for (i, entity) in self.entities.iter_mut().enumerate() { if entity.rotation_speed != 0.0 { - let rotation = cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed)); + let rotation = + cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed)); entity.mx_world = entity.mx_world * rotation; } temp_buf_data.data[i] = EntityUniforms { model: entity.mx_world.clone(), - color: [entity.color.r, entity.color.g, entity.color.b, entity.color.a], + color: [ + entity.color.r, + entity.color.g, + entity.color.b, + entity.color.a, + ], }; } let temp_buf = temp_buf_data.finish(); for (i, entity) in self.entities.iter().enumerate() { - encoder.copy_buffer_to_buffer(&temp_buf, i as u32 * size, &entity.uniform_buf, 0, size); + encoder.copy_buffer_to_buffer( + &temp_buf, + i as u32 * size, + &entity.uniform_buf, + 0, + size, + ); } } if self.lights_are_dirty { self.lights_are_dirty = false; let size = (self.lights.len() * mem::size_of::()) as u32; - let temp_buf_data = - device.create_buffer_mapped(self.lights.len(), wgpu::BufferUsageFlags::TRANSFER_SRC); + let temp_buf_data = device + .create_buffer_mapped(self.lights.len(), wgpu::BufferUsageFlags::TRANSFER_SRC); for (i, light) in self.lights.iter().enumerate() { temp_buf_data.data[i] = light.to_raw(); } - encoder.copy_buffer_to_buffer(&temp_buf_data.finish(), 0, &self.light_uniform_buf, 0, size); + encoder.copy_buffer_to_buffer( + &temp_buf_data.finish(), + 0, + &self.light_uniform_buf, + 0, + size, + ); } - + for (i, light) in self.lights.iter().enumerate() { // The light uniform buffer already has the projection, // let's just copy it over to the shadow uniform buffer. @@ -730,7 +747,7 @@ impl framework::Example for Example { pass.set_bind_group(1, &entity.bind_group); pass.set_index_buffer(&entity.index_buf, 0); pass.set_vertex_buffers(&[(&entity.vertex_buf, 0)]); - pass.draw_indexed(0 .. entity.index_count as u32, 0, 0..1); + pass.draw_indexed(0..entity.index_count as u32, 0, 0..1); } } @@ -741,7 +758,12 @@ impl framework::Example for Example { attachment: &frame.view, load_op: wgpu::LoadOp::Clear, store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }, + clear_color: wgpu::Color { + r: 0.1, + g: 0.2, + b: 0.3, + a: 1.0, + }, }], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor { attachment: &self.forward_depth, @@ -760,13 +782,11 @@ impl framework::Example for Example { pass.set_bind_group(1, &entity.bind_group); pass.set_index_buffer(&entity.index_buf, 0); pass.set_vertex_buffers(&[(&entity.vertex_buf, 0)]); - pass.draw_indexed(0 .. entity.index_count as u32, 0, 0..1); + pass.draw_indexed(0..entity.index_count as u32, 0, 0..1); } } - device - .get_queue() - .submit(&[encoder.finish()]); + device.get_queue().submit(&[encoder.finish()]); } } diff --git a/wgpu-native/src/binding_model.rs b/wgpu-native/src/binding_model.rs index 66eb224e6..634f2bf28 100644 --- a/wgpu-native/src/binding_model.rs +++ b/wgpu-native/src/binding_model.rs @@ -1,12 +1,8 @@ use crate::track::TrackerSet; -use crate::{ - LifeGuard, - BindGroupLayoutId, BufferId, SamplerId, TextureViewId, -}; +use crate::{BindGroupLayoutId, BufferId, LifeGuard, SamplerId, TextureViewId}; use bitflags::bitflags; - bitflags! { #[repr(transparent)] pub struct ShaderStageFlags: u32 { diff --git a/wgpu-native/src/command/allocator.rs b/wgpu-native/src/command/allocator.rs index b09b08ea3..3f50c2c8c 100644 --- a/wgpu-native/src/command/allocator.rs +++ b/wgpu-native/src/command/allocator.rs @@ -110,7 +110,10 @@ impl CommandAllocator { pub fn maintain(&self, last_done: SubmissionIndex) { let mut inner = self.inner.lock(); for i in (0..inner.pending.len()).rev() { - let index = inner.pending[i].life_guard.submission_index.load(Ordering::Acquire); + let index = inner.pending[i] + .life_guard + .submission_index + .load(Ordering::Acquire); if index <= last_done { let cmd_buf = inner.pending.swap_remove(i); inner.recycle(cmd_buf); diff --git a/wgpu-native/src/command/bind.rs b/wgpu-native/src/command/bind.rs index 6746a9ffb..a66d9bd51 100644 --- a/wgpu-native/src/command/bind.rs +++ b/wgpu-native/src/command/bind.rs @@ -1,8 +1,4 @@ -use crate::{ - BindGroupHandle, Stored, - BindGroupId, BindGroupLayoutId, PipelineLayoutId, -}; - +use crate::{BindGroupHandle, BindGroupId, BindGroupLayoutId, PipelineLayoutId, Stored}; pub struct BindGroupPair { layout_id: BindGroupLayoutId, @@ -17,10 +13,14 @@ pub struct BindGroupEntry { impl BindGroupEntry { fn provide(&mut self, bind_group_id: BindGroupId, bind_group: &BindGroupHandle) -> bool { - if let Some(BindGroupPair { ref layout_id, ref group_id }) = self.provided { + if let Some(BindGroupPair { + ref layout_id, + ref group_id, + }) = self.provided + { if group_id.value == bind_group_id { assert_eq!(*layout_id, bind_group.layout_id); - return false + return false; } } @@ -36,14 +36,17 @@ impl BindGroupEntry { } pub fn expect_layout( - &mut self, bind_group_layout_id: BindGroupLayoutId, + &mut self, + bind_group_layout_id: BindGroupLayoutId, ) -> Option { let some = Some(bind_group_layout_id); if self.expected_layout_id != some { self.expected_layout_id = some; match self.provided { - Some(BindGroupPair { layout_id, ref group_id }) - if layout_id == bind_group_layout_id => Some(group_id.value), + Some(BindGroupPair { + layout_id, + ref group_id, + }) if layout_id == bind_group_layout_id => Some(group_id.value), Some(_) | None => None, } } else { @@ -66,7 +69,10 @@ impl Binder { } pub(crate) fn provide_entry( - &mut self, index: usize, bind_group_id: BindGroupId, bind_group: &BindGroupHandle + &mut self, + index: usize, + bind_group_id: BindGroupId, + bind_group: &BindGroupHandle, ) -> Option { self.ensure_length(index + 1); if self.entries[index].provide(bind_group_id, bind_group) { diff --git a/wgpu-native/src/command/compute.rs b/wgpu-native/src/command/compute.rs index b9b4e5f1d..0fb579a11 100644 --- a/wgpu-native/src/command/compute.rs +++ b/wgpu-native/src/command/compute.rs @@ -1,9 +1,8 @@ -use crate::command::bind::{Binder}; +use crate::command::bind::Binder; use crate::hub::HUB; use crate::track::{Stitch, TrackerSet}; use crate::{ - Stored, CommandBuffer, - BindGroupId, CommandBufferId, ComputePassId, ComputePipelineId, + BindGroupId, CommandBuffer, CommandBufferId, ComputePassId, ComputePipelineId, Stored, }; use hal; @@ -11,7 +10,6 @@ use hal::command::RawCommandBuffer; use std::iter; - pub struct ComputePass { raw: B::CommandBuffer, cmb_id: Stored, @@ -36,9 +34,8 @@ pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandB //TODO: transitions? - HUB.command_buffers - .write() - [pass.cmb_id.value].raw + HUB.command_buffers.write()[pass.cmb_id.value] + .raw .push(pass.raw); pass.cmb_id.value } @@ -46,10 +43,7 @@ pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandB #[no_mangle] pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) { unsafe { - HUB.compute_passes - .write() - [pass_id].raw - .dispatch([x, y, z]); + HUB.compute_passes.write()[pass_id].raw.dispatch([x, y, z]); } } @@ -76,7 +70,10 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( &*HUB.textures.read(), ); - if let Some(pipeline_layout_id) = pass.binder.provide_entry(index as usize, bind_group_id, bind_group) { + if let Some(pipeline_layout_id) = + pass.binder + .provide_entry(index as usize, bind_group_id, bind_group) + { let pipeline_layout_guard = HUB.pipeline_layouts.read(); unsafe { pass.raw.bind_compute_descriptor_sets( @@ -104,7 +101,7 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline( } if pass.binder.pipeline_layout_id == Some(pipeline.layout_id.clone()) { - return + return; } let pipeline_layout_guard = HUB.pipeline_layouts.read(); @@ -112,9 +109,12 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline( let bing_group_guard = HUB.bind_groups.read(); pass.binder.pipeline_layout_id = Some(pipeline.layout_id.clone()); - pass.binder.ensure_length(pipeline_layout.bind_group_layout_ids.len()); + pass.binder + .ensure_length(pipeline_layout.bind_group_layout_ids.len()); - for (index, (entry, &bgl_id)) in pass.binder.entries + for (index, (entry, &bgl_id)) in pass + .binder + .entries .iter_mut() .zip(&pipeline_layout.bind_group_layout_ids) .enumerate() @@ -126,7 +126,7 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline( &pipeline_layout.raw, index, iter::once(desc_set), - &[] + &[], ); } } diff --git a/wgpu-native/src/command/mod.rs b/wgpu-native/src/command/mod.rs index b3617991f..ec4bb5ce6 100644 --- a/wgpu-native/src/command/mod.rs +++ b/wgpu-native/src/command/mod.rs @@ -9,35 +9,29 @@ pub use self::compute::*; pub use self::render::*; pub use self::transfer::*; +use crate::conv; use crate::device::{ - FramebufferKey, RenderPassKey, RenderPassContext, - all_buffer_stages, all_image_stages, + all_buffer_stages, all_image_stages, FramebufferKey, RenderPassContext, RenderPassKey, }; -use crate::hub::{HUB, Storage}; +use crate::hub::{Storage, HUB}; use crate::resource::TexturePlacement; use crate::swap_chain::{SwapChainLink, SwapImageEpoch}; use crate::track::{DummyUsage, Stitch, TrackerSet}; -use crate::conv; use crate::{ - BufferHandle, TextureHandle, - CommandBufferId, CommandEncoderId, DeviceId, - TextureViewId, - TextureUsageFlags, Color, - LifeGuard, Stored, - CommandBufferHandle, + BufferHandle, Color, CommandBufferHandle, CommandBufferId, CommandEncoderId, DeviceId, + LifeGuard, Stored, TextureHandle, TextureUsageFlags, TextureViewId, }; #[cfg(feature = "local")] -use crate::{RenderPassId, ComputePassId}; +use crate::{ComputePassId, RenderPassId}; use back::Backend; use hal::command::RawCommandBuffer; -use hal::{Device as _Device}; +use hal::Device as _Device; use log::trace; use std::collections::hash_map::Entry; -use std::{iter, slice}; use std::thread::ThreadId; - +use std::{iter, slice}; #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] @@ -78,7 +72,6 @@ pub struct RenderPassDescriptor { pub depth_stencil_attachment: *const RenderPassDepthStencilAttachmentDescriptor, } - pub struct CommandBuffer { pub(crate) raw: Vec, is_recording: bool, @@ -98,19 +91,22 @@ impl CommandBufferHandle { buffer_guard: &Storage, texture_guard: &Storage, ) { - let buffer_barriers = base.buffers - .consume_by_replace(&head.buffers, stitch) - .map(|(id, transit)| { - let b = &buffer_guard[id]; - trace!("transit buffer {:?} {:?}", id, transit); - hal::memory::Barrier::Buffer { - states: conv::map_buffer_state(transit.start) .. conv::map_buffer_state(transit.end), - target: &b.raw, - range: None .. None, - families: None, - } - }); - let texture_barriers = base.textures + let buffer_barriers = + base.buffers + .consume_by_replace(&head.buffers, stitch) + .map(|(id, transit)| { + let b = &buffer_guard[id]; + trace!("transit buffer {:?} {:?}", id, transit); + hal::memory::Barrier::Buffer { + states: conv::map_buffer_state(transit.start) + ..conv::map_buffer_state(transit.end), + target: &b.raw, + range: None..None, + families: None, + } + }); + let texture_barriers = base + .textures .consume_by_replace(&head.textures, stitch) .map(|(id, transit)| { let t = &texture_guard[id]; @@ -124,14 +120,12 @@ impl CommandBufferHandle { families: None, } }); - base.views - .consume_by_extend(&head.views) - .unwrap(); + base.views.consume_by_extend(&head.views).unwrap(); let stages = all_buffer_stages() | all_image_stages(); unsafe { raw.pipeline_barrier( - stages .. stages, + stages..stages, hal::memory::Dependencies::empty(), buffer_barriers.chain(texture_barriers), ); @@ -150,10 +144,7 @@ pub struct CommandEncoderDescriptor { pub extern "C" fn wgpu_command_encoder_finish( command_encoder_id: CommandEncoderId, ) -> CommandBufferId { - HUB.command_buffers - .write() - [command_encoder_id] - .is_recording = false; //TODO: check for the old value + HUB.command_buffers.write()[command_encoder_id].is_recording = false; //TODO: check for the old value command_encoder_id } @@ -176,15 +167,9 @@ pub fn command_encoder_begin_render_pass( } let mut extent = None; - let color_attachments = unsafe { - slice::from_raw_parts( - desc.color_attachments, - desc.color_attachments_length, - ) - }; - let depth_stencil_attachment = unsafe { - desc.depth_stencil_attachment.as_ref() - }; + let color_attachments = + unsafe { slice::from_raw_parts(desc.color_attachments, desc.color_attachments_length) }; + let depth_stencil_attachment = unsafe { desc.depth_stencil_attachment.as_ref() }; let rp_key = { let trackers = &mut cmb.trackers; @@ -197,7 +182,9 @@ pub fn command_encoder_begin_render_pass( } else { extent = Some(view.extent); } - trackers.views.query(at.attachment, &view.life_guard.ref_count, DummyUsage); + trackers + .views + .query(at.attachment, &view.life_guard.ref_count, DummyUsage); let query = trackers.textures.query( view.texture_id.value, &view.texture_id.ref_count, @@ -220,17 +207,13 @@ pub fn command_encoder_begin_render_pass( let view = &view_guard[at.attachment]; if view.is_owned_by_swap_chain { - let link = match HUB.textures - .read() - [view.texture_id.value].placement - { + let link = match HUB.textures.read()[view.texture_id.value].placement { TexturePlacement::SwapChain(ref link) => SwapChainLink { swap_chain_id: link.swap_chain_id.clone(), epoch: *link.epoch.lock(), image_index: link.image_index, }, - TexturePlacement::Memory(_) | - TexturePlacement::Void => unreachable!() + TexturePlacement::Memory(_) | TexturePlacement::Void => unreachable!(), }; swap_chain_links.push(link); } @@ -240,7 +223,9 @@ pub fn command_encoder_begin_render_pass( } else { extent = Some(view.extent); } - trackers.views.query(at.attachment, &view.life_guard.ref_count, DummyUsage); + trackers + .views + .query(at.attachment, &view.life_guard.ref_count, DummyUsage); let query = trackers.textures.query( view.texture_id.value, &view.texture_id.ref_count, @@ -297,21 +282,14 @@ pub fn command_encoder_begin_render_pass( let mut framebuffer_cache = device.framebuffers.lock(); let fb_key = FramebufferKey { - colors: color_attachments - .iter() - .map(|at| at.attachment) - .collect(), - depth_stencil: depth_stencil_attachment - .map(|at| at.attachment), + colors: color_attachments.iter().map(|at| at.attachment).collect(), + depth_stencil: depth_stencil_attachment.map(|at| at.attachment), }; let framebuffer = match framebuffer_cache.entry(fb_key) { Entry::Occupied(e) => e.into_mut(), Entry::Vacant(e) => { let fb = { - let attachments = e - .key() - .all() - .map(|&id| &view_guard[id].raw); + let attachments = e.key().all().map(|&id| &view_guard[id].raw); unsafe { device @@ -355,10 +333,13 @@ pub fn command_encoder_begin_render_pass( hal::command::SubpassContents::Inline, ); current_comb.set_scissors(0, iter::once(&rect)); - current_comb.set_viewports(0, iter::once(hal::pso::Viewport { - rect, - depth: 0.0 .. 1.0, - })); + current_comb.set_viewports( + 0, + iter::once(hal::pso::Viewport { + rect, + depth: 0.0..1.0, + }), + ); } let context = RenderPassContext { @@ -366,8 +347,7 @@ pub fn command_encoder_begin_render_pass( .iter() .map(|at| view_guard[at.attachment].format) .collect(), - depth_stencil: depth_stencil_attachment - .map(|at| view_guard[at.attachment].format), + depth_stencil: depth_stencil_attachment.map(|at| view_guard[at.attachment].format), }; RenderPass::new( diff --git a/wgpu-native/src/command/render.rs b/wgpu-native/src/command/render.rs index 1d69bf02f..3b7fa0bbe 100644 --- a/wgpu-native/src/command/render.rs +++ b/wgpu-native/src/command/render.rs @@ -1,18 +1,16 @@ use crate::command::bind::Binder; use crate::device::RenderPassContext; use crate::hub::HUB; -use crate::resource::{BufferUsageFlags}; +use crate::resource::BufferUsageFlags; use crate::track::{Stitch, TrackerSet}; use crate::{ - CommandBuffer, Stored, - BindGroupId, BufferId, CommandBufferId, RenderPassId, RenderPipelineId, + BindGroupId, BufferId, CommandBuffer, CommandBufferId, RenderPassId, RenderPipelineId, Stored, }; use hal::command::RawCommandBuffer; use std::{iter, slice}; - pub struct RenderPass { raw: B::CommandBuffer, cmb_id: Stored, @@ -70,18 +68,18 @@ pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) -> CommandBuf #[no_mangle] pub extern "C" fn wgpu_render_pass_set_index_buffer( - pass_id: RenderPassId, buffer_id: BufferId, offset: u32 + pass_id: RenderPassId, + buffer_id: BufferId, + offset: u32, ) { let mut pass_guard = HUB.render_passes.write(); let buffer_guard = HUB.buffers.read(); let pass = &mut pass_guard[pass_id]; - let buffer = pass.trackers.buffers - .get_with_extended_usage( - &*buffer_guard, - buffer_id, - BufferUsageFlags::INDEX, - ) + let buffer = pass + .trackers + .buffers + .get_with_extended_usage(&*buffer_guard, buffer_id, BufferUsageFlags::INDEX) .unwrap(); let view = hal::buffer::IndexBufferView { @@ -104,21 +102,14 @@ pub extern "C" fn wgpu_render_pass_set_vertex_buffers( ) { let mut pass_guard = HUB.render_passes.write(); let buffer_guard = HUB.buffers.read(); - let buffers = unsafe { - slice::from_raw_parts(buffer_ptr, count) - }; - let offsets = unsafe { - slice::from_raw_parts(offset_ptr, count) - }; + let buffers = unsafe { slice::from_raw_parts(buffer_ptr, count) }; + let offsets = unsafe { slice::from_raw_parts(offset_ptr, count) }; let pass = &mut pass_guard[pass_id]; for &id in buffers { - pass.trackers.buffers - .get_with_extended_usage( - &*buffer_guard, - id, - BufferUsageFlags::VERTEX, - ) + pass.trackers + .buffers + .get_with_extended_usage(&*buffer_guard, id, BufferUsageFlags::VERTEX) .unwrap(); } @@ -141,13 +132,10 @@ pub extern "C" fn wgpu_render_pass_draw( first_instance: u32, ) { unsafe { - HUB.render_passes - .write() - [pass_id].raw - .draw( - first_vertex .. first_vertex + vertex_count, - first_instance .. first_instance + instance_count, - ); + HUB.render_passes.write()[pass_id].raw.draw( + first_vertex..first_vertex + vertex_count, + first_instance..first_instance + instance_count, + ); } } @@ -161,14 +149,11 @@ pub extern "C" fn wgpu_render_pass_draw_indexed( first_instance: u32, ) { unsafe { - HUB.render_passes - .write() - [pass_id].raw - .draw_indexed( - first_index .. first_index + index_count, - base_vertex, - first_instance .. first_instance + instance_count, - ); + HUB.render_passes.write()[pass_id].raw.draw_indexed( + first_index..first_index + index_count, + base_vertex, + first_instance..first_instance + instance_count, + ); } } @@ -185,7 +170,10 @@ pub extern "C" fn wgpu_render_pass_set_bind_group( pass.trackers.consume_by_extend(&bind_group.used); - if let Some(pipeline_layout_id) = pass.binder.provide_entry(index as usize, bind_group_id, bind_group) { + if let Some(pipeline_layout_id) = + pass.binder + .provide_entry(index as usize, bind_group_id, bind_group) + { let pipeline_layout_guard = HUB.pipeline_layouts.read(); let pipeline_layout = &pipeline_layout_guard[pipeline_layout_id]; unsafe { @@ -209,15 +197,17 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( let pipeline_guard = HUB.render_pipelines.read(); let pipeline = &pipeline_guard[pipeline_id]; - assert_eq!(pass.context, pipeline.pass_context, - "The render pipeline is not compatible with the pass!"); + assert_eq!( + pass.context, pipeline.pass_context, + "The render pipeline is not compatible with the pass!" + ); unsafe { pass.raw.bind_graphics_pipeline(&pipeline.raw); } if pass.binder.pipeline_layout_id == Some(pipeline.layout_id.clone()) { - return + return; } let pipeline_layout_guard = HUB.pipeline_layouts.read(); @@ -225,9 +215,12 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( let bind_group_guard = HUB.bind_groups.read(); pass.binder.pipeline_layout_id = Some(pipeline.layout_id.clone()); - pass.binder.ensure_length(pipeline_layout.bind_group_layout_ids.len()); + pass.binder + .ensure_length(pipeline_layout.bind_group_layout_ids.len()); - for (index, (entry, &bgl_id)) in pass.binder.entries + for (index, (entry, &bgl_id)) in pass + .binder + .entries .iter_mut() .zip(&pipeline_layout.bind_group_layout_ids) .enumerate() @@ -239,7 +232,7 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( &pipeline_layout.raw, index, iter::once(desc_set), - &[] + &[], ); } } diff --git a/wgpu-native/src/command/transfer.rs b/wgpu-native/src/command/transfer.rs index 76d11d426..3c285892d 100644 --- a/wgpu-native/src/command/transfer.rs +++ b/wgpu-native/src/command/transfer.rs @@ -1,19 +1,16 @@ +use crate::conv; use crate::device::{all_buffer_stages, all_image_stages}; use crate::hub::HUB; use crate::resource::TexturePlacement; use crate::swap_chain::SwapChainLink; -use crate::conv; use crate::{ - BufferId, CommandBufferId, TextureId, - BufferUsageFlags, TextureUsageFlags, - Extent3d, Origin3d, + BufferId, BufferUsageFlags, CommandBufferId, Extent3d, Origin3d, TextureId, TextureUsageFlags, }; use hal::command::RawCommandBuffer; use std::iter; - const BITS_PER_BYTE: u32 = 8; #[repr(C)] @@ -36,7 +33,7 @@ pub struct TextureCopyView { #[no_mangle] pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer( command_buffer_id: CommandBufferId, - src: BufferId, + src: BufferId, src_offset: u32, dst: BufferId, dst_offset: u32, @@ -46,32 +43,28 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer( let cmb = &mut cmb_guard[command_buffer_id]; let buffer_guard = HUB.buffers.read(); - let (src_buffer, src_usage) = cmb.trackers.buffers - .get_with_replaced_usage( - &*buffer_guard, - src, - BufferUsageFlags::TRANSFER_SRC, - ) + let (src_buffer, src_usage) = cmb + .trackers + .buffers + .get_with_replaced_usage(&*buffer_guard, src, BufferUsageFlags::TRANSFER_SRC) .unwrap(); let src_barrier = src_usage.map(|old| hal::memory::Barrier::Buffer { - states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_READ, + states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_READ, target: &src_buffer.raw, families: None, - range: None .. None, + range: None..None, }); - let (dst_buffer, dst_usage) = cmb.trackers.buffers - .get_with_replaced_usage( - &*buffer_guard, - dst, - BufferUsageFlags::TRANSFER_DST, - ) + let (dst_buffer, dst_usage) = cmb + .trackers + .buffers + .get_with_replaced_usage(&*buffer_guard, dst, BufferUsageFlags::TRANSFER_DST) .unwrap(); let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Buffer { - states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_WRITE, + states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_WRITE, target: &dst_buffer.raw, families: None, - range: None .. None, + range: None..None, }); let region = hal::command::BufferCopy { @@ -82,15 +75,11 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer( let cmb_raw = cmb.raw.last_mut().unwrap(); unsafe { cmb_raw.pipeline_barrier( - all_buffer_stages() .. all_buffer_stages(), + all_buffer_stages()..all_buffer_stages(), hal::memory::Dependencies::empty(), src_barrier.into_iter().chain(dst_barrier), ); - cmb_raw.copy_buffer( - &src_buffer.raw, - &dst_buffer.raw, - iter::once(region), - ); + cmb_raw.copy_buffer(&src_buffer.raw, &dst_buffer.raw, iter::once(region)); } } @@ -106,7 +95,9 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture( let buffer_guard = HUB.buffers.read(); let texture_guard = HUB.textures.read(); - let (src_buffer, src_usage) = cmb.trackers.buffers + let (src_buffer, src_usage) = cmb + .trackers + .buffers .get_with_replaced_usage( &*buffer_guard, source.buffer, @@ -114,13 +105,15 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture( ) .unwrap(); let src_barrier = src_usage.map(|old| hal::memory::Barrier::Buffer { - states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_READ, + states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_READ, target: &src_buffer.raw, families: None, - range: None .. None, + range: None..None, }); - let (dst_texture, dst_usage) = cmb.trackers.textures + let (dst_texture, dst_usage) = cmb + .trackers + .textures .get_with_replaced_usage( &*texture_guard, destination.texture, @@ -130,7 +123,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture( let aspects = dst_texture.full_range.aspects; let dst_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_DST, aspects); let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Image { - states: conv::map_texture_state(old, aspects) .. dst_texture_state, + states: conv::map_texture_state(old, aspects)..dst_texture_state, target: &dst_texture.raw, families: None, range: dst_texture.full_range.clone(), @@ -145,7 +138,9 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture( } let bytes_per_texel = conv::map_texture_format(dst_texture.format) - .surface_desc().bits as u32 / BITS_PER_BYTE; + .surface_desc() + .bits as u32 + / BITS_PER_BYTE; let buffer_width = source.row_pitch / bytes_per_texel; assert_eq!(source.row_pitch % bytes_per_texel, 0); let region = hal::command::BufferImageCopy { @@ -155,7 +150,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture( image_layers: hal::image::SubresourceLayers { aspects, //TODO level: destination.level as hal::image::Level, - layers: destination.slice as u16 .. destination.slice as u16 + 1, + layers: destination.slice as u16..destination.slice as u16 + 1, }, image_offset: conv::map_origin(destination.origin), image_extent: conv::map_extent(copy_size), @@ -164,7 +159,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture( let stages = all_buffer_stages() | all_image_stages(); unsafe { cmb_raw.pipeline_barrier( - stages .. stages, + stages..stages, hal::memory::Dependencies::empty(), src_barrier.into_iter().chain(dst_barrier), ); @@ -189,7 +184,9 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer( let buffer_guard = HUB.buffers.read(); let texture_guard = HUB.textures.read(); - let (src_texture, src_usage) = cmb.trackers.textures + let (src_texture, src_usage) = cmb + .trackers + .textures .get_with_replaced_usage( &*texture_guard, source.texture, @@ -199,7 +196,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer( let aspects = src_texture.full_range.aspects; let src_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_SRC, aspects); let src_barrier = src_usage.map(|old| hal::memory::Barrier::Image { - states: conv::map_texture_state(old, aspects) .. src_texture_state, + states: conv::map_texture_state(old, aspects)..src_texture_state, target: &src_texture.raw, families: None, range: src_texture.full_range.clone(), @@ -210,7 +207,9 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer( TexturePlacement::Memory(_) => (), } - let (dst_buffer, dst_usage) = cmb.trackers.buffers + let (dst_buffer, dst_usage) = cmb + .trackers + .buffers .get_with_replaced_usage( &*buffer_guard, destination.buffer, @@ -218,14 +217,16 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer( ) .unwrap(); let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Buffer { - states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_WRITE, + states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_WRITE, target: &dst_buffer.raw, families: None, - range: None .. None, + range: None..None, }); let bytes_per_texel = conv::map_texture_format(src_texture.format) - .surface_desc().bits as u32 / BITS_PER_BYTE; + .surface_desc() + .bits as u32 + / BITS_PER_BYTE; let buffer_width = destination.row_pitch / bytes_per_texel; assert_eq!(destination.row_pitch % bytes_per_texel, 0); let region = hal::command::BufferImageCopy { @@ -235,7 +236,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer( image_layers: hal::image::SubresourceLayers { aspects, //TODO level: source.level as hal::image::Level, - layers: source.slice as u16 .. source.slice as u16 + 1, + layers: source.slice as u16..source.slice as u16 + 1, }, image_offset: conv::map_origin(source.origin), image_extent: conv::map_extent(copy_size), @@ -244,7 +245,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer( let stages = all_buffer_stages() | all_image_stages(); unsafe { cmb_raw.pipeline_barrier( - stages .. stages, + stages..stages, hal::memory::Dependencies::empty(), src_barrier.into_iter().chain(dst_barrier), ); @@ -268,14 +269,18 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture( let cmb = &mut cmb_guard[command_buffer_id]; let texture_guard = HUB.textures.read(); - let (src_texture, src_usage) = cmb.trackers.textures + let (src_texture, src_usage) = cmb + .trackers + .textures .get_with_replaced_usage( &*texture_guard, source.texture, TextureUsageFlags::TRANSFER_SRC, ) .unwrap(); - let (dst_texture, dst_usage) = cmb.trackers.textures + let (dst_texture, dst_usage) = cmb + .trackers + .textures .get_with_replaced_usage( &*texture_guard, destination.texture, @@ -288,13 +293,13 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture( let dst_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_DST, aspects); let src_barrier = src_usage.map(|old| hal::memory::Barrier::Image { - states: conv::map_texture_state(old, aspects) .. src_texture_state, + states: conv::map_texture_state(old, aspects)..src_texture_state, target: &src_texture.raw, families: None, range: src_texture.full_range.clone(), }); let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Image { - states: conv::map_texture_state(old, aspects) .. dst_texture_state, + states: conv::map_texture_state(old, aspects)..dst_texture_state, target: &dst_texture.raw, families: None, range: dst_texture.full_range.clone(), @@ -312,13 +317,13 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture( src_subresource: hal::image::SubresourceLayers { aspects, level: source.level as hal::image::Level, - layers: source.slice as u16 .. source.slice as u16 + 1, + layers: source.slice as u16..source.slice as u16 + 1, }, src_offset: conv::map_origin(source.origin), dst_subresource: hal::image::SubresourceLayers { aspects, level: destination.level as hal::image::Level, - layers: destination.slice as u16 .. destination.slice as u16 + 1, + layers: destination.slice as u16..destination.slice as u16 + 1, }, dst_offset: conv::map_origin(destination.origin), extent: conv::map_extent(copy_size), @@ -326,7 +331,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture( let cmb_raw = cmb.raw.last_mut().unwrap(); unsafe { cmb_raw.pipeline_barrier( - all_image_stages() .. all_image_stages(), + all_image_stages()..all_image_stages(), hal::memory::Dependencies::empty(), src_barrier.into_iter().chain(dst_barrier), ); diff --git a/wgpu-native/src/conv.rs b/wgpu-native/src/conv.rs index 7e8a7038c..7126e353e 100644 --- a/wgpu-native/src/conv.rs +++ b/wgpu-native/src/conv.rs @@ -1,15 +1,11 @@ -use crate::{ - binding_model, command, pipeline, resource, Color, - Extent3d, Origin3d, -}; - +use crate::{binding_model, command, pipeline, resource, Color, Extent3d, Origin3d}; pub fn map_buffer_usage( usage: resource::BufferUsageFlags, ) -> (hal::buffer::Usage, hal::memory::Properties) { + use crate::resource::BufferUsageFlags as W; use hal::buffer::Usage as U; use hal::memory::Properties as P; - use crate::resource::BufferUsageFlags as W; let mut hal_memory = P::empty(); if usage.contains(W::MAP_READ) { @@ -46,8 +42,8 @@ pub fn map_texture_usage( usage: resource::TextureUsageFlags, aspects: hal::format::Aspects, ) -> hal::image::Usage { - use hal::image::Usage as U; use crate::resource::TextureUsageFlags as W; + use hal::image::Usage as U; let mut value = U::empty(); if usage.contains(W::TRANSFER_SRC) { @@ -121,8 +117,8 @@ pub fn map_extent(extent: Extent3d) -> hal::image::Extent { } pub fn map_primitive_topology(primitive_topology: pipeline::PrimitiveTopology) -> hal::Primitive { - use hal::Primitive as H; use crate::pipeline::PrimitiveTopology::*; + use hal::Primitive as H; match primitive_topology { PointList => H::PointList, LineList => H::LineList, @@ -136,8 +132,8 @@ pub fn map_color_state_descriptor( desc: &pipeline::ColorStateDescriptor, ) -> hal::pso::ColorBlendDesc { let color_mask = desc.write_mask; - let blend_state = if desc.color != pipeline::BlendDescriptor::REPLACE || - desc.alpha != pipeline::BlendDescriptor::REPLACE + let blend_state = if desc.color != pipeline::BlendDescriptor::REPLACE + || desc.alpha != pipeline::BlendDescriptor::REPLACE { hal::pso::BlendState::On { color: map_blend_descriptor(&desc.color), @@ -150,8 +146,8 @@ pub fn map_color_state_descriptor( } fn map_color_write_flags(flags: pipeline::ColorWriteFlags) -> hal::pso::ColorMask { - use hal::pso::ColorMask as H; use crate::pipeline::ColorWriteFlags as F; + use hal::pso::ColorMask as H; let mut value = H::empty(); if flags.contains(F::RED) { @@ -170,8 +166,8 @@ fn map_color_write_flags(flags: pipeline::ColorWriteFlags) -> hal::pso::ColorMas } fn map_blend_descriptor(blend_desc: &pipeline::BlendDescriptor) -> hal::pso::BlendOp { - use hal::pso::BlendOp as H; use crate::pipeline::BlendOperation::*; + use hal::pso::BlendOp as H; match blend_desc.operation { Add => H::Add { src: map_blend_factor(blend_desc.src_factor), @@ -191,8 +187,8 @@ fn map_blend_descriptor(blend_desc: &pipeline::BlendDescriptor) -> hal::pso::Ble } fn map_blend_factor(blend_factor: pipeline::BlendFactor) -> hal::pso::Factor { - use hal::pso::Factor as H; use crate::pipeline::BlendFactor::*; + use hal::pso::Factor as H; match blend_factor { Zero => H::Zero, One => H::One, @@ -214,7 +210,9 @@ pub fn map_depth_stencil_state_descriptor( desc: &pipeline::DepthStencilStateDescriptor, ) -> hal::pso::DepthStencilDesc { hal::pso::DepthStencilDesc { - depth: if desc.depth_write_enabled || desc.depth_compare != resource::CompareFunction::Always { + depth: if desc.depth_write_enabled + || desc.depth_compare != resource::CompareFunction::Always + { hal::pso::DepthTest::On { fun: map_compare_function(desc.depth_compare), write: desc.depth_write_enabled, @@ -223,13 +221,22 @@ pub fn map_depth_stencil_state_descriptor( hal::pso::DepthTest::Off }, depth_bounds: false, // TODO - stencil: if desc.stencil_read_mask != !0 || desc.stencil_write_mask != !0 || - desc.stencil_front != pipeline::StencilStateFaceDescriptor::IGNORE || - desc.stencil_back != pipeline::StencilStateFaceDescriptor::IGNORE + stencil: if desc.stencil_read_mask != !0 + || desc.stencil_write_mask != !0 + || desc.stencil_front != pipeline::StencilStateFaceDescriptor::IGNORE + || desc.stencil_back != pipeline::StencilStateFaceDescriptor::IGNORE { hal::pso::StencilTest::On { - front: map_stencil_face(&desc.stencil_front, desc.stencil_read_mask, desc.stencil_write_mask), - back: map_stencil_face(&desc.stencil_back, desc.stencil_read_mask, desc.stencil_write_mask), + front: map_stencil_face( + &desc.stencil_front, + desc.stencil_read_mask, + desc.stencil_write_mask, + ), + back: map_stencil_face( + &desc.stencil_back, + desc.stencil_read_mask, + desc.stencil_write_mask, + ), } } else { hal::pso::StencilTest::Off @@ -254,8 +261,8 @@ fn map_stencil_face( } pub fn map_compare_function(compare_function: resource::CompareFunction) -> hal::pso::Comparison { - use hal::pso::Comparison as H; use crate::resource::CompareFunction::*; + use hal::pso::Comparison as H; match compare_function { Never => H::Never, Less => H::Less, @@ -269,8 +276,8 @@ pub fn map_compare_function(compare_function: resource::CompareFunction) -> hal: } fn map_stencil_operation(stencil_operation: pipeline::StencilOperation) -> hal::pso::StencilOp { - use hal::pso::StencilOp as H; use crate::pipeline::StencilOperation::*; + use hal::pso::StencilOp as H; match stencil_operation { Keep => H::Keep, Zero => H::Zero, @@ -284,8 +291,8 @@ fn map_stencil_operation(stencil_operation: pipeline::StencilOperation) -> hal:: } pub fn map_texture_format(texture_format: resource::TextureFormat) -> hal::format::Format { - use hal::format::Format as H; use crate::resource::TextureFormat::*; + use hal::format::Format as H; match texture_format { // Normal 8 bit formats R8Unorm => H::R8Unorm, @@ -355,8 +362,8 @@ pub fn map_texture_format(texture_format: resource::TextureFormat) -> hal::forma } pub fn map_vertex_format(vertex_format: pipeline::VertexFormat) -> hal::format::Format { - use hal::format::Format as H; use crate::pipeline::VertexFormat::*; + use hal::format::Format as H; match vertex_format { Uchar => H::R8Uint, Uchar2 => H::Rg8Uint, @@ -379,7 +386,7 @@ pub fn map_vertex_format(vertex_format: pipeline::VertexFormat) -> hal::format:: Ushort2 => H::Rg16Uint, Ushort3 => H::Rgb16Uint, Ushort4 => H::Rgba16Uint, - Short => H::R16Int, + Short => H::R16Int, Short2 => H::Rg16Int, Short3 => H::Rgb16Int, Short4 => H::Rgba16Int, @@ -417,11 +424,15 @@ fn checked_u32_as_u16(value: u32) -> u16 { pub fn map_texture_dimension_size( dimension: resource::TextureDimension, - Extent3d { width, height, depth }: Extent3d, + Extent3d { + width, + height, + depth, + }: Extent3d, array_size: u32, ) -> hal::image::Kind { - use hal::image::Kind as H; use crate::resource::TextureDimension::*; + use hal::image::Kind as H; match dimension { D1 => { assert_eq!(height, 1); @@ -442,8 +453,8 @@ pub fn map_texture_dimension_size( pub fn map_texture_view_dimension( dimension: resource::TextureViewDimension, ) -> hal::image::ViewKind { - use hal::image::ViewKind as H; use crate::resource::TextureViewDimension::*; + use hal::image::ViewKind as H; match dimension { D1 => H::D1, D2 => H::D2, @@ -455,8 +466,8 @@ pub fn map_texture_view_dimension( } pub fn map_texture_aspect_flags(aspect: resource::TextureAspectFlags) -> hal::format::Aspects { - use hal::format::Aspects; use crate::resource::TextureAspectFlags as Taf; + use hal::format::Aspects; let mut flags = Aspects::empty(); if aspect.contains(Taf::COLOR) { @@ -472,8 +483,8 @@ pub fn map_texture_aspect_flags(aspect: resource::TextureAspectFlags) -> hal::fo } pub fn map_buffer_state(usage: resource::BufferUsageFlags) -> hal::buffer::State { - use hal::buffer::Access as A; use crate::resource::BufferUsageFlags as W; + use hal::buffer::Access as A; let mut access = A::empty(); if usage.contains(W::TRANSFER_SRC) { @@ -502,8 +513,8 @@ pub fn map_texture_state( usage: resource::TextureUsageFlags, aspects: hal::format::Aspects, ) -> hal::image::State { - use hal::image::{Access as A, Layout as L}; use crate::resource::TextureUsageFlags as W; + use hal::image::{Access as A, Layout as L}; let is_color = aspects.contains(hal::format::Aspects::COLOR); let layout = match usage { @@ -568,8 +579,8 @@ pub fn map_filter(filter: resource::FilterMode) -> hal::image::Filter { } pub fn map_wrap(address: resource::AddressMode) -> hal::image::WrapMode { - use hal::image::WrapMode as W; use crate::resource::AddressMode as Am; + use hal::image::WrapMode as W; match address { Am::ClampToEdge => W::Clamp, Am::Repeat => W::Tile, @@ -579,7 +590,7 @@ pub fn map_wrap(address: resource::AddressMode) -> hal::image::WrapMode { } pub fn map_rasterization_state_descriptor( - desc: &pipeline::RasterizationStateDescriptor + desc: &pipeline::RasterizationStateDescriptor, ) -> hal::pso::Rasterizer { hal::pso::Rasterizer { depth_clamping: false, @@ -593,7 +604,10 @@ pub fn map_rasterization_state_descriptor( pipeline::FrontFace::Ccw => hal::pso::FrontFace::CounterClockwise, pipeline::FrontFace::Cw => hal::pso::FrontFace::Clockwise, }, - depth_bias: if desc.depth_bias != 0 || desc.depth_bias_slope_scale != 0.0 || desc.depth_bias_clamp != 0.0 { + depth_bias: if desc.depth_bias != 0 + || desc.depth_bias_slope_scale != 0.0 + || desc.depth_bias_clamp != 0.0 + { Some(hal::pso::State::Static(hal::pso::DepthBias { const_factor: desc.depth_bias as f32, slope_factor: desc.depth_bias_slope_scale, diff --git a/wgpu-native/src/device.rs b/wgpu-native/src/device.rs index b209f133b..b1cab1158 100644 --- a/wgpu-native/src/device.rs +++ b/wgpu-native/src/device.rs @@ -1,18 +1,17 @@ -use crate::{binding_model, command, conv, pipeline, resource, swap_chain}; use crate::hub::HUB; -use crate::track::{DummyUsage, Stitch, TrackerSet, TrackPermit}; +use crate::track::{DummyUsage, Stitch, TrackPermit, TrackerSet}; +use crate::{binding_model, command, conv, pipeline, resource, swap_chain}; use crate::{ - LifeGuard, RefCount, Stored, SubmissionIndex, - BufferMapAsyncStatus, BufferMapOperation, -}; -use crate::{ - BufferId, CommandBufferId, AdapterId, DeviceId, QueueId, - BindGroupId, TextureId, TextureViewId, SurfaceId, + AdapterId, BindGroupId, BufferId, CommandBufferId, DeviceId, QueueId, SurfaceId, TextureId, + TextureViewId, }; #[cfg(feature = "local")] use crate::{ - BindGroupLayoutId, PipelineLayoutId, SamplerId, SwapChainId, - ShaderModuleId, CommandEncoderId, RenderPipelineId, ComputePipelineId, + BindGroupLayoutId, CommandEncoderId, ComputePipelineId, PipelineLayoutId, RenderPipelineId, + SamplerId, ShaderModuleId, SwapChainId, +}; +use crate::{ + BufferMapAsyncStatus, BufferMapOperation, LifeGuard, RefCount, Stored, SubmissionIndex, }; use arrayvec::ArrayVec; @@ -20,40 +19,34 @@ use back; use hal::backend::FastHashMap; use hal::command::RawCommandBuffer; use hal::queue::RawCommandQueue; -use hal::{ - self, - DescriptorPool as _DescriptorPool, - Device as _Device, - Surface as _Surface, -}; +use hal::{self, DescriptorPool as _DescriptorPool, Device as _Device, Surface as _Surface}; use log::{info, trace}; //use rendy_memory::{allocator, Config, Heaps}; -use parking_lot::{Mutex}; +use parking_lot::Mutex; -use std::{ffi, iter, slice}; use std::collections::hash_map::Entry; use std::sync::atomic::Ordering; - +use std::{ffi, iter, slice}; pub fn all_buffer_stages() -> hal::pso::PipelineStage { use hal::pso::PipelineStage as Ps; - Ps::DRAW_INDIRECT | - Ps::VERTEX_INPUT | - Ps::VERTEX_SHADER | - Ps::FRAGMENT_SHADER | - Ps::COMPUTE_SHADER | - Ps::TRANSFER | - Ps::HOST + Ps::DRAW_INDIRECT + | Ps::VERTEX_INPUT + | Ps::VERTEX_SHADER + | Ps::FRAGMENT_SHADER + | Ps::COMPUTE_SHADER + | Ps::TRANSFER + | Ps::HOST } pub fn all_image_stages() -> hal::pso::PipelineStage { use hal::pso::PipelineStage as Ps; - Ps::EARLY_FRAGMENT_TESTS | - Ps::LATE_FRAGMENT_TESTS | - Ps::COLOR_ATTACHMENT_OUTPUT | - Ps::VERTEX_SHADER | - Ps::FRAGMENT_SHADER | - Ps::COMPUTE_SHADER | - Ps::TRANSFER + Ps::EARLY_FRAGMENT_TESTS + | Ps::LATE_FRAGMENT_TESTS + | Ps::COLOR_ATTACHMENT_OUTPUT + | Ps::VERTEX_SHADER + | Ps::FRAGMENT_SHADER + | Ps::COMPUTE_SHADER + | Ps::TRANSFER } #[derive(Clone, Debug, Hash, PartialEq)] @@ -120,7 +113,10 @@ impl DestroyedResources { } fn map(&mut self, buffer: BufferId, ref_count: RefCount) { - self.mapped.push(Stored{value: buffer, ref_count}); + self.mapped.push(Stored { + value: buffer, + ref_count, + }); } /// Returns the last submission index that is done. @@ -128,9 +124,7 @@ impl DestroyedResources { let mut last_done = 0; for i in (0..self.active.len()).rev() { - if unsafe { - device.get_fence_status(&self.active[i].fence).unwrap() - } { + if unsafe { device.get_fence_status(&self.active[i].fence).unwrap() } { let a = self.active.swap_remove(i); last_done = last_done.max(a.index); self.free.extend(a.resources.into_iter().map(|(_, r)| r)); @@ -164,10 +158,7 @@ impl DestroyedResources { } impl DestroyedResources { - fn triage_referenced( - &mut self, - trackers: &mut TrackerSet, - ) { + fn triage_referenced(&mut self, trackers: &mut TrackerSet) { for i in (0..self.referenced.len()).rev() { let num_refs = self.referenced[i].1.load(); // Before destruction, a resource is expected to have the following strong refs: @@ -176,7 +167,11 @@ impl DestroyedResources { // 3. in this list if num_refs <= 3 { let resource_id = self.referenced.swap_remove(i).0; - assert_eq!(num_refs, 3, "Resource {:?} misses some references", resource_id); + assert_eq!( + num_refs, 3, + "Resource {:?} misses some references", + resource_id + ); let (life_guard, resource) = match resource_id { ResourceId::Buffer(id) => { trackers.buffers.remove(id); @@ -202,10 +197,7 @@ impl DestroyedResources { }; let submit_index = life_guard.submission_index.load(Ordering::Acquire); - match self.active - .iter_mut() - .find(|a| a.index == submit_index) - { + match self.active.iter_mut().find(|a| a.index == submit_index) { Some(a) => a.resources.push((Some(resource_id), resource)), None => self.free.push(resource), } @@ -223,8 +215,11 @@ impl DestroyedResources { Some(BufferMapOperation::Write(..)) => resource::BufferUsageFlags::MAP_WRITE, _ => unreachable!(), }; - trackers.buffers.get_with_replaced_usage(&buffer_guard, resource_id, usage).unwrap(); - + trackers + .buffers + .get_with_replaced_usage(&buffer_guard, resource_id, usage) + .unwrap(); + let submit_index = buf.life_guard.submission_index.load(Ordering::Acquire); self.active .iter_mut() @@ -236,7 +231,10 @@ impl DestroyedResources { fn triage_framebuffers( &mut self, - framebuffers: &mut FastHashMap::Framebuffer>, + framebuffers: &mut FastHashMap< + FramebufferKey, + ::Framebuffer, + >, ) { let texture_view_guard = HUB.texture_views.read(); let remove_list = framebuffers @@ -245,7 +243,7 @@ impl DestroyedResources { let mut last_submit: SubmissionIndex = 0; for &at in key.all() { if texture_view_guard.contains(at) { - return None + return None; } // This attachment is no longer registered. // Let's see if it's used by any of the active submissions. @@ -258,14 +256,11 @@ impl DestroyedResources { } Some((key.clone(), last_submit)) }) - .collect::>(); + .collect::>(); for (ref key, submit_index) in remove_list { let resource = NativeResource::Framebuffer(framebuffers.remove(key).unwrap()); - match self.active - .iter_mut() - .find(|a| a.index == submit_index) - { + match self.active.iter_mut().find(|a| a.index == submit_index) { Some(a) => a.resources.push((None, resource)), None => self.free.push(resource), } @@ -288,7 +283,7 @@ impl DestroyedResources { (BufferMapAsyncStatus::Error, None) } } - }, + } BufferMapOperation::Write(range, ..) => { match map_buffer(raw, &mut buffer, range.clone(), false, true) { Ok(ptr) => (BufferMapAsyncStatus::Success, Some(ptr)), @@ -297,13 +292,17 @@ impl DestroyedResources { (BufferMapAsyncStatus::Error, None) } } - }, + } } }; match operation.unwrap() { - BufferMapOperation::Read(_, callback, userdata) => callback(result, ptr.unwrap_or(std::ptr::null_mut()), userdata), - BufferMapOperation::Write(_, callback, userdata) => callback(result, ptr.unwrap_or(std::ptr::null_mut()), userdata), + BufferMapOperation::Read(_, callback, userdata) => { + callback(result, ptr.unwrap_or(std::ptr::null_mut()), userdata) + } + BufferMapOperation::Write(_, callback, userdata) => { + callback(result, ptr.unwrap_or(std::ptr::null_mut()), userdata) + } }; } } @@ -317,10 +316,21 @@ fn map_buffer( write: bool, ) -> Result<*mut u8, hal::mapping::Error> { let pointer = unsafe { raw.map_memory(&buffer.memory, range.clone()) }?; - if read && !buffer.memory_properties.contains(hal::memory::Properties::COHERENT) { - unsafe { raw.invalidate_mapped_memory_ranges(iter::once((&buffer.memory, range.clone()))).unwrap() }; // TODO + if read + && !buffer + .memory_properties + .contains(hal::memory::Properties::COHERENT) + { + unsafe { + raw.invalidate_mapped_memory_ranges(iter::once((&buffer.memory, range.clone()))) + .unwrap() + }; // TODO } - if write && !buffer.memory_properties.contains(hal::memory::Properties::COHERENT) { + if write + && !buffer + .memory_properties + .contains(hal::memory::Properties::COHERENT) + { buffer.mapped_write_ranges.push(range.clone()); } Ok(pointer) @@ -393,7 +403,8 @@ impl Device { }, ], ) - }.unwrap() + } + .unwrap(), ); // don't start submission index at zero @@ -423,12 +434,10 @@ impl Device { } } - pub struct ShaderModule { pub(crate) raw: B::ShaderModule, } - pub fn device_create_buffer( device_id: DeviceId, desc: &resource::BufferDescriptor, @@ -437,12 +446,8 @@ pub fn device_create_buffer( let device = &device_guard[device_id]; let (usage, memory_properties) = conv::map_buffer_usage(desc.usage); - let mut buffer = unsafe { - device.raw.create_buffer(desc.size as u64, usage).unwrap() - }; - let requirements = unsafe { - device.raw.get_buffer_requirements(&buffer) - }; + let mut buffer = unsafe { device.raw.create_buffer(desc.size as u64, usage).unwrap() }; + let requirements = unsafe { device.raw.get_buffer_requirements(&buffer) }; let device_type = device .mem_props .memory_types @@ -450,20 +455,20 @@ pub fn device_create_buffer( .enumerate() .position(|(id, memory_type)| { requirements.type_mask & (1 << id) != 0 - && memory_type - .properties - .contains(memory_properties) + && memory_type.properties.contains(memory_properties) }) .unwrap() .into(); // TODO: allocate with rendy let memory = unsafe { - device.raw + device + .raw .allocate_memory(device_type, requirements.size) .unwrap() }; unsafe { - device.raw + device + .raw .bind_buffer_memory(&memory, 0, &mut buffer) .unwrap() }; @@ -488,9 +493,8 @@ pub fn device_track_buffer( ref_count: RefCount, flags: resource::BufferUsageFlags, ) { - let query = HUB.devices - .read() - [device_id].trackers + let query = HUB.devices.read()[device_id] + .trackers .lock() .buffers .query(buffer_id, &ref_count, flags); @@ -506,7 +510,12 @@ pub extern "C" fn wgpu_device_create_buffer( let buffer = device_create_buffer(device_id, desc); let ref_count = buffer.life_guard.ref_count.clone(); let id = HUB.buffers.register_local(buffer); - device_track_buffer(device_id, id, ref_count, resource::BufferUsageFlags::empty()); + device_track_buffer( + device_id, + id, + ref_count, + resource::BufferUsageFlags::empty(), + ); id } @@ -515,7 +524,7 @@ pub extern "C" fn wgpu_device_create_buffer( pub extern "C" fn wgpu_device_create_buffer_mapped( device_id: DeviceId, desc: &resource::BufferDescriptor, - mapped_ptr_out: *mut *mut u8 + mapped_ptr_out: *mut *mut u8, ) -> BufferId { let mut desc = desc.clone(); desc.usage |= resource::BufferUsageFlags::MAP_WRITE; @@ -525,16 +534,25 @@ pub extern "C" fn wgpu_device_create_buffer_mapped( let device = &device_guard[device_id]; match map_buffer(&device.raw, &mut buffer, 0..(desc.size as u64), false, true) { - Ok(ptr) => unsafe { *mapped_ptr_out = ptr; } + Ok(ptr) => unsafe { + *mapped_ptr_out = ptr; + }, Err(e) => { log::error!("failed to create buffer in a mapped state: {}", e); - unsafe { *mapped_ptr_out = std::ptr::null_mut(); } + unsafe { + *mapped_ptr_out = std::ptr::null_mut(); + } } } let ref_count = buffer.life_guard.ref_count.clone(); let id = HUB.buffers.register_local(buffer); - device_track_buffer(device_id, id, ref_count, resource::BufferUsageFlags::MAP_WRITE); + device_track_buffer( + device_id, + id, + ref_count, + resource::BufferUsageFlags::MAP_WRITE, + ); id } @@ -542,9 +560,8 @@ pub extern "C" fn wgpu_device_create_buffer_mapped( pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { let buffer_guard = HUB.buffers.read(); let buffer = &buffer_guard[buffer_id]; - HUB.devices - .read() - [buffer.device_id.value].destroyed + HUB.devices.read()[buffer.device_id.value] + .destroyed .lock() .destroy( ResourceId::Buffer(buffer_id), @@ -574,9 +591,7 @@ pub fn device_create_texture( ) } .unwrap(); - let requirements = unsafe { - device.raw.get_image_requirements(&image) - }; + let requirements = unsafe { device.raw.get_image_requirements(&image) }; let device_type = device .mem_props .memory_types @@ -593,12 +608,14 @@ pub fn device_create_texture( .into(); // TODO: allocate with rendy let memory = unsafe { - device.raw + device + .raw .allocate_memory(device_type, requirements.size) .unwrap() }; unsafe { - device.raw + device + .raw .bind_image_memory(&memory, 0, &mut image) .unwrap() }; @@ -613,25 +630,24 @@ pub fn device_create_texture( format: desc.format, full_range: hal::image::SubresourceRange { aspects, - levels: 0 .. 1, //TODO: mips - layers: 0 .. desc.array_size as u16, + levels: 0..1, //TODO: mips + layers: 0..desc.array_size as u16, }, placement: resource::TexturePlacement::Memory(memory), life_guard: LifeGuard::new(), } } -pub fn device_track_texture( - device_id: DeviceId, - texture_id: TextureId, - ref_count: RefCount, -) { - let query = HUB.devices - .read() - [device_id].trackers +pub fn device_track_texture(device_id: DeviceId, texture_id: TextureId, ref_count: RefCount) { + let query = HUB.devices.read()[device_id] + .trackers .lock() .textures - .query(texture_id, &ref_count, resource::TextureUsageFlags::UNINITIALIZED); + .query( + texture_id, + &ref_count, + resource::TextureUsageFlags::UNINITIALIZED, + ); assert!(query.initialized); } @@ -658,9 +674,8 @@ pub fn texture_create_view( let texture = &texture_guard[texture_id]; let raw = unsafe { - HUB.devices - .read() - [texture.device_id.value].raw + HUB.devices.read()[texture.device_id.value] + .raw .create_image_view( &texture.raw, view_kind, @@ -685,17 +700,10 @@ pub fn texture_create_view( } } -pub fn device_track_view( - texture_id: TextureId, - view_id: BufferId, - ref_count: RefCount, -) { - let device_id = HUB.textures - .read() - [texture_id].device_id.value; - let query = HUB.devices - .read() - [device_id].trackers +pub fn device_track_view(texture_id: TextureId, view_id: BufferId, ref_count: RefCount) { + let device_id = HUB.textures.read()[texture_id].device_id.value; + let query = HUB.devices.read()[device_id] + .trackers .lock() .views .query(view_id, &ref_count, DummyUsage); @@ -714,8 +722,8 @@ pub extern "C" fn wgpu_texture_create_view( conv::map_texture_view_dimension(desc.dimension), hal::image::SubresourceRange { aspects: conv::map_texture_aspect_flags(desc.aspect), - levels: desc.base_mip_level as u8 .. (desc.base_mip_level + desc.level_count) as u8, - layers: desc.base_array_layer as u16 .. (desc.base_array_layer + desc.array_count) as u16, + levels: desc.base_mip_level as u8..(desc.base_mip_level + desc.level_count) as u8, + layers: desc.base_array_layer as u16..(desc.base_array_layer + desc.array_count) as u16, }, ); let ref_count = view.life_guard.ref_count.clone(); @@ -739,12 +747,7 @@ pub extern "C" fn wgpu_texture_create_default_view(texture_id: TextureId) -> Tex }; (texture.format, view_kind, texture.full_range.clone()) }; - let view = texture_create_view( - texture_id, - format, - view_kind, - range, - ); + let view = texture_create_view(texture_id, format, view_kind, range); let ref_count = view.life_guard.ref_count.clone(); let id = HUB.texture_views.register_local(view); device_track_view(texture_id, id, ref_count); @@ -755,9 +758,8 @@ pub extern "C" fn wgpu_texture_create_default_view(texture_id: TextureId) -> Tex pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) { let texture_guard = HUB.textures.read(); let texture = &texture_guard[texture_id]; - HUB.devices - .read() - [texture.device_id.value].destroyed + HUB.devices.read()[texture.device_id.value] + .destroyed .lock() .destroy( ResourceId::Texture(texture_id), @@ -769,22 +771,16 @@ pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) { pub extern "C" fn wgpu_texture_view_destroy(texture_view_id: TextureViewId) { let texture_view_guard = HUB.texture_views.read(); let view = &texture_view_guard[texture_view_id]; - let device_id = HUB.textures - .read() - [view.texture_id.value].device_id.value; - HUB.devices - .read() - [device_id].destroyed - .lock() - .destroy( - ResourceId::TextureView(texture_view_id), - view.life_guard.ref_count.clone(), - ); + let device_id = HUB.textures.read()[view.texture_id.value].device_id.value; + HUB.devices.read()[device_id].destroyed.lock().destroy( + ResourceId::TextureView(texture_view_id), + view.life_guard.ref_count.clone(), + ); } - pub fn device_create_sampler( - device_id: DeviceId, desc: &resource::SamplerDescriptor + device_id: DeviceId, + desc: &resource::SamplerDescriptor, ) -> resource::Sampler { let device_guard = HUB.devices.read(); let device = &device_guard[device_id]; @@ -799,7 +795,7 @@ pub fn device_create_sampler( conv::map_wrap(desc.t_address_mode), ), lod_bias: 0.0.into(), - lod_range: desc.lod_min_clamp.into() .. desc.lod_max_clamp.into(), + lod_range: desc.lod_min_clamp.into()..desc.lod_max_clamp.into(), comparison: if desc.compare_function == resource::CompareFunction::Always { None } else { @@ -812,27 +808,21 @@ pub fn device_create_sampler( }), anisotropic: hal::image::Anisotropic::Off, //TODO }; - let raw = unsafe { - device.raw - .create_sampler(info) - .unwrap() - }; + let raw = unsafe { device.raw.create_sampler(info).unwrap() }; - resource::Sampler { - raw, - } + resource::Sampler { raw } } #[cfg(feature = "local")] #[no_mangle] pub extern "C" fn wgpu_device_create_sampler( - device_id: DeviceId, desc: &resource::SamplerDescriptor + device_id: DeviceId, + desc: &resource::SamplerDescriptor, ) -> SamplerId { let sampler = device_create_sampler(device_id, desc); HUB.samplers.register_local(sampler) } - pub fn device_create_bind_group_layout( device_id: DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, @@ -840,9 +830,8 @@ pub fn device_create_bind_group_layout( let bindings = unsafe { slice::from_raw_parts(desc.bindings, desc.bindings_length) }; let raw = unsafe { - HUB.devices - .read() - [device_id].raw + HUB.devices.read()[device_id] + .raw .create_descriptor_set_layout( bindings.iter().map(|binding| { hal::pso::DescriptorSetLayoutBinding { @@ -858,9 +847,7 @@ pub fn device_create_bind_group_layout( .unwrap() }; - binding_model::BindGroupLayout { - raw, - } + binding_model::BindGroupLayout { raw } } #[cfg(feature = "local")] @@ -877,9 +864,8 @@ pub fn device_create_pipeline_layout( device_id: DeviceId, desc: &binding_model::PipelineLayoutDescriptor, ) -> binding_model::PipelineLayout { - let bind_group_layout_ids = unsafe { - slice::from_raw_parts(desc.bind_group_layouts, desc.bind_group_layouts_length) - }; + let bind_group_layout_ids = + unsafe { slice::from_raw_parts(desc.bind_group_layouts, desc.bind_group_layouts_length) }; let bind_group_layout_guard = HUB.bind_group_layouts.read(); let descriptor_set_layouts = bind_group_layout_ids .iter() @@ -887,19 +873,15 @@ pub fn device_create_pipeline_layout( // TODO: push constants let pipeline_layout = unsafe { - HUB.devices - .read() - [device_id].raw + HUB.devices.read()[device_id] + .raw .create_pipeline_layout(descriptor_set_layouts, &[]) } .unwrap(); binding_model::PipelineLayout { raw: pipeline_layout, - bind_group_layout_ids: bind_group_layout_ids - .iter() - .cloned() - .collect(), + bind_group_layout_ids: bind_group_layout_ids.iter().cloned().collect(), } } @@ -921,16 +903,10 @@ pub fn device_create_bind_group( let device = &device_guard[device_id]; let bind_group_layout_guard = HUB.bind_group_layouts.read(); let bind_group_layout = &bind_group_layout_guard[desc.layout]; - let bindings = unsafe { - slice::from_raw_parts(desc.bindings, desc.bindings_length as usize) - }; + let bindings = unsafe { slice::from_raw_parts(desc.bindings, desc.bindings_length as usize) }; let mut desc_pool = device.desc_pool.lock(); - let desc_set = unsafe { - desc_pool - .allocate_set(&bind_group_layout.raw) - .unwrap() - }; + let desc_set = unsafe { desc_pool.allocate_set(&bind_group_layout.raw).unwrap() }; let buffer_guard = HUB.buffers.read(); let sampler_guard = HUB.samplers.read(); @@ -942,14 +918,15 @@ pub fn device_create_bind_group( for b in bindings { let descriptor = match b.resource { binding_model::BindingResource::Buffer(ref bb) => { - let buffer = used.buffers + let buffer = used + .buffers .get_with_extended_usage( &*buffer_guard, bb.buffer, resource::BufferUsageFlags::UNIFORM, ) .unwrap(); - let range = Some(bb.offset as u64) .. Some((bb.offset + bb.size) as u64); + let range = Some(bb.offset as u64)..Some((bb.offset + bb.size) as u64); hal::pso::Descriptor::Buffer(&buffer.raw, range) } binding_model::BindingResource::Sampler(id) => { @@ -1006,16 +983,14 @@ pub extern "C" fn wgpu_bind_group_destroy(bind_group_id: BindGroupId) { HUB.bind_groups.unregister(bind_group_id); } - pub fn device_create_shader_module( device_id: DeviceId, desc: &pipeline::ShaderModuleDescriptor, ) -> ShaderModule { let spv = unsafe { slice::from_raw_parts(desc.code.bytes, desc.code.length) }; let shader = unsafe { - HUB.devices - .read() - [device_id].raw + HUB.devices.read()[device_id] + .raw .create_shader_module(spv) .unwrap() }; @@ -1104,18 +1079,25 @@ pub extern "C" fn wgpu_queue_submit( let comb = &mut command_buffer_guard[cmb_id]; swap_chain_links.extend(comb.swap_chain_links.drain(..)); // update submission IDs - comb.life_guard.submission_index + comb.life_guard + .submission_index .store(old_submit_index, Ordering::Release); for id in comb.trackers.buffers.used() { - buffer_guard[id].life_guard.submission_index + buffer_guard[id] + .life_guard + .submission_index .store(old_submit_index, Ordering::Release); } for id in comb.trackers.textures.used() { - texture_guard[id].life_guard.submission_index + texture_guard[id] + .life_guard + .submission_index .store(old_submit_index, Ordering::Release); } for id in comb.trackers.views.used() { - texture_view_guard[id].life_guard.submission_index + texture_view_guard[id] + .life_guard + .submission_index .store(old_submit_index, Ordering::Release); } @@ -1151,17 +1133,18 @@ pub extern "C" fn wgpu_queue_submit( let command_buffer_guard = HUB.command_buffers.read(); let surface_guard = HUB.surfaces.read(); - let wait_semaphores = swap_chain_links - .into_iter() - .flat_map(|link| { - //TODO: check the epoch - surface_guard[link.swap_chain_id].swap_chain - .as_ref() - .map(|swap_chain| ( + let wait_semaphores = swap_chain_links.into_iter().flat_map(|link| { + //TODO: check the epoch + surface_guard[link.swap_chain_id] + .swap_chain + .as_ref() + .map(|swap_chain| { + ( &swap_chain.frames[link.image_index as usize].sem_available, hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT, - )) - }); + ) + }) + }); let submission = hal::queue::Submission::<_, _, &[::Semaphore]> { @@ -1217,7 +1200,6 @@ pub extern "C" fn wgpu_queue_submit( } } - pub fn device_create_render_pipeline( device_id: DeviceId, desc: &pipeline::RenderPipelineDescriptor, @@ -1228,15 +1210,9 @@ pub fn device_create_render_pipeline( let layout = &pipeline_layout_guard[desc.layout].raw; let shader_module_guard = HUB.shader_modules.read(); - let color_states = unsafe { - slice::from_raw_parts( - desc.color_states, - desc.color_states_length, - ) - }; - let depth_stencil_state = unsafe { - desc.depth_stencil_state.as_ref() - }; + let color_states = + unsafe { slice::from_raw_parts(desc.color_states, desc.color_states_length) }; + let depth_stencil_state = unsafe { desc.depth_stencil_state.as_ref() }; let rp_key = RenderPassKey { colors: color_states @@ -1249,14 +1225,13 @@ pub fn device_create_render_pipeline( layouts: hal::image::Layout::General..hal::image::Layout::General, }) .collect(), - depth_stencil: depth_stencil_state - .map(|at| hal::pass::Attachment { - format: Some(conv::map_texture_format(at.format)), - samples: desc.sample_count as u8, - ops: hal::pass::AttachmentOps::PRESERVE, - stencil_ops: hal::pass::AttachmentOps::PRESERVE, - layouts: hal::image::Layout::General..hal::image::Layout::General, - }), + depth_stencil: depth_stencil_state.map(|at| hal::pass::Attachment { + format: Some(conv::map_texture_format(at.format)), + samples: desc.sample_count as u8, + ops: hal::pass::AttachmentOps::PRESERVE, + stencil_ops: hal::pass::AttachmentOps::PRESERVE, + layouts: hal::image::Layout::General..hal::image::Layout::General, + }), }; let mut render_pass_cache = device.render_passes.lock(); @@ -1327,13 +1302,16 @@ pub fn device_create_render_pipeline( let rasterizer = conv::map_rasterization_state_descriptor(&desc.rasterization_state); let desc_vbs = unsafe { - slice::from_raw_parts(desc.vertex_buffer_state.vertex_buffers, desc.vertex_buffer_state.vertex_buffers_count) + slice::from_raw_parts( + desc.vertex_buffer_state.vertex_buffers, + desc.vertex_buffer_state.vertex_buffers_count, + ) }; let mut vertex_buffers = Vec::with_capacity(desc_vbs.len()); let mut attributes = Vec::new(); for (i, vb_state) in desc_vbs.iter().enumerate() { if vb_state.attributes_count == 0 { - continue + continue; } vertex_buffers.push(hal::pso::VertexBufferDesc { binding: i as u32, @@ -1343,9 +1321,8 @@ pub fn device_create_render_pipeline( pipeline::InputStepMode::Instance => 1, }, }); - let desc_atts = unsafe { - slice::from_raw_parts(vb_state.attributes, vb_state.attributes_count) - }; + let desc_atts = + unsafe { slice::from_raw_parts(vb_state.attributes, vb_state.attributes_count) }; for attribute in desc_atts { attributes.push(hal::pso::AttributeDesc { location: attribute.attribute_index, @@ -1413,19 +1390,16 @@ pub fn device_create_render_pipeline( // TODO: cache let pipeline = unsafe { - device.raw + device + .raw .create_graphics_pipeline(&pipeline_desc, None) .unwrap() }; let pass_context = RenderPassContext { - colors: color_states - .iter() - .map(|state| state.format) - .collect(), - depth_stencil: depth_stencil_state - .map(|state| state.format), - }; + colors: color_states.iter().map(|state| state.format).collect(), + depth_stencil: depth_stencil_state.map(|state| state.format), + }; pipeline::RenderPipeline { raw: pipeline, @@ -1517,7 +1491,9 @@ pub fn device_create_swap_chain( let (caps, formats, _present_modes, _composite_alphas) = { let adapter_guard = HUB.adapters.read(); let adapter = &adapter_guard[device.adapter_id]; - assert!(surface.raw.supports_queue_family(&adapter.queue_families[0])); + assert!(surface + .raw + .supports_queue_family(&adapter.queue_families[0])); surface.raw.compatibility(&adapter.physical_device) }; let num_frames = caps.image_count.start; //TODO: configure? @@ -1530,9 +1506,12 @@ pub fn device_create_swap_chain( ); if let Some(formats) = formats { - assert!(formats.contains(&config.format), + assert!( + formats.contains(&config.format), "Requested format {:?} is not in supported list: {:?}", - config.format, formats); + config.format, + formats + ); } //TODO: properly exclusive range /* TODO: this is way too restrictive @@ -1549,35 +1528,35 @@ pub fn device_create_swap_chain( let mut destroyed = device.destroyed.lock(); assert_eq!(old.device_id.value, device_id); for frame in old.frames { - destroyed.destroy(ResourceId::Texture(frame.texture_id.value), frame.texture_id.ref_count); - destroyed.destroy(ResourceId::TextureView(frame.view_id.value), frame.view_id.ref_count); + destroyed.destroy( + ResourceId::Texture(frame.texture_id.value), + frame.texture_id.ref_count, + ); + destroyed.destroy( + ResourceId::TextureView(frame.view_id.value), + frame.view_id.ref_count, + ); } - unsafe { - old.command_pool.reset() - }; + unsafe { old.command_pool.reset() }; (Some(old.raw), old.sem_available, old.command_pool) } _ => unsafe { - let sem_available = device.raw - .create_semaphore() - .unwrap(); - let command_pool = device.raw + let sem_available = device.raw.create_semaphore().unwrap(); + let command_pool = device + .raw .create_command_pool_typed( &device.queue_group, hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL, ) .unwrap(); (None, sem_available, command_pool) - } + }, }; let (raw, backbuffer) = unsafe { - device.raw - .create_swapchain( - &mut surface.raw, - config.with_image_usage(usage), - old_raw, - ) + device + .raw + .create_swapchain(&mut surface.raw, config.with_image_usage(usage), old_raw) .unwrap() }; surface.swap_chain = Some(swap_chain::SwapChain { @@ -1610,8 +1589,8 @@ pub fn device_create_swap_chain( format: desc.format, full_range: hal::image::SubresourceRange { aspects: hal::format::Aspects::COLOR, - levels: 0 .. 1, - layers: 0 .. 1, + levels: 0..1, + layers: 0..1, }, placement: resource::TexturePlacement::Void, life_guard: LifeGuard::new(), @@ -1625,9 +1604,7 @@ pub fn swap_chain_populate_textures( textures: Vec>, ) { let mut surface_guard = HUB.surfaces.write(); - let swap_chain = surface_guard[swap_chain_id].swap_chain - .as_mut() - .unwrap(); + let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); let device_guard = HUB.devices.read(); let device = &device_guard[swap_chain.device_id.value]; let mut trackers = device.trackers.lock(); @@ -1637,7 +1614,8 @@ pub fn swap_chain_populate_textures( let kind = texture.kind; let view_raw = unsafe { - device.raw + device + .raw .create_image_view( &texture.raw, hal::image::ViewKind::D2, @@ -1646,7 +1624,7 @@ pub fn swap_chain_populate_textures( texture.full_range.clone(), ) .unwrap() - }; + }; texture.placement = resource::TexturePlacement::SwapChain(swap_chain::SwapChainLink { swap_chain_id, //TODO: strongly epoch: Mutex::new(0), @@ -1672,14 +1650,12 @@ pub fn swap_chain_populate_textures( life_guard: LifeGuard::new(), }; let view_id = Stored { - ref_count: view.life_guard.ref_count.clone(), - value: HUB.texture_views.register_local(view), + ref_count: view.life_guard.ref_count.clone(), + value: HUB.texture_views.register_local(view), }; - trackers.views.query( - view_id.value, - &view_id.ref_count, - DummyUsage, - ); + trackers + .views + .query(view_id.value, &view_id.ref_count, DummyUsage); swap_chain.frames.push(swap_chain::Frame { texture_id, @@ -1704,11 +1680,12 @@ pub extern "C" fn wgpu_device_create_swap_chain( surface_id } - #[no_mangle] pub extern "C" fn wgpu_buffer_set_sub_data( buffer_id: BufferId, - start: u32, count: u32, data: *const u8, + start: u32, + count: u32, + data: *const u8, ) { let buffer_guard = HUB.buffers.read(); let buffer = &buffer_guard[buffer_id]; @@ -1718,7 +1695,8 @@ pub extern "C" fn wgpu_buffer_set_sub_data( //Note: this is just doing `update_buffer`, which is limited to 64KB trace!("transit {:?} to transfer dst", buffer_id); - let barrier = device.trackers + let barrier = device + .trackers .lock() .buffers .transit( @@ -1730,19 +1708,22 @@ pub extern "C" fn wgpu_buffer_set_sub_data( .unwrap() .into_source() .map(|old| hal::memory::Barrier::Buffer { - states: conv::map_buffer_state(old) .. - hal::buffer::State::TRANSFER_WRITE, + states: conv::map_buffer_state(old)..hal::buffer::State::TRANSFER_WRITE, target: &buffer.raw, families: None, - range: None .. None, //TODO: could be partial + range: None..None, //TODO: could be partial }); // Note: this is not pretty. If we need one-time service command buffers, // we'll need to have some internal abstractions for them to be safe. - let mut comb = device.com_allocator.allocate(buffer.device_id.clone(), &device.raw); + let mut comb = device + .com_allocator + .allocate(buffer.device_id.clone(), &device.raw); // mark as used by the next submission, conservatively let last_submit_index = device.life_guard.submission_index.load(Ordering::Acquire); - comb.life_guard.submission_index.store(last_submit_index + 1, Ordering::Release); + comb.life_guard + .submission_index + .store(last_submit_index + 1, Ordering::Release); unsafe { let raw = comb.raw.last_mut().unwrap(); raw.begin( @@ -1750,7 +1731,7 @@ pub extern "C" fn wgpu_buffer_set_sub_data( hal::command::CommandBufferInheritanceInfo::default(), ); raw.pipeline_barrier( - all_buffer_stages() .. hal::pso::PipelineStage::TRANSFER, + all_buffer_stages()..hal::pso::PipelineStage::TRANSFER, hal::memory::Dependencies::empty(), barrier, ); @@ -1779,13 +1760,18 @@ pub extern "C" fn wgpu_device_destroy(device_id: BufferId) { HUB.devices.unregister(device_id); } -pub type BufferMapReadCallback = extern "C" fn(status: BufferMapAsyncStatus, data: *const u8, userdata: *mut u8); -pub type BufferMapWriteCallback = extern "C" fn(status: BufferMapAsyncStatus, data: *mut u8, userdata: *mut u8); +pub type BufferMapReadCallback = + extern "C" fn(status: BufferMapAsyncStatus, data: *const u8, userdata: *mut u8); +pub type BufferMapWriteCallback = + extern "C" fn(status: BufferMapAsyncStatus, data: *mut u8, userdata: *mut u8); #[no_mangle] pub extern "C" fn wgpu_buffer_map_read_async( buffer_id: BufferId, - start: u32, size: u32, callback: BufferMapReadCallback, userdata: *mut u8, + start: u32, + size: u32, + callback: BufferMapReadCallback, + userdata: *mut u8, ) { let mut buffer_guard = HUB.buffers.write(); let buffer = &mut buffer_guard[buffer_id]; @@ -1793,9 +1779,8 @@ pub extern "C" fn wgpu_buffer_map_read_async( let range = start as u64..(start + size) as u64; buffer.pending_map_operation = Some(BufferMapOperation::Read(range, callback, userdata)); - HUB.devices - .read() - [buffer.device_id.value].destroyed + HUB.devices.read()[buffer.device_id.value] + .destroyed .lock() .map(buffer_id, buffer.life_guard.ref_count.clone()); } @@ -1803,7 +1788,10 @@ pub extern "C" fn wgpu_buffer_map_read_async( #[no_mangle] pub extern "C" fn wgpu_buffer_map_write_async( buffer_id: BufferId, - start: u32, size: u32, callback: BufferMapWriteCallback, userdata: *mut u8, + start: u32, + size: u32, + callback: BufferMapWriteCallback, + userdata: *mut u8, ) { let mut buffer_guard = HUB.buffers.write(); let buffer = &mut buffer_guard[buffer_id]; @@ -1811,24 +1799,31 @@ pub extern "C" fn wgpu_buffer_map_write_async( let range = start as u64..(start + size) as u64; buffer.pending_map_operation = Some(BufferMapOperation::Write(range, callback, userdata)); - HUB.devices - .read() - [buffer.device_id.value].destroyed + HUB.devices.read()[buffer.device_id.value] + .destroyed .lock() .map(buffer_id, buffer.life_guard.ref_count.clone()); } #[no_mangle] -pub extern "C" fn wgpu_buffer_unmap( - buffer_id: BufferId, -) { +pub extern "C" fn wgpu_buffer_unmap(buffer_id: BufferId) { let mut buffer_guard = HUB.buffers.write(); let buffer = &mut buffer_guard[buffer_id]; let device_guard = HUB.devices.read(); let device = &device_guard[buffer.device_id.value]; if !buffer.mapped_write_ranges.is_empty() { - unsafe { device.raw.flush_mapped_memory_ranges( buffer.mapped_write_ranges.iter().map(|r| {(&buffer.memory, r.clone())}) ).unwrap() }; // TODO + unsafe { + device + .raw + .flush_mapped_memory_ranges( + buffer + .mapped_write_ranges + .iter() + .map(|r| (&buffer.memory, r.clone())), + ) + .unwrap() + }; // TODO buffer.mapped_write_ranges.clear(); } diff --git a/wgpu-native/src/hub.rs b/wgpu-native/src/hub.rs index 9e70a49b5..b8063944b 100644 --- a/wgpu-native/src/hub.rs +++ b/wgpu-native/src/hub.rs @@ -1,24 +1,21 @@ use crate::{ - AdapterHandle, BindGroupLayoutHandle, BindGroupHandle, - CommandBufferHandle, DeviceHandle, InstanceHandle, - RenderPassHandle, ComputePassHandle, - PipelineLayoutHandle, RenderPipelineHandle, ComputePipelineHandle, ShaderModuleHandle, - BufferHandle, SamplerHandle, TextureHandle, TextureViewHandle, - SurfaceHandle, + AdapterHandle, BindGroupHandle, BindGroupLayoutHandle, BufferHandle, CommandBufferHandle, + ComputePassHandle, ComputePipelineHandle, DeviceHandle, InstanceHandle, PipelineLayoutHandle, + RenderPassHandle, RenderPipelineHandle, SamplerHandle, ShaderModuleHandle, SurfaceHandle, + TextureHandle, TextureViewHandle, }; use lazy_static::lazy_static; -use parking_lot::RwLock; #[cfg(feature = "local")] use parking_lot::Mutex; +use parking_lot::RwLock; #[cfg(feature = "serde")] -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use vec_map::VecMap; use std::ops; use std::sync::Arc; - pub(crate) type Index = u32; pub(crate) type Epoch = u32; #[derive(Clone, Copy, Debug, Hash, PartialEq)] @@ -55,9 +52,7 @@ pub struct IdentityManager { impl IdentityManager { pub fn alloc(&mut self) -> Id { match self.free.pop() { - Some(index) => { - Id(index, self.epochs[index as usize]) - } + Some(index) => Id(index, self.epochs[index as usize]), None => { let id = Id(self.epochs.len() as Index, 1); self.epochs.push(id.1); @@ -104,7 +99,7 @@ impl Storage { pub fn contains(&self, id: Id) -> bool { match self.map.get(id.0 as usize) { Some(&(_, epoch)) if epoch == id.1 => true, - _ => false + _ => false, } } } @@ -120,9 +115,7 @@ impl Default for Registry { Registry { #[cfg(feature = "local")] identity: Mutex::new(IdentityManager::default()), - data: RwLock::new(Storage { - map: VecMap::new(), - }), + data: RwLock::new(Storage { map: VecMap::new() }), } } } diff --git a/wgpu-native/src/instance.rs b/wgpu-native/src/instance.rs index cbdda906c..1c6336e1d 100644 --- a/wgpu-native/src/instance.rs +++ b/wgpu-native/src/instance.rs @@ -1,17 +1,13 @@ use crate::hub::HUB; -use crate::{ - AdapterHandle, DeviceHandle, SurfaceHandle, - AdapterId, InstanceId, -}; +use crate::{AdapterHandle, AdapterId, DeviceHandle, InstanceId, SurfaceHandle}; #[cfg(feature = "local")] use crate::{DeviceId, SurfaceId}; #[cfg(feature = "remote")] -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use hal::{self, Instance as _Instance, PhysicalDevice as _PhysicalDevice}; - #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] @@ -56,10 +52,7 @@ pub extern "C" fn wgpu_instance_create_surface_from_winit( instance_id: InstanceId, window: &winit::Window, ) -> SurfaceId { - let raw = HUB.instances - .read() - [instance_id] - .create_surface(window); + let raw = HUB.instances.read()[instance_id].create_surface(window); let surface = SurfaceHandle::new(raw); HUB.surfaces.register_local(surface) } @@ -74,11 +67,7 @@ pub fn instance_create_surface_from_xlib( unimplemented!(); #[cfg(all(unix, feature = "gfx-backend-vulkan"))] - SurfaceHandle::new(HUB.instances - .read() - [instance_id] - .create_surface_from_xlib(display, window) - ) + SurfaceHandle::new(HUB.instances.read()[instance_id].create_surface_from_xlib(display, window)) } #[cfg(feature = "local")] @@ -101,11 +90,7 @@ pub fn instance_create_surface_from_macos_layer( unimplemented!(); #[cfg(feature = "gfx-backend-metal")] - SurfaceHandle::new(HUB.instances - .read() - [instance_id] - .create_surface_from_layer(layer as *mut _) - ) + SurfaceHandle::new(HUB.instances.read()[instance_id].create_surface_from_layer(layer as *mut _)) } #[cfg(feature = "local")] @@ -128,16 +113,10 @@ pub fn instance_create_surface_from_windows_hwnd( let raw = unimplemented!(); #[cfg(any(feature = "gfx-backend-dx11", feature = "gfx-backend-dx12"))] - let raw = HUB.instances - .read() - [instance_id] - .create_surface_from_hwnd(hwnd); + let raw = HUB.instances.read()[instance_id].create_surface_from_hwnd(hwnd); #[cfg(all(target_os = "windows", feature = "gfx-backend-vulkan"))] - let raw = HUB.instances - .read() - [instance_id] - .create_surface_from_hwnd(hinstance, hwnd); + let raw = HUB.instances.read()[instance_id].create_surface_from_hwnd(hinstance, hwnd); #[cfg_attr(not(target_os = "windows"), allow(unreachable_code))] SurfaceHandle::new(raw) @@ -154,10 +133,7 @@ pub extern "C" fn wgpu_instance_create_surface_from_windows_hwnd( HUB.surfaces.register_local(surface) } -pub fn instance_get_adapter( - instance_id: InstanceId, - desc: &AdapterDescriptor, -) -> AdapterHandle { +pub fn instance_get_adapter(instance_id: InstanceId, desc: &AdapterDescriptor) -> AdapterHandle { let instance_guard = HUB.instances.read(); let instance = &instance_guard[instance_id]; let (mut low, mut high, mut other) = (None, None, None); @@ -186,10 +162,7 @@ pub extern "C" fn wgpu_instance_get_adapter( HUB.adapters.register_local(adapter) } -pub fn adapter_create_device( - adapter_id: AdapterId, - _desc: &DeviceDescriptor, -) -> DeviceHandle { +pub fn adapter_create_device(adapter_id: AdapterId, _desc: &DeviceDescriptor) -> DeviceHandle { let adapter_guard = HUB.adapters.read(); let adapter = &adapter_guard[adapter_id]; let (raw, queue_group) = adapter.open_with::<_, hal::General>(1, |_qf| true).unwrap(); diff --git a/wgpu-native/src/lib.rs b/wgpu-native/src/lib.rs index 7a1afcf47..8acf154fe 100644 --- a/wgpu-native/src/lib.rs +++ b/wgpu-native/src/lib.rs @@ -34,12 +34,12 @@ mod track; pub use self::binding_model::*; pub use self::command::*; pub use self::device::*; +#[cfg(feature = "remote")] +pub use self::hub::{Id, IdentityManager, Registry, HUB}; pub use self::instance::*; pub use self::pipeline::*; pub use self::resource::*; pub use self::swap_chain::*; -#[cfg(feature = "remote")] -pub use self::hub::{HUB, Id, IdentityManager, Registry}; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -53,7 +53,6 @@ pub struct RefCount(ptr::NonNull); unsafe impl Send for RefCount {} unsafe impl Sync for RefCount {} - impl RefCount { const MAX: usize = 1 << 24; @@ -99,7 +98,6 @@ struct Stored { ref_count: RefCount, } - #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct Color { diff --git a/wgpu-native/src/pipeline.rs b/wgpu-native/src/pipeline.rs index 2e9293867..94048113f 100644 --- a/wgpu-native/src/pipeline.rs +++ b/wgpu-native/src/pipeline.rs @@ -1,8 +1,6 @@ use crate::device::RenderPassContext; use crate::resource; -use crate::{ - ByteArray, PipelineLayoutId, ShaderModuleId, -}; +use crate::{ByteArray, PipelineLayoutId, ShaderModuleId}; use bitflags::bitflags; @@ -147,7 +145,7 @@ pub enum VertexFormat { Ushort2 = 18, Ushort3 = 19, Ushort4 = 20, - Short = 21, + Short = 21, Short2 = 22, Short3 = 23, Short4 = 24, @@ -175,7 +173,7 @@ pub enum VertexFormat { Int2 = 46, Int3 = 47, Int4 = 48, - } +} #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] diff --git a/wgpu-native/src/resource.rs b/wgpu-native/src/resource.rs index 20bce19ee..93eb593c5 100644 --- a/wgpu-native/src/resource.rs +++ b/wgpu-native/src/resource.rs @@ -1,9 +1,8 @@ -use crate::{ - Extent3d, LifeGuard, RefCount, Stored, - DeviceId, TextureId, - BufferMapReadCallback, BufferMapWriteCallback, -}; use crate::swap_chain::{SwapChainLink, SwapImageEpoch}; +use crate::{ + BufferMapReadCallback, BufferMapWriteCallback, DeviceId, Extent3d, LifeGuard, RefCount, Stored, + TextureId, +}; use bitflags::bitflags; use hal; @@ -176,8 +175,9 @@ impl TexturePlacement { pub fn as_swap_chain(&self) -> &SwapChainLink> { match *self { TexturePlacement::SwapChain(ref link) => link, - TexturePlacement::Memory(_) | - TexturePlacement::Void => panic!("Expected swap chain link!"), + TexturePlacement::Memory(_) | TexturePlacement::Void => { + panic!("Expected swap chain link!") + } } } } diff --git a/wgpu-native/src/swap_chain.rs b/wgpu-native/src/swap_chain.rs index f239fa482..918f7f099 100644 --- a/wgpu-native/src/swap_chain.rs +++ b/wgpu-native/src/swap_chain.rs @@ -1,11 +1,8 @@ -use crate::{ - Extent3d, Stored, - DeviceId, SwapChainId, TextureId, TextureViewId, -}; -use crate::{conv, resource}; use crate::device::all_image_stages; use crate::hub::HUB; -use crate::track::{TrackPermit}; +use crate::track::TrackPermit; +use crate::{conv, resource}; +use crate::{DeviceId, Extent3d, Stored, SwapChainId, TextureId, TextureViewId}; use hal; use hal::{Device as _Device, Swapchain as _Swapchain}; @@ -14,7 +11,6 @@ use parking_lot::Mutex; use std::{iter, mem}; - pub type SwapImageEpoch = u16; pub(crate) struct SwapChainLink { @@ -96,20 +92,17 @@ pub struct SwapChainOutput { } #[no_mangle] -pub extern "C" fn wgpu_swap_chain_get_next_texture( - swap_chain_id: SwapChainId, -) -> SwapChainOutput { +pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -> SwapChainOutput { let (image_index, device_id, descriptor) = { let mut surface_guard = HUB.surfaces.write(); - let swap_chain = surface_guard - [swap_chain_id].swap_chain - .as_mut() - .unwrap(); + let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); let sync = hal::FrameSync::Semaphore(&swap_chain.sem_available); - let result = unsafe { - swap_chain.raw.acquire_image(!0, sync) - }; - (result.ok(), swap_chain.device_id.value, swap_chain.desc.clone()) + let result = unsafe { swap_chain.raw.acquire_image(!0, sync) }; + ( + result.ok(), + swap_chain.device_id.value, + swap_chain.desc.clone(), + ) }; #[cfg(not(feature = "local"))] @@ -125,10 +118,7 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture( } let mut surface_guard = HUB.surfaces.write(); - let swap_chain = surface_guard - [swap_chain_id].swap_chain - .as_mut() - .unwrap(); + let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); let image_index = match image_index { Some(index) => index, @@ -141,8 +131,11 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture( let device_guard = HUB.devices.read(); let device = &device_guard[device_id]; - assert_ne!(swap_chain.acquired.len(), swap_chain.acquired.capacity(), - "Unable to acquire any more swap chain images before presenting"); + assert_ne!( + swap_chain.acquired.len(), + swap_chain.acquired.capacity(), + "Unable to acquire any more swap chain images before presenting" + ); swap_chain.acquired.push(image_index); let frame = &mut swap_chain.frames[image_index as usize]; @@ -151,7 +144,10 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture( } mem::swap(&mut frame.sem_available, &mut swap_chain.sem_available); - HUB.textures.read()[frame.texture_id.value].placement.as_swap_chain().bump_epoch(); + HUB.textures.read()[frame.texture_id.value] + .placement + .as_swap_chain() + .bump_epoch(); SwapChainOutput { texture_id: frame.texture_id.value, @@ -160,14 +156,9 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture( } #[no_mangle] -pub extern "C" fn wgpu_swap_chain_present( - swap_chain_id: SwapChainId, -) { +pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) { let mut surface_guard = HUB.surfaces.write(); - let swap_chain = surface_guard - [swap_chain_id].swap_chain - .as_mut() - .unwrap(); + let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); let image_index = swap_chain.acquired.remove(0); let frame = &mut swap_chain.frames[image_index as usize]; @@ -182,7 +173,8 @@ pub extern "C" fn wgpu_swap_chain_present( //TODO: support for swapchain being sampled or read by the shader? trace!("transit {:?} to present", frame.texture_id.value); - let barrier = device.trackers + let barrier = device + .trackers .lock() .textures .transit( @@ -194,8 +186,11 @@ pub extern "C" fn wgpu_swap_chain_present( .unwrap() .into_source() .map(|old| hal::memory::Barrier::Image { - states: conv::map_texture_state(old, hal::format::Aspects::COLOR) .. - (hal::image::Access::COLOR_ATTACHMENT_WRITE, hal::image::Layout::Present), + states: conv::map_texture_state(old, hal::format::Aspects::COLOR) + ..( + hal::image::Access::COLOR_ATTACHMENT_WRITE, + hal::image::Layout::Present, + ), target: &texture.raw, families: None, range: texture.full_range.clone(), @@ -204,7 +199,7 @@ pub extern "C" fn wgpu_swap_chain_present( let err = unsafe { frame.comb.begin(false); frame.comb.pipeline_barrier( - all_image_stages() .. hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT, + all_image_stages()..hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT, hal::memory::Dependencies::empty(), barrier, ); diff --git a/wgpu-native/src/track.rs b/wgpu-native/src/track.rs index ea5b20887..c221d0fb9 100644 --- a/wgpu-native/src/track.rs +++ b/wgpu-native/src/track.rs @@ -1,9 +1,6 @@ -use crate::hub::{NewId, Id, Index, Epoch, Storage}; +use crate::hub::{Epoch, Id, Index, NewId, Storage}; use crate::resource::{BufferUsageFlags, TextureUsageFlags}; -use crate::{ - RefCount, - BufferId, TextureId, TextureViewId, -}; +use crate::{BufferId, RefCount, TextureId, TextureViewId}; use bitflags::bitflags; use hal::backend::FastHashMap; @@ -14,7 +11,6 @@ use std::marker::PhantomData; use std::mem; use std::ops::{BitOr, Range}; - #[derive(Clone, Debug, PartialEq)] #[allow(unused)] pub enum Tracktion { @@ -27,10 +23,8 @@ pub enum Tracktion { impl Tracktion { pub fn into_source(self) -> Option { match self { - Tracktion::Init | - Tracktion::Keep => None, - Tracktion::Extend { old } | - Tracktion::Replace { old } => Some(old), + Tracktion::Init | Tracktion::Keep => None, + Tracktion::Extend { old } | Tracktion::Replace { old } => Some(old), } } } @@ -125,15 +119,9 @@ impl TrackerSet { } pub fn consume_by_extend(&mut self, other: &Self) { - self.buffers - .consume_by_extend(&other.buffers) - .unwrap(); - self.textures - .consume_by_extend(&other.textures) - .unwrap(); - self.views - .consume_by_extend(&other.views) - .unwrap(); + self.buffers.consume_by_extend(&other.buffers).unwrap(); + self.textures.consume_by_extend(&other.textures).unwrap(); + self.views.consume_by_extend(&other.views).unwrap(); } } @@ -224,8 +212,10 @@ impl + PartialEq> Tracker impl 'a + Iterator)> { - other.map.iter().flat_map(move |(&index, new)| { - match self.map.entry(index) { + other + .map + .iter() + .flat_map(move |(&index, new)| match self.map.entry(index) { Entry::Vacant(e) => { e.insert(new.clone()); None @@ -240,11 +230,10 @@ impl + PartialEq> Tracker new.init, Stitch::Last => new.last, }; - Some((I::new(index, new.epoch), old .. state)) + Some((I::new(index, new.epoch), old..state)) } } - } - }) + }) } /// Consume another tacker, adding it's transitions to `self`. @@ -262,7 +251,7 @@ impl + PartialEq> Tracker + PartialEq> Tracker(&'a self) -> impl 'a + Iterator { - self.map.iter().map(|(&index, track)| I::new(index, track.epoch)) + self.map + .iter() + .map(|(&index, track)| I::new(index, track.epoch)) } } @@ -310,11 +301,15 @@ impl + PartialEq> Tracker { ) -> Result<(&'a T, Option), U> { let item = &storage[id]; self.transit(id, item.borrow(), usage, TrackPermit::REPLACE) - .map(|tracktion| (item, match tracktion { - Tracktion::Init | - Tracktion::Keep => None, - Tracktion::Extend { ..} => unreachable!(), - Tracktion::Replace { old } => Some(old), - })) + .map(|tracktion| { + ( + item, + match tracktion { + Tracktion::Init | Tracktion::Keep => None, + Tracktion::Extend { .. } => unreachable!(), + Tracktion::Replace { old } => Some(old), + }, + ) + }) } } diff --git a/wgpu-remote/src/lib.rs b/wgpu-remote/src/lib.rs index 12ef9c0eb..c2c67f349 100644 --- a/wgpu-remote/src/lib.rs +++ b/wgpu-remote/src/lib.rs @@ -1,10 +1,9 @@ use ipc_channel::ipc::IpcSender; use parking_lot::Mutex; -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use wgpu_native as wgn; - #[derive(Serialize, Deserialize)] pub enum InstanceMessage { InstanceGetAdapter(wgn::InstanceId, wgn::AdapterDescriptor, wgn::AdapterId), @@ -41,7 +40,6 @@ impl Client { } } - #[no_mangle] pub extern "C" fn wgpu_instance_get_adapter( client: &Client, @@ -49,7 +47,11 @@ pub extern "C" fn wgpu_instance_get_adapter( desc: &wgn::AdapterDescriptor, ) -> wgn::AdapterId { let id = client.identity.lock().adapters.alloc(); - let msg = GlobalMessage::Instance(InstanceMessage::InstanceGetAdapter(instance_id, desc.clone(), id)); + let msg = GlobalMessage::Instance(InstanceMessage::InstanceGetAdapter( + instance_id, + desc.clone(), + id, + )); client.channel.send(msg).unwrap(); id } @@ -61,7 +63,11 @@ pub extern "C" fn wgpu_adapter_create_device( desc: &wgn::DeviceDescriptor, ) -> wgn::DeviceId { let id = client.identity.lock().devices.alloc(); - let msg = GlobalMessage::Instance(InstanceMessage::AdapterCreateDevice(adapter_id, desc.clone(), id)); + let msg = GlobalMessage::Instance(InstanceMessage::AdapterCreateDevice( + adapter_id, + desc.clone(), + id, + )); client.channel.send(msg).unwrap(); id } diff --git a/wgpu-rs/src/lib.rs b/wgpu-rs/src/lib.rs index 9ffe4f341..cd456656a 100644 --- a/wgpu-rs/src/lib.rs +++ b/wgpu-rs/src/lib.rs @@ -10,22 +10,19 @@ use std::slice; pub use wgn::winit; pub use wgn::{ - AdapterDescriptor, BindGroupLayoutBinding, BindingType, - BlendDescriptor, BlendOperation, BlendFactor, BufferMapAsyncStatus, ColorWriteFlags, - RasterizationStateDescriptor, CullMode, FrontFace, - BufferDescriptor, BufferUsageFlags, - IndexFormat, InputStepMode, ShaderAttributeIndex, VertexAttributeDescriptor, VertexFormat, - Color, CommandEncoderDescriptor, - ColorStateDescriptor, DepthStencilStateDescriptor, StencilStateFaceDescriptor, StencilOperation, - DeviceDescriptor, Extensions, Extent3d, LoadOp, Origin3d, PowerPreference, PrimitiveTopology, - RenderPassColorAttachmentDescriptor, RenderPassDepthStencilAttachmentDescriptor, - ShaderModuleDescriptor, ShaderStageFlags, StoreOp, SwapChainDescriptor, - SamplerDescriptor, AddressMode, FilterMode, BorderColor, CompareFunction, - TextureDescriptor, TextureDimension, TextureFormat, TextureUsageFlags, - TextureViewDescriptor, TextureViewDimension, TextureAspectFlags, + AdapterDescriptor, AddressMode, BindGroupLayoutBinding, BindingType, BlendDescriptor, + BlendFactor, BlendOperation, BorderColor, BufferDescriptor, BufferMapAsyncStatus, + BufferUsageFlags, Color, ColorStateDescriptor, ColorWriteFlags, CommandEncoderDescriptor, + CompareFunction, CullMode, DepthStencilStateDescriptor, DeviceDescriptor, Extensions, Extent3d, + FilterMode, FrontFace, IndexFormat, InputStepMode, LoadOp, Origin3d, PowerPreference, + PrimitiveTopology, RasterizationStateDescriptor, RenderPassColorAttachmentDescriptor, + RenderPassDepthStencilAttachmentDescriptor, SamplerDescriptor, ShaderAttributeIndex, + ShaderModuleDescriptor, ShaderStageFlags, StencilOperation, StencilStateFaceDescriptor, + StoreOp, SwapChainDescriptor, TextureAspectFlags, TextureDescriptor, TextureDimension, + TextureFormat, TextureUsageFlags, TextureViewDescriptor, TextureViewDimension, + VertexAttributeDescriptor, VertexFormat, }; - //TODO: avoid heap allocating vectors during resource creation. #[derive(Default)] struct Temp { @@ -34,7 +31,6 @@ struct Temp { command_buffers: Vec, } - pub struct Instance { id: wgn::InstanceId, } @@ -127,7 +123,6 @@ pub struct Queue<'a> { temp: &'a mut Temp, } - pub enum BindingResource<'a> { Buffer { buffer: &'a Buffer, @@ -239,7 +234,9 @@ pub struct CreateBufferMapped<'a, T> { } impl<'a, T> CreateBufferMapped<'a, T> - where T: Copy { +where + T: Copy, +{ pub fn fill_from_slice(self, slice: &[T]) -> Buffer { self.data.copy_from_slice(slice); self.finish() @@ -247,9 +244,7 @@ impl<'a, T> CreateBufferMapped<'a, T> pub fn finish(self) -> Buffer { wgn::wgpu_buffer_unmap(self.id); - Buffer { - id: self.id, - } + Buffer { id: self.id } } } @@ -414,7 +409,8 @@ impl Device { primitive_topology: desc.primitive_topology, color_states: temp_color_states.as_ptr(), color_states_length: temp_color_states.len(), - depth_stencil_state: desc.depth_stencil_state + depth_stencil_state: desc + .depth_stencil_state .as_ref() .map_or(ptr::null(), |p| p as *const _), vertex_buffer_state: wgn::VertexBufferStateDescriptor { @@ -451,22 +447,28 @@ impl Device { } } - pub fn create_buffer_mapped<'a, T>(&self, count: usize, usage: BufferUsageFlags) -> CreateBufferMapped<'a, T> - where T: 'static + Copy { + pub fn create_buffer_mapped<'a, T>( + &self, + count: usize, + usage: BufferUsageFlags, + ) -> CreateBufferMapped<'a, T> + where + T: 'static + Copy, + { let type_size = std::mem::size_of::() as u32; assert_ne!(type_size, 0); - let desc = BufferDescriptor{ + let desc = BufferDescriptor { size: type_size * count as u32, usage, }; - let mut ptr : *mut u8 = std::ptr::null_mut(); + let mut ptr: *mut u8 = std::ptr::null_mut(); let id = wgn::wgpu_device_create_buffer_mapped(self.id, &desc, &mut ptr as *mut *mut u8); let data = unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, count) }; - CreateBufferMapped{id, data} + CreateBufferMapped { id, data } } pub fn create_texture(&self, desc: &TextureDescriptor) -> Texture { @@ -502,15 +504,19 @@ pub enum BufferMapAsyncResult { Error, } -struct BufferMapReadAsyncUserData - where F: FnOnce(BufferMapAsyncResult<&[T]>) { +struct BufferMapReadAsyncUserData +where + F: FnOnce(BufferMapAsyncResult<&[T]>), +{ size: u32, callback: F, phantom: std::marker::PhantomData, } struct BufferMapWriteAsyncUserData - where F: FnOnce(BufferMapAsyncResult<&mut [T]>) { +where + F: FnOnce(BufferMapAsyncResult<&mut [T]>), +{ size: u32, callback: F, phantom: std::marker::PhantomData, @@ -522,15 +528,29 @@ impl Buffer { } pub fn map_read_async(&self, start: u32, size: u32, callback: F) - where T: 'static + Copy, F: FnOnce(BufferMapAsyncResult<&[T]>) { + where + T: 'static + Copy, + F: FnOnce(BufferMapAsyncResult<&[T]>), + { let type_size = std::mem::size_of::() as u32; assert_ne!(type_size, 0); assert_eq!(size % type_size, 0); - extern "C" fn buffer_map_read_callback_wrapper(status: wgn::BufferMapAsyncStatus, data: *const u8, userdata: *mut u8) - where F: FnOnce(BufferMapAsyncResult<&[T]>) { - let userdata = unsafe { Box::from_raw(userdata as *mut BufferMapReadAsyncUserData) }; - let data = unsafe { slice::from_raw_parts(data as *const T, userdata.size as usize / std::mem::size_of::()) }; + extern "C" fn buffer_map_read_callback_wrapper( + status: wgn::BufferMapAsyncStatus, + data: *const u8, + userdata: *mut u8, + ) where + F: FnOnce(BufferMapAsyncResult<&[T]>), + { + let userdata = + unsafe { Box::from_raw(userdata as *mut BufferMapReadAsyncUserData) }; + let data = unsafe { + slice::from_raw_parts( + data as *const T, + userdata.size as usize / std::mem::size_of::(), + ) + }; if let wgn::BufferMapAsyncStatus::Success = status { (userdata.callback)(BufferMapAsyncResult::Success::<&[T]>(data)); } else { @@ -538,20 +558,44 @@ impl Buffer { } } - let userdata = Box::new(BufferMapReadAsyncUserData{size, callback, phantom: std::marker::PhantomData}); - wgn::wgpu_buffer_map_read_async(self.id, start, size, buffer_map_read_callback_wrapper::, Box::into_raw(userdata) as *mut u8); + let userdata = Box::new(BufferMapReadAsyncUserData { + size, + callback, + phantom: std::marker::PhantomData, + }); + wgn::wgpu_buffer_map_read_async( + self.id, + start, + size, + buffer_map_read_callback_wrapper::, + Box::into_raw(userdata) as *mut u8, + ); } pub fn map_write_async(&self, start: u32, size: u32, callback: F) - where T: 'static + Copy, F: FnOnce(BufferMapAsyncResult<&mut [T]>) { + where + T: 'static + Copy, + F: FnOnce(BufferMapAsyncResult<&mut [T]>), + { let type_size = std::mem::size_of::() as u32; assert_ne!(type_size, 0); assert_eq!(size % type_size, 0); - extern "C" fn buffer_map_write_callback_wrapper(status: wgn::BufferMapAsyncStatus, data: *mut u8, userdata: *mut u8) - where F: FnOnce(BufferMapAsyncResult<&mut [T]>) { - let userdata = unsafe { Box::from_raw(userdata as *mut BufferMapWriteAsyncUserData) }; - let data = unsafe { slice::from_raw_parts_mut(data as *mut T, userdata.size as usize / std::mem::size_of::()) }; + extern "C" fn buffer_map_write_callback_wrapper( + status: wgn::BufferMapAsyncStatus, + data: *mut u8, + userdata: *mut u8, + ) where + F: FnOnce(BufferMapAsyncResult<&mut [T]>), + { + let userdata = + unsafe { Box::from_raw(userdata as *mut BufferMapWriteAsyncUserData) }; + let data = unsafe { + slice::from_raw_parts_mut( + data as *mut T, + userdata.size as usize / std::mem::size_of::(), + ) + }; if let wgn::BufferMapAsyncStatus::Success = status { (userdata.callback)(BufferMapAsyncResult::Success::<&mut [T]>(data)); } else { @@ -559,8 +603,18 @@ impl Buffer { } } - let userdata = Box::new(BufferMapWriteAsyncUserData{size, callback, phantom: std::marker::PhantomData}); - wgn::wgpu_buffer_map_write_async(self.id, start, size, buffer_map_write_callback_wrapper::, Box::into_raw(userdata) as *mut u8); + let userdata = Box::new(BufferMapWriteAsyncUserData { + size, + callback, + phantom: std::marker::PhantomData, + }); + wgn::wgpu_buffer_map_write_async( + self.id, + start, + size, + buffer_map_write_callback_wrapper::, + Box::into_raw(userdata) as *mut u8, + ); } pub fn unmap(&self) { @@ -800,9 +854,9 @@ impl<'a> Drop for ComputePass<'a> { impl<'a> Queue<'a> { pub fn submit(&mut self, command_buffers: &[CommandBuffer]) { self.temp.command_buffers.clear(); - self.temp.command_buffers.extend( - command_buffers.iter().map(|cb| cb.id) - ); + self.temp + .command_buffers + .extend(command_buffers.iter().map(|cb| cb.id)); wgn::wgpu_queue_submit( self.id,