diff --git a/Cargo.toml b/Cargo.toml index f6f1158add..f3b16da1e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,8 @@ categories = ["gui"] [features] # Enables a debug view in native platforms (press F12) debug = ["iced_winit/debug"] +# Enables support for SVG rendering +svg = ["iced_wgpu/svg"] [badges] maintenance = { status = "actively-developed" } diff --git a/examples/resources/tiger.svg b/examples/resources/tiger.svg new file mode 100644 index 0000000000..679edec2eb --- /dev/null +++ b/examples/resources/tiger.svg @@ -0,0 +1,725 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/svg.rs b/examples/svg.rs new file mode 100644 index 0000000000..cdf238f0df --- /dev/null +++ b/examples/svg.rs @@ -0,0 +1,54 @@ +use iced::{Container, Element, Length, Sandbox, Settings}; + +pub fn main() { + Tiger::run(Settings::default()) +} + +#[derive(Default)] +struct Tiger; + +impl Sandbox for Tiger { + type Message = (); + + fn new() -> Self { + Self::default() + } + + fn title(&self) -> String { + String::from("SVG - Iced") + } + + fn update(&mut self, _message: ()) {} + + fn view(&mut self) -> Element<()> { + #[cfg(feature = "svg")] + let content = { + use iced::{Column, Svg}; + + Column::new() + .width(Length::Shrink) + .padding(20) + .push(Svg::new(format!( + "{}/examples/resources/tiger.svg", + env!("CARGO_MANIFEST_DIR") + ))) + }; + + #[cfg(not(feature = "svg"))] + let content = { + use iced::{HorizontalAlignment, Text}; + + Text::new("You need to enable the `svg` feature!") + .width(Length::Shrink) + .horizontal_alignment(HorizontalAlignment::Center) + .size(30) + }; + + Container::new(content) + .width(Length::Fill) + .height(Length::Fill) + .center_x() + .center_y() + .into() + } +} diff --git a/native/src/widget.rs b/native/src/widget.rs index 71dcdc0d74..ee7232cb3a 100644 --- a/native/src/widget.rs +++ b/native/src/widget.rs @@ -24,6 +24,7 @@ pub mod button; pub mod checkbox; pub mod column; pub mod container; +pub mod svg; pub mod image; pub mod radio; pub mod row; @@ -51,6 +52,8 @@ pub use scrollable::Scrollable; #[doc(no_inline)] pub use slider::Slider; #[doc(no_inline)] +pub use svg::Svg; +#[doc(no_inline)] pub use text::Text; #[doc(no_inline)] pub use text_input::TextInput; diff --git a/native/src/widget/svg.rs b/native/src/widget/svg.rs new file mode 100644 index 0000000000..9580f19586 --- /dev/null +++ b/native/src/widget/svg.rs @@ -0,0 +1,187 @@ +//! Display vector graphics in your application. +use crate::{layout, Element, Hasher, Layout, Length, Point, Size, Widget}; + +use std::{ + hash::Hash, + path::{Path, PathBuf}, +}; + +/// A vector graphics image. +/// +/// An [`Svg`] image resizes smoothly without losing any quality. +/// +/// [`Svg`] images can have a considerable rendering cost when resized, +/// specially when they are complex. +/// +/// [`Svg`]: struct.Svg.html +#[derive(Debug, Clone)] +pub struct Svg { + handle: Handle, + width: Length, + height: Length, +} + +impl Svg { + /// Creates a new [`Svg`] from the given [`Handle`]. + /// + /// [`Svg`]: struct.Svg.html + /// [`Handle`]: struct.Handle.html + pub fn new(handle: impl Into) -> Self { + Svg { + handle: handle.into(), + width: Length::Fill, + height: Length::Fill, + } + } + + /// Sets the width of the [`Svg`]. + /// + /// [`Svg`]: struct.Svg.html + pub fn width(mut self, width: Length) -> Self { + self.width = width; + self + } + + /// Sets the height of the [`Svg`]. + /// + /// [`Svg`]: struct.Svg.html + pub fn height(mut self, height: Length) -> Self { + self.height = height; + self + } +} + +impl Widget for Svg +where + Renderer: self::Renderer, +{ + fn width(&self) -> Length { + self.width + } + + fn height(&self) -> Length { + self.height + } + + fn layout( + &self, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let (width, height) = renderer.dimensions(&self.handle); + + let aspect_ratio = width as f32 / height as f32; + + let mut size = limits + .width(self.width) + .height(self.height) + .resolve(Size::new(width as f32, height as f32)); + + let viewport_aspect_ratio = size.width / size.height; + + if viewport_aspect_ratio > aspect_ratio { + size.width = width as f32 * size.height / height as f32; + } else { + size.height = height as f32 * size.width / width as f32; + } + + layout::Node::new(size) + } + + fn draw( + &self, + renderer: &mut Renderer, + layout: Layout<'_>, + _cursor_position: Point, + ) -> Renderer::Output { + renderer.draw(self.handle.clone(), layout) + } + + fn hash_layout(&self, state: &mut Hasher) { + self.width.hash(state); + self.height.hash(state); + } +} + +/// An [`Svg`] handle. +/// +/// [`Svg`]: struct.Svg.html +#[derive(Debug, Clone)] +pub struct Handle { + id: u64, + path: PathBuf, +} + +impl Handle { + /// Creates an SVG [`Handle`] pointing to the vector image of the given + /// path. + /// + /// [`Handle`]: struct.Handle.html + pub fn from_path>(path: T) -> Handle { + use std::hash::Hasher as _; + + let path = path.into(); + + let mut hasher = Hasher::default(); + path.hash(&mut hasher); + + Handle { + id: hasher.finish(), + path, + } + } + + /// Returns the unique identifier of the [`Handle`]. + /// + /// [`Handle`]: struct.Handle.html + pub fn id(&self) -> u64 { + self.id + } + + /// Returns a reference to the path of the [`Handle`]. + /// + /// [`Handle`]: enum.Handle.html + pub fn path(&self) -> &Path { + &self.path + } +} + +impl From for Handle { + fn from(path: String) -> Handle { + Handle::from_path(path) + } +} + +impl From<&str> for Handle { + fn from(path: &str) -> Handle { + Handle::from_path(path) + } +} + +/// The renderer of an [`Svg`]. +/// +/// Your [renderer] will need to implement this trait before being able to use +/// an [`Svg`] in your user interface. +/// +/// [`Svg`]: struct.Svg.html +/// [renderer]: ../../renderer/index.html +pub trait Renderer: crate::Renderer { + /// Returns the default dimensions of an [`Svg`] located on the given path. + /// + /// [`Svg`]: struct.Svg.html + fn dimensions(&self, handle: &Handle) -> (u32, u32); + + /// Draws an [`Svg`]. + /// + /// [`Svg`]: struct.Svg.html + fn draw(&mut self, handle: Handle, layout: Layout<'_>) -> Self::Output; +} + +impl<'a, Message, Renderer> From for Element<'a, Message, Renderer> +where + Renderer: self::Renderer, +{ + fn from(icon: Svg) -> Element<'a, Message, Renderer> { + Element::new(icon) + } +} diff --git a/src/native.rs b/src/native.rs index 3537dd5215..c6ddf25b84 100644 --- a/src/native.rs +++ b/src/native.rs @@ -80,12 +80,17 @@ pub mod widget { pub use iced_winit::image::{Handle, Image}; } + pub mod svg { + //! Display vector graphics in your user interface. + pub use iced_winit::svg::{Handle, Svg}; + } + pub use iced_winit::{Checkbox, Radio, Text}; #[doc(no_inline)] pub use { button::Button, image::Image, scrollable::Scrollable, slider::Slider, - text_input::TextInput, + svg::Svg, text_input::TextInput, }; /// A container that distributes its contents vertically. diff --git a/wgpu/Cargo.toml b/wgpu/Cargo.toml index 47ec053717..bb24191466 100644 --- a/wgpu/Cargo.toml +++ b/wgpu/Cargo.toml @@ -7,6 +7,9 @@ description = "A wgpu renderer for Iced" license = "MIT AND OFL-1.1" repository = "https://github.com/hecrj/iced" +[features] +svg = ["resvg"] + [dependencies] iced_native = { version = "0.1.0", path = "../native" } wgpu = "0.4" @@ -17,3 +20,4 @@ image = "0.22" glam = "0.8" font-kit = "0.4" log = "0.4" +resvg = { version = "0.8", features = ["raqote-backend"], optional = true } diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 7e4e267080..4558ffb060 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -1,19 +1,17 @@ +mod raster; +#[cfg(feature = "svg")] +mod vector; + use crate::Transformation; -use iced_native::{ - image::{Data, Handle}, - Rectangle, -}; - -use std::{ - cell::RefCell, - collections::{HashMap, HashSet}, - mem, - rc::Rc, -}; +use iced_native::{image, svg, Rectangle}; + +use std::{cell::RefCell, mem}; #[derive(Debug)] pub struct Pipeline { - cache: RefCell, + raster_cache: RefCell, + #[cfg(feature = "svg")] + vector_cache: RefCell, pipeline: wgpu::RenderPipeline, uniforms: wgpu::Buffer, @@ -193,7 +191,9 @@ impl Pipeline { }); Pipeline { - cache: RefCell::new(Cache::new()), + raster_cache: RefCell::new(raster::Cache::new()), + #[cfg(feature = "svg")] + vector_cache: RefCell::new(vector::Cache::new()), pipeline, uniforms: uniforms_buffer, @@ -205,37 +205,19 @@ impl Pipeline { } } - pub fn dimensions(&self, handle: &Handle) -> (u32, u32) { - self.load(handle); + pub fn dimensions(&self, handle: &image::Handle) -> (u32, u32) { + let mut cache = self.raster_cache.borrow_mut(); + let memory = cache.load(&handle); - self.cache.borrow_mut().get(handle).unwrap().dimensions() + memory.dimensions() } - fn load(&self, handle: &Handle) { - if !self.cache.borrow().contains(&handle) { - let memory = match handle.data() { - Data::Path(path) => { - if let Ok(image) = image::open(path) { - Memory::Host { - image: image.to_bgra(), - } - } else { - Memory::NotFound - } - } - Data::Bytes(bytes) => { - if let Ok(image) = image::load_from_memory(&bytes) { - Memory::Host { - image: image.to_bgra(), - } - } else { - Memory::Invalid - } - } - }; + #[cfg(feature = "svg")] + pub fn viewport_dimensions(&self, handle: &svg::Handle) -> (u32, u32) { + let mut cache = self.vector_cache.borrow_mut(); + let svg = cache.load(&handle); - let _ = self.cache.borrow_mut().insert(&handle, memory); - } + svg.viewport_dimensions() } pub fn draw( @@ -246,6 +228,7 @@ impl Pipeline { transformation: Transformation, bounds: Rectangle, target: &wgpu::TextureView, + _scale: f32, ) { let uniforms_buffer = device .create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC) @@ -266,15 +249,34 @@ impl Pipeline { // // [1]: https://github.com/nical/guillotiere for image in instances { - self.load(&image.handle); - - if let Some(texture) = self - .cache - .borrow_mut() - .get(&image.handle) - .unwrap() - .upload(device, encoder, &self.texture_layout) - { + let uploaded_texture = match &image.handle { + Handle::Raster(handle) => { + let mut cache = self.raster_cache.borrow_mut(); + let memory = cache.load(&handle); + + memory.upload(device, encoder, &self.texture_layout) + } + Handle::Vector(_handle) => { + #[cfg(feature = "svg")] + { + let mut cache = self.vector_cache.borrow_mut(); + + cache.upload( + _handle, + image.scale, + _scale, + device, + encoder, + &self.texture_layout, + ) + } + + #[cfg(not(feature = "svg"))] + None + } + }; + + if let Some(texture) = uploaded_texture { let instance_buffer = device .create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC) .fill_from_slice(&[Instance { @@ -337,151 +339,10 @@ impl Pipeline { } pub fn trim_cache(&mut self) { - self.cache.borrow_mut().trim(); - } -} - -#[derive(Debug)] -enum Memory { - Host { - image: image::ImageBuffer, Vec>, - }, - Device { - bind_group: Rc, - width: u32, - height: u32, - }, - NotFound, - Invalid, -} - -impl Memory { - fn dimensions(&self) -> (u32, u32) { - match self { - Memory::Host { image } => image.dimensions(), - Memory::Device { width, height, .. } => (*width, *height), - Memory::NotFound => (1, 1), - Memory::Invalid => (1, 1), - } - } - - fn upload( - &mut self, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - texture_layout: &wgpu::BindGroupLayout, - ) -> Option> { - match self { - Memory::Host { image } => { - let (width, height) = image.dimensions(); - - let extent = wgpu::Extent3d { - width, - height, - depth: 1, - }; - - let texture = device.create_texture(&wgpu::TextureDescriptor { - size: extent, - array_layer_count: 1, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Bgra8UnormSrgb, - usage: wgpu::TextureUsage::COPY_DST - | wgpu::TextureUsage::SAMPLED, - }); - - let slice = image.clone().into_raw(); - - let temp_buf = device - .create_buffer_mapped( - slice.len(), - wgpu::BufferUsage::COPY_SRC, - ) - .fill_from_slice(&slice[..]); - - encoder.copy_buffer_to_texture( - wgpu::BufferCopyView { - buffer: &temp_buf, - offset: 0, - row_pitch: 4 * width as u32, - image_height: height as u32, - }, - wgpu::TextureCopyView { - texture: &texture, - array_layer: 0, - mip_level: 0, - origin: wgpu::Origin3d { - x: 0.0, - y: 0.0, - z: 0.0, - }, - }, - extent, - ); - - let bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - layout: texture_layout, - bindings: &[wgpu::Binding { - binding: 0, - resource: wgpu::BindingResource::TextureView( - &texture.create_default_view(), - ), - }], - }); - - let bind_group = Rc::new(bind_group); - - *self = Memory::Device { - bind_group: bind_group.clone(), - width, - height, - }; + self.raster_cache.borrow_mut().trim(); - Some(bind_group) - } - Memory::Device { bind_group, .. } => Some(bind_group.clone()), - Memory::NotFound => None, - Memory::Invalid => None, - } - } -} - -#[derive(Debug)] -struct Cache { - map: HashMap, - hits: HashSet, -} - -impl Cache { - fn new() -> Self { - Self { - map: HashMap::new(), - hits: HashSet::new(), - } - } - - fn contains(&self, handle: &Handle) -> bool { - self.map.contains_key(&handle.id()) - } - - fn get(&mut self, handle: &Handle) -> Option<&mut Memory> { - let _ = self.hits.insert(handle.id()); - - self.map.get_mut(&handle.id()) - } - - fn insert(&mut self, handle: &Handle, memory: Memory) { - let _ = self.map.insert(handle.id(), memory); - } - - fn trim(&mut self) { - let hits = &self.hits; - - self.map.retain(|k, _| hits.contains(k)); - self.hits.clear(); + #[cfg(feature = "svg")] + self.vector_cache.borrow_mut().trim(); } } @@ -491,6 +352,11 @@ pub struct Image { pub scale: [f32; 2], } +pub enum Handle { + Raster(image::Handle), + Vector(svg::Handle), +} + #[repr(C)] #[derive(Clone, Copy)] pub struct Vertex { diff --git a/wgpu/src/image/raster.rs b/wgpu/src/image/raster.rs new file mode 100644 index 0000000000..fa10787977 --- /dev/null +++ b/wgpu/src/image/raster.rs @@ -0,0 +1,176 @@ +use iced_native::image; +use std::{ + collections::{HashMap, HashSet}, + rc::Rc, +}; + +#[derive(Debug)] +pub enum Memory { + Host(::image::ImageBuffer<::image::Bgra, Vec>), + Device { + bind_group: Rc, + width: u32, + height: u32, + }, + NotFound, + Invalid, +} + +impl Memory { + pub fn dimensions(&self) -> (u32, u32) { + match self { + Memory::Host(image) => image.dimensions(), + Memory::Device { width, height, .. } => (*width, *height), + Memory::NotFound => (1, 1), + Memory::Invalid => (1, 1), + } + } + + pub fn upload( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + texture_layout: &wgpu::BindGroupLayout, + ) -> Option> { + match self { + Memory::Host(image) => { + let (width, height) = image.dimensions(); + + let extent = wgpu::Extent3d { + width, + height, + depth: 1, + }; + + let texture = device.create_texture(&wgpu::TextureDescriptor { + size: extent, + array_layer_count: 1, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + usage: wgpu::TextureUsage::COPY_DST + | wgpu::TextureUsage::SAMPLED, + }); + + let temp_buf = { + let flat_samples = image.as_flat_samples(); + let slice = flat_samples.as_slice(); + + device + .create_buffer_mapped( + slice.len(), + wgpu::BufferUsage::COPY_SRC, + ) + .fill_from_slice(slice) + }; + + encoder.copy_buffer_to_texture( + wgpu::BufferCopyView { + buffer: &temp_buf, + offset: 0, + row_pitch: 4 * width as u32, + image_height: height as u32, + }, + wgpu::TextureCopyView { + texture: &texture, + array_layer: 0, + mip_level: 0, + origin: wgpu::Origin3d { + x: 0.0, + y: 0.0, + z: 0.0, + }, + }, + extent, + ); + + let bind_group = + device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: texture_layout, + bindings: &[wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::TextureView( + &texture.create_default_view(), + ), + }], + }); + + let bind_group = Rc::new(bind_group); + + *self = Memory::Device { + bind_group: bind_group.clone(), + width, + height, + }; + + Some(bind_group) + } + Memory::Device { bind_group, .. } => Some(bind_group.clone()), + Memory::NotFound => None, + Memory::Invalid => None, + } + } +} + +#[derive(Debug)] +pub struct Cache { + map: HashMap, + hits: HashSet, +} + +impl Cache { + pub fn new() -> Self { + Self { + map: HashMap::new(), + hits: HashSet::new(), + } + } + + pub fn load(&mut self, handle: &image::Handle) -> &mut Memory { + if self.contains(handle) { + return self.get(handle).unwrap(); + } + + let memory = match handle.data() { + image::Data::Path(path) => { + if let Ok(image) = ::image::open(path) { + Memory::Host(image.to_bgra()) + } else { + Memory::NotFound + } + } + image::Data::Bytes(bytes) => { + if let Ok(image) = ::image::load_from_memory(&bytes) { + Memory::Host(image.to_bgra()) + } else { + Memory::Invalid + } + } + }; + + self.insert(handle, memory); + self.get(handle).unwrap() + } + + pub fn trim(&mut self) { + let hits = &self.hits; + + self.map.retain(|k, _| hits.contains(k)); + self.hits.clear(); + } + + fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory> { + let _ = self.hits.insert(handle.id()); + + self.map.get_mut(&handle.id()) + } + + fn insert(&mut self, handle: &image::Handle, memory: Memory) { + let _ = self.map.insert(handle.id(), memory); + } + + fn contains(&self, handle: &image::Handle) -> bool { + self.map.contains_key(&handle.id()) + } +} diff --git a/wgpu/src/image/vector.rs b/wgpu/src/image/vector.rs new file mode 100644 index 0000000000..aa712372e2 --- /dev/null +++ b/wgpu/src/image/vector.rs @@ -0,0 +1,192 @@ +use iced_native::svg; +use std::{ + collections::{HashMap, HashSet}, + rc::Rc, +}; + +pub enum Svg { + Loaded { tree: resvg::usvg::Tree }, + NotFound, +} + +impl Svg { + pub fn viewport_dimensions(&self) -> (u32, u32) { + match self { + Svg::Loaded { tree } => { + let size = tree.svg_node().size; + + (size.width() as u32, size.height() as u32) + } + Svg::NotFound => (1, 1), + } + } +} + +impl std::fmt::Debug for Svg { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Svg") + } +} + +#[derive(Debug)] +pub struct Cache { + svgs: HashMap, + rasterized: HashMap<(u64, u32, u32), Rc>, + svg_hits: HashSet, + rasterized_hits: HashSet<(u64, u32, u32)>, +} + +impl Cache { + pub fn new() -> Self { + Self { + svgs: HashMap::new(), + rasterized: HashMap::new(), + svg_hits: HashSet::new(), + rasterized_hits: HashSet::new(), + } + } + + pub fn load(&mut self, handle: &svg::Handle) -> &Svg { + if self.svgs.contains_key(&handle.id()) { + return self.svgs.get(&handle.id()).unwrap(); + } + + let opt = resvg::Options::default(); + + let svg = match resvg::usvg::Tree::from_file(handle.path(), &opt.usvg) { + Ok(tree) => Svg::Loaded { tree }, + Err(_) => Svg::NotFound, + }; + + let _ = self.svgs.insert(handle.id(), svg); + self.svgs.get(&handle.id()).unwrap() + } + + pub fn upload( + &mut self, + handle: &svg::Handle, + [width, height]: [f32; 2], + scale: f32, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + texture_layout: &wgpu::BindGroupLayout, + ) -> Option> { + let id = handle.id(); + + let (width, height) = ( + (scale * width).round() as u32, + (scale * height).round() as u32, + ); + + // 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 let Some(bind_group) = self.rasterized.get(&(id, width, height)) { + let _ = self.svg_hits.insert(id); + let _ = self.rasterized_hits.insert((id, width, height)); + + return Some(bind_group.clone()); + } + + match self.load(handle) { + Svg::Loaded { tree } => { + let extent = wgpu::Extent3d { + width, + height, + depth: 1, + }; + + let texture = device.create_texture(&wgpu::TextureDescriptor { + size: extent, + array_layer_count: 1, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + usage: wgpu::TextureUsage::COPY_DST + | wgpu::TextureUsage::SAMPLED, + }); + + let temp_buf = { + let screen_size = + resvg::ScreenSize::new(width, height).unwrap(); + + let mut canvas = resvg::raqote::DrawTarget::new( + width as i32, + height as i32, + ); + + resvg::backend_raqote::render_to_canvas( + &tree, + &resvg::Options::default(), + screen_size, + &mut canvas, + ); + + let slice = canvas.get_data(); + + device + .create_buffer_mapped( + slice.len(), + wgpu::BufferUsage::COPY_SRC, + ) + .fill_from_slice(slice) + }; + + encoder.copy_buffer_to_texture( + wgpu::BufferCopyView { + buffer: &temp_buf, + offset: 0, + row_pitch: 4 * width as u32, + image_height: height as u32, + }, + wgpu::TextureCopyView { + texture: &texture, + array_layer: 0, + mip_level: 0, + origin: wgpu::Origin3d { + x: 0.0, + y: 0.0, + z: 0.0, + }, + }, + extent, + ); + + let bind_group = + device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: texture_layout, + bindings: &[wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::TextureView( + &texture.create_default_view(), + ), + }], + }); + + let bind_group = Rc::new(bind_group); + + let _ = self + .rasterized + .insert((id, width, height), bind_group.clone()); + + let _ = self.svg_hits.insert(id); + let _ = self.rasterized_hits.insert((id, width, height)); + + Some(bind_group) + } + Svg::NotFound => None, + } + } + + pub fn trim(&mut self) { + let svg_hits = &self.svg_hits; + let rasterized_hits = &self.rasterized_hits; + + self.svgs.retain(|k, _| svg_hits.contains(k)); + self.rasterized.retain(|k, _| rasterized_hits.contains(k)); + self.svg_hits.clear(); + self.rasterized_hits.clear(); + } +} diff --git a/wgpu/src/primitive.rs b/wgpu/src/primitive.rs index 04264e5d54..958cc17f65 100644 --- a/wgpu/src/primitive.rs +++ b/wgpu/src/primitive.rs @@ -1,6 +1,6 @@ use iced_native::{ - image, Background, Color, Font, HorizontalAlignment, Rectangle, Vector, - VerticalAlignment, + image, svg, Background, Color, Font, HorizontalAlignment, Rectangle, + Vector, VerticalAlignment, }; /// A rendering primitive. @@ -46,6 +46,14 @@ pub enum Primitive { /// The bounds of the image bounds: Rectangle, }, + /// An SVG primitive + Svg { + /// The path of the SVG file + handle: svg::Handle, + + /// The bounds of the viewport + bounds: Rectangle, + }, /// A clip primitive Clip { /// The bounds of the clip diff --git a/wgpu/src/renderer.rs b/wgpu/src/renderer.rs index fa52bd96e8..365ef1ef4c 100644 --- a/wgpu/src/renderer.rs +++ b/wgpu/src/renderer.rs @@ -1,4 +1,4 @@ -use crate::{quad, text, Image, Primitive, Quad, Transformation}; +use crate::{image, quad, text, Image, Primitive, Quad, Transformation}; use iced_native::{ renderer::{Debugger, Windowed}, Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget, @@ -232,7 +232,14 @@ impl Renderer { } Primitive::Image { handle, bounds } => { layer.images.push(Image { - handle: handle.clone(), + handle: image::Handle::Raster(handle.clone()), + position: [bounds.x, bounds.y], + scale: [bounds.width, bounds.height], + }); + } + Primitive::Svg { handle, bounds } => { + layer.images.push(Image { + handle: image::Handle::Vector(handle.clone()), position: [bounds.x, bounds.y], scale: [bounds.width, bounds.height], }); @@ -342,6 +349,7 @@ impl Renderer { translated_and_scaled, bounds, target, + dpi, ); } diff --git a/wgpu/src/renderer/widget.rs b/wgpu/src/renderer/widget.rs index 52410bee43..91f107e829 100644 --- a/wgpu/src/renderer/widget.rs +++ b/wgpu/src/renderer/widget.rs @@ -8,3 +8,6 @@ mod scrollable; mod slider; mod text; mod text_input; + +#[cfg(feature = "svg")] +mod svg; diff --git a/wgpu/src/renderer/widget/svg.rs b/wgpu/src/renderer/widget/svg.rs new file mode 100644 index 0000000000..67bc3fe1f0 --- /dev/null +++ b/wgpu/src/renderer/widget/svg.rs @@ -0,0 +1,22 @@ +use crate::{Primitive, Renderer}; +use iced_native::{svg, Layout, MouseCursor}; + +impl svg::Renderer for Renderer { + fn dimensions(&self, handle: &svg::Handle) -> (u32, u32) { + self.image_pipeline.viewport_dimensions(handle) + } + + fn draw( + &mut self, + handle: svg::Handle, + layout: Layout<'_>, + ) -> Self::Output { + ( + Primitive::Svg { + handle, + bounds: layout.bounds(), + }, + MouseCursor::OutOfBounds, + ) + } +} diff --git a/wgpu/src/text/font.rs b/wgpu/src/text/font.rs index 31df5bf404..7346ccdb45 100644 --- a/wgpu/src/text/font.rs +++ b/wgpu/src/text/font.rs @@ -1,5 +1,6 @@ -pub use font_kit::error::SelectionError as LoadError; -pub use font_kit::family_name::FamilyName as Family; +pub use font_kit::{ + error::SelectionError as LoadError, family_name::FamilyName as Family, +}; pub struct Source { raw: font_kit::source::SystemSource,