From 578ea4abb8a2dd0d53d7087322796bf9ad541b56 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 12 Feb 2020 08:49:42 +0100 Subject: Finish `clock` example --- wgpu/src/widget/canvas/layer.rs | 63 +++++++++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 8 deletions(-) (limited to 'wgpu/src/widget/canvas/layer.rs') diff --git a/wgpu/src/widget/canvas/layer.rs b/wgpu/src/widget/canvas/layer.rs index f97634e4..c239a254 100644 --- a/wgpu/src/widget/canvas/layer.rs +++ b/wgpu/src/widget/canvas/layer.rs @@ -1,13 +1,28 @@ -use crate::canvas::Frame; +use crate::{canvas::Frame, triangle}; -pub trait Layer: std::fmt::Debug {} +use iced_native::Size; +use std::cell::RefCell; +use std::sync::Arc; + +pub trait Layer: std::fmt::Debug { + fn draw(&self, bounds: Size) -> Arc; +} use std::marker::PhantomData; -use std::sync::{Arc, Weak}; #[derive(Debug)] pub struct Cached { input: PhantomData, + cache: RefCell, +} + +#[derive(Debug)] +enum Cache { + Empty, + Filled { + mesh: Arc, + bounds: Size, + }, } impl Cached @@ -15,14 +30,19 @@ where T: Drawable + std::fmt::Debug, { pub fn new() -> Self { - Cached { input: PhantomData } + Cached { + input: PhantomData, + cache: RefCell::new(Cache::Empty), + } } - pub fn clear(&mut self) {} + pub fn clear(&mut self) { + *self.cache.borrow_mut() = Cache::Empty; + } pub fn with<'a>(&'a self, input: &'a T) -> impl Layer + 'a { Bind { - cache: self, + layer: self, input: input, } } @@ -30,11 +50,38 @@ where #[derive(Debug)] struct Bind<'a, T: Drawable> { - cache: &'a Cached, + layer: &'a Cached, input: &'a T, } -impl<'a, T> Layer for Bind<'a, T> where T: Drawable + std::fmt::Debug {} +impl<'a, T> Layer for Bind<'a, T> +where + T: Drawable + std::fmt::Debug, +{ + fn draw(&self, current_bounds: Size) -> Arc { + use std::ops::Deref; + + if let Cache::Filled { mesh, bounds } = + self.layer.cache.borrow().deref() + { + if *bounds == current_bounds { + return mesh.clone(); + } + } + + let mut frame = Frame::new(current_bounds.width, current_bounds.height); + self.input.draw(&mut frame); + + let mesh = Arc::new(frame.into_mesh()); + + *self.layer.cache.borrow_mut() = Cache::Filled { + mesh: mesh.clone(), + bounds: current_bounds, + }; + + mesh + } +} pub trait Drawable { fn draw(&self, frame: &mut Frame); -- cgit