Skip to main content

cranpose_render_common/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4/// Source-over blending of straight-alpha byte pixels.
5pub mod byte_blend;
6/// Debug switches read from environment variables, with programmatic overrides.
7pub mod dev_overlay;
8
9/// The frame background every renderer clears to (linear values; sRGB
10/// surfaces display this as rgb(75, 75, 86)). One definition so backends
11/// cannot drift.
12pub const FRAME_CLEAR_COLOR: [f32; 4] = [18.0 / 255.0, 18.0 / 255.0, 24.0 / 255.0, 1.0];
13/// CPU sampling of brushes at a point, for the software renderers.
14pub mod brush_sampling;
15pub mod font_source;
16/// Blur kernel and rectangle helpers shared by the renderers.
17pub mod geometry;
18/// Glyph masks and the cache renderers keep them in.
19pub mod glyph_mask;
20pub mod glyph_reach;
21/// The render graph: the layers and primitives that a scene builds for a renderer to draw.
22pub mod graph;
23mod graph_hash;
24/// The retained scene: the render graph together with the hit targets built from it.
25pub mod graph_scene;
26/// Collecting hit targets from a render graph.
27pub mod hit_graph;
28/// Pixel comparison and resampling of RGBA images, for renderer tests.
29pub mod image_compare;
30#[cfg(feature = "installed-fonts")]
31pub mod installed_fonts;
32/// Rules for when a graphics layer is drawn into its own offscreen buffer and with which alpha.
33pub mod layer_composition;
34mod layer_recycling;
35pub mod layer_shadow;
36/// Transform math of a graphics layer, re-exported from `cranpose_ui_graphics`.
37pub mod layer_transform;
38mod node_window_bounds;
39/// Lowering of draw primitives to the shape, image and text draw calls of a renderer.
40pub mod primitive_emit;
41/// Keys of the cached rasters of layers.
42pub mod raster_cache;
43/// Shared cases that every renderer backend is checked against.
44pub mod render_contract;
45/// 16-bit pixels of the format most small displays take.
46pub mod rgb565;
47/// Building and updating the render graph from the layout tree.
48pub mod scene_builder;
49/// Which mesh surface of a 3D scene a window point shows.
50pub mod scene_pick;
51pub mod shape_sdf;
52/// Where a window's scenes put their 3D layers: frames, spaces, doorways
53/// and what the eye sees.
54pub mod space;
55/// Colors, brushes and corner radii resolved against the properties of a graphics layer.
56pub mod style_shared;
57/// A laid-out text's glyphs placed for a renderer that draws from an atlas.
58pub mod text_atlas;
59/// The pixels a text's glyph masks are painted into.
60pub mod text_canvas;
61/// Span backgrounds and the lines under and through a text.
62pub mod text_decoration;
63/// The typefaces a renderer hands the app its text lays out with.
64pub mod text_fonts;
65/// The glyphs of a laid-out text placed on pixels with their paints.
66pub mod text_glyphs;
67pub mod text_mask_gamma;
68pub mod text_paint;
69/// A laid-out text's glyphs rasterized into pixels.
70pub mod text_raster;
71mod text_shadow;
72mod thread_state;
73
74#[cfg(test)]
75#[path = "tests/pointer_slices.rs"]
76mod pointer_slices;
77
78use cranpose_core::{MemoryApplier, collections::map::HashSet};
79use cranpose_foundation::nodes::input::PointerEvent;
80use cranpose_ui::LayoutTree;
81pub use cranpose_ui_graphics::Brush;
82use cranpose_ui_graphics::Size;
83
84/// What changed in a node since the scene last drew it, and so how the scene
85/// updates what it drew for that node.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum NodeUpdate {
88    /// Its layout, children or draw commands changed: the scene records it
89    /// again.
90    Content,
91    /// Only state its draws read changed: its layer keeps its children and
92    /// records the node's draws again.
93    Draws,
94    /// Its graphics-layer properties changed and it drew the same.
95    Layer,
96    /// It moved in its parent and kept its size: its layer moves and keeps
97    /// what it drew.
98    Moved,
99    /// It moved and its layer properties changed: its layer moves, takes the
100    /// new properties and keeps what it drew.
101    MovedLayer,
102}
103
104impl NodeUpdate {
105    /// The update a node named with both `self` and `other` needs: content
106    /// wins over the others, draws with any other change need the content,
107    /// and a move with a layer change moves the layer with its new
108    /// properties.
109    #[must_use]
110    pub fn merge(self, other: Self) -> Self {
111        use NodeUpdate::{Content, Draws, Layer, Moved, MovedLayer};
112        match (self, other) {
113            (Content, _) | (_, Content) => Content,
114            (Draws, Draws) => Draws,
115            (Draws, _) | (_, Draws) => Content,
116            (Moved, Moved) => Moved,
117            (Layer, Layer) => Layer,
118            (Moved | Layer | MovedLayer, Moved | Layer | MovedLayer) => MovedLayer,
119        }
120    }
121}
122
123/// The nodes whose drawing changed since the last scene, each with the
124/// update it needs. A node may be named more than once: its updates merge
125/// (see [`NodeUpdate::merge`]).
126///
127/// ```
128/// use cranpose_core::NodeId;
129/// use cranpose_render_common::{NodeUpdate, SceneUpdates};
130/// let updates: SceneUpdates<'_> = &[
131///     (NodeId(1), NodeUpdate::Content),
132///     (NodeId(3), NodeUpdate::Moved),
133/// ];
134/// assert_eq!(updates.len(), 2);
135/// ```
136pub type SceneUpdates<'a> = &'a [(cranpose_core::NodeId, NodeUpdate)];
137
138/// Trait implemented by hit-test targets stored inside a [`RenderScene`].
139pub trait HitTestTarget {
140    /// Dispatches a pointer event to this target's handlers.
141    fn dispatch(&self, event: PointerEvent);
142
143    /// Dispatches a pointer event using the current live node state when available.
144    ///
145    /// Render-scene hit targets may cache closures from an older scene build. Pointer
146    /// dispatch goes through this hook so implementations can resolve fresh handlers
147    /// from the current applier while still using the target's geometry snapshot.
148    fn dispatch_with_applier(&self, _applier: &mut MemoryApplier, event: PointerEvent) {
149        self.dispatch(event);
150    }
151
152    /// Returns the NodeId associated with this hit target.
153    /// Used by HitPathTracker to cache stable identity instead of geometry.
154    fn node_id(&self) -> cranpose_core::NodeId;
155
156    /// The pointer's appearance while it hovers this target, when the target
157    /// names one.
158    ///
159    /// The shell asks the hit list top-down and applies the first answer, so
160    /// the innermost region under the pointer decides the cursor.
161    fn pointer_icon(&self) -> Option<cranpose_ui_graphics::PointerIcon> {
162        None
163    }
164
165    /// Returns the node capture path that should stay attached to this target's gesture.
166    ///
167    /// The default is just this target's own node. Renderers can override this to
168    /// include stable ancestor pointer-input nodes that must continue receiving
169    /// Move/Up/Cancel even if the original descendant target is recycled.
170    fn capture_path(&self) -> Vec<cranpose_core::NodeId> {
171        vec![self.node_id()]
172    }
173}
174
175/// Trait describing the minimal surface area required by the application
176/// shell to process pointer events and refresh the frame graph.
177pub trait RenderScene {
178    /// The hit target type that hit testing returns.
179    type HitTarget: HitTestTarget + Clone;
180
181    /// Removes the render graph and all hit targets.
182    fn clear(&mut self);
183
184    /// Performs hit testing at the given coordinates.
185    /// Returns hit targets ordered by z-index (top-to-bottom).
186    fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget>;
187
188    /// The one target a press reaches when it misses every target but lands
189    /// inside a small target grown to the minimum touch size: the nearest such
190    /// target, and none when the point is outside every grown target.
191    fn hit_test_near(&self, _x: f32, _y: f32) -> Option<Self::HitTarget> {
192        None
193    }
194
195    /// Returns NodeIds of all hit regions at the given coordinates.
196    /// This is a convenience method equivalent to `hit_test().map(|h| h.node_id())`.
197    fn hit_test_nodes(&self, x: f32, y: f32) -> Vec<cranpose_core::NodeId> {
198        self.hit_test(x, y)
199            .into_iter()
200            .map(|h| h.node_id())
201            .collect()
202    }
203
204    /// Finds a hit target by NodeId with fresh geometry from the current scene.
205    ///
206    /// This is the key method for HitPathTracker-style gesture handling:
207    /// - On PointerDown, we cache NodeIds (not geometry)
208    /// - On Move/Up/Cancel, we call this to get fresh HitTarget with current geometry
209    /// - Handler closures are preserved (same Rc), so internal state survives
210    ///
211    /// Returns None if the node no longer exists in the scene (e.g., removed during gesture).
212    fn find_target(&self, node_id: cranpose_core::NodeId) -> Option<Self::HitTarget>;
213
214    /// The hit targets on the mesh surfaces of the scene the node `scene`
215    /// shows that `ray` reaches, in the space the scene's eye stands in,
216    /// ordered by z-index (top-to-bottom): a controller's, a hand's or a
217    /// gaze's, which need not start at the eye.
218    fn hit_test_ray(
219        &self,
220        _scene: cranpose_core::NodeId,
221        _ray: cranpose_ui_graphics::space::Ray,
222    ) -> Vec<Self::HitTarget> {
223        Vec::new()
224    }
225
226    /// Visits each mesh surface the eyes of the window's scenes see, by its
227    /// node, with the map from its content to the window as the eye shows
228    /// it, through the doorways it lies behind: where the nodes on it show.
229    fn surface_windows(
230        &self,
231        _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::ProjectiveTransform),
232    ) {
233    }
234
235    /// Where the hit target of `node_id` shows in the window when it lies on
236    /// a mesh surface of a 3D scene: its bounds as the scene's camera shows
237    /// them, also through a doorway and for an eye that walked through one.
238    /// `None` for a flat target, a target behind the eye or no target.
239    fn surface_window_bounds(
240        &self,
241        _node_id: cranpose_core::NodeId,
242    ) -> Option<cranpose_ui_graphics::Rect> {
243        None
244    }
245
246    /// Visits each layout node the scene draws with the bounds of its rect
247    /// in the window, through the graphics layers above it and its own, and
248    /// on a mesh surface as the scene's camera shows it: where it shows.
249    fn node_window_bounds(
250        &self,
251        _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::Rect),
252    ) {
253    }
254
255    /// A count that grows when an update moves a layer in its parent without a layout pass, as
256    /// an animated graphics layer or `offset_with` does: what read [`Self::node_window_bounds`]
257    /// reads them again when it changes.
258    fn layer_moves(&self) -> u64 {
259        0
260    }
261
262    /// Replaces the set with retained visual observation owners, preserving its capacity.
263    /// Returns whether the scene provides this information.
264    fn collect_retained_visual_observation_nodes(
265        &self,
266        nodes: &mut HashSet<cranpose_core::NodeId>,
267    ) -> bool {
268        nodes.clear();
269        false
270    }
271}
272
273/// Abstraction implemented by concrete renderer backends.
274pub trait Renderer {
275    /// The scene type that holds the render graph and the hit targets of this renderer.
276    type Scene: RenderScene;
277    /// Error returned when the scene cannot be rebuilt or updated.
278    type Error;
279
280    /// Installs renderer-provided app services into the target AppContext.
281    ///
282    /// AppShell calls this before the first composition pass.
283    /// Renderers that provide text measurement or other per-app services should install
284    /// them here rather than as constructor side effects.
285    fn attach_app_context_services(&mut self, _app_context: &cranpose_ui::AppContext) {}
286
287    /// Takes in the fonts installed since the renderer last looked (see
288    /// `installed_fonts::install_font_file`). A renderer that installed the
289    /// app's text measurer installs one with the new faces, so text lays out
290    /// again with them.
291    ///
292    /// AppShell calls this before the layout of a frame that follows an
293    /// install.
294    fn apply_installed_fonts(&mut self, _app_context: &cranpose_ui::AppContext) {}
295
296    /// Sets how many device pixels the renderer draws for one logical unit.
297    ///
298    /// AppShell sets its primary renderer's scale to the density it lays
299    /// out with, at construction and on every density change, so a host
300    /// sets it only for the renderers of other surfaces. Renderers that take
301    /// the scale with each draw ignore it.
302    fn set_root_scale(&mut self, _scale: f32) {}
303
304    /// The scene that holds the render graph and the hit targets.
305    fn scene(&self) -> &Self::Scene;
306    /// Mutable access to the scene.
307    fn scene_mut(&mut self) -> &mut Self::Scene;
308
309    /// Rebuilds the scene from `layout_tree` for a viewport of the given size.
310    fn rebuild_scene(
311        &mut self,
312        layout_tree: &LayoutTree,
313        viewport: Size,
314    ) -> Result<(), Self::Error>;
315
316    /// Rebuilds the scene by traversing the LayoutNode tree directly via Applier.
317    ///
318    /// This is the new architecture that eliminates per-frame LayoutTree reconstruction.
319    /// Implementors must read layout state from LayoutNode.layout_state() directly.
320    fn rebuild_scene_from_applier(
321        &mut self,
322        applier: &mut MemoryApplier,
323        root: cranpose_core::NodeId,
324        viewport: Size,
325    ) -> Result<(), Self::Error>;
326
327    /// Updates the scene for the nodes in `updates`, and the hit targets when the update changed
328    /// one or the geometry above one. The default implementation rebuilds the whole scene.
329    fn update_scene_from_applier(
330        &mut self,
331        applier: &mut MemoryApplier,
332        root: cranpose_core::NodeId,
333        viewport: Size,
334        updates: SceneUpdates<'_>,
335    ) -> Result<(), Self::Error> {
336        let _ = updates;
337        self.rebuild_scene_from_applier(applier, root, viewport)
338    }
339
340    /// Updates the scene when only what is drawn changed: nothing was composed or laid out. The
341    /// default implementation calls `update_scene_from_applier`.
342    fn update_visual_scene_from_applier(
343        &mut self,
344        applier: &mut MemoryApplier,
345        root: cranpose_core::NodeId,
346        viewport: Size,
347        updates: SceneUpdates<'_>,
348    ) -> Result<(), Self::Error> {
349        self.update_scene_from_applier(applier, root, viewport, updates)
350    }
351
352    /// Draw a development overlay (e.g., FPS counter) on top of the scene.
353    ///
354    /// This is called after rebuild_scene when dev options are enabled.
355    /// The text, laid out in `overlay`, is drawn directly by the renderer
356    /// without affecting composition.
357    ///
358    /// Default implementation does nothing.
359    fn draw_dev_overlay(&mut self, _overlay: &cranpose_ui::PreparedTextLayout, _viewport: Size) {}
360
361    /// Replaces the developer inspector graph outside the application scene.
362    ///
363    /// Passing `None` removes the inspector. Its primitives must not participate
364    /// in application hit testing, layout, or accessibility.
365    fn set_inspector_overlay(&mut self, _graph: Option<graph::RenderGraph>) {}
366
367    /// Tells the renderer that its app held still between the last frame and the next one: the
368    /// shell asked the platform for no frame and no update. A renderer that compares frames to
369    /// draw only what changed counts the frames on either side of the pause apart.
370    ///
371    /// AppShell calls this before the first frame after such a pause.
372    fn note_held_still(&mut self) {}
373
374    /// Tells the renderer that a pointer is held on the app's controls for the coming frame: the
375    /// user may move it at any moment, so the frame is not one to spend on work that holds the
376    /// frames after it back, such as a WebGL program link.
377    ///
378    /// AppShell calls this before each frame drawn while a pointer is held.
379    fn note_pointer_held(&mut self) {}
380
381    /// Runs one step of the pipeline builds that wait for a frame, where frames run them (a WebGL
382    /// page links one program at a frame's end), while the app draws none: a page that stands
383    /// still still builds what its next touch draws. Returns whether builds still wait.
384    ///
385    /// The platform calls this in its idle periods while it has no frame to draw.
386    fn build_while_idle(&mut self) -> bool {
387        false
388    }
389
390    /// Returns whether renderer-side cache materialization needs a visible follow-up frame.
391    fn needs_frame_warmup(&self) -> bool {
392        false
393    }
394
395    /// Returns whether the last frame drew a placeholder for an effect whose
396    /// pipelines are still compiling, so its picture is not final yet; the
397    /// renderer asks for the frame that replaces it once they land.
398    fn awaits_pipelines(&self) -> bool {
399        false
400    }
401}