diff options
author | 2022-12-13 09:31:57 +0100 | |
---|---|---|
committer | 2022-12-13 09:31:57 +0100 | |
commit | 2e6d90f141217bad83eacd392562c13d7485881f (patch) | |
tree | baa2c507076073aed4fd24abc9c7a7949d85c039 /wgpu | |
parent | ba95042fff378213f5029b2b164d79e768482a47 (diff) | |
parent | 02182eea45537c9eb5b2bddfdff822bb8a3d143d (diff) | |
download | iced-2e6d90f141217bad83eacd392562c13d7485881f.tar.gz iced-2e6d90f141217bad83eacd392562c13d7485881f.tar.bz2 iced-2e6d90f141217bad83eacd392562c13d7485881f.zip |
Merge branch 'master' into feat/slider-orientation
Diffstat (limited to '')
-rw-r--r-- | graphics/src/image/raster.rs (renamed from wgpu/src/image/raster.rs) | 86 | ||||
-rw-r--r-- | graphics/src/image/vector.rs (renamed from wgpu/src/image/vector.rs) | 95 | ||||
-rw-r--r-- | wgpu/Cargo.toml | 54 | ||||
-rw-r--r-- | wgpu/src/backend.rs | 29 | ||||
-rw-r--r-- | wgpu/src/buffer.rs | 3 | ||||
-rw-r--r-- | wgpu/src/buffer/dynamic.rs | 219 | ||||
-rw-r--r-- | wgpu/src/buffer/static.rs | 117 | ||||
-rw-r--r-- | wgpu/src/image.rs | 75 | ||||
-rw-r--r-- | wgpu/src/image/atlas.rs | 205 | ||||
-rw-r--r-- | wgpu/src/image/atlas/allocation.rs | 6 | ||||
-rw-r--r-- | wgpu/src/image/atlas/allocator.rs | 4 | ||||
-rw-r--r-- | wgpu/src/image/atlas/entry.rs | 10 | ||||
-rw-r--r-- | wgpu/src/lib.rs | 7 | ||||
-rw-r--r-- | wgpu/src/quad.rs | 2 | ||||
-rw-r--r-- | wgpu/src/shader/gradient.wgsl | 88 | ||||
-rw-r--r-- | wgpu/src/shader/quad.wgsl | 47 | ||||
-rw-r--r-- | wgpu/src/shader/solid.wgsl (renamed from wgpu/src/shader/triangle.wgsl) | 0 | ||||
-rw-r--r-- | wgpu/src/triangle.rs | 954 |
18 files changed, 1402 insertions, 599 deletions
diff --git a/wgpu/src/image/raster.rs b/graphics/src/image/raster.rs index 2b4d4af3..da46c30f 100644 --- a/wgpu/src/image/raster.rs +++ b/graphics/src/image/raster.rs @@ -1,43 +1,53 @@ -use crate::image::atlas::{self, Atlas}; +//! Raster image loading and caching. +use crate::image::Storage; +use crate::Size; + use iced_native::image; -use std::collections::{HashMap, HashSet}; use bitflags::bitflags; +use std::collections::{HashMap, HashSet}; +/// Entry in cache corresponding to an image handle #[derive(Debug)] -pub enum Memory { - Host(::image_rs::ImageBuffer<::image_rs::Bgra<u8>, Vec<u8>>), - Device(atlas::Entry), +pub enum Memory<T: Storage> { + /// Image data on host + Host(::image_rs::ImageBuffer<::image_rs::Rgba<u8>, Vec<u8>>), + /// Storage entry + Device(T::Entry), + /// Image not found NotFound, + /// Invalid image data Invalid, } -impl Memory { - pub fn dimensions(&self) -> (u32, u32) { +impl<T: Storage> Memory<T> { + /// Width and height of image + pub fn dimensions(&self) -> Size<u32> { + use crate::image::storage::Entry; + match self { - Memory::Host(image) => image.dimensions(), + Memory::Host(image) => { + let (width, height) = image.dimensions(); + + Size::new(width, height) + } Memory::Device(entry) => entry.size(), - Memory::NotFound => (1, 1), - Memory::Invalid => (1, 1), + Memory::NotFound => Size::new(1, 1), + Memory::Invalid => Size::new(1, 1), } } } +/// Caches image raster data #[derive(Debug)] -pub struct Cache { - map: HashMap<u64, Memory>, +pub struct Cache<T: Storage> { + map: HashMap<u64, Memory<T>>, hits: HashSet<u64>, } -impl Cache { - pub fn new() -> Self { - Self { - map: HashMap::new(), - hits: HashSet::new(), - } - } - - pub fn load(&mut self, handle: &image::Handle) -> &mut Memory { +impl<T: Storage> Cache<T> { + /// Load image + pub fn load(&mut self, handle: &image::Handle) -> &mut Memory<T> { if self.contains(handle) { return self.get(handle).unwrap(); } @@ -53,7 +63,7 @@ impl Cache { }) .unwrap_or_else(Operation::empty); - Memory::Host(operation.perform(image.to_bgra8())) + Memory::Host(operation.perform(image.to_rgba8())) } else { Memory::NotFound } @@ -65,12 +75,12 @@ impl Cache { .ok() .unwrap_or_else(Operation::empty); - Memory::Host(operation.perform(image.to_bgra8())) + Memory::Host(operation.perform(image.to_rgba8())) } else { Memory::Invalid } } - image::Data::Pixels { + image::Data::Rgba { width, height, pixels, @@ -91,19 +101,19 @@ impl Cache { self.get(handle).unwrap() } + /// Load image and upload raster data pub fn upload( &mut self, handle: &image::Handle, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - atlas: &mut Atlas, - ) -> Option<&atlas::Entry> { + state: &mut T::State<'_>, + storage: &mut T, + ) -> Option<&T::Entry> { let memory = self.load(handle); if let Memory::Host(image) = memory { let (width, height) = image.dimensions(); - let entry = atlas.upload(width, height, image, device, encoder)?; + let entry = storage.upload(width, height, image, state)?; *memory = Memory::Device(entry); } @@ -115,7 +125,8 @@ impl Cache { } } - pub fn trim(&mut self, atlas: &mut Atlas) { + /// Trim cache misses from cache + pub fn trim(&mut self, storage: &mut T, state: &mut T::State<'_>) { let hits = &self.hits; self.map.retain(|k, memory| { @@ -123,7 +134,7 @@ impl Cache { if !retain { if let Memory::Device(entry) = memory { - atlas.remove(entry); + storage.remove(entry, state); } } @@ -133,13 +144,13 @@ impl Cache { self.hits.clear(); } - fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory> { + fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory<T>> { let _ = self.hits.insert(handle.id()); self.map.get_mut(&handle.id()) } - fn insert(&mut self, handle: &image::Handle, memory: Memory) { + fn insert(&mut self, handle: &image::Handle, memory: Memory<T>) { let _ = self.map.insert(handle.id(), memory); } @@ -148,6 +159,15 @@ impl Cache { } } +impl<T: Storage> Default for Cache<T> { + fn default() -> Self { + Self { + map: HashMap::new(), + hits: HashSet::new(), + } + } +} + bitflags! { struct Operation: u8 { const FLIP_HORIZONTALLY = 0b001; diff --git a/wgpu/src/image/vector.rs b/graphics/src/image/vector.rs index b08a0aa2..82d77aff 100644 --- a/wgpu/src/image/vector.rs +++ b/graphics/src/image/vector.rs @@ -1,46 +1,48 @@ -use crate::image::atlas::{self, Atlas}; +//! Vector image loading and caching +use crate::image::Storage; +use crate::Color; use iced_native::svg; +use iced_native::Size; use std::collections::{HashMap, HashSet}; use std::fs; +/// Entry in cache corresponding to an svg handle pub enum Svg { + /// Parsed svg Loaded(usvg::Tree), + /// Svg not found or failed to parse NotFound, } impl Svg { - pub fn viewport_dimensions(&self) -> (u32, u32) { + /// Viewport width and height + pub fn viewport_dimensions(&self) -> Size<u32> { match self { Svg::Loaded(tree) => { let size = tree.svg_node().size; - (size.width() as u32, size.height() as u32) + Size::new(size.width() as u32, size.height() as u32) } - Svg::NotFound => (1, 1), + Svg::NotFound => Size::new(1, 1), } } } +/// Caches svg vector and raster data #[derive(Debug)] -pub struct Cache { +pub struct Cache<T: Storage> { svgs: HashMap<u64, Svg>, - rasterized: HashMap<(u64, u32, u32), atlas::Entry>, + rasterized: HashMap<(u64, u32, u32, ColorFilter), T::Entry>, svg_hits: HashSet<u64>, - rasterized_hits: HashSet<(u64, u32, u32)>, + rasterized_hits: HashSet<(u64, u32, u32, ColorFilter)>, } -impl Cache { - pub fn new() -> Self { - Self { - svgs: HashMap::new(), - rasterized: HashMap::new(), - svg_hits: HashSet::new(), - rasterized_hits: HashSet::new(), - } - } +type ColorFilter = Option<[u8; 4]>; +impl<T: Storage> Cache<T> { + /// Load svg pub fn load(&mut self, handle: &svg::Handle) -> &Svg { if self.svgs.contains_key(&handle.id()) { return self.svgs.get(&handle.id()).unwrap(); @@ -73,15 +75,16 @@ impl Cache { self.svgs.get(&handle.id()).unwrap() } + /// Load svg and upload raster data pub fn upload( &mut self, handle: &svg::Handle, + color: Option<Color>, [width, height]: [f32; 2], scale: f32, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - texture_atlas: &mut Atlas, - ) -> Option<&atlas::Entry> { + state: &mut T::State<'_>, + storage: &mut T, + ) -> Option<&T::Entry> { let id = handle.id(); let (width, height) = ( @@ -89,15 +92,18 @@ impl Cache { (scale * height).ceil() as u32, ); + let color = color.map(Color::into_rgba8); + let key = (id, width, height, color); + // TODO: Optimize! // We currently rerasterize the SVG when its size changes. This is slow // as heck. A GPU rasterizer like `pathfinder` may perform better. // It would be cool to be able to smooth resize the `svg` example. - if self.rasterized.contains_key(&(id, width, height)) { + if self.rasterized.contains_key(&key) { let _ = self.svg_hits.insert(id); - let _ = self.rasterized_hits.insert((id, width, height)); + let _ = self.rasterized_hits.insert(key); - return self.rasterized.get(&(id, width, height)); + return self.rasterized.get(&key); } match self.load(handle) { @@ -123,28 +129,32 @@ impl Cache { )?; let mut rgba = img.take(); - rgba.chunks_exact_mut(4).for_each(|rgba| rgba.swap(0, 2)); - - let allocation = texture_atlas.upload( - width, - height, - bytemuck::cast_slice(rgba.as_slice()), - device, - encoder, - )?; + + if let Some(color) = color { + rgba.chunks_exact_mut(4).for_each(|rgba| { + if rgba[3] > 0 { + rgba[0] = color[0]; + rgba[1] = color[1]; + rgba[2] = color[2]; + } + }); + } + + let allocation = storage.upload(width, height, &rgba, state)?; log::debug!("allocating {} {}x{}", id, width, height); let _ = self.svg_hits.insert(id); - let _ = self.rasterized_hits.insert((id, width, height)); - let _ = self.rasterized.insert((id, width, height), allocation); + let _ = self.rasterized_hits.insert(key); + let _ = self.rasterized.insert(key, allocation); - self.rasterized.get(&(id, width, height)) + self.rasterized.get(&key) } Svg::NotFound => None, } } - pub fn trim(&mut self, atlas: &mut Atlas) { + /// Load svg and upload raster data + pub fn trim(&mut self, storage: &mut T, state: &mut T::State<'_>) { let svg_hits = &self.svg_hits; let rasterized_hits = &self.rasterized_hits; @@ -153,7 +163,7 @@ impl Cache { let retain = rasterized_hits.contains(k); if !retain { - atlas.remove(entry); + storage.remove(entry, state); } retain @@ -163,6 +173,17 @@ impl Cache { } } +impl<T: Storage> Default for Cache<T> { + fn default() -> Self { + Self { + svgs: HashMap::new(), + rasterized: HashMap::new(), + svg_hits: HashSet::new(), + rasterized_hits: HashSet::new(), + } + } +} + impl std::fmt::Debug for Svg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { diff --git a/wgpu/Cargo.toml b/wgpu/Cargo.toml index 55eec73f..a40d9967 100644 --- a/wgpu/Cargo.toml +++ b/wgpu/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "iced_wgpu" -version = "0.5.1" +version = "0.7.0" authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"] edition = "2021" description = "A wgpu renderer for Iced" @@ -8,19 +8,19 @@ license = "MIT AND OFL-1.1" repository = "https://github.com/iced-rs/iced" [features] -svg = ["resvg", "usvg", "tiny-skia"] -image = ["png", "jpeg", "jpeg_rayon", "gif", "webp", "bmp"] -png = ["image_rs/png"] -jpeg = ["image_rs/jpeg"] -jpeg_rayon = ["image_rs/jpeg_rayon"] -gif = ["image_rs/gif"] -webp = ["image_rs/webp"] -pnm = ["image_rs/pnm"] -ico = ["image_rs/ico"] -bmp = ["image_rs/bmp"] -hdr = ["image_rs/hdr"] -dds = ["image_rs/dds"] -farbfeld = ["image_rs/farbfeld"] +svg = ["iced_graphics/svg"] +image = ["iced_graphics/image"] +png = ["iced_graphics/png"] +jpeg = ["iced_graphics/jpeg"] +jpeg_rayon = ["iced_graphics/jpeg_rayon"] +gif = ["iced_graphics/gif"] +webp = ["iced_graphics/webp"] +pnm = ["iced_graphics/pnm"] +ico = ["iced_graphics/ico"] +bmp = ["iced_graphics/bmp"] +hdr = ["iced_graphics/hdr"] +dds = ["iced_graphics/dds"] +farbfeld = ["iced_graphics/farbfeld"] canvas = ["iced_graphics/canvas"] qr_code = ["iced_graphics/qr_code"] default_system_font = ["iced_graphics/font-source"] @@ -35,7 +35,6 @@ raw-window-handle = "0.5" log = "0.4" guillotiere = "0.6" futures = "0.3" -kamadak-exif = "0.5" bitflags = "1.2" [dependencies.bytemuck] @@ -43,31 +42,20 @@ version = "1.9" features = ["derive"] [dependencies.iced_native] -version = "0.5" +version = "0.7" path = "../native" [dependencies.iced_graphics] -version = "0.3" +version = "0.5" path = "../graphics" features = ["font-fallback", "font-icons"] -[dependencies.image_rs] -version = "0.23" -package = "image" -default-features = false -optional = true - -[dependencies.resvg] -version = "0.18" -optional = true - -[dependencies.usvg] -version = "0.18" -optional = true +[dependencies.encase] +version = "0.3.0" +features = ["glam"] -[dependencies.tiny-skia] -version = "0.6" -optional = true +[dependencies.glam] +version = "0.21.3" [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] diff --git a/wgpu/src/backend.rs b/wgpu/src/backend.rs index 8c875254..946eb712 100644 --- a/wgpu/src/backend.rs +++ b/wgpu/src/backend.rs @@ -10,7 +10,7 @@ use iced_graphics::{Primitive, Viewport}; use iced_native::alignment; use iced_native::{Font, Size}; -#[cfg(any(feature = "image_rs", feature = "svg"))] +#[cfg(any(feature = "image", feature = "svg"))] use crate::image; /// A [`wgpu`] graphics backend for [`iced`]. @@ -23,7 +23,7 @@ pub struct Backend { text_pipeline: text::Pipeline, triangle_pipeline: triangle::Pipeline, - #[cfg(any(feature = "image_rs", feature = "svg"))] + #[cfg(any(feature = "image", feature = "svg"))] image_pipeline: image::Pipeline, default_text_size: u16, @@ -47,7 +47,7 @@ impl Backend { let triangle_pipeline = triangle::Pipeline::new(device, format, settings.antialiasing); - #[cfg(any(feature = "image_rs", feature = "svg"))] + #[cfg(any(feature = "image", feature = "svg"))] let image_pipeline = image::Pipeline::new(device, format); Self { @@ -55,7 +55,7 @@ impl Backend { text_pipeline, triangle_pipeline, - #[cfg(any(feature = "image_rs", feature = "svg"))] + #[cfg(any(feature = "image", feature = "svg"))] image_pipeline, default_text_size: settings.default_text_size, @@ -94,13 +94,12 @@ impl Backend { staging_belt, encoder, frame, - target_size.width, - target_size.height, + target_size, ); } - #[cfg(any(feature = "image_rs", feature = "svg"))] - self.image_pipeline.trim_cache(); + #[cfg(any(feature = "image", feature = "svg"))] + self.image_pipeline.trim_cache(device, encoder); } fn flush( @@ -112,8 +111,7 @@ impl Backend { staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, - target_width: u32, - target_height: u32, + target_size: Size<u32>, ) { let bounds = (layer.bounds * scale_factor).snap(); @@ -143,15 +141,14 @@ impl Backend { staging_belt, encoder, target, - target_width, - target_height, + target_size, scaled, scale_factor, &layer.meshes, ); } - #[cfg(any(feature = "image_rs", feature = "svg"))] + #[cfg(any(feature = "image", feature = "svg"))] { if !layer.images.is_empty() { let scaled = transformation @@ -297,9 +294,9 @@ impl backend::Text for Backend { } } -#[cfg(feature = "image_rs")] +#[cfg(feature = "image")] impl backend::Image for Backend { - fn dimensions(&self, handle: &iced_native::image::Handle) -> (u32, u32) { + fn dimensions(&self, handle: &iced_native::image::Handle) -> Size<u32> { self.image_pipeline.dimensions(handle) } } @@ -309,7 +306,7 @@ impl backend::Svg for Backend { fn viewport_dimensions( &self, handle: &iced_native::svg::Handle, - ) -> (u32, u32) { + ) -> Size<u32> { self.image_pipeline.viewport_dimensions(handle) } } diff --git a/wgpu/src/buffer.rs b/wgpu/src/buffer.rs new file mode 100644 index 00000000..7c092d0b --- /dev/null +++ b/wgpu/src/buffer.rs @@ -0,0 +1,3 @@ +//! Utilities for buffer operations. +pub mod dynamic; +pub mod r#static; diff --git a/wgpu/src/buffer/dynamic.rs b/wgpu/src/buffer/dynamic.rs new file mode 100644 index 00000000..18be03dd --- /dev/null +++ b/wgpu/src/buffer/dynamic.rs @@ -0,0 +1,219 @@ +//! Utilities for uniform buffer operations. +use encase::private::WriteInto; +use encase::ShaderType; + +use std::fmt; +use std::marker::PhantomData; + +/// A dynamic buffer is any type of buffer which does not have a static offset. +#[derive(Debug)] +pub struct Buffer<T: ShaderType> { + offsets: Vec<wgpu::DynamicOffset>, + cpu: Internal, + gpu: wgpu::Buffer, + label: &'static str, + size: u64, + _data: PhantomData<T>, +} + +impl<T: ShaderType + WriteInto> Buffer<T> { + /// Creates a new dynamic uniform buffer. + pub fn uniform(device: &wgpu::Device, label: &'static str) -> Self { + Buffer::new( + device, + Internal::Uniform(encase::DynamicUniformBuffer::new(Vec::new())), + label, + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + ) + } + + #[cfg(not(target_arch = "wasm32"))] + /// Creates a new dynamic storage buffer. + pub fn storage(device: &wgpu::Device, label: &'static str) -> Self { + Buffer::new( + device, + Internal::Storage(encase::DynamicStorageBuffer::new(Vec::new())), + label, + wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + ) + } + + fn new( + device: &wgpu::Device, + dynamic_buffer_type: Internal, + label: &'static str, + usage: wgpu::BufferUsages, + ) -> Self { + let initial_size = u64::from(T::min_size()); + + Self { + offsets: Vec::new(), + cpu: dynamic_buffer_type, + gpu: Buffer::<T>::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 cpu 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. + /// + /// If the gpu buffer is resized, its bind group will need to be recreated! + 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 { + Internal::Uniform(_) => { + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST + } + #[cfg(not(target_arch = "wasm32"))] + Internal::Storage(_) => { + wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST + } + }; + + self.gpu = Buffer::<T>::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) + .copied() + .expect("Index not found in offsets."); + + 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(); + } +} + +// Currently supported dynamic buffers. +enum Internal { + Uniform(encase::DynamicUniformBuffer<Vec<u8>>), + #[cfg(not(target_arch = "wasm32"))] + //storage buffers are not supported on wgpu wasm target (yet) + Storage(encase::DynamicStorageBuffer<Vec<u8>>), +} + +impl Internal { + /// Writes the current value to its CPU buffer with proper alignment. + pub(super) fn write<T: ShaderType + WriteInto>( + &mut self, + value: &T, + ) -> wgpu::DynamicOffset { + match self { + Internal::Uniform(buf) => buf + .write(value) + .expect("Error when writing to dynamic uniform buffer.") + as u32, + #[cfg(not(target_arch = "wasm32"))] + Internal::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<u8> { + match self { + Internal::Uniform(buf) => buf.as_ref(), + #[cfg(not(target_arch = "wasm32"))] + Internal::Storage(buf) => buf.as_ref(), + } + } + + /// Resets the CPU buffer. + pub(super) fn clear(&mut self) { + match self { + Internal::Uniform(buf) => { + buf.as_mut().clear(); + buf.set_offset(0); + } + #[cfg(not(target_arch = "wasm32"))] + Internal::Storage(buf) => { + buf.as_mut().clear(); + buf.set_offset(0); + } + } + } +} + +impl fmt::Debug for Internal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Uniform(_) => write!(f, "Internal::Uniform(_)"), + #[cfg(not(target_arch = "wasm32"))] + Self::Storage(_) => write!(f, "Internal::Storage(_)"), + } + } +} diff --git a/wgpu/src/buffer/static.rs b/wgpu/src/buffer/static.rs new file mode 100644 index 00000000..ef87422f --- /dev/null +++ b/wgpu/src/buffer/static.rs @@ -0,0 +1,117 @@ +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) & no dynamic offsets. +#[derive(Debug)] +pub struct Buffer<T> { + //stored sequentially per mesh iteration; refers to the offset index in the GPU buffer + offsets: Vec<wgpu::BufferAddress>, + label: &'static str, + usages: wgpu::BufferUsages, + gpu: wgpu::Buffer, + size: wgpu::BufferAddress, + _data: PhantomData<T>, +} + +impl<T: Pod + Zeroable> Buffer<T> { + /// Initialize a new static buffer. + pub fn new( + device: &wgpu::Device, + label: &'static str, + usages: wgpu::BufferUsages, + ) -> Self { + let size = (mem::size_of::<T>() as u64) * DEFAULT_STATIC_BUFFER_COUNT; + + Self { + offsets: Vec::new(), + label, + usages, + gpu: Self::gpu_buffer(device, label, size, usages), + size, + _data: PhantomData, + } + } + + 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 resize(&mut self, device: &wgpu::Device, new_count: usize) -> bool { + let size = (mem::size_of::<T>() * 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 with a memcpy & stores its offset. + /// + /// Returns the size of the written bytes. + 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) { + 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)..) + } + + /// Clears any temporary data from the buffer. + pub fn clear(&mut self) { + self.offsets.clear() + } +} diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index d964aed7..390bad90 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -1,22 +1,23 @@ mod atlas; -#[cfg(feature = "image_rs")] -mod raster; +#[cfg(feature = "image")] +use iced_graphics::image::raster; #[cfg(feature = "svg")] -mod vector; +use iced_graphics::image::vector; use crate::Transformation; use atlas::Atlas; use iced_graphics::layer; -use iced_native::Rectangle; +use iced_native::{Rectangle, Size}; + use std::cell::RefCell; use std::mem; use bytemuck::{Pod, Zeroable}; -#[cfg(feature = "image_rs")] +#[cfg(feature = "image")] use iced_native::image; #[cfg(feature = "svg")] @@ -24,10 +25,10 @@ use iced_native::svg; #[derive(Debug)] pub struct Pipeline { - #[cfg(feature = "image_rs")] - raster_cache: RefCell<raster::Cache>, + #[cfg(feature = "image")] + raster_cache: RefCell<raster::Cache<Atlas>>, #[cfg(feature = "svg")] - vector_cache: RefCell<vector::Cache>, + vector_cache: RefCell<vector::Cache<Atlas>>, pipeline: wgpu::RenderPipeline, uniforms: wgpu::Buffer, @@ -242,11 +243,11 @@ impl Pipeline { }); Pipeline { - #[cfg(feature = "image_rs")] - raster_cache: RefCell::new(raster::Cache::new()), + #[cfg(feature = "image")] + raster_cache: RefCell::new(raster::Cache::default()), #[cfg(feature = "svg")] - vector_cache: RefCell::new(vector::Cache::new()), + vector_cache: RefCell::new(vector::Cache::default()), pipeline, uniforms: uniforms_buffer, @@ -261,8 +262,8 @@ impl Pipeline { } } - #[cfg(feature = "image_rs")] - pub fn dimensions(&self, handle: &image::Handle) -> (u32, u32) { + #[cfg(feature = "image")] + pub fn dimensions(&self, handle: &image::Handle) -> Size<u32> { let mut cache = self.raster_cache.borrow_mut(); let memory = cache.load(handle); @@ -270,7 +271,7 @@ impl Pipeline { } #[cfg(feature = "svg")] - pub fn viewport_dimensions(&self, handle: &svg::Handle) -> (u32, u32) { + pub fn viewport_dimensions(&self, handle: &svg::Handle) -> Size<u32> { let mut cache = self.vector_cache.borrow_mut(); let svg = cache.load(handle); @@ -290,7 +291,7 @@ impl Pipeline { ) { let instances: &mut Vec<Instance> = &mut Vec::new(); - #[cfg(feature = "image_rs")] + #[cfg(feature = "image")] let mut raster_cache = self.raster_cache.borrow_mut(); #[cfg(feature = "svg")] @@ -298,12 +299,11 @@ impl Pipeline { for image in images { match &image { - #[cfg(feature = "image_rs")] + #[cfg(feature = "image")] layer::Image::Raster { handle, bounds } => { if let Some(atlas_entry) = raster_cache.upload( handle, - device, - encoder, + &mut (device, encoder), &mut self.texture_atlas, ) { add_instances( @@ -314,19 +314,23 @@ impl Pipeline { ); } } - #[cfg(not(feature = "image_rs"))] + #[cfg(not(feature = "image"))] layer::Image::Raster { .. } => {} #[cfg(feature = "svg")] - layer::Image::Vector { handle, bounds } => { + layer::Image::Vector { + handle, + color, + bounds, + } => { let size = [bounds.width, bounds.height]; if let Some(atlas_entry) = vector_cache.upload( handle, + *color, size, _scale, - device, - encoder, + &mut (device, encoder), &mut self.texture_atlas, ) { add_instances( @@ -446,12 +450,20 @@ impl Pipeline { } } - pub fn trim_cache(&mut self) { - #[cfg(feature = "image_rs")] - self.raster_cache.borrow_mut().trim(&mut self.texture_atlas); + pub fn trim_cache( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + ) { + #[cfg(feature = "image")] + self.raster_cache + .borrow_mut() + .trim(&mut self.texture_atlas, &mut (device, encoder)); #[cfg(feature = "svg")] - self.vector_cache.borrow_mut().trim(&mut self.texture_atlas); + self.vector_cache + .borrow_mut() + .trim(&mut self.texture_atlas, &mut (device, encoder)); } } @@ -509,15 +521,18 @@ fn add_instances( add_instance(image_position, image_size, allocation, instances); } atlas::Entry::Fragmented { fragments, size } => { - let scaling_x = image_size[0] / size.0 as f32; - let scaling_y = image_size[1] / size.1 as f32; + let scaling_x = image_size[0] / size.width as f32; + let scaling_y = image_size[1] / size.height as f32; for fragment in fragments { let allocation = &fragment.allocation; let [x, y] = image_position; let (fragment_x, fragment_y) = fragment.position; - let (fragment_width, fragment_height) = allocation.size(); + let Size { + width: fragment_width, + height: fragment_height, + } = allocation.size(); let position = [ x + fragment_x as f32 * scaling_x, @@ -543,7 +558,7 @@ fn add_instance( instances: &mut Vec<Instance>, ) { let (x, y) = allocation.position(); - let (width, height) = allocation.size(); + let Size { width, height } = allocation.size(); let layer = allocation.layer(); let instance = Instance { diff --git a/wgpu/src/image/atlas.rs b/wgpu/src/image/atlas.rs index 953dd4e2..eafe2f96 100644 --- a/wgpu/src/image/atlas.rs +++ b/wgpu/src/image/atlas.rs @@ -4,8 +4,6 @@ mod allocation; mod allocator; mod layer; -use std::num::NonZeroU32; - pub use allocation::Allocation; pub use entry::Entry; pub use layer::Layer; @@ -14,6 +12,11 @@ use allocator::Allocator; pub const SIZE: u32 = 2048; +use iced_graphics::image; +use iced_graphics::Size; + +use std::num::NonZeroU32; + #[derive(Debug)] pub struct Atlas { texture: wgpu::Texture, @@ -35,7 +38,7 @@ impl Atlas { mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Bgra8UnormSrgb, + format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, @@ -61,99 +64,6 @@ impl Atlas { self.layers.len() } - pub fn upload( - &mut self, - width: u32, - height: u32, - data: &[u8], - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - ) -> Option<Entry> { - use wgpu::util::DeviceExt; - - let entry = { - let current_size = self.layers.len(); - let entry = self.allocate(width, height)?; - - // We grow the internal texture after allocating if necessary - let new_layers = self.layers.len() - current_size; - self.grow(new_layers, device, encoder); - - entry - }; - - log::info!("Allocated atlas entry: {:?}", entry); - - // It is a webgpu requirement that: - // BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0 - // So we calculate padded_width by rounding width up to the next - // multiple of wgpu::COPY_BYTES_PER_ROW_ALIGNMENT. - let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; - let padding = (align - (4 * width) % align) % align; - let padded_width = (4 * width + padding) as usize; - let padded_data_size = padded_width * height as usize; - - let mut padded_data = vec![0; padded_data_size]; - - for row in 0..height as usize { - let offset = row * padded_width; - - padded_data[offset..offset + 4 * width as usize].copy_from_slice( - &data[row * 4 * width as usize..(row + 1) * 4 * width as usize], - ) - } - - let buffer = - device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("iced_wgpu::image staging buffer"), - contents: &padded_data, - usage: wgpu::BufferUsages::COPY_SRC, - }); - - match &entry { - Entry::Contiguous(allocation) => { - self.upload_allocation( - &buffer, width, height, padding, 0, allocation, encoder, - ); - } - Entry::Fragmented { fragments, .. } => { - for fragment in fragments { - let (x, y) = fragment.position; - let offset = (y * padded_width as u32 + 4 * x) as usize; - - self.upload_allocation( - &buffer, - width, - height, - padding, - offset, - &fragment.allocation, - encoder, - ); - } - } - } - - log::info!("Current atlas: {:?}", self); - - Some(entry) - } - - pub fn remove(&mut self, entry: &Entry) { - log::info!("Removing atlas entry: {:?}", entry); - - match entry { - Entry::Contiguous(allocation) => { - self.deallocate(allocation); - } - Entry::Fragmented { fragments, .. } => { - for fragment in fragments { - self.deallocate(&fragment.allocation); - } - } - } - } - fn allocate(&mut self, width: u32, height: u32) -> Option<Entry> { // Allocate one layer if texture fits perfectly if width == SIZE && height == SIZE { @@ -204,7 +114,7 @@ impl Atlas { } return Some(Entry::Fragmented { - size: (width, height), + size: Size::new(width, height), fragments, }); } @@ -284,7 +194,7 @@ impl Atlas { encoder: &mut wgpu::CommandEncoder, ) { let (x, y) = allocation.position(); - let (width, height) = allocation.size(); + let Size { width, height } = allocation.size(); let layer = allocation.layer(); let extent = wgpu::Extent3d { @@ -336,7 +246,7 @@ impl Atlas { mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Bgra8UnormSrgb, + format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, @@ -388,3 +298,100 @@ impl Atlas { }); } } + +impl image::Storage for Atlas { + type Entry = Entry; + type State<'a> = (&'a wgpu::Device, &'a mut wgpu::CommandEncoder); + + fn upload( + &mut self, + width: u32, + height: u32, + data: &[u8], + (device, encoder): &mut Self::State<'_>, + ) -> Option<Self::Entry> { + use wgpu::util::DeviceExt; + + let entry = { + let current_size = self.layers.len(); + let entry = self.allocate(width, height)?; + + // We grow the internal texture after allocating if necessary + let new_layers = self.layers.len() - current_size; + self.grow(new_layers, device, encoder); + + entry + }; + + log::info!("Allocated atlas entry: {:?}", entry); + + // It is a webgpu requirement that: + // BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0 + // So we calculate padded_width by rounding width up to the next + // multiple of wgpu::COPY_BYTES_PER_ROW_ALIGNMENT. + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padding = (align - (4 * width) % align) % align; + let padded_width = (4 * width + padding) as usize; + let padded_data_size = padded_width * height as usize; + + let mut padded_data = vec![0; padded_data_size]; + + for row in 0..height as usize { + let offset = row * padded_width; + + padded_data[offset..offset + 4 * width as usize].copy_from_slice( + &data[row * 4 * width as usize..(row + 1) * 4 * width as usize], + ) + } + + let buffer = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("iced_wgpu::image staging buffer"), + contents: &padded_data, + usage: wgpu::BufferUsages::COPY_SRC, + }); + + match &entry { + Entry::Contiguous(allocation) => { + self.upload_allocation( + &buffer, width, height, padding, 0, allocation, encoder, + ); + } + Entry::Fragmented { fragments, .. } => { + for fragment in fragments { + let (x, y) = fragment.position; + let offset = (y * padded_width as u32 + 4 * x) as usize; + + self.upload_allocation( + &buffer, + width, + height, + padding, + offset, + &fragment.allocation, + encoder, + ); + } + } + } + + log::info!("Current atlas: {:?}", self); + + Some(entry) + } + + fn remove(&mut self, entry: &Entry, _: &mut Self::State<'_>) { + log::info!("Removing atlas entry: {:?}", entry); + + match entry { + Entry::Contiguous(allocation) => { + self.deallocate(allocation); + } + Entry::Fragmented { fragments, .. } => { + for fragment in fragments { + self.deallocate(&fragment.allocation); + } + } + } + } +} diff --git a/wgpu/src/image/atlas/allocation.rs b/wgpu/src/image/atlas/allocation.rs index 59b7239f..43aba875 100644 --- a/wgpu/src/image/atlas/allocation.rs +++ b/wgpu/src/image/atlas/allocation.rs @@ -1,5 +1,7 @@ use crate::image::atlas::{self, allocator}; +use iced_graphics::Size; + #[derive(Debug)] pub enum Allocation { Partial { @@ -19,10 +21,10 @@ impl Allocation { } } - pub fn size(&self) -> (u32, u32) { + pub fn size(&self) -> Size<u32> { match self { Allocation::Partial { region, .. } => region.size(), - Allocation::Full { .. } => (atlas::SIZE, atlas::SIZE), + Allocation::Full { .. } => Size::new(atlas::SIZE, atlas::SIZE), } } diff --git a/wgpu/src/image/atlas/allocator.rs b/wgpu/src/image/atlas/allocator.rs index 7a4ff5b1..03effdcb 100644 --- a/wgpu/src/image/atlas/allocator.rs +++ b/wgpu/src/image/atlas/allocator.rs @@ -46,10 +46,10 @@ impl Region { (rectangle.min.x as u32, rectangle.min.y as u32) } - pub fn size(&self) -> (u32, u32) { + pub fn size(&self) -> iced_graphics::Size<u32> { let size = self.allocation.rectangle.size(); - (size.width as u32, size.height as u32) + iced_graphics::Size::new(size.width as u32, size.height as u32) } } diff --git a/wgpu/src/image/atlas/entry.rs b/wgpu/src/image/atlas/entry.rs index 9b3f16df..69c05a50 100644 --- a/wgpu/src/image/atlas/entry.rs +++ b/wgpu/src/image/atlas/entry.rs @@ -1,17 +1,19 @@ use crate::image::atlas; +use iced_graphics::image; +use iced_graphics::Size; + #[derive(Debug)] pub enum Entry { Contiguous(atlas::Allocation), Fragmented { - size: (u32, u32), + size: Size<u32>, fragments: Vec<Fragment>, }, } -impl Entry { - #[cfg(feature = "image_rs")] - pub fn size(&self) -> (u32, u32) { +impl image::storage::Entry for Entry { + fn size(&self) -> Size<u32> { match self { Entry::Contiguous(allocation) => allocation.size(), Entry::Fragmented { size, .. } => *size, diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 3a98c6bd..e4a38005 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -16,7 +16,7 @@ //! - Meshes of triangles, useful to draw geometry freely. //! //! [Iced]: https://github.com/iced-rs/iced -//! [`iced_native`]: https://github.com/iced-rs/iced/tree/0.4/native +//! [`iced_native`]: https://github.com/iced-rs/iced/tree/0.6/native //! [`wgpu`]: https://github.com/gfx-rs/wgpu-rs //! [WebGPU API]: https://gpuweb.github.io/gpuweb/ //! [`wgpu_glyph`]: https://github.com/hecrj/wgpu_glyph @@ -39,12 +39,13 @@ #![cfg_attr(docsrs, feature(doc_cfg))] pub mod settings; -pub mod triangle; pub mod window; mod backend; +mod buffer; mod quad; mod text; +mod triangle; pub use iced_graphics::{Antialiasing, Color, Error, Primitive, Viewport}; pub use iced_native::Theme; @@ -55,7 +56,7 @@ pub use settings::Settings; pub(crate) use iced_graphics::Transformation; -#[cfg(any(feature = "image_rs", feature = "svg"))] +#[cfg(any(feature = "image", feature = "svg"))] mod image; /// A [`wgpu`] graphics renderer for [`iced`]. diff --git a/wgpu/src/quad.rs b/wgpu/src/quad.rs index a117df64..027a34be 100644 --- a/wgpu/src/quad.rs +++ b/wgpu/src/quad.rs @@ -91,7 +91,7 @@ impl Pipeline { 2 => Float32x2, 3 => Float32x4, 4 => Float32x4, - 5 => Float32, + 5 => Float32x4, 6 => Float32, ), }, diff --git a/wgpu/src/shader/gradient.wgsl b/wgpu/src/shader/gradient.wgsl new file mode 100644 index 00000000..63825aec --- /dev/null +++ b/wgpu/src/shader/gradient.wgsl @@ -0,0 +1,88 @@ +struct Uniforms { + transform: mat4x4<f32>, + //xy = start, wz = end + position: vec4<f32>, + //x = start stop, y = end stop, zw = padding + stop_range: vec4<i32>, +} + +struct Stop { + color: vec4<f32>, + offset: f32, +}; + +@group(0) @binding(0) +var<uniform> uniforms: Uniforms; + +@group(0) @binding(1) +var<storage, read> color_stops: array<Stop>; + +struct VertexOutput { + @builtin(position) position: vec4<f32>, + @location(0) raw_position: vec2<f32> +} + +@vertex +fn vs_main(@location(0) input: vec2<f32>) -> VertexOutput { + var output: VertexOutput; + output.position = uniforms.transform * vec4<f32>(input.xy, 0.0, 1.0); + output.raw_position = input; + + return output; +} + +//TODO: rewrite without branching +@fragment +fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> { + let start = uniforms.position.xy; + let end = uniforms.position.zw; + let start_stop = uniforms.stop_range.x; + let end_stop = uniforms.stop_range.y; + + let v1 = end - start; + let v2 = input.raw_position.xy - start; + let unit = normalize(v1); + let offset = dot(unit, v2) / length(v1); + + let min_stop = color_stops[start_stop]; + let max_stop = color_stops[end_stop]; + + var color: vec4<f32>; + + if (offset <= min_stop.offset) { + color = min_stop.color; + } else if (offset >= max_stop.offset) { + color = max_stop.color; + } else { + var min = min_stop; + var max = max_stop; + var min_index = start_stop; + var max_index = end_stop; + + loop { + if (min_index >= max_index - 1) { + break; + } + + let index = min_index + (max_index - min_index) / 2; + + let stop = color_stops[index]; + + if (offset <= stop.offset) { + max = stop; + max_index = index; + } else { + min = stop; + min_index = index; + } + } + + color = mix(min.color, max.color, smoothstep( + min.offset, + max.offset, + offset + )); + } + + return color; +} diff --git a/wgpu/src/shader/quad.wgsl b/wgpu/src/shader/quad.wgsl index 73edd97c..cf4f7e4d 100644 --- a/wgpu/src/shader/quad.wgsl +++ b/wgpu/src/shader/quad.wgsl @@ -11,7 +11,7 @@ struct VertexInput { @location(2) scale: vec2<f32>, @location(3) color: vec4<f32>, @location(4) border_color: vec4<f32>, - @location(5) border_radius: f32, + @location(5) border_radius: vec4<f32>, @location(6) border_width: f32, } @@ -21,7 +21,7 @@ struct VertexOutput { @location(1) border_color: vec4<f32>, @location(2) pos: vec2<f32>, @location(3) scale: vec2<f32>, - @location(4) border_radius: f32, + @location(4) border_radius: vec4<f32>, @location(5) border_width: f32, } @@ -32,9 +32,12 @@ fn vs_main(input: VertexInput) -> VertexOutput { var pos: vec2<f32> = input.pos * globals.scale; var scale: vec2<f32> = input.scale * globals.scale; - var border_radius: f32 = min( - input.border_radius, - min(input.scale.x, input.scale.y) / 2.0 + var min_border_radius = min(input.scale.x, input.scale.y) * 0.5; + var border_radius: vec4<f32> = vec4<f32>( + min(input.border_radius.x, min_border_radius), + min(input.border_radius.y, min_border_radius), + min(input.border_radius.z, min_border_radius), + min(input.border_radius.w, min_border_radius) ); var transform: mat4x4<f32> = mat4x4<f32>( @@ -76,6 +79,18 @@ fn distance_alg( return sqrt(dist.x * dist.x + dist.y * dist.y); } +// Based on the fragement position and the center of the quad, select one of the 4 radi. +// Order matches CSS border radius attribute: +// radi.x = top-left, radi.y = top-right, radi.z = bottom-right, radi.w = bottom-left +fn select_border_radius(radi: vec4<f32>, position: vec2<f32>, center: vec2<f32>) -> f32 { + var rx = radi.x; + var ry = radi.y; + rx = select(radi.x, radi.y, position.x > center.x); + ry = select(radi.w, radi.z, position.x > center.x); + rx = select(rx, ry, position.y > center.y); + return rx; +} + @fragment fn fs_main( @@ -83,14 +98,17 @@ fn fs_main( ) -> @location(0) vec4<f32> { var mixed_color: vec4<f32> = input.color; + var border_radius = select_border_radius( + input.border_radius, + input.position.xy, + (input.pos + input.scale * 0.5).xy + ); + if (input.border_width > 0.0) { - var internal_border: f32 = max( - input.border_radius - input.border_width, - 0.0 - ); + var internal_border: f32 = max(border_radius - input.border_width, 0.0); var internal_distance: f32 = distance_alg( - vec2<f32>(input.position.x, input.position.y), + input.position.xy, input.pos + vec2<f32>(input.border_width, input.border_width), input.scale - vec2<f32>(input.border_width * 2.0, input.border_width * 2.0), internal_border @@ -109,13 +127,14 @@ fn fs_main( vec2<f32>(input.position.x, input.position.y), input.pos, input.scale, - input.border_radius + border_radius ); var radius_alpha: f32 = 1.0 - smoothstep( - max(input.border_radius - 0.5, 0.0), - input.border_radius + 0.5, - dist); + max(border_radius - 0.5, 0.0), + border_radius + 0.5, + dist + ); return vec4<f32>(mixed_color.x, mixed_color.y, mixed_color.z, mixed_color.w * radius_alpha); } diff --git a/wgpu/src/shader/triangle.wgsl b/wgpu/src/shader/solid.wgsl index b24402f8..b24402f8 100644 --- a/wgpu/src/shader/triangle.wgsl +++ b/wgpu/src/shader/solid.wgsl diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index fd06dddf..b33b488a 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -1,77 +1,24 @@ //! Draw meshes of triangles. -use crate::{settings, Transformation}; -use iced_graphics::layer; - -use bytemuck::{Pod, Zeroable}; -use std::mem; - -pub use iced_graphics::triangle::{Mesh2D, Vertex2D}; - mod msaa; -const UNIFORM_BUFFER_SIZE: usize = 50; -const VERTEX_BUFFER_SIZE: usize = 10_000; -const INDEX_BUFFER_SIZE: usize = 10_000; +use crate::buffer::r#static::Buffer; +use crate::settings; +use crate::Transformation; + +use iced_graphics::layer::mesh::{self, Mesh}; +use iced_graphics::triangle::ColoredVertex2D; +use iced_graphics::Size; #[derive(Debug)] -pub(crate) struct Pipeline { - pipeline: wgpu::RenderPipeline, +pub struct Pipeline { blit: Option<msaa::Blit>, - constants_layout: wgpu::BindGroupLayout, - constants: wgpu::BindGroup, - uniforms_buffer: Buffer<Uniforms>, - vertex_buffer: Buffer<Vertex2D>, index_buffer: Buffer<u32>, -} + index_strides: Vec<u32>, + solid: solid::Pipeline, -#[derive(Debug)] -struct Buffer<T> { - label: &'static str, - raw: wgpu::Buffer, - size: usize, - usage: wgpu::BufferUsages, - _type: std::marker::PhantomData<T>, -} - -impl<T> Buffer<T> { - pub fn new( - label: &'static str, - device: &wgpu::Device, - size: usize, - usage: wgpu::BufferUsages, - ) -> Self { - let raw = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(label), - size: (std::mem::size_of::<T>() * size) as u64, - usage, - mapped_at_creation: false, - }); - - Buffer { - label, - raw, - size, - usage, - _type: std::marker::PhantomData, - } - } - - pub fn expand(&mut self, device: &wgpu::Device, size: usize) -> bool { - let needs_resize = self.size < size; - - if needs_resize { - self.raw = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(self.label), - size: (std::mem::size_of::<T>() * size) as u64, - usage: self.usage, - mapped_at_creation: false, - }); - - self.size = size; - } - - needs_resize - } + /// Gradients are currently not supported on WASM targets due to their need of storage buffers. + #[cfg(not(target_arch = "wasm32"))] + gradient: gradient::Pipeline, } impl Pipeline { @@ -80,124 +27,18 @@ impl Pipeline { format: wgpu::TextureFormat, antialiasing: Option<settings::Antialiasing>, ) -> Pipeline { - let constants_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu::triangle uniforms layout"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: true, - min_binding_size: wgpu::BufferSize::new( - mem::size_of::<Uniforms>() as u64, - ), - }, - count: None, - }], - }); - - let constants_buffer = Buffer::new( - "iced_wgpu::triangle uniforms buffer", - device, - UNIFORM_BUFFER_SIZE, - wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - ); - - let constant_bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu::triangle uniforms bind group"), - layout: &constants_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer( - wgpu::BufferBinding { - buffer: &constants_buffer.raw, - offset: 0, - size: wgpu::BufferSize::new(std::mem::size_of::< - Uniforms, - >( - ) - as u64), - }, - ), - }], - }); - - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu::triangle pipeline layout"), - push_constant_ranges: &[], - bind_group_layouts: &[&constants_layout], - }); - - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu::triangle::shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( - include_str!("shader/triangle.wgsl"), - )), - }); - - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu::triangle pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: "vs_main", - buffers: &[wgpu::VertexBufferLayout { - array_stride: mem::size_of::<Vertex2D>() as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &wgpu::vertex_attr_array!( - // Position - 0 => Float32x2, - // Color - 1 => Float32x4, - ), - }], - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: "fs_main", - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState::ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Cw, - ..Default::default() - }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: antialiasing.map(|a| a.sample_count()).unwrap_or(1), - mask: !0, - alpha_to_coverage_enabled: false, - }, - multiview: None, - }); - Pipeline { - pipeline, blit: antialiasing.map(|a| msaa::Blit::new(device, format, a)), - constants_layout, - constants: constant_bind_group, - uniforms_buffer: constants_buffer, - vertex_buffer: Buffer::new( - "iced_wgpu::triangle vertex buffer", - device, - VERTEX_BUFFER_SIZE, - wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, - ), index_buffer: Buffer::new( - "iced_wgpu::triangle index buffer", device, - INDEX_BUFFER_SIZE, + "iced_wgpu::triangle vertex buffer", wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, ), + index_strides: Vec::new(), + solid: solid::Pipeline::new(device, format, antialiasing), + + #[cfg(not(target_arch = "wasm32"))] + gradient: gradient::Pipeline::new(device, format, antialiasing), } } @@ -207,139 +48,204 @@ impl Pipeline { staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, - target_width: u32, - target_height: u32, + target_size: Size<u32>, transformation: Transformation, scale_factor: f32, - meshes: &[layer::Mesh<'_>], + meshes: &[Mesh<'_>], ) { - // This looks a bit crazy, but we are just counting how many vertices - // and indices we will need to handle. - // TODO: Improve readability - let (total_vertices, total_indices) = meshes - .iter() - .map(|layer::Mesh { buffers, .. }| { - (buffers.vertices.len(), buffers.indices.len()) - }) - .fold((0, 0), |(total_v, total_i), (v, i)| { - (total_v + v, total_i + i) - }); - - // Then we ensure the current buffers are big enough, resizing if - // necessary - let _ = self.vertex_buffer.expand(device, total_vertices); - let _ = self.index_buffer.expand(device, total_indices); - - // If the uniforms buffer is resized, then we need to recreate its - // bind group. - if self.uniforms_buffer.expand(device, meshes.len()) { - self.constants = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu::triangle uniforms buffer"), - layout: &self.constants_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer( - wgpu::BufferBinding { - buffer: &self.uniforms_buffer.raw, - offset: 0, - size: wgpu::BufferSize::new( - std::mem::size_of::<Uniforms>() as u64, - ), - }, - ), - }], - }); + // Count the total amount of vertices & indices we need to handle + let count = mesh::attribute_count_of(meshes); + + // Then we ensure the current attribute buffers are big enough, resizing if necessary. + // 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.index_buffer.resize(device, count.indices); + let _ = self.solid.vertices.resize(device, count.solid_vertices); + + #[cfg(not(target_arch = "wasm32"))] + let _ = self + .gradient + .vertices + .resize(device, count.gradient_vertices); + + // Prepare dynamic buffers & data store for writing + self.index_strides.clear(); + self.solid.vertices.clear(); + self.solid.uniforms.clear(); + + #[cfg(not(target_arch = "wasm32"))] + { + self.gradient.uniforms.clear(); + self.gradient.vertices.clear(); + self.gradient.storage.clear(); } - let mut uniforms: Vec<Uniforms> = Vec::with_capacity(meshes.len()); - let mut offsets: Vec<( - wgpu::BufferAddress, - wgpu::BufferAddress, - usize, - )> = Vec::with_capacity(meshes.len()); - let mut last_vertex = 0; - let mut last_index = 0; + let mut solid_vertex_offset = 0; + let mut index_offset = 0; + + #[cfg(not(target_arch = "wasm32"))] + let mut gradient_vertex_offset = 0; - // We upload everything upfront for mesh in meshes { - let transform = (transformation - * Transformation::translate(mesh.origin.x, mesh.origin.y)) - .into(); - - let vertices = bytemuck::cast_slice(&mesh.buffers.vertices); - let indices = bytemuck::cast_slice(&mesh.buffers.indices); - - if let (Some(vertices_size), Some(indices_size)) = ( - wgpu::BufferSize::new(vertices.len() as u64), - wgpu::BufferSize::new(indices.len() as u64), - ) { - { - let mut vertex_buffer = staging_belt.write_buffer( - encoder, - &self.vertex_buffer.raw, - (std::mem::size_of::<Vertex2D>() * last_vertex) as u64, - vertices_size, + let origin = mesh.origin(); + let indices = mesh.indices(); + + let transform = + transformation * Transformation::translate(origin.x, origin.y); + + let new_index_offset = self.index_buffer.write( + device, + staging_belt, + encoder, + index_offset, + indices, + ); + + index_offset += new_index_offset; + self.index_strides.push(indices.len() as u32); + + //push uniform data to CPU buffers + match mesh { + Mesh::Solid { buffers, .. } => { + self.solid.uniforms.push(&solid::Uniforms::new(transform)); + + let written_bytes = self.solid.vertices.write( device, + staging_belt, + encoder, + solid_vertex_offset, + &buffers.vertices, ); - vertex_buffer.copy_from_slice(vertices); + solid_vertex_offset += written_bytes; } - - { - let mut index_buffer = staging_belt.write_buffer( - encoder, - &self.index_buffer.raw, - (std::mem::size_of::<u32>() * last_index) as u64, - indices_size, + #[cfg(not(target_arch = "wasm32"))] + Mesh::Gradient { + buffers, gradient, .. + } => { + let written_bytes = self.gradient.vertices.write( device, + staging_belt, + encoder, + gradient_vertex_offset, + &buffers.vertices, ); - index_buffer.copy_from_slice(indices); + gradient_vertex_offset += written_bytes; + + match gradient { + iced_graphics::Gradient::Linear(linear) => { + use glam::{IVec4, Vec4}; + + let start_offset = self.gradient.color_stop_offset; + let end_offset = (linear.color_stops.len() as i32) + + start_offset + - 1; + + self.gradient.uniforms.push(&gradient::Uniforms { + transform: transform.into(), + direction: Vec4::new( + linear.start.x, + linear.start.y, + linear.end.x, + linear.end.y, + ), + stop_range: IVec4::new( + start_offset, + end_offset, + 0, + 0, + ), + }); + + self.gradient.color_stop_offset = end_offset + 1; + + let stops: Vec<gradient::ColorStop> = linear + .color_stops + .iter() + .map(|stop| { + let [r, g, b, a] = stop.color.into_linear(); + + gradient::ColorStop { + offset: stop.offset, + color: Vec4::new(r, g, b, a), + } + }) + .collect(); + + self.gradient + .color_stops_pending_write + .color_stops + .extend(stops); + } + } } + #[cfg(target_arch = "wasm32")] + Mesh::Gradient { .. } => {} + } + } - uniforms.push(transform); - offsets.push(( - last_vertex as u64, - last_index as u64, - mesh.buffers.indices.len(), - )); + // Write uniform data to GPU + if count.solid_vertices > 0 { + let uniforms_resized = self.solid.uniforms.resize(device); - last_vertex += mesh.buffers.vertices.len(); - last_index += mesh.buffers.indices.len(); + if uniforms_resized { + self.solid.bind_group = solid::Pipeline::bind_group( + device, + self.solid.uniforms.raw(), + &self.solid.bind_group_layout, + ) } + + self.solid.uniforms.write(device, staging_belt, encoder); } - let uniforms = bytemuck::cast_slice(&uniforms); + #[cfg(not(target_arch = "wasm32"))] + if count.gradient_vertices > 0 { + // First write the pending color stops to the CPU buffer + self.gradient + .storage + .push(&self.gradient.color_stops_pending_write); + + // Resize buffers if needed + let uniforms_resized = self.gradient.uniforms.resize(device); + let storage_resized = self.gradient.storage.resize(device); + + if uniforms_resized || storage_resized { + self.gradient.bind_group = gradient::Pipeline::bind_group( + device, + self.gradient.uniforms.raw(), + self.gradient.storage.raw(), + &self.gradient.bind_group_layout, + ); + } - if let Some(uniforms_size) = - wgpu::BufferSize::new(uniforms.len() as u64) - { - let mut uniforms_buffer = staging_belt.write_buffer( - encoder, - &self.uniforms_buffer.raw, - 0, - uniforms_size, - device, - ); + // Write to GPU + self.gradient.uniforms.write(device, staging_belt, encoder); + self.gradient.storage.write(device, staging_belt, encoder); - uniforms_buffer.copy_from_slice(uniforms); + // Cleanup + self.gradient.color_stop_offset = 0; + self.gradient.color_stops_pending_write.color_stops.clear(); } + // Configure render pass { - let (attachment, resolve_target, load) = - if let Some(blit) = &mut self.blit { - let (attachment, resolve_target) = - blit.targets(device, target_width, target_height); - - ( - attachment, - Some(resolve_target), - wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), - ) - } else { - (target, None, wgpu::LoadOp::Load) - }; + let (attachment, resolve_target, load) = if let Some(blit) = + &mut self.blit + { + let (attachment, resolve_target) = + blit.targets(device, target_size.width, target_size.height); + + ( + attachment, + Some(resolve_target), + wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + ) + } else { + (target, None, wgpu::LoadOp::Load) + }; let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -354,12 +260,13 @@ impl Pipeline { depth_stencil_attachment: None, }); - render_pass.set_pipeline(&self.pipeline); + let mut num_solids = 0; + #[cfg(not(target_arch = "wasm32"))] + let mut num_gradients = 0; + let mut last_is_solid = None; - for (i, (vertex_offset, index_offset, indices)) in - offsets.into_iter().enumerate() - { - let clip_bounds = (meshes[i].clip_bounds * scale_factor).snap(); + for (index, mesh) in meshes.iter().enumerate() { + let clip_bounds = (mesh.clip_bounds() * scale_factor).snap(); render_pass.set_scissor_rect( clip_bounds.x, @@ -368,62 +275,459 @@ impl Pipeline { clip_bounds.height, ); - render_pass.set_bind_group( - 0, - &self.constants, - &[(std::mem::size_of::<Uniforms>() * i) as u32], - ); + match mesh { + Mesh::Solid { .. } => { + if !last_is_solid.unwrap_or(false) { + render_pass.set_pipeline(&self.solid.pipeline); + + last_is_solid = Some(true); + } + + render_pass.set_bind_group( + 0, + &self.solid.bind_group, + &[self.solid.uniforms.offset_at_index(num_solids)], + ); + + render_pass.set_vertex_buffer( + 0, + self.solid.vertices.slice_from_index(num_solids), + ); + + num_solids += 1; + } + #[cfg(not(target_arch = "wasm32"))] + Mesh::Gradient { .. } => { + if last_is_solid.unwrap_or(true) { + render_pass.set_pipeline(&self.gradient.pipeline); + + last_is_solid = Some(false); + } + + render_pass.set_bind_group( + 0, + &self.gradient.bind_group, + &[self + .gradient + .uniforms + .offset_at_index(num_gradients)], + ); + + render_pass.set_vertex_buffer( + 0, + self.gradient + .vertices + .slice_from_index(num_gradients), + ); + + num_gradients += 1; + } + #[cfg(target_arch = "wasm32")] + Mesh::Gradient { .. } => {} + }; render_pass.set_index_buffer( - self.index_buffer - .raw - .slice(index_offset * mem::size_of::<u32>() as u64..), + self.index_buffer.slice_from_index(index), wgpu::IndexFormat::Uint32, ); - render_pass.set_vertex_buffer( + render_pass.draw_indexed( + 0..(self.index_strides[index] as u32), 0, - self.vertex_buffer.raw.slice( - vertex_offset * mem::size_of::<Vertex2D>() as u64.., - ), + 0..1, ); - - render_pass.draw_indexed(0..indices as u32, 0, 0..1); } } + self.index_buffer.clear(); + if let Some(blit) = &mut self.blit { blit.draw(encoder, target); } } } -#[repr(C)] -#[derive(Debug, Clone, Copy, Zeroable, Pod)] -struct Uniforms { - transform: [f32; 16], - // We need to align this to 256 bytes to please `wgpu`... - // TODO: Be smarter and stop wasting memory! - _padding_a: [f32; 32], - _padding_b: [f32; 16], +fn fragment_target( + texture_format: wgpu::TextureFormat, +) -> Option<wgpu::ColorTargetState> { + Some(wgpu::ColorTargetState { + format: texture_format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + }) +} + +fn primitive_state() -> wgpu::PrimitiveState { + wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Cw, + ..Default::default() + } +} + +fn multisample_state( + antialiasing: Option<settings::Antialiasing>, +) -> wgpu::MultisampleState { + wgpu::MultisampleState { + count: antialiasing.map(|a| a.sample_count()).unwrap_or(1), + mask: !0, + alpha_to_coverage_enabled: false, + } } -impl Default for Uniforms { - fn default() -> Self { - Self { - transform: *Transformation::identity().as_ref(), - _padding_a: [0.0; 32], - _padding_b: [0.0; 16], +mod solid { + use crate::buffer::dynamic; + use crate::buffer::r#static::Buffer; + use crate::settings; + use crate::triangle; + use encase::ShaderType; + use iced_graphics::Transformation; + + #[derive(Debug)] + pub struct Pipeline { + pub pipeline: wgpu::RenderPipeline, + pub vertices: Buffer<triangle::ColoredVertex2D>, + pub uniforms: dynamic::Buffer<Uniforms>, + pub bind_group_layout: wgpu::BindGroupLayout, + pub bind_group: wgpu::BindGroup, + } + + #[derive(Debug, Clone, Copy, ShaderType)] + pub struct Uniforms { + transform: glam::Mat4, + } + + impl Uniforms { + pub fn new(transform: Transformation) -> Self { + Self { + transform: transform.into(), + } + } + } + + impl Pipeline { + /// Creates a new [SolidPipeline] using `solid.wgsl` shader. + pub fn new( + device: &wgpu::Device, + format: wgpu::TextureFormat, + antialiasing: Option<settings::Antialiasing>, + ) -> Self { + let vertices = Buffer::new( + device, + "iced_wgpu::triangle::solid vertex buffer", + wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + ); + + let uniforms = dynamic::Buffer::uniform( + device, + "iced_wgpu::triangle::solid uniforms", + ); + + let bind_group_layout = device.create_bind_group_layout( + &wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu::triangle::solid bind group layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: Some(Uniforms::min_size()), + }, + count: None, + }], + }, + ); + + let bind_group = + Self::bind_group(device, uniforms.raw(), &bind_group_layout); + + let layout = device.create_pipeline_layout( + &wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu::triangle::solid pipeline layout"), + bind_group_layouts: &[&bind_group_layout], + push_constant_ranges: &[], + }, + ); + + let shader = + device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some( + "iced_wgpu::triangle::solid create shader module", + ), + source: wgpu::ShaderSource::Wgsl( + std::borrow::Cow::Borrowed(include_str!( + "shader/solid.wgsl" + )), + ), + }); + + let pipeline = device.create_render_pipeline( + &wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu::triangle::solid pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: "vs_main", + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::< + triangle::ColoredVertex2D, + >() + as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array!( + // Position + 0 => Float32x2, + // Color + 1 => Float32x4, + ), + }], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: "fs_main", + targets: &[triangle::fragment_target(format)], + }), + primitive: triangle::primitive_state(), + depth_stencil: None, + multisample: triangle::multisample_state(antialiasing), + multiview: None, + }, + ); + + Self { + pipeline, + vertices, + uniforms, + bind_group_layout, + bind_group, + } + } + + pub fn bind_group( + device: &wgpu::Device, + buffer: &wgpu::Buffer, + layout: &wgpu::BindGroupLayout, + ) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu::triangle::solid bind group"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer( + wgpu::BufferBinding { + buffer, + offset: 0, + size: Some(Uniforms::min_size()), + }, + ), + }], + }) } } } -impl From<Transformation> for Uniforms { - fn from(transformation: Transformation) -> Uniforms { - Self { - transform: transformation.into(), - _padding_a: [0.0; 32], - _padding_b: [0.0; 16], +#[cfg(not(target_arch = "wasm32"))] +mod gradient { + use crate::buffer::dynamic; + use crate::buffer::r#static::Buffer; + use crate::settings; + use crate::triangle; + + use encase::ShaderType; + use glam::{IVec4, Vec4}; + use iced_graphics::triangle::Vertex2D; + + #[derive(Debug)] + pub struct Pipeline { + pub pipeline: wgpu::RenderPipeline, + pub vertices: Buffer<Vertex2D>, + pub uniforms: dynamic::Buffer<Uniforms>, + pub storage: dynamic::Buffer<Storage>, + pub color_stop_offset: i32, + //Need to store these and then write them all at once + //or else they will be padded to 256 and cause gaps in the storage buffer + pub color_stops_pending_write: Storage, + pub bind_group_layout: wgpu::BindGroupLayout, + pub bind_group: wgpu::BindGroup, + } + + #[derive(Debug, ShaderType)] + pub struct Uniforms { + pub transform: glam::Mat4, + //xy = start, zw = end + pub direction: Vec4, + //x = start stop, y = end stop, zw = padding + pub stop_range: IVec4, + } + + #[derive(Debug, ShaderType)] + pub struct ColorStop { + pub color: Vec4, + pub offset: f32, + } + + #[derive(Debug, ShaderType)] + pub struct Storage { + #[size(runtime)] + pub color_stops: Vec<ColorStop>, + } + + impl Pipeline { + /// Creates a new [GradientPipeline] using `gradient.wgsl` shader. + pub(super) fn new( + device: &wgpu::Device, + format: wgpu::TextureFormat, + antialiasing: Option<settings::Antialiasing>, + ) -> Self { + let vertices = Buffer::new( + device, + "iced_wgpu::triangle::gradient vertex buffer", + wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + ); + + let uniforms = dynamic::Buffer::uniform( + device, + "iced_wgpu::triangle::gradient uniforms", + ); + + //Note: with a WASM target storage buffers are not supported. Will need to use UBOs & static + // sized array (eg like the 32-sized array on OpenGL side right now) to make gradients work + let storage = dynamic::Buffer::storage( + device, + "iced_wgpu::triangle::gradient storage", + ); + + let bind_group_layout = device.create_bind_group_layout( + &wgpu::BindGroupLayoutDescriptor { + label: Some( + "iced_wgpu::triangle::gradient bind group layout", + ), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: Some(Uniforms::min_size()), + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { + read_only: true, + }, + has_dynamic_offset: false, + min_binding_size: Some(Storage::min_size()), + }, + count: None, + }, + ], + }, + ); + + let bind_group = Pipeline::bind_group( + device, + uniforms.raw(), + storage.raw(), + &bind_group_layout, + ); + + let layout = device.create_pipeline_layout( + &wgpu::PipelineLayoutDescriptor { + label: Some( + "iced_wgpu::triangle::gradient pipeline layout", + ), + bind_group_layouts: &[&bind_group_layout], + push_constant_ranges: &[], + }, + ); + + let shader = + device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some( + "iced_wgpu::triangle::gradient create shader module", + ), + source: wgpu::ShaderSource::Wgsl( + std::borrow::Cow::Borrowed(include_str!( + "shader/gradient.wgsl" + )), + ), + }); + + let pipeline = device.create_render_pipeline( + &wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu::triangle::gradient pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: "vs_main", + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<Vertex2D>() + as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array!( + // Position + 0 => Float32x2, + ), + }], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: "fs_main", + targets: &[triangle::fragment_target(format)], + }), + primitive: triangle::primitive_state(), + depth_stencil: None, + multisample: triangle::multisample_state(antialiasing), + multiview: None, + }, + ); + + Self { + pipeline, + vertices, + uniforms, + storage, + color_stop_offset: 0, + color_stops_pending_write: Storage { + color_stops: vec![], + }, + bind_group_layout, + bind_group, + } + } + + pub fn bind_group( + device: &wgpu::Device, + uniform_buffer: &wgpu::Buffer, + storage_buffer: &wgpu::Buffer, + layout: &wgpu::BindGroupLayout, + ) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu::triangle::gradient bind group"), + layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer( + wgpu::BufferBinding { + buffer: uniform_buffer, + offset: 0, + size: Some(Uniforms::min_size()), + }, + ), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: storage_buffer.as_entire_binding(), + }, + ], + }) } } } |