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(all(
42    target_arch = "wasm32",
43    any(
44        not(feature = "fragile-send-sync-non-atomic-wasm"),
45        target_feature = "atomics"
46    )
47)))]
48type AnyBox = Box<dyn std::any::Any + Send + Sync>;
49#[cfg(all(
50    target_arch = "wasm32",
51    any(
52        not(feature = "fragile-send-sync-non-atomic-wasm"),
53        target_feature = "atomics"
54    )
55))]
56type AnyBox = Box<dyn std::any::Any>;
57
58#[cfg(not(all(
59    target_arch = "wasm32",
60    any(
61        not(feature = "fragile-send-sync-non-atomic-wasm"),
62        target_feature = "atomics"
63    )
64)))]
65pub trait MaybeSendSync: Send + Sync + 'static {}
66#[cfg(not(all(
67    target_arch = "wasm32",
68    any(
69        not(feature = "fragile-send-sync-non-atomic-wasm"),
70        target_feature = "atomics"
71    )
72)))]
73impl<T: Send + Sync + 'static> MaybeSendSync for T {}
74
75#[cfg(all(
76    target_arch = "wasm32",
77    any(
78        not(feature = "fragile-send-sync-non-atomic-wasm"),
79        target_feature = "atomics"
80    )
81))]
82pub trait MaybeSendSync: 'static {}
83#[cfg(all(
84    target_arch = "wasm32",
85    any(
86        not(feature = "fragile-send-sync-non-atomic-wasm"),
87        target_feature = "atomics"
88    )
89))]
90impl<T: 'static> MaybeSendSync for T {}
91
92#[derive(Default)]
93pub struct CallbackResources {
94    map: HashMap<TypeId, AnyBox>,
95}
96
97impl CallbackResources {
98    pub fn insert<T: MaybeSendSync>(&mut self, value: T) {
99        self.map.insert(TypeId::of::<T>(), Box::new(value));
100    }
101
102    pub fn get<T: MaybeSendSync>(&self) -> Option<&T> {
103        self.map
104            .get(&TypeId::of::<T>())
105            .and_then(|b| b.downcast_ref::<T>())
106    }
107
108    pub fn get_mut<T: MaybeSendSync>(&mut self) -> Option<&mut T> {
109        self.map
110            .get_mut(&TypeId::of::<T>())
111            .and_then(|b| b.downcast_mut::<T>())
112    }
113
114    pub fn get_or_insert_with<T: MaybeSendSync + Default>(&mut self) -> &mut T {
115        let id = TypeId::of::<T>();
116        self.map.entry(id).or_insert_with(|| Box::new(T::default()));
117        self.map.get_mut(&id).unwrap().downcast_mut::<T>().unwrap()
118    }
119
120    pub fn remove<T: 'static>(&mut self) -> Option<T> {
121        self.map
122            .remove(&TypeId::of::<T>())
123            .and_then(|b| b.downcast::<T>().ok())
124            .map(|b| *b)
125    }
126
127    pub fn contains<T: 'static>(&self) -> bool {
128        self.map.contains_key(&TypeId::of::<T>())
129    }
130}
131
132#[derive(Clone, Copy, Debug)]
133pub struct ScreenDescriptor {
134    pub size_in_pixels: [u32; 2],
135    pub pixels_per_point: f32,
136    /// Target surface format (e.g. `Bgra8UnormSrgb`), so `prepare` can create pipelines.
137    pub target_format: wgpu::TextureFormat,
138    /// MSAA sample count of the surface render pass (1 or 4).
139    pub sample_count: u32,
140}
141
142/// Trait for custom wgpu rendering inside a `repose` layout rect.
143pub trait WgpuCallback: Send + Sync + 'static {
144    /// Called before the main `repose` render pass, with access to `device`/`queue`/`encoder`
145    /// for buffer uploads. Can return extra command buffers to be submitted.
146    fn prepare(
147        &self,
148        _device: &wgpu::Device,
149        _queue: &wgpu::Queue,
150        _encoder: &mut wgpu::CommandEncoder,
151        _screen_descriptor: &ScreenDescriptor,
152        _resources: &mut CallbackResources,
153    ) -> Vec<wgpu::CommandBuffer> {
154        Vec::new()
155    }
156
157    /// Called after all `prepare` calls, before `paint`. For cross-callback sync.
158    fn finish_prepare(
159        &self,
160        _device: &wgpu::Device,
161        _queue: &wgpu::Queue,
162        _encoder: &mut wgpu::CommandEncoder,
163        _screen_descriptor: &ScreenDescriptor,
164        _resources: &mut CallbackResources,
165    ) -> Vec<wgpu::CommandBuffer> {
166        Vec::new()
167    }
168
169    fn paint(
170        &self,
171        info: PaintCallbackInfo,
172        render_pass: &mut wgpu::RenderPass<'static>,
173        resources: &CallbackResources,
174    );
175}
176
177pub struct Callback(pub Box<dyn WgpuCallback>);
178
179impl Callback {
180    #[deprecated(note = "rect is ignored; use Callback::new(callback) - layout supplies rect")]
181    pub fn new_paint_callback(
182        _rect: Rect,
183        callback: impl WgpuCallback + 'static,
184    ) -> PaintCallbackPayload {
185        Arc::new(Self(Box::new(callback)))
186    }
187
188    /// Create payload without caring about rect (rect is supplied via `SceneNode`).
189    // Public API used downstream; keep the `new` name despite the Arc return.
190    #[allow(clippy::new_ret_no_self)]
191    pub fn new(callback: impl WgpuCallback + 'static) -> PaintCallbackPayload {
192        Arc::new(Self(Box::new(callback)))
193    }
194
195    /// Idiomatic helper: create an `Embedded` view directly from a `WgpuCallback`.
196    /// `Modifier` supplies the layout rect.
197    pub fn embedded_view(
198        modifier: repose_core::Modifier,
199        callback: impl WgpuCallback + 'static,
200    ) -> repose_core::View {
201        let payload = Self::new(callback);
202        let mut m = modifier.paint_callback(payload);
203        let has_size = m.size.is_some()
204            || m.width.is_some()
205            || m.height.is_some()
206            || m.fill_max.is_some()
207            || m.fill_max_w.is_some()
208            || m.fill_max_h.is_some();
209        if !has_size {
210            m = m.size(repose_core::Dp(100.0), repose_core::Dp(100.0));
211        }
212        repose_core::View::new(0, repose_core::ViewKind::Box).modifier(m)
213    }
214}