Merged svg pipeline into image
This commit is contained in:
parent
f737c6da24
commit
895eaef99b
8 changed files with 92 additions and 656 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
//! Display an icon.
|
//! Display an icon.
|
||||||
use crate::{
|
use crate::{
|
||||||
layout, Element, Hasher, Layout, Length, Point, Rectangle, Widget,
|
image, layout, Element, Hasher, Layout, Length, Point, Rectangle, Widget,
|
||||||
};
|
};
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
|
@ -11,7 +11,7 @@ use std::{
|
||||||
/// A simple icon_loader widget.
|
/// A simple icon_loader widget.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Icon {
|
pub struct Icon {
|
||||||
path: PathBuf,
|
handle: image::Handle,
|
||||||
size: Length,
|
size: Length,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -21,7 +21,7 @@ impl Icon {
|
||||||
/// [`Icon`]: struct.Icon.html
|
/// [`Icon`]: struct.Icon.html
|
||||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||||
Icon {
|
Icon {
|
||||||
path: path.into(),
|
handle: image::Handle::from_path(path),
|
||||||
size: Length::Fill,
|
size: Length::Fill,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -37,7 +37,7 @@ impl Icon {
|
||||||
|
|
||||||
impl<Message, Renderer> Widget<Message, Renderer> for Icon
|
impl<Message, Renderer> Widget<Message, Renderer> for Icon
|
||||||
where
|
where
|
||||||
Renderer: self::Renderer,
|
Renderer: image::Renderer,
|
||||||
{
|
{
|
||||||
fn width(&self) -> Length {
|
fn width(&self) -> Length {
|
||||||
self.size
|
self.size
|
||||||
|
|
@ -65,9 +65,7 @@ where
|
||||||
layout: Layout<'_>,
|
layout: Layout<'_>,
|
||||||
_cursor_position: Point,
|
_cursor_position: Point,
|
||||||
) -> Renderer::Output {
|
) -> Renderer::Output {
|
||||||
let bounds = layout.bounds();
|
renderer.draw(self.handle.clone(), layout)
|
||||||
|
|
||||||
renderer.draw(bounds, self.path.as_path())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hash_layout(&self, state: &mut Hasher) {
|
fn hash_layout(&self, state: &mut Hasher) {
|
||||||
|
|
@ -75,24 +73,9 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The renderer of an [`Icon`].
|
|
||||||
///
|
|
||||||
/// Your [renderer] will need to implement this trait before being
|
|
||||||
/// able to use [`Icon`] in your [`UserInterface`].
|
|
||||||
///
|
|
||||||
/// [`Icon`]: struct.Icon.html
|
|
||||||
/// [renderer]: ../../renderer/index.html
|
|
||||||
/// [`UserInterface`]: ../../struct.UserInterface.html
|
|
||||||
pub trait Renderer: crate::Renderer {
|
|
||||||
/// Draws an [`Icon`].
|
|
||||||
///
|
|
||||||
/// [`Icon`]: struct.Icon.html
|
|
||||||
fn draw(&mut self, bounds: Rectangle, path: &Path) -> Self::Output;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, Message, Renderer> From<Icon> for Element<'a, Message, Renderer>
|
impl<'a, Message, Renderer> From<Icon> for Element<'a, Message, Renderer>
|
||||||
where
|
where
|
||||||
Renderer: self::Renderer,
|
Renderer: image::Renderer,
|
||||||
{
|
{
|
||||||
fn from(icon: Icon) -> Element<'a, Message, Renderer> {
|
fn from(icon: Icon) -> Element<'a, Message, Renderer> {
|
||||||
Element::new(icon)
|
Element::new(icon)
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ use iced_native::{
|
||||||
use std::{
|
use std::{
|
||||||
cell::RefCell,
|
cell::RefCell,
|
||||||
collections::{HashMap, HashSet},
|
collections::{HashMap, HashSet},
|
||||||
|
fmt,
|
||||||
mem,
|
mem,
|
||||||
rc::Rc,
|
rc::Rc,
|
||||||
};
|
};
|
||||||
|
|
@ -215,19 +216,27 @@ impl Pipeline {
|
||||||
if !self.cache.borrow().contains(&handle) {
|
if !self.cache.borrow().contains(&handle) {
|
||||||
let memory = match handle.data() {
|
let memory = match handle.data() {
|
||||||
Data::Path(path) => {
|
Data::Path(path) => {
|
||||||
if let Ok(image) = image::open(path) {
|
if let Some(ext) = path.extension() {
|
||||||
Memory::Host {
|
if ext == "svg" || ext == "svgz" || ext == "SVG" || ext == "SVGZ" {
|
||||||
image: image.to_bgra(),
|
let opt = resvg::Options::default();
|
||||||
|
match resvg::usvg::Tree::from_file(path, &opt.usvg) {
|
||||||
|
Ok(tree) => Memory::Host(HostMemory::Svg(tree)),
|
||||||
|
Err(_) => Memory::Invalid,
|
||||||
}
|
}
|
||||||
|
} else if let Ok(image) = image::open(path) {
|
||||||
|
Memory::Host(HostMemory::Image(image.to_bgra()))
|
||||||
|
} else {
|
||||||
|
Memory::NotFound
|
||||||
|
}
|
||||||
|
} else if let Ok(image) = image::open(path) {
|
||||||
|
Memory::Host(HostMemory::Image(image.to_bgra()))
|
||||||
} else {
|
} else {
|
||||||
Memory::NotFound
|
Memory::NotFound
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Data::Bytes(bytes) => {
|
Data::Bytes(bytes) => {
|
||||||
if let Ok(image) = image::load_from_memory(&bytes) {
|
if let Ok(image) = image::load_from_memory(&bytes) {
|
||||||
Memory::Host {
|
Memory::Host(HostMemory::Image(image.to_bgra()))
|
||||||
image: image.to_bgra(),
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
Memory::Invalid
|
Memory::Invalid
|
||||||
}
|
}
|
||||||
|
|
@ -246,6 +255,7 @@ impl Pipeline {
|
||||||
transformation: Transformation,
|
transformation: Transformation,
|
||||||
bounds: Rectangle<u32>,
|
bounds: Rectangle<u32>,
|
||||||
target: &wgpu::TextureView,
|
target: &wgpu::TextureView,
|
||||||
|
dpi: f32,
|
||||||
) {
|
) {
|
||||||
let uniforms_buffer = device
|
let uniforms_buffer = device
|
||||||
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC)
|
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC)
|
||||||
|
|
@ -273,7 +283,13 @@ impl Pipeline {
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.get(&image.handle)
|
.get(&image.handle)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.upload(device, encoder, &self.texture_layout)
|
.upload(
|
||||||
|
device,
|
||||||
|
encoder,
|
||||||
|
&self.texture_layout,
|
||||||
|
(image.scale[0] * dpi) as u32,
|
||||||
|
(image.scale[1] * dpi) as u32,
|
||||||
|
)
|
||||||
{
|
{
|
||||||
let instance_buffer = device
|
let instance_buffer = device
|
||||||
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC)
|
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC)
|
||||||
|
|
@ -341,11 +357,26 @@ impl Pipeline {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum HostMemory {
|
||||||
|
Image(image::ImageBuffer<image::Bgra<u8>, Vec<u8>>),
|
||||||
|
Svg(resvg::usvg::Tree),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for HostMemory {
|
||||||
|
fn fmt(
|
||||||
|
&self,
|
||||||
|
f: &mut fmt::Formatter<'_>,
|
||||||
|
) -> Result<(), fmt::Error> {
|
||||||
|
match self {
|
||||||
|
HostMemory::Image(_) => write!(f, "HostMemory::Image"),
|
||||||
|
HostMemory::Svg(_) => write!(f, "HostMemory::Svg"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum Memory {
|
enum Memory {
|
||||||
Host {
|
Host(HostMemory),
|
||||||
image: image::ImageBuffer<image::Bgra<u8>, Vec<u8>>,
|
|
||||||
},
|
|
||||||
Device {
|
Device {
|
||||||
bind_group: Rc<wgpu::BindGroup>,
|
bind_group: Rc<wgpu::BindGroup>,
|
||||||
width: u32,
|
width: u32,
|
||||||
|
|
@ -358,7 +389,13 @@ enum Memory {
|
||||||
impl Memory {
|
impl Memory {
|
||||||
fn dimensions(&self) -> (u32, u32) {
|
fn dimensions(&self) -> (u32, u32) {
|
||||||
match self {
|
match self {
|
||||||
Memory::Host { image } => image.dimensions(),
|
Memory::Host(host_memory) => match host_memory {
|
||||||
|
HostMemory::Image(image) => image.dimensions(),
|
||||||
|
HostMemory::Svg(tree) => {
|
||||||
|
let size = tree.svg_node().size;
|
||||||
|
(size.width() as u32, size.height() as u32)
|
||||||
|
}
|
||||||
|
}
|
||||||
Memory::Device { width, height, .. } => (*width, *height),
|
Memory::Device { width, height, .. } => (*width, *height),
|
||||||
Memory::NotFound => (1, 1),
|
Memory::NotFound => (1, 1),
|
||||||
Memory::Invalid => (1, 1),
|
Memory::Invalid => (1, 1),
|
||||||
|
|
@ -370,10 +407,15 @@ impl Memory {
|
||||||
device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
encoder: &mut wgpu::CommandEncoder,
|
encoder: &mut wgpu::CommandEncoder,
|
||||||
texture_layout: &wgpu::BindGroupLayout,
|
texture_layout: &wgpu::BindGroupLayout,
|
||||||
|
svg_width: u32,
|
||||||
|
svg_height: u32,
|
||||||
) -> Option<Rc<wgpu::BindGroup>> {
|
) -> Option<Rc<wgpu::BindGroup>> {
|
||||||
match self {
|
match self {
|
||||||
Memory::Host { image } => {
|
Memory::Host(host_memory) => {
|
||||||
let (width, height) = image.dimensions();
|
let (width, height) = match host_memory {
|
||||||
|
HostMemory::Image(image) => image.dimensions(),
|
||||||
|
HostMemory::Svg(_) => (svg_width, svg_height),
|
||||||
|
};
|
||||||
|
|
||||||
let extent = wgpu::Extent3d {
|
let extent = wgpu::Extent3d {
|
||||||
width,
|
width,
|
||||||
|
|
@ -392,14 +434,37 @@ impl Memory {
|
||||||
| wgpu::TextureUsage::SAMPLED,
|
| wgpu::TextureUsage::SAMPLED,
|
||||||
});
|
});
|
||||||
|
|
||||||
let slice = image.clone().into_raw();
|
let temp_buf = match host_memory {
|
||||||
|
HostMemory::Image(image) => {
|
||||||
let temp_buf = device
|
let flat_samples = image.as_flat_samples();
|
||||||
.create_buffer_mapped(
|
let slice = flat_samples.as_slice();
|
||||||
|
device.create_buffer_mapped(
|
||||||
slice.len(),
|
slice.len(),
|
||||||
wgpu::BufferUsage::COPY_SRC,
|
wgpu::BufferUsage::COPY_SRC,
|
||||||
)
|
)
|
||||||
.fill_from_slice(&slice[..]);
|
.fill_from_slice(slice)
|
||||||
|
},
|
||||||
|
HostMemory::Svg(tree) => {
|
||||||
|
let mut canvas =
|
||||||
|
resvg::raqote::DrawTarget::new(width as i32, height as i32);
|
||||||
|
let opt = resvg::Options::default();
|
||||||
|
let screen_size =
|
||||||
|
resvg::ScreenSize::new(width, height).unwrap();
|
||||||
|
resvg::backend_raqote::render_to_canvas(
|
||||||
|
tree,
|
||||||
|
&opt,
|
||||||
|
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(
|
encoder.copy_buffer_to_texture(
|
||||||
wgpu::BufferCopyView {
|
wgpu::BufferCopyView {
|
||||||
|
|
|
||||||
|
|
@ -28,13 +28,11 @@ mod image;
|
||||||
mod primitive;
|
mod primitive;
|
||||||
mod quad;
|
mod quad;
|
||||||
mod renderer;
|
mod renderer;
|
||||||
mod svg;
|
|
||||||
mod text;
|
mod text;
|
||||||
mod transformation;
|
mod transformation;
|
||||||
|
|
||||||
pub(crate) use crate::image::Image;
|
pub(crate) use crate::image::Image;
|
||||||
pub(crate) use quad::Quad;
|
pub(crate) use quad::Quad;
|
||||||
pub(crate) use svg::Svg;
|
|
||||||
pub(crate) use transformation::Transformation;
|
pub(crate) use transformation::Transformation;
|
||||||
|
|
||||||
pub use primitive::Primitive;
|
pub use primitive::Primitive;
|
||||||
|
|
|
||||||
|
|
@ -46,13 +46,6 @@ pub enum Primitive {
|
||||||
/// The bounds of the image
|
/// The bounds of the image
|
||||||
bounds: Rectangle,
|
bounds: Rectangle,
|
||||||
},
|
},
|
||||||
/// A svg icon primitive
|
|
||||||
Svg {
|
|
||||||
/// The path of the icon
|
|
||||||
handle: crate::svg::Handle,
|
|
||||||
/// The bounds of the icon
|
|
||||||
bounds: Rectangle,
|
|
||||||
},
|
|
||||||
/// A clip primitive
|
/// A clip primitive
|
||||||
Clip {
|
Clip {
|
||||||
/// The bounds of the clip
|
/// The bounds of the clip
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
use crate::{quad, text, Image, Primitive, Quad, Svg, Transformation};
|
use crate::{quad, text, Image, Primitive, Quad, Transformation};
|
||||||
use iced_native::{
|
use iced_native::{
|
||||||
renderer::{Debugger, Windowed},
|
renderer::{Debugger, Windowed},
|
||||||
Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget,
|
Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget,
|
||||||
|
|
@ -23,7 +23,6 @@ pub struct Renderer {
|
||||||
queue: Queue,
|
queue: Queue,
|
||||||
quad_pipeline: quad::Pipeline,
|
quad_pipeline: quad::Pipeline,
|
||||||
image_pipeline: crate::image::Pipeline,
|
image_pipeline: crate::image::Pipeline,
|
||||||
svg_pipeline: crate::svg::Pipeline,
|
|
||||||
text_pipeline: text::Pipeline,
|
text_pipeline: text::Pipeline,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -32,7 +31,6 @@ struct Layer<'a> {
|
||||||
offset: Vector<u32>,
|
offset: Vector<u32>,
|
||||||
quads: Vec<Quad>,
|
quads: Vec<Quad>,
|
||||||
images: Vec<Image>,
|
images: Vec<Image>,
|
||||||
svgs: Vec<Svg>,
|
|
||||||
text: Vec<wgpu_glyph::Section<'a>>,
|
text: Vec<wgpu_glyph::Section<'a>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -43,7 +41,6 @@ impl<'a> Layer<'a> {
|
||||||
offset,
|
offset,
|
||||||
quads: Vec::new(),
|
quads: Vec::new(),
|
||||||
images: Vec::new(),
|
images: Vec::new(),
|
||||||
svgs: Vec::new(),
|
|
||||||
text: Vec::new(),
|
text: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -67,14 +64,12 @@ impl Renderer {
|
||||||
let text_pipeline = text::Pipeline::new(&mut device);
|
let text_pipeline = text::Pipeline::new(&mut device);
|
||||||
let quad_pipeline = quad::Pipeline::new(&mut device);
|
let quad_pipeline = quad::Pipeline::new(&mut device);
|
||||||
let image_pipeline = crate::image::Pipeline::new(&mut device);
|
let image_pipeline = crate::image::Pipeline::new(&mut device);
|
||||||
let svg_pipeline = crate::svg::Pipeline::new(&mut device);
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
device,
|
device,
|
||||||
queue,
|
queue,
|
||||||
quad_pipeline,
|
quad_pipeline,
|
||||||
image_pipeline,
|
image_pipeline,
|
||||||
svg_pipeline,
|
|
||||||
text_pipeline,
|
text_pipeline,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -133,7 +128,6 @@ impl Renderer {
|
||||||
|
|
||||||
self.queue.submit(&[encoder.finish()]);
|
self.queue.submit(&[encoder.finish()]);
|
||||||
self.image_pipeline.trim_cache();
|
self.image_pipeline.trim_cache();
|
||||||
self.svg_pipeline.trim_cache();
|
|
||||||
|
|
||||||
*mouse_cursor
|
*mouse_cursor
|
||||||
}
|
}
|
||||||
|
|
@ -243,11 +237,6 @@ impl Renderer {
|
||||||
scale: [bounds.width, bounds.height],
|
scale: [bounds.width, bounds.height],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Primitive::Svg { handle, bounds } => layer.svgs.push(Svg {
|
|
||||||
handle: handle.clone(),
|
|
||||||
position: [bounds.x, bounds.y],
|
|
||||||
scale: [bounds.width, bounds.height],
|
|
||||||
}),
|
|
||||||
Primitive::Clip {
|
Primitive::Clip {
|
||||||
bounds,
|
bounds,
|
||||||
offset,
|
offset,
|
||||||
|
|
@ -353,23 +342,6 @@ impl Renderer {
|
||||||
translated_and_scaled,
|
translated_and_scaled,
|
||||||
bounds,
|
bounds,
|
||||||
target,
|
target,
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if layer.svgs.len() > 0 {
|
|
||||||
let translated = transformation
|
|
||||||
* Transformation::translate(
|
|
||||||
-(layer.offset.x as f32),
|
|
||||||
-(layer.offset.y as f32),
|
|
||||||
);
|
|
||||||
|
|
||||||
self.svg_pipeline.draw(
|
|
||||||
&mut self.device,
|
|
||||||
encoder,
|
|
||||||
&layer.svgs,
|
|
||||||
translated,
|
|
||||||
bounds,
|
|
||||||
target,
|
|
||||||
dpi,
|
dpi,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
mod button;
|
mod button;
|
||||||
mod checkbox;
|
mod checkbox;
|
||||||
mod column;
|
mod column;
|
||||||
mod icon;
|
|
||||||
mod image;
|
mod image;
|
||||||
mod radio;
|
mod radio;
|
||||||
mod row;
|
mod row;
|
||||||
|
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
use crate::{svg::Handle, Primitive, Renderer};
|
|
||||||
use iced_native::{icon, MouseCursor, Rectangle};
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
impl icon::Renderer for Renderer {
|
|
||||||
fn draw(&mut self, bounds: Rectangle, path: &Path) -> Self::Output {
|
|
||||||
(
|
|
||||||
Primitive::Svg {
|
|
||||||
handle: Handle::from_path(path),
|
|
||||||
bounds,
|
|
||||||
},
|
|
||||||
MouseCursor::OutOfBounds,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
559
wgpu/src/svg.rs
559
wgpu/src/svg.rs
|
|
@ -1,559 +0,0 @@
|
||||||
use crate::Transformation;
|
|
||||||
use iced_native::{Hasher, Rectangle};
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
cell::RefCell,
|
|
||||||
collections::{HashMap, HashSet},
|
|
||||||
fmt::Debug,
|
|
||||||
hash::{Hash, Hasher as _},
|
|
||||||
mem,
|
|
||||||
path::PathBuf,
|
|
||||||
rc::Rc,
|
|
||||||
u32,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Pipeline {
|
|
||||||
cache: RefCell<Cache>,
|
|
||||||
|
|
||||||
pipeline: wgpu::RenderPipeline,
|
|
||||||
uniforms: wgpu::Buffer,
|
|
||||||
vertices: wgpu::Buffer,
|
|
||||||
indices: wgpu::Buffer,
|
|
||||||
instances: wgpu::Buffer,
|
|
||||||
constants: wgpu::BindGroup,
|
|
||||||
texture_layout: wgpu::BindGroupLayout,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Pipeline {
|
|
||||||
pub fn new(device: &wgpu::Device) -> Self {
|
|
||||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
|
||||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
|
||||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
|
||||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
|
||||||
mag_filter: wgpu::FilterMode::Linear,
|
|
||||||
min_filter: wgpu::FilterMode::Linear,
|
|
||||||
mipmap_filter: wgpu::FilterMode::Linear,
|
|
||||||
lod_min_clamp: -100.0,
|
|
||||||
lod_max_clamp: 100.0,
|
|
||||||
compare_function: wgpu::CompareFunction::Always,
|
|
||||||
});
|
|
||||||
|
|
||||||
let constant_layout =
|
|
||||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
||||||
bindings: &[
|
|
||||||
wgpu::BindGroupLayoutBinding {
|
|
||||||
binding: 0,
|
|
||||||
visibility: wgpu::ShaderStage::VERTEX,
|
|
||||||
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
|
|
||||||
},
|
|
||||||
wgpu::BindGroupLayoutBinding {
|
|
||||||
binding: 1,
|
|
||||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
|
||||||
ty: wgpu::BindingType::Sampler,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
let uniforms = Uniforms {
|
|
||||||
transform: Transformation::identity().into(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let uniforms_buffer = device
|
|
||||||
.create_buffer_mapped(
|
|
||||||
1,
|
|
||||||
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
|
|
||||||
)
|
|
||||||
.fill_from_slice(&[uniforms]);
|
|
||||||
|
|
||||||
let constant_bind_group =
|
|
||||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
||||||
layout: &constant_layout,
|
|
||||||
bindings: &[
|
|
||||||
wgpu::Binding {
|
|
||||||
binding: 0,
|
|
||||||
resource: wgpu::BindingResource::Buffer {
|
|
||||||
buffer: &uniforms_buffer,
|
|
||||||
range: 0..std::mem::size_of::<Uniforms>() as u64,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
wgpu::Binding {
|
|
||||||
binding: 1,
|
|
||||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
let texture_layout =
|
|
||||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
||||||
bindings: &[wgpu::BindGroupLayoutBinding {
|
|
||||||
binding: 0,
|
|
||||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
|
||||||
ty: wgpu::BindingType::SampledTexture {
|
|
||||||
multisampled: false,
|
|
||||||
dimension: wgpu::TextureViewDimension::D2,
|
|
||||||
},
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
|
|
||||||
let layout =
|
|
||||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
|
||||||
bind_group_layouts: &[&constant_layout, &texture_layout],
|
|
||||||
});
|
|
||||||
|
|
||||||
let vs = include_bytes!("shader/image.vert.spv");
|
|
||||||
let vs_module = device.create_shader_module(
|
|
||||||
&wgpu::read_spirv(std::io::Cursor::new(&vs[..]))
|
|
||||||
.expect("Read image vertex shader as SPIR-V"),
|
|
||||||
);
|
|
||||||
|
|
||||||
let fs = include_bytes!("shader/image.frag.spv");
|
|
||||||
let fs_module = device.create_shader_module(
|
|
||||||
&wgpu::read_spirv(std::io::Cursor::new(&fs[..]))
|
|
||||||
.expect("Read image fragment shader as SPIR-V"),
|
|
||||||
);
|
|
||||||
|
|
||||||
let pipeline =
|
|
||||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
|
||||||
layout: &layout,
|
|
||||||
vertex_stage: wgpu::ProgrammableStageDescriptor {
|
|
||||||
module: &vs_module,
|
|
||||||
entry_point: "main",
|
|
||||||
},
|
|
||||||
fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
|
|
||||||
module: &fs_module,
|
|
||||||
entry_point: "main",
|
|
||||||
}),
|
|
||||||
rasterization_state: Some(wgpu::RasterizationStateDescriptor {
|
|
||||||
front_face: wgpu::FrontFace::Cw,
|
|
||||||
cull_mode: wgpu::CullMode::None,
|
|
||||||
depth_bias: 0,
|
|
||||||
depth_bias_slope_scale: 0.0,
|
|
||||||
depth_bias_clamp: 0.0,
|
|
||||||
}),
|
|
||||||
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
|
|
||||||
color_states: &[wgpu::ColorStateDescriptor {
|
|
||||||
format: wgpu::TextureFormat::Bgra8UnormSrgb,
|
|
||||||
color_blend: wgpu::BlendDescriptor {
|
|
||||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
|
||||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
|
||||||
operation: wgpu::BlendOperation::Add,
|
|
||||||
},
|
|
||||||
alpha_blend: wgpu::BlendDescriptor {
|
|
||||||
src_factor: wgpu::BlendFactor::One,
|
|
||||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
|
||||||
operation: wgpu::BlendOperation::Add,
|
|
||||||
},
|
|
||||||
write_mask: wgpu::ColorWrite::ALL,
|
|
||||||
}],
|
|
||||||
depth_stencil_state: None,
|
|
||||||
index_format: wgpu::IndexFormat::Uint16,
|
|
||||||
vertex_buffers: &[
|
|
||||||
wgpu::VertexBufferDescriptor {
|
|
||||||
stride: mem::size_of::<Vertex>() as u64,
|
|
||||||
step_mode: wgpu::InputStepMode::Vertex,
|
|
||||||
attributes: &[wgpu::VertexAttributeDescriptor {
|
|
||||||
shader_location: 0,
|
|
||||||
format: wgpu::VertexFormat::Float2,
|
|
||||||
offset: 0,
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
wgpu::VertexBufferDescriptor {
|
|
||||||
stride: mem::size_of::<Instance>() as u64,
|
|
||||||
step_mode: wgpu::InputStepMode::Instance,
|
|
||||||
attributes: &[
|
|
||||||
wgpu::VertexAttributeDescriptor {
|
|
||||||
shader_location: 1,
|
|
||||||
format: wgpu::VertexFormat::Float2,
|
|
||||||
offset: 0,
|
|
||||||
},
|
|
||||||
wgpu::VertexAttributeDescriptor {
|
|
||||||
shader_location: 2,
|
|
||||||
format: wgpu::VertexFormat::Float2,
|
|
||||||
offset: 4 * 2,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
sample_count: 1,
|
|
||||||
sample_mask: !0,
|
|
||||||
alpha_to_coverage_enabled: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
let vertices = device
|
|
||||||
.create_buffer_mapped(QUAD_VERTS.len(), wgpu::BufferUsage::VERTEX)
|
|
||||||
.fill_from_slice(&QUAD_VERTS);
|
|
||||||
|
|
||||||
let indices = device
|
|
||||||
.create_buffer_mapped(QUAD_INDICES.len(), wgpu::BufferUsage::INDEX)
|
|
||||||
.fill_from_slice(&QUAD_INDICES);
|
|
||||||
|
|
||||||
let instances = device.create_buffer(&wgpu::BufferDescriptor {
|
|
||||||
size: mem::size_of::<Instance>() as u64,
|
|
||||||
usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST,
|
|
||||||
});
|
|
||||||
|
|
||||||
Pipeline {
|
|
||||||
cache: RefCell::new(Cache::new()),
|
|
||||||
|
|
||||||
pipeline,
|
|
||||||
uniforms: uniforms_buffer,
|
|
||||||
vertices,
|
|
||||||
indices,
|
|
||||||
instances,
|
|
||||||
constants: constant_bind_group,
|
|
||||||
texture_layout,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load(&self, handle: &Handle) {
|
|
||||||
if !self.cache.borrow().contains(&handle) {
|
|
||||||
if !handle.path.is_file() {
|
|
||||||
let mem = Memory::NotFound;
|
|
||||||
|
|
||||||
let _ = self.cache.borrow_mut().insert(&handle, mem);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut opt = resvg::Options::default();
|
|
||||||
opt.usvg.path = Some(handle.path.clone());
|
|
||||||
|
|
||||||
let mem =
|
|
||||||
match resvg::usvg::Tree::from_file(&handle.path, &opt.usvg) {
|
|
||||||
Ok(tree) => Memory::Host { tree },
|
|
||||||
Err(_) => Memory::Invalid,
|
|
||||||
};
|
|
||||||
|
|
||||||
let _ = self.cache.borrow_mut().insert(&handle, mem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn draw(
|
|
||||||
&mut self,
|
|
||||||
device: &mut wgpu::Device,
|
|
||||||
encoder: &mut wgpu::CommandEncoder,
|
|
||||||
svgs: &[Svg],
|
|
||||||
transformation: Transformation,
|
|
||||||
bounds: Rectangle<u32>,
|
|
||||||
target: &wgpu::TextureView,
|
|
||||||
dpi: f32,
|
|
||||||
) {
|
|
||||||
let uniforms_buffer = device
|
|
||||||
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC)
|
|
||||||
.fill_from_slice(&[Uniforms {
|
|
||||||
transform: transformation.into(),
|
|
||||||
}]);
|
|
||||||
|
|
||||||
encoder.copy_buffer_to_buffer(
|
|
||||||
&uniforms_buffer,
|
|
||||||
0,
|
|
||||||
&self.uniforms,
|
|
||||||
0,
|
|
||||||
std::mem::size_of::<Uniforms>() as u64,
|
|
||||||
);
|
|
||||||
|
|
||||||
// TODO: Batch draw calls using a texture atlas
|
|
||||||
// Guillotière[1] by @nical can help us a lot here.
|
|
||||||
//
|
|
||||||
// [1]: https://github.com/nical/guillotiere
|
|
||||||
for svg in svgs {
|
|
||||||
self.load(&svg.handle);
|
|
||||||
|
|
||||||
if let Some(texture) =
|
|
||||||
self.cache.borrow_mut().get(&svg.handle).unwrap().upload(
|
|
||||||
device,
|
|
||||||
encoder,
|
|
||||||
&self.texture_layout,
|
|
||||||
(svg.scale[0] * dpi) as u32,
|
|
||||||
(svg.scale[1] * dpi) as u32,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
let instance_buffer = device
|
|
||||||
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC)
|
|
||||||
.fill_from_slice(&[Instance {
|
|
||||||
_position: svg.position,
|
|
||||||
_scale: svg.scale,
|
|
||||||
}]);
|
|
||||||
|
|
||||||
encoder.copy_buffer_to_buffer(
|
|
||||||
&instance_buffer,
|
|
||||||
0,
|
|
||||||
&self.instances,
|
|
||||||
0,
|
|
||||||
mem::size_of::<Instance>() as u64,
|
|
||||||
);
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut render_pass = encoder.begin_render_pass(
|
|
||||||
&wgpu::RenderPassDescriptor {
|
|
||||||
color_attachments: &[
|
|
||||||
wgpu::RenderPassColorAttachmentDescriptor {
|
|
||||||
attachment: target,
|
|
||||||
resolve_target: None,
|
|
||||||
load_op: wgpu::LoadOp::Load,
|
|
||||||
store_op: wgpu::StoreOp::Store,
|
|
||||||
clear_color: wgpu::Color::TRANSPARENT,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
depth_stencil_attachment: None,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
render_pass.set_pipeline(&self.pipeline);
|
|
||||||
render_pass.set_bind_group(0, &self.constants, &[]);
|
|
||||||
render_pass.set_bind_group(1, &texture, &[]);
|
|
||||||
render_pass.set_index_buffer(&self.indices, 0);
|
|
||||||
render_pass.set_vertex_buffers(
|
|
||||||
0,
|
|
||||||
&[(&self.vertices, 0), (&self.instances, 0)],
|
|
||||||
);
|
|
||||||
render_pass.set_scissor_rect(
|
|
||||||
bounds.x,
|
|
||||||
bounds.y,
|
|
||||||
bounds.width,
|
|
||||||
bounds.height,
|
|
||||||
);
|
|
||||||
|
|
||||||
render_pass.draw_indexed(
|
|
||||||
0..QUAD_INDICES.len() as u32,
|
|
||||||
0,
|
|
||||||
0..1 as u32,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn trim_cache(&mut self) {
|
|
||||||
self.cache.borrow_mut().trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct Handle {
|
|
||||||
id: u64,
|
|
||||||
path: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Handle {
|
|
||||||
/// Returns the unique id of this [`Handle`]
|
|
||||||
///
|
|
||||||
/// [`Handle`]: struct.Handle.html
|
|
||||||
pub fn id(&self) -> u64 {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a svg [`Handle`] pointing to the svg icon of the given path.
|
|
||||||
///
|
|
||||||
/// [`Handle`]: struct.Handle.html
|
|
||||||
pub fn from_path<T: Into<PathBuf>>(path: T) -> Handle {
|
|
||||||
let path = path.into();
|
|
||||||
let mut hasher = Hasher::default();
|
|
||||||
path.hash(&mut hasher);
|
|
||||||
|
|
||||||
Self {
|
|
||||||
id: hasher.finish(),
|
|
||||||
path,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Hash for Handle {
|
|
||||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
self.id.hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum Memory {
|
|
||||||
Host { tree: resvg::usvg::Tree },
|
|
||||||
Device { bind_group: Rc<wgpu::BindGroup> },
|
|
||||||
NotFound,
|
|
||||||
Invalid,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Memory {
|
|
||||||
fn upload(
|
|
||||||
&mut self,
|
|
||||||
device: &wgpu::Device,
|
|
||||||
encoder: &mut wgpu::CommandEncoder,
|
|
||||||
texture_layout: &wgpu::BindGroupLayout,
|
|
||||||
width: u32,
|
|
||||||
height: u32,
|
|
||||||
) -> Option<Rc<wgpu::BindGroup>> {
|
|
||||||
match self {
|
|
||||||
Memory::Host { tree } => {
|
|
||||||
println!("{} {}", width, height);
|
|
||||||
|
|
||||||
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 mut canvas =
|
|
||||||
resvg::raqote::DrawTarget::new(width as i32, height as i32);
|
|
||||||
let opt = resvg::Options::default();
|
|
||||||
let screen_size =
|
|
||||||
resvg::ScreenSize::new(width, height).unwrap();
|
|
||||||
resvg::backend_raqote::render_to_canvas(
|
|
||||||
tree,
|
|
||||||
&opt,
|
|
||||||
screen_size,
|
|
||||||
&mut canvas,
|
|
||||||
);
|
|
||||||
let slice = canvas.get_data();
|
|
||||||
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: width * 4,
|
|
||||||
image_height: height,
|
|
||||||
},
|
|
||||||
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(),
|
|
||||||
};
|
|
||||||
|
|
||||||
Some(bind_group)
|
|
||||||
}
|
|
||||||
Memory::Device { bind_group, .. } => Some(bind_group.clone()),
|
|
||||||
Memory::NotFound => None,
|
|
||||||
Memory::Invalid => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Debug for Memory {
|
|
||||||
fn fmt(
|
|
||||||
&self,
|
|
||||||
f: &mut std::fmt::Formatter<'_>,
|
|
||||||
) -> Result<(), std::fmt::Error> {
|
|
||||||
match self {
|
|
||||||
Memory::Host { .. } => write!(f, "Memory::Host"),
|
|
||||||
Memory::Device { .. } => write!(f, "Memory::Device"),
|
|
||||||
Memory::NotFound => write!(f, "Memory::NotFound"),
|
|
||||||
Memory::Invalid => write!(f, "Memory::Invalid"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct Cache {
|
|
||||||
map: HashMap<u64, Memory>,
|
|
||||||
hits: HashSet<u64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Svg {
|
|
||||||
pub handle: Handle,
|
|
||||||
pub position: [f32; 2],
|
|
||||||
pub scale: [f32; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub struct Vertex {
|
|
||||||
_position: [f32; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
const QUAD_INDICES: [u16; 6] = [0, 1, 2, 0, 2, 3];
|
|
||||||
|
|
||||||
const QUAD_VERTS: [Vertex; 4] = [
|
|
||||||
Vertex {
|
|
||||||
_position: [0.0, 0.0],
|
|
||||||
},
|
|
||||||
Vertex {
|
|
||||||
_position: [1.0, 0.0],
|
|
||||||
},
|
|
||||||
Vertex {
|
|
||||||
_position: [1.0, 1.0],
|
|
||||||
},
|
|
||||||
Vertex {
|
|
||||||
_position: [0.0, 1.0],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
struct Instance {
|
|
||||||
_position: [f32; 2],
|
|
||||||
_scale: [f32; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
struct Uniforms {
|
|
||||||
transform: [f32; 16],
|
|
||||||
}
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue