use crate::core::{self, Rectangle};
use crate::graphics::Viewport;
use rustc_hash::FxHashMap;
use std::any::{Any, TypeId};
use std::fmt::Debug;
pub type Batch = Vec<Instance>;
pub trait Primitive: Debug + Send + Sync + 'static {
fn prepare(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
storage: &mut Storage,
bounds: &Rectangle,
viewport: &Viewport,
);
fn render(
&self,
encoder: &mut wgpu::CommandEncoder,
storage: &Storage,
target: &wgpu::TextureView,
clip_bounds: &Rectangle<u32>,
);
}
#[derive(Debug)]
pub struct Instance {
pub bounds: Rectangle,
pub primitive: Box<dyn Primitive>,
}
impl Instance {
pub fn new(bounds: Rectangle, primitive: impl Primitive) -> Self {
Instance {
bounds,
primitive: Box::new(primitive),
}
}
}
pub trait Renderer: core::Renderer {
fn draw_primitive(&mut self, bounds: Rectangle, primitive: impl Primitive);
}
#[derive(Default, Debug)]
pub struct Storage {
pipelines: FxHashMap<TypeId, Box<dyn Any + Send>>,
}
impl Storage {
pub fn has<T: 'static>(&self) -> bool {
self.pipelines.contains_key(&TypeId::of::<T>())
}
pub fn store<T: 'static + Send>(&mut self, data: T) {
let _ = self.pipelines.insert(TypeId::of::<T>(), Box::new(data));
}
pub fn get<T: 'static>(&self) -> Option<&T> {
self.pipelines.get(&TypeId::of::<T>()).map(|pipeline| {
pipeline
.downcast_ref::<T>()
.expect("Value with this type does not exist in Storage.")
})
}
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.pipelines.get_mut(&TypeId::of::<T>()).map(|pipeline| {
pipeline
.downcast_mut::<T>()
.expect("Value with this type does not exist in Storage.")
})
}
}