ori_graphics/
renderer.rs

1use std::any::{Any, TypeId};
2
3use glam::Vec2;
4
5use crate::{ImageData, ImageHandle, Rect, TextHit, TextSection};
6
7pub trait Renderer: Any {
8    fn window_size(&self) -> Vec2;
9    fn create_image(&self, data: &ImageData) -> ImageHandle;
10    fn messure_text(&self, section: &TextSection) -> Option<Rect>;
11    fn hit_text(&self, section: &TextSection, position: Vec2) -> Option<TextHit>;
12
13    fn scale(&self) -> f32 {
14        1.0
15    }
16}
17
18impl dyn Renderer {
19    pub fn downcast_ref<T: Renderer>(&self) -> Option<&T> {
20        // SAFETY: This obeys the safety rules of `Any::downcast_ref`.
21        if TypeId::of::<T>() == Any::type_id(&*self) {
22            unsafe { Some(&*(self as *const dyn Renderer as *const T)) }
23        } else {
24            None
25        }
26    }
27
28    pub fn downcast_mut<T: Renderer>(&mut self) -> Option<&mut T> {
29        // SAFETY: This obeys the safety rules of `Any::downcast_mut`.
30        if TypeId::of::<T>() == Any::type_id(&*self) {
31            unsafe { Some(&mut *(self as *mut dyn Renderer as *mut T)) }
32        } else {
33            None
34        }
35    }
36}