Skip to main content

repose_render_wgpu/
callback.rs

1//! The core crate stores `Arc<dyn Any>` in `SceneNode::Callback`; this crate
2//! provides the concrete `Callback` wrapper and the `WgpuCallback` trait that
3//! the renderer downcasts to.
4//!
5//! ```ignore
6//! use repose_core::prelude::*; // remember_mutable, request_frame, Modifier, View, PaintCallbackInfo
7//! use repose_render_wgpu::{Callback, WgpuCallback, CallbackResources};
8//! use repose_ui::Embedded; // or repose_canvas::Embedded
9//!
10//! struct MyTriangle { angle: f32 }
11//! impl WgpuCallback for MyTriangle {
12//!     fn prepare(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, screen: &repose_render_wgpu::ScreenDescriptor, resources: &mut CallbackResources) {
13//!         // resources.get_or_insert_with::<Pipelines>() -> update uniform buffer with self.angle
14//!     }
15//!     fn paint(&self, info: PaintCallbackInfo, rpass: &mut wgpu::RenderPass, resources: &CallbackResources) {
16//!         // info.viewport is layout rect (physical px), renderer already set viewport -> info.viewport
17//!         // resources.get::<Pipelines>().unwrap().paint(rpass)
18//!     }
19//! }
20//!
21//! fn MyView() -> View {
22//!     let angle = remember_mutable(|| 0f32);
23//!     // Signal is !Send -> snapshot Copy value into callback (not the Signal itself)
24//!     let payload = { let a = *angle.get(); Callback::new(MyTriangle{ angle: a }) };
25//!     Embedded(
26//!         Modifier::new().size(300.0,300.0)
27//!             .on_pointer_move({ let a=angle.clone(); move |ev: PointerEvent| { a.update(|v| *v+=ev.position.x*0.01); request_frame() } }),
28//!         payload,
29//!     )
30//! }
31//! // For offscreen textures (bevy render target) use register_native_texture -> Image.
32//! ```
33
34use std::any::TypeId;
35use std::collections::HashMap;
36use std::sync::Arc;
37
38use repose_core::{PaintCallbackInfo, PaintCallbackPayload, Rect};
39
40/// Type-map for callback-shared wgpu resources (pipelines, buffers, etc.).
41#[cfg(not(target_arch = "wasm32"))]
42type AnyBox = Box<dyn std::any::Any + Send + Sync>;
43#[cfg(target_arch = "wasm32")]
44type AnyBox = Box<dyn std::any::Any>;
45
46#[cfg(not(target_arch = "wasm32"))]
47pub trait MaybeSendSync: Send + Sync + 'static {}
48#[cfg(not(target_arch = "wasm32"))]
49impl<T: Send + Sync + 'static> MaybeSendSync for T {}
50
51#[cfg(target_arch = "wasm32")]
52pub trait MaybeSendSync: 'static {}
53#[cfg(target_arch = "wasm32")]
54impl<T: 'static> MaybeSendSync for T {}
55
56#[derive(Default)]
57pub struct CallbackResources {
58    map: HashMap<TypeId, AnyBox>,
59}
60
61impl CallbackResources {
62    pub fn insert<T: MaybeSendSync>(&mut self, value: T) {
63        self.map.insert(TypeId::of::<T>(), Box::new(value));
64    }
65
66    pub fn get<T: MaybeSendSync>(&self) -> Option<&T> {
67        self.map
68            .get(&TypeId::of::<T>())
69            .and_then(|b| b.downcast_ref::<T>())
70    }
71
72    pub fn get_mut<T: MaybeSendSync>(&mut self) -> Option<&mut T> {
73        self.map
74            .get_mut(&TypeId::of::<T>())
75            .and_then(|b| b.downcast_mut::<T>())
76    }
77
78    pub fn get_or_insert_with<T: MaybeSendSync + Default>(&mut self) -> &mut T {
79        let id = TypeId::of::<T>();
80        if !self.map.contains_key(&id) {
81            self.map.insert(id, Box::new(T::default()));
82        }
83        self.map.get_mut(&id).unwrap().downcast_mut::<T>().unwrap()
84    }
85
86    pub fn remove<T: 'static>(&mut self) -> Option<T> {
87        self.map
88            .remove(&TypeId::of::<T>())
89            .and_then(|b| b.downcast::<T>().ok())
90            .map(|b| *b)
91    }
92
93    pub fn contains<T: 'static>(&self) -> bool {
94        self.map.contains_key(&TypeId::of::<T>())
95    }
96}
97
98#[derive(Clone, Copy, Debug)]
99pub struct ScreenDescriptor {
100    pub size_in_pixels: [u32; 2],
101    pub pixels_per_point: f32,
102    /// Target surface format (e.g. `Bgra8UnormSrgb`), so `prepare` can create pipelines.
103    pub target_format: wgpu::TextureFormat,
104    /// MSAA sample count of the surface render pass (1 or 4).
105    pub sample_count: u32,
106}
107
108/// Trait for custom wgpu rendering inside a `repose` layout rect.
109pub trait WgpuCallback: Send + Sync + 'static {
110    /// Called before the main `repose` render pass, with access to `device`/`queue`/`encoder`
111    /// for buffer uploads. Can return extra command buffers to be submitted.
112    fn prepare(
113        &self,
114        _device: &wgpu::Device,
115        _queue: &wgpu::Queue,
116        _encoder: &mut wgpu::CommandEncoder,
117        _screen_descriptor: &ScreenDescriptor,
118        _resources: &mut CallbackResources,
119    ) -> Vec<wgpu::CommandBuffer> {
120        Vec::new()
121    }
122
123    /// Called after all `prepare` calls, before `paint`. For cross-callback sync.
124    fn finish_prepare(
125        &self,
126        _device: &wgpu::Device,
127        _queue: &wgpu::Queue,
128        _encoder: &mut wgpu::CommandEncoder,
129        _screen_descriptor: &ScreenDescriptor,
130        _resources: &mut CallbackResources,
131    ) -> Vec<wgpu::CommandBuffer> {
132        Vec::new()
133    }
134
135    fn paint(
136        &self,
137        info: PaintCallbackInfo,
138        render_pass: &mut wgpu::RenderPass<'static>,
139        resources: &CallbackResources,
140    );
141}
142
143pub struct Callback(pub Box<dyn WgpuCallback>);
144
145impl Callback {
146    #[deprecated(note = "rect is ignored; use Callback::new(callback) - layout supplies rect")]
147    pub fn new_paint_callback(
148        _rect: Rect,
149        callback: impl WgpuCallback + 'static,
150    ) -> PaintCallbackPayload {
151        Arc::new(Self(Box::new(callback)))
152    }
153
154    /// Create payload without caring about rect (rect is supplied via `SceneNode`).
155    pub fn new(callback: impl WgpuCallback + 'static) -> PaintCallbackPayload {
156        Arc::new(Self(Box::new(callback)))
157    }
158
159    /// Idiomatic helper: create an `Embedded` view directly from a `WgpuCallback`.
160    /// `Modifier` supplies the layout rect.
161    pub fn embedded_view(
162        modifier: repose_core::Modifier,
163        callback: impl WgpuCallback + 'static,
164    ) -> repose_core::View {
165        let payload = Self::new(callback);
166        let mut m = modifier.paint_callback(payload);
167        let has_size = m.size.is_some()
168            || m.width.is_some()
169            || m.height.is_some()
170            || m.fill_max.is_some()
171            || m.fill_max_w.is_some()
172            || m.fill_max_h.is_some();
173        if !has_size {
174            m = m.size(100.0, 100.0);
175        }
176        repose_core::View::new(0, repose_core::ViewKind::Box).modifier(m)
177    }
178}