From 30432cbade3d9b25c4df62656a7494db3f4ea82a Mon Sep 17 00:00:00 2001 From: shan Date: Wed, 5 Oct 2022 10:49:58 -0700 Subject: Readjusted namespaces, removed Geometry example as it's no longer relevant. --- wgpu/src/buffers.rs | 124 +++++++++++++++++++++- wgpu/src/buffers/buffer.rs | 124 ---------------------- wgpu/src/buffers/dynamic.rs | 201 ++++++++++++++++++++++++++++++++++++ wgpu/src/buffers/dynamic_buffers.rs | 201 ------------------------------------ wgpu/src/triangle.rs | 22 ++-- wgpu/src/triangle/gradient.rs | 2 +- wgpu/src/triangle/solid.rs | 2 +- 7 files changed, 337 insertions(+), 339 deletions(-) delete mode 100644 wgpu/src/buffers/buffer.rs create mode 100644 wgpu/src/buffers/dynamic.rs delete mode 100644 wgpu/src/buffers/dynamic_buffers.rs (limited to 'wgpu/src') diff --git a/wgpu/src/buffers.rs b/wgpu/src/buffers.rs index f94d175d..fd6ca244 100644 --- a/wgpu/src/buffers.rs +++ b/wgpu/src/buffers.rs @@ -1,3 +1,123 @@ //! Utilities for buffer operations. -pub mod buffer; -pub mod dynamic_buffers; \ No newline at end of file +pub mod dynamic; + +use bytemuck::{Pod, Zeroable}; +use std::marker::PhantomData; +use std::mem; + +//128 triangles/indices +const DEFAULT_STATIC_BUFFER_COUNT: wgpu::BufferAddress = 128; + +/// A generic buffer struct useful for items which have no alignment requirements +/// (e.g. Vertex, Index buffers) and are set once and never changed until destroyed. +#[derive(Debug)] +pub(crate) struct StaticBuffer { + //stored sequentially per mesh iteration; refers to the offset index in the GPU buffer + offsets: Vec, + label: &'static str, + usages: wgpu::BufferUsages, + gpu: wgpu::Buffer, + //the static size of the buffer + size: wgpu::BufferAddress, + _data: PhantomData, +} + +impl StaticBuffer { + /// Initialize a new static buffer. + pub fn new( + device: &wgpu::Device, + label: &'static str, + usages: wgpu::BufferUsages, + ) -> Self { + let size = (mem::size_of::() as u64) * DEFAULT_STATIC_BUFFER_COUNT; + + Self { + offsets: Vec::new(), + label, + usages, + gpu: Self::gpu_buffer(device, label, size, usages), + size, + _data: Default::default(), + } + } + + fn gpu_buffer( + device: &wgpu::Device, + label: &'static str, + size: wgpu::BufferAddress, + usage: wgpu::BufferUsages, + ) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size, + usage, + mapped_at_creation: false, + }) + } + + /// Returns whether or not the buffer needs to be recreated. This can happen whenever mesh data + /// changes & a redraw is requested. + pub fn recreate_if_needed( + &mut self, + device: &wgpu::Device, + new_count: usize, + ) -> bool { + let size = + wgpu::BufferAddress::from((mem::size_of::() * new_count) as u64); + + if self.size <= size { + self.offsets.clear(); + self.size = size; + self.gpu = Self::gpu_buffer(device, self.label, size, self.usages); + true + } else { + false + } + } + + /// Writes the current vertex data to the gpu buffer if it is currently writable with a memcpy & + /// stores its offset. + /// + /// This will return either the offset of the written bytes, or `None` if the GPU buffer is not + /// currently writable. + pub fn write( + &mut self, + device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, + encoder: &mut wgpu::CommandEncoder, + offset: u64, + content: &[T], + ) -> u64 { + let bytes = bytemuck::cast_slice(content); + let bytes_size = bytes.len() as u64; + + if let Some(buffer_size) = wgpu::BufferSize::new(bytes_size as u64) { + let mut buffer = staging_belt.write_buffer( + encoder, + &self.gpu, + offset, + buffer_size, + device, + ); + + buffer.copy_from_slice(bytes); + + self.offsets.push(offset); + } + + bytes_size + } + + fn offset_at(&self, index: usize) -> &wgpu::BufferAddress { + self.offsets + .get(index) + .expect("Offset at index does not exist.") + } + + /// Returns the slice calculated from the offset stored at the given index. + /// e.g. to calculate the slice for the 2nd mesh in the layer, this would be the offset at index + /// 1 that we stored earlier when writing. + pub fn slice_from_index(&self, index: usize) -> wgpu::BufferSlice<'_> { + self.gpu.slice(self.offset_at(index)..) + } +} \ No newline at end of file diff --git a/wgpu/src/buffers/buffer.rs b/wgpu/src/buffers/buffer.rs deleted file mode 100644 index a44120d3..00000000 --- a/wgpu/src/buffers/buffer.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! Utilities for static buffer operations. -use bytemuck::{Pod, Zeroable}; -use std::marker::PhantomData; -use std::mem; - -//128 triangles/indices -const DEFAULT_STATIC_BUFFER_COUNT: wgpu::BufferAddress = 128; - -/// A generic buffer struct useful for items which have no alignment requirements -/// (e.g. Vertex, Index buffers) and are set once and never changed until destroyed. -#[derive(Debug)] -pub(crate) struct StaticBuffer { - //stored sequentially per mesh iteration; refers to the offset index in the GPU buffer - offsets: Vec, - label: &'static str, - usages: wgpu::BufferUsages, - gpu: wgpu::Buffer, - //the static size of the buffer - size: wgpu::BufferAddress, - _data: PhantomData, -} - -impl StaticBuffer { - /// Initialize a new static buffer. - pub fn new( - device: &wgpu::Device, - label: &'static str, - usages: wgpu::BufferUsages, - ) -> Self { - let size = (mem::size_of::() as u64) * DEFAULT_STATIC_BUFFER_COUNT; - - Self { - offsets: Vec::new(), - label, - usages, - gpu: Self::gpu_buffer(device, label, size, usages), - size, - _data: Default::default(), - } - } - - fn gpu_buffer( - device: &wgpu::Device, - label: &'static str, - size: wgpu::BufferAddress, - usage: wgpu::BufferUsages, - ) -> wgpu::Buffer { - device.create_buffer(&wgpu::BufferDescriptor { - label: Some(label), - size, - usage, - mapped_at_creation: false, - }) - } - - /// Returns whether or not the buffer needs to be recreated. This can happen whenever mesh data - /// changes & a redraw is requested. - pub fn recreate_if_needed( - &mut self, - device: &wgpu::Device, - new_count: usize, - ) -> bool { - let size = - wgpu::BufferAddress::from((mem::size_of::() * new_count) as u64); - - if self.size <= size { - self.offsets.clear(); - self.size = size; - self.gpu = Self::gpu_buffer(device, self.label, size, self.usages); - true - } else { - false - } - } - - /// Writes the current vertex data to the gpu buffer if it is currently writable with a memcpy & - /// stores its offset. - /// - /// This will return either the offset of the written bytes, or `None` if the GPU buffer is not - /// currently writable. - pub fn write( - &mut self, - device: &wgpu::Device, - staging_belt: &mut wgpu::util::StagingBelt, - encoder: &mut wgpu::CommandEncoder, - offset: u64, - content: &[T], - ) -> u64 { - let bytes = bytemuck::cast_slice(content); - let bytes_size = bytes.len() as u64; - - if let Some(buffer_size) = wgpu::BufferSize::new(bytes_size as u64) { - //offset has to be divisible by 8 for alignment reasons - let actual_offset = if offset % 8 != 0 { offset + 4 } else { offset }; - - let mut buffer = staging_belt.write_buffer( - encoder, - &self.gpu, - actual_offset, - buffer_size, - device, - ); - - buffer.copy_from_slice(bytes); - - self.offsets.push(actual_offset); - } - - bytes_size - } - - fn offset_at(&self, index: usize) -> &wgpu::BufferAddress { - self.offsets - .get(index) - .expect("Offset at index does not exist.") - } - - /// Returns the slice calculated from the offset stored at the given index. - /// e.g. to calculate the slice for the 2nd mesh in the layer, this would be the offset at index - /// 1 that we stored earlier when writing. - pub fn slice_from_index(&self, index: usize) -> wgpu::BufferSlice<'_> { - self.gpu.slice(self.offset_at(index)..) - } -} diff --git a/wgpu/src/buffers/dynamic.rs b/wgpu/src/buffers/dynamic.rs new file mode 100644 index 00000000..75cc202c --- /dev/null +++ b/wgpu/src/buffers/dynamic.rs @@ -0,0 +1,201 @@ +//! Utilities for uniform buffer operations. +use encase::private::WriteInto; +use encase::ShaderType; +use std::marker::PhantomData; + +// Currently supported dynamic buffers. +enum DynamicBufferType { + Uniform(encase::DynamicUniformBuffer>), + Storage(encase::DynamicStorageBuffer>), +} + +impl DynamicBufferType { + /// Writes the current value to its CPU buffer with proper alignment. + pub(super) fn write( + &mut self, + value: &T, + ) -> wgpu::DynamicOffset { + match self { + DynamicBufferType::Uniform(buf) => buf + .write(value) + .expect("Error when writing to dynamic uniform buffer.") + as u32, + DynamicBufferType::Storage(buf) => buf + .write(value) + .expect("Error when writing to dynamic storage buffer.") + as u32, + } + } + + /// Returns bytearray of aligned CPU buffer. + pub(super) fn get_ref(&self) -> &Vec { + match self { + DynamicBufferType::Uniform(buf) => buf.as_ref(), + DynamicBufferType::Storage(buf) => buf.as_ref(), + } + } + + /// Resets the CPU buffer. + pub(super) fn clear(&mut self) { + match self { + DynamicBufferType::Uniform(buf) => { + buf.as_mut().clear(); + buf.set_offset(0); + } + DynamicBufferType::Storage(buf) => { + buf.as_mut().clear(); + buf.set_offset(0); + } + } + } +} + +pub(crate) struct DynamicBuffer { + offsets: Vec, + cpu: DynamicBufferType, + gpu: wgpu::Buffer, + label: &'static str, + size: u64, + _data: PhantomData, +} + +impl DynamicBuffer { + /// Creates a new dynamic uniform buffer. + pub fn uniform(device: &wgpu::Device, label: &'static str) -> Self { + DynamicBuffer::new( + device, + DynamicBufferType::Uniform(encase::DynamicUniformBuffer::new( + Vec::new(), + )), + label, + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + ) + } + + /// Creates a new dynamic storage buffer. + pub fn storage(device: &wgpu::Device, label: &'static str) -> Self { + DynamicBuffer::new( + device, + DynamicBufferType::Storage(encase::DynamicStorageBuffer::new( + Vec::new(), + )), + label, + wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + ) + } + + fn new( + device: &wgpu::Device, + dynamic_buffer_type: DynamicBufferType, + label: &'static str, + usage: wgpu::BufferUsages, + ) -> Self { + let initial_size = u64::from(T::min_size()); + + Self { + offsets: Vec::new(), + cpu: dynamic_buffer_type, + gpu: DynamicBuffer::::create_gpu_buffer( + device, + label, + usage, + initial_size, + ), + label, + size: initial_size, + _data: Default::default(), + } + } + + fn create_gpu_buffer( + device: &wgpu::Device, + label: &'static str, + usage: wgpu::BufferUsages, + size: u64, + ) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size, + usage, + mapped_at_creation: false, + }) + } + + /// Write a new value to the CPU buffer with proper alignment. Stores the returned offset value + /// in the buffer for future use. + pub fn push(&mut self, value: &T) { + //this write operation on the buffer will adjust for uniform alignment requirements + let offset = self.cpu.write(value); + self.offsets.push(offset as u32); + } + + /// Resize buffer contents if necessary. This will re-create the GPU buffer if current size is + /// less than the newly computed size from the CPU buffer. + pub fn resize(&mut self, device: &wgpu::Device) -> bool { + let new_size = self.cpu.get_ref().len() as u64; + + if self.size < new_size { + let usages = match self.cpu { + DynamicBufferType::Uniform(_) => { + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST + } + DynamicBufferType::Storage(_) => { + wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST + } + }; + + //Re-create the GPU buffer since it needs to be resized. + self.gpu = DynamicBuffer::::create_gpu_buffer( + device, self.label, usages, new_size, + ); + self.size = new_size; + true + } else { + false + } + } + + /// Write the contents of this dynamic buffer to the GPU via staging belt command. + pub fn write( + &mut self, + device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, + encoder: &mut wgpu::CommandEncoder, + ) { + let size = self.cpu.get_ref().len(); + + if let Some(buffer_size) = wgpu::BufferSize::new(size as u64) { + let mut buffer = staging_belt.write_buffer( + encoder, + &self.gpu, + 0, + buffer_size, + device, + ); + + buffer.copy_from_slice(self.cpu.get_ref()); + } + } + + // Gets the aligned offset at the given index from the CPU buffer. + pub fn offset_at_index(&self, index: usize) -> wgpu::DynamicOffset { + let offset = self + .offsets + .get(index) + .expect("Index not found in offsets.") + .clone(); + + offset + } + + /// Returns a reference to the GPU buffer. + pub fn raw(&self) -> &wgpu::Buffer { + &self.gpu + } + + /// Reset the buffer. + pub fn clear(&mut self) { + self.offsets.clear(); + self.cpu.clear(); + } +} diff --git a/wgpu/src/buffers/dynamic_buffers.rs b/wgpu/src/buffers/dynamic_buffers.rs deleted file mode 100644 index 75cc202c..00000000 --- a/wgpu/src/buffers/dynamic_buffers.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! Utilities for uniform buffer operations. -use encase::private::WriteInto; -use encase::ShaderType; -use std::marker::PhantomData; - -// Currently supported dynamic buffers. -enum DynamicBufferType { - Uniform(encase::DynamicUniformBuffer>), - Storage(encase::DynamicStorageBuffer>), -} - -impl DynamicBufferType { - /// Writes the current value to its CPU buffer with proper alignment. - pub(super) fn write( - &mut self, - value: &T, - ) -> wgpu::DynamicOffset { - match self { - DynamicBufferType::Uniform(buf) => buf - .write(value) - .expect("Error when writing to dynamic uniform buffer.") - as u32, - DynamicBufferType::Storage(buf) => buf - .write(value) - .expect("Error when writing to dynamic storage buffer.") - as u32, - } - } - - /// Returns bytearray of aligned CPU buffer. - pub(super) fn get_ref(&self) -> &Vec { - match self { - DynamicBufferType::Uniform(buf) => buf.as_ref(), - DynamicBufferType::Storage(buf) => buf.as_ref(), - } - } - - /// Resets the CPU buffer. - pub(super) fn clear(&mut self) { - match self { - DynamicBufferType::Uniform(buf) => { - buf.as_mut().clear(); - buf.set_offset(0); - } - DynamicBufferType::Storage(buf) => { - buf.as_mut().clear(); - buf.set_offset(0); - } - } - } -} - -pub(crate) struct DynamicBuffer { - offsets: Vec, - cpu: DynamicBufferType, - gpu: wgpu::Buffer, - label: &'static str, - size: u64, - _data: PhantomData, -} - -impl DynamicBuffer { - /// Creates a new dynamic uniform buffer. - pub fn uniform(device: &wgpu::Device, label: &'static str) -> Self { - DynamicBuffer::new( - device, - DynamicBufferType::Uniform(encase::DynamicUniformBuffer::new( - Vec::new(), - )), - label, - wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - ) - } - - /// Creates a new dynamic storage buffer. - pub fn storage(device: &wgpu::Device, label: &'static str) -> Self { - DynamicBuffer::new( - device, - DynamicBufferType::Storage(encase::DynamicStorageBuffer::new( - Vec::new(), - )), - label, - wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - ) - } - - fn new( - device: &wgpu::Device, - dynamic_buffer_type: DynamicBufferType, - label: &'static str, - usage: wgpu::BufferUsages, - ) -> Self { - let initial_size = u64::from(T::min_size()); - - Self { - offsets: Vec::new(), - cpu: dynamic_buffer_type, - gpu: DynamicBuffer::::create_gpu_buffer( - device, - label, - usage, - initial_size, - ), - label, - size: initial_size, - _data: Default::default(), - } - } - - fn create_gpu_buffer( - device: &wgpu::Device, - label: &'static str, - usage: wgpu::BufferUsages, - size: u64, - ) -> wgpu::Buffer { - device.create_buffer(&wgpu::BufferDescriptor { - label: Some(label), - size, - usage, - mapped_at_creation: false, - }) - } - - /// Write a new value to the CPU buffer with proper alignment. Stores the returned offset value - /// in the buffer for future use. - pub fn push(&mut self, value: &T) { - //this write operation on the buffer will adjust for uniform alignment requirements - let offset = self.cpu.write(value); - self.offsets.push(offset as u32); - } - - /// Resize buffer contents if necessary. This will re-create the GPU buffer if current size is - /// less than the newly computed size from the CPU buffer. - pub fn resize(&mut self, device: &wgpu::Device) -> bool { - let new_size = self.cpu.get_ref().len() as u64; - - if self.size < new_size { - let usages = match self.cpu { - DynamicBufferType::Uniform(_) => { - wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST - } - DynamicBufferType::Storage(_) => { - wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST - } - }; - - //Re-create the GPU buffer since it needs to be resized. - self.gpu = DynamicBuffer::::create_gpu_buffer( - device, self.label, usages, new_size, - ); - self.size = new_size; - true - } else { - false - } - } - - /// Write the contents of this dynamic buffer to the GPU via staging belt command. - pub fn write( - &mut self, - device: &wgpu::Device, - staging_belt: &mut wgpu::util::StagingBelt, - encoder: &mut wgpu::CommandEncoder, - ) { - let size = self.cpu.get_ref().len(); - - if let Some(buffer_size) = wgpu::BufferSize::new(size as u64) { - let mut buffer = staging_belt.write_buffer( - encoder, - &self.gpu, - 0, - buffer_size, - device, - ); - - buffer.copy_from_slice(self.cpu.get_ref()); - } - } - - // Gets the aligned offset at the given index from the CPU buffer. - pub fn offset_at_index(&self, index: usize) -> wgpu::DynamicOffset { - let offset = self - .offsets - .get(index) - .expect("Index not found in offsets.") - .clone(); - - offset - } - - /// Returns a reference to the GPU buffer. - pub fn raw(&self) -> &wgpu::Buffer { - &self.gpu - } - - /// Reset the buffer. - pub fn clear(&mut self) { - self.offsets.clear(); - self.cpu.clear(); - } -} diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index df5e3132..c22f118c 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -4,13 +4,13 @@ use core::fmt; use std::fmt::Formatter; use iced_graphics::layer::{attribute_count_of, Mesh}; -use iced_graphics::shader::Shader; -use iced_graphics::Size; +use iced_graphics::{layer, Size}; -use crate::buffers::buffer::StaticBuffer; +use crate::buffers::StaticBuffer; use crate::triangle::gradient::GradientPipeline; use crate::triangle::solid::SolidPipeline; pub use iced_graphics::triangle::{Mesh2D, Vertex2D}; +use layer::mesh; mod gradient; mod msaa; @@ -107,7 +107,9 @@ impl Pipeline { //We are not currently using the return value of these functions as we have no system in //place to calculate mesh diff, or to know whether or not that would be more performant for //the majority of use cases. Therefore we will write GPU data every frame (for now). - let _ = self.vertex_buffer.recreate_if_needed(device, total_vertices); + let _ = self + .vertex_buffer + .recreate_if_needed(device, total_vertices); let _ = self.index_buffer.recreate_if_needed(device, total_indices); //prepare dynamic buffers & data store for writing @@ -144,11 +146,11 @@ impl Pipeline { self.index_strides.push(mesh.buffers.indices.len() as u32); //push uniform data to CPU buffers - match mesh.shader { - Shader::Solid(color) => { + match mesh.style { + mesh::Style::Solid(color) => { self.pipelines.solid.push(transform, color); } - Shader::Gradient(gradient) => { + mesh::Style::Gradient(gradient) => { self.pipelines.gradient.push(transform, gradient); } } @@ -204,15 +206,15 @@ impl Pipeline { clip_bounds.height, ); - match mesh.shader { - Shader::Solid(_) => { + match mesh.style { + mesh::Style::Solid(_) => { self.pipelines.solid.configure_render_pass( &mut render_pass, num_solids, ); num_solids += 1; } - Shader::Gradient(_) => { + mesh::Style::Gradient(_) => { self.pipelines.gradient.configure_render_pass( &mut render_pass, num_gradients, diff --git a/wgpu/src/triangle/gradient.rs b/wgpu/src/triangle/gradient.rs index 15b6b7e0..e8c6d7db 100644 --- a/wgpu/src/triangle/gradient.rs +++ b/wgpu/src/triangle/gradient.rs @@ -1,4 +1,4 @@ -use crate::buffers::dynamic_buffers::DynamicBuffer; +use crate::buffers::dynamic::DynamicBuffer; use crate::settings; use crate::triangle::{ default_fragment_target, default_multisample_state, diff --git a/wgpu/src/triangle/solid.rs b/wgpu/src/triangle/solid.rs index e7e9098a..d2b4d13b 100644 --- a/wgpu/src/triangle/solid.rs +++ b/wgpu/src/triangle/solid.rs @@ -1,4 +1,4 @@ -use crate::buffers::dynamic_buffers::DynamicBuffer; +use crate::buffers::dynamic::DynamicBuffer; use crate::triangle::{ default_fragment_target, default_multisample_state, default_triangle_primitive_state, vertex_buffer_layout, -- cgit