Skip to content

Commit

Permalink
Cache Svg load result properly
Browse files Browse the repository at this point in the history
This avoids trying to reload the file constantly on every frame.
  • Loading branch information
hecrj committed Dec 15, 2019
1 parent 232d487 commit 514ccf8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 20 deletions.
7 changes: 2 additions & 5 deletions wgpu/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,9 @@ impl Pipeline {
#[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);

if let Some(svg) = cache.load(&handle) {
svg.viewport_dimensions()
} else {
(1, 1)
}
svg.viewport_dimensions()
}

pub fn draw(
Expand Down
35 changes: 20 additions & 15 deletions wgpu/src/image/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,21 @@ use std::{
rc::Rc,
};

pub struct Svg {
tree: resvg::usvg::Tree,
pub enum Svg {
Loaded { tree: resvg::usvg::Tree },
NotFound,
}

impl Svg {
pub fn viewport_dimensions(&self) -> (u32, u32) {
let size = self.tree.svg_node().size;
match self {
Svg::Loaded { tree } => {
let size = tree.svg_node().size;

(size.width() as u32, size.height() as u32)
(size.width() as u32, size.height() as u32)
}
Svg::NotFound => (1, 1),
}
}
}

Expand Down Expand Up @@ -40,21 +46,20 @@ impl Cache {
}
}

pub fn load(&mut self, handle: &svg::Handle) -> Option<&Svg> {
pub fn load(&mut self, handle: &svg::Handle) -> &Svg {
if self.svgs.contains_key(&handle.id()) {
return self.svgs.get(&handle.id());
return self.svgs.get(&handle.id()).unwrap();
}

let opt = resvg::Options::default();

match resvg::usvg::Tree::from_file(handle.path(), &opt.usvg) {
Ok(tree) => {
let _ = self.svgs.insert(handle.id(), Svg { tree });
}
Err(_) => {}
let svg = match resvg::usvg::Tree::from_file(handle.path(), &opt.usvg) {
Ok(tree) => Svg::Loaded { tree },
Err(_) => Svg::NotFound,
};

self.svgs.get(&handle.id())
let _ = self.svgs.insert(handle.id(), svg);
self.svgs.get(&handle.id()).unwrap()
}

pub fn upload(
Expand Down Expand Up @@ -85,7 +90,7 @@ impl Cache {
}

match self.load(handle) {
Some(svg) => {
Svg::Loaded { tree } => {
let extent = wgpu::Extent3d {
width,
height,
Expand Down Expand Up @@ -113,7 +118,7 @@ impl Cache {
);

resvg::backend_raqote::render_to_canvas(
&svg.tree,
&tree,
&resvg::Options::default(),
screen_size,
&mut canvas,
Expand Down Expand Up @@ -171,7 +176,7 @@ impl Cache {

Some(bind_group)
}
None => None,
Svg::NotFound => None,
}
}

Expand Down

0 comments on commit 514ccf8

Please sign in to comment.