Skip to main content

cranpose_render_common/
graph_scene.rs

1use std::{
2    cell::{Cell, Ref, RefCell},
3    rc::Rc,
4};
5
6use cranpose_core::{
7    MemoryApplier, NodeId,
8    collections::map::{HashMap, HashSet},
9};
10use cranpose_foundation::{MINIMUM_TOUCH_TARGET_SIZE, PointerEvent, PointerEventKind};
11use cranpose_ui::{LayoutNode, ModifierNodeSlices, SubcomposeLayoutNode};
12use cranpose_ui_graphics::{Point, PointerIcon, Rect, RoundedCornerShape, shared_sort, space::Ray};
13
14#[cfg(feature = "layer-tree")]
15use crate::graph::LayerNode;
16use crate::{
17    HitTestTarget, RenderScene, SceneUpdates,
18    graph::ProjectiveTransform,
19    left_nodes::LeftNodes,
20    scene_pick::{ScenePick, SurfaceHolds},
21    scene_store::{LayerRef, RecordEvents, SceneStore},
22};
23
24/// Counters and once-only warnings that a scene collects while it dispatches pointer events.
25pub struct RenderDiagnostics {
26    reported_warnings: RefCell<HashSet<&'static str>>,
27    live_modifier_slice_lookup_miss_count: Cell<usize>,
28}
29
30impl RenderDiagnostics {
31    /// Creates diagnostics with no warnings reported and no lookup misses counted.
32    pub fn new() -> Self {
33        Self {
34            reported_warnings: RefCell::new(HashSet::default()),
35            live_modifier_slice_lookup_miss_count: Cell::new(0),
36        }
37    }
38
39    /// Returns true the first time it is called with `key`, so that a warning is reported once.
40    pub fn claim_warning_once(&self, key: &'static str) -> bool {
41        self.reported_warnings.borrow_mut().insert(key)
42    }
43
44    /// Counts one pointer dispatch that fell back to the captured modifier slices because the live
45    /// node could not be found.
46    pub fn record_live_modifier_slice_lookup_miss(&self) {
47        self.live_modifier_slice_lookup_miss_count.set(
48            self.live_modifier_slice_lookup_miss_count
49                .get()
50                .saturating_add(1),
51        );
52    }
53
54    /// Number of pointer dispatches that did not find the live node and used the modifier slices
55    /// captured at build time instead.
56    pub fn live_modifier_slice_lookup_miss_count(&self) -> usize {
57        self.live_modifier_slice_lookup_miss_count.get()
58    }
59}
60
61impl Default for RenderDiagnostics {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67/// A clip that cuts a hit target, kept as a transformed rectangle.
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub struct HitClip {
70    /// The clip rectangle after the layer transforms, as four corners in window space.
71    pub quad: [[f32; 2]; 4],
72    /// Axis-aligned bounds of `quad` in window coordinates.
73    pub bounds: Rect,
74}
75
76/// A mesh surface of a scene, as the hit targets on its content see it:
77/// the scene's pick, which surface it is, and the clips above it.
78pub struct SurfaceTarget {
79    /// Finds the surface and content point a window point shows.
80    pub pick: Rc<ScenePick>,
81    /// The surface's index in `pick`: of its layer's owner mesh.
82    pub index: usize,
83    /// Axis-aligned bounds of the clips above the surface, in window space.
84    pub outer_clip_bounds: Option<Rect>,
85    /// The clips above the surface, as quads in window space.
86    pub outer_clips: Vec<HitClip>,
87}
88
89const WINDOW_BOUNDS_STEPS: u16 = 2;
90
91impl SurfaceTarget {
92    /// Where `local`, a rect of a target's own space into which
93    /// `content_to_local` maps the surface's content, shows in the window:
94    /// the bounds of a grid of its points in front of the eye; `None` when
95    /// none is.
96    pub fn window_bounds(
97        &self,
98        content_to_local: &ProjectiveTransform,
99        local: Rect,
100    ) -> Option<Rect> {
101        let local_to_content = content_to_local.inverse()?;
102        let steps = f32::from(WINDOW_BOUNDS_STEPS);
103        let grid = (0..=WINDOW_BOUNDS_STEPS)
104            .flat_map(|row| (0..=WINDOW_BOUNDS_STEPS).map(move |column| (row, column)));
105        grid.filter_map(|(row, column)| {
106            let point = Point::new(
107                local.x + local.width * f32::from(column) / steps,
108                local.y + local.height * f32::from(row) / steps,
109            );
110            let content = local_to_content.map_point(point);
111            self.pick.window_point(self.index, content)
112        })
113        .map(|point| Rect {
114            x: point.x,
115            y: point.y,
116            width: 0.0,
117            height: 0.0,
118        })
119        .reduce(|bounds, point| bounds.union(point))
120    }
121}
122
123/// Where a hit target on a mesh surface lies on the surface's content.
124#[derive(Clone, Copy)]
125pub struct SurfaceGeometry<'a> {
126    /// The surface the target is on.
127    pub target: &'a Rc<SurfaceTarget>,
128    /// Maps the surface's content into the node's local space.
129    pub content_to_local: ProjectiveTransform,
130    /// Axis-aligned bounds of the clips within the surface, in content
131    /// space, or `None` when none clips.
132    pub clip_bounds: Option<Rect>,
133    /// The clips within the surface, as quads in content space.
134    pub clips: &'a [HitClip],
135}
136
137impl SurfaceGeometry<'_> {
138    /// Where `local`, a rect of the target's own space, shows in the window.
139    pub fn window_bounds(&self, local: Rect) -> Option<Rect> {
140        self.target.window_bounds(&self.content_to_local, local)
141    }
142}
143
144/// Geometry for a hit target, borrowing the clip chain until the sink records it.
145#[derive(Clone, Copy)]
146pub struct HitGeometry<'a> {
147    /// Axis-aligned bounds of `quad` in window coordinates.
148    pub rect: Rect,
149    /// The node's rectangle after the layer transforms, as four corners in window space.
150    pub quad: [[f32; 2]; 4],
151    /// The node's own rectangle in its local space.
152    pub local_bounds: Rect,
153    /// Maps window coordinates into the node's local space.
154    pub world_to_local: ProjectiveTransform,
155    /// Axis-aligned bounds of the ancestors' clips in window space, or `None` when none clips.
156    pub hit_clip_bounds: Option<Rect>,
157    /// Clips of the ancestors that cut the target, as transformed quads in window space.
158    pub hit_clips: &'a [HitClip],
159    /// For a target on a mesh surface, where it lies on the surface's
160    /// content. The window-space fields above then hold the surface's flat
161    /// stand-in, exact only on a flat mesh; the surface decides the hit.
162    pub surface: Option<SurfaceGeometry<'a>>,
163}
164
165/// What a hit target answers with: the shape that narrows its bounds, and the
166/// node's modifier slices, which hold the pointer handlers it dispatches to
167/// and the pointer icon it asks for while hovered.
168pub struct HitTargetSpec<'a> {
169    /// Narrows the target's rectangle to a rounded shape, so a point in a
170    /// corner cutout misses it.
171    pub shape: Option<RoundedCornerShape>,
172    /// The node's slices, shared by the target rather than copied.
173    pub handlers: &'a Rc<ModifierNodeSlices>,
174}
175
176/// A hit target in window space: the node's geometry, clips and pointer handlers.
177#[derive(Clone)]
178pub struct HitRegion {
179    /// The layout node that owns the target.
180    pub node_id: NodeId,
181    /// Nodes that keep receiving the move, up and cancel events of a gesture that starts here: this
182    /// node first, then its pointer-input ancestors from the nearest outward.
183    pub capture_path: Vec<NodeId>,
184    /// Axis-aligned bounds of `quad` in window coordinates.
185    pub rect: Rect,
186    /// The node's rectangle after the layer transforms, as four corners in window space.
187    pub quad: [[f32; 2]; 4],
188    /// The node's own rectangle in its local space.
189    pub local_bounds: Rect,
190    /// Maps window coordinates into the node's local space.
191    pub world_to_local: ProjectiveTransform,
192    /// Rounded shape that narrows the target's rectangle, or `None` for a plain rectangle.
193    pub shape: Option<RoundedCornerShape>,
194    /// The node's modifier slices, shared with the scene: its pointer
195    /// handlers and pointer icon.
196    pub handlers: Rc<ModifierNodeSlices>,
197    /// Draw order of the target. A larger value is drawn later and is hit first.
198    pub z_index: usize,
199    /// Axis-aligned bounds of the ancestors' clips in window space, or `None` when none clips.
200    pub hit_clip_bounds: Option<Rect>,
201    /// Clips of the ancestors that cut this target, as transformed quads in window space.
202    pub hit_clips: Vec<HitClip>,
203    surface: Option<Rc<SurfaceRegion>>,
204    diagnostics: Rc<RenderDiagnostics>,
205}
206
207struct SurfaceRegion {
208    target: Rc<SurfaceTarget>,
209    content_to_local: ProjectiveTransform,
210    clip_bounds: Option<Rect>,
211    clips: Vec<HitClip>,
212}
213
214impl SurfaceRegion {
215    fn local_point(&self, window: Point) -> Option<Point> {
216        let target = &self.target;
217        if target
218            .outer_clip_bounds
219            .is_some_and(|clip| !clip.contains(window.x, window.y))
220            || !target
221                .outer_clips
222                .iter()
223                .all(|clip| point_in_quad(window, clip.quad))
224        {
225            return None;
226        }
227        self.local_in(target.pick.content_point(window, target.index)?)
228    }
229
230    fn local_point_along(&self, ray: Ray) -> Option<Point> {
231        let target = &self.target;
232        self.local_in(target.pick.content_point_along(ray, target.index)?)
233    }
234
235    fn local_in(&self, content: Point) -> Option<Point> {
236        if self
237            .clip_bounds
238            .is_some_and(|clip| !clip.contains(content.x, content.y))
239            || !self
240                .clips
241                .iter()
242                .all(|clip| point_in_quad(content, clip.quad))
243        {
244            return None;
245        }
246        self.content_to_local.map_point_in_front(content)
247    }
248
249    fn drag_point(&self, event: &PointerEvent) -> Option<Point> {
250        let target = &self.target;
251        let content = match event.ray {
252            Some(ray) => target.pick.drag_point_along(ray, target.index)?,
253            None => target
254                .pick
255                .drag_point(event.global_position, target.index)?,
256        };
257        Some(self.content_to_local.map_point(content))
258    }
259}
260
261struct HitRegionInit<'a> {
262    node_id: NodeId,
263    capture_path: Vec<NodeId>,
264    geometry: HitGeometry<'a>,
265    clip_buffer: Vec<HitClip>,
266    shape: Option<RoundedCornerShape>,
267    handlers: Rc<ModifierNodeSlices>,
268    z_index: usize,
269    diagnostics: Rc<RenderDiagnostics>,
270}
271
272impl Default for HitRegionInit<'_> {
273    fn default() -> Self {
274        Self {
275            node_id: NodeId(0),
276            capture_path: Vec::new(),
277            geometry: HitGeometry {
278                rect: Rect {
279                    x: 0.0,
280                    y: 0.0,
281                    width: 0.0,
282                    height: 0.0,
283                },
284                quad: [[0.0, 0.0]; 4],
285                local_bounds: Rect {
286                    x: 0.0,
287                    y: 0.0,
288                    width: 0.0,
289                    height: 0.0,
290                },
291                world_to_local: ProjectiveTransform::identity(),
292                hit_clip_bounds: None,
293                hit_clips: &[],
294                surface: None,
295            },
296            clip_buffer: Vec::new(),
297            shape: None,
298            handlers: Rc::default(),
299            z_index: 0,
300            diagnostics: Rc::new(RenderDiagnostics::new()),
301        }
302    }
303}
304
305impl HitRegion {
306    fn with_diagnostics(init: HitRegionInit<'_>) -> Self {
307        let HitRegionInit {
308            node_id,
309            capture_path,
310            geometry,
311            clip_buffer: mut hit_clips,
312            shape,
313            handlers,
314            z_index,
315            diagnostics,
316        } = init;
317        let HitGeometry {
318            rect,
319            quad,
320            local_bounds,
321            world_to_local,
322            hit_clip_bounds,
323            hit_clips: clips,
324            surface,
325        } = geometry;
326        hit_clips.extend_from_slice(clips);
327        Self {
328            node_id,
329            capture_path,
330            rect,
331            quad,
332            local_bounds,
333            world_to_local,
334            shape,
335            handlers,
336            z_index,
337            hit_clip_bounds,
338            hit_clips,
339            surface: surface.map(|surface| {
340                Rc::new(SurfaceRegion {
341                    target: Rc::clone(surface.target),
342                    content_to_local: surface.content_to_local,
343                    clip_bounds: surface.clip_bounds,
344                    clips: surface.clips.to_vec(),
345                })
346            }),
347            diagnostics,
348        }
349    }
350
351    fn contains(&self, x: f32, y: f32) -> bool {
352        if let Some(surface) = &self.surface {
353            return surface
354                .local_point(Point { x, y })
355                .is_some_and(|local| self.contains_local(local));
356        }
357        if !self.rect.contains(x, y) {
358            return false;
359        }
360
361        if let Some(clip_bounds) = self.hit_clip_bounds
362            && !clip_bounds.contains(x, y)
363        {
364            return false;
365        }
366
367        let point = Point { x, y };
368        if !point_in_quad(point, self.quad) {
369            return false;
370        }
371
372        for clip in &self.hit_clips {
373            if !point_in_quad(point, clip.quad) {
374                return false;
375            }
376        }
377
378        let Some(local_point) = self.world_to_local.map_point_in_front(point) else {
379            return false;
380        };
381        self.contains_local(local_point)
382    }
383
384    fn contains_local(&self, local_point: Point) -> bool {
385        if let Some(shape) = self.shape {
386            point_in_rounded_rect(local_point, self.local_bounds, shape)
387        } else {
388            self.local_bounds.contains(local_point.x, local_point.y)
389        }
390    }
391
392    fn reach_distance(&self, x: f32, y: f32) -> Option<f32> {
393        if self.handlers.pointer_inputs().is_empty() || self.surface.is_some() {
394            return None;
395        }
396        if let Some(clip_bounds) = self.hit_clip_bounds
397            && !clip_bounds.contains(x, y)
398        {
399            return None;
400        }
401        let grow_x = ((MINIMUM_TOUCH_TARGET_SIZE - self.rect.width) / 2.0).max(0.0);
402        let grow_y = ((MINIMUM_TOUCH_TARGET_SIZE - self.rect.height) / 2.0).max(0.0);
403        if grow_x <= 0.0 && grow_y <= 0.0 {
404            return None;
405        }
406        let right = self.rect.x + self.rect.width;
407        let bottom = self.rect.y + self.rect.height;
408        let in_reach = x >= self.rect.x - grow_x
409            && x <= right + grow_x
410            && y >= self.rect.y - grow_y
411            && y <= bottom + grow_y;
412        if !in_reach {
413            return None;
414        }
415        let dx = (self.rect.x - x).max(x - right).max(0.0);
416        let dy = (self.rect.y - y).max(y - bottom).max(0.0);
417        Some(dx * dx + dy * dy)
418    }
419
420    fn localize_event(&self, event: &PointerEvent) -> PointerEvent {
421        let local = match &self.surface {
422            Some(surface) => surface
423                .drag_point(event)
424                .unwrap_or_else(|| self.world_to_local.map_point(event.global_position)),
425            None => self.world_to_local.map_point(event.global_position),
426        };
427        event.copy_with_local_position(Point {
428            x: local.x - self.local_bounds.x,
429            y: local.y - self.local_bounds.y,
430        })
431    }
432
433    fn dispatch_modifier_slices(&self, modifier_slices: &ModifierNodeSlices, event: PointerEvent) {
434        if should_skip_consumed_event(&event) {
435            return;
436        }
437
438        modifier_slices.dispatch_pointer_event(self.localize_event(&event));
439    }
440
441    fn live_modifier_slices(&self, applier: &mut MemoryApplier) -> Option<Rc<ModifierNodeSlices>> {
442        if let Ok(modifier_slices) =
443            applier.with_node::<LayoutNode, _>(self.node_id, |node| node.modifier_slices_snapshot())
444        {
445            return Some(modifier_slices);
446        }
447
448        applier
449            .with_node::<SubcomposeLayoutNode, _>(self.node_id, |node| {
450                node.modifier_slices_snapshot()
451            })
452            .ok()
453    }
454}
455
456fn is_terminal_pointer_event(kind: PointerEventKind) -> bool {
457    matches!(kind, PointerEventKind::Up | PointerEventKind::Cancel)
458}
459
460fn should_skip_consumed_event(event: &PointerEvent) -> bool {
461    event.is_consumed() && !is_terminal_pointer_event(event.kind)
462}
463
464impl HitTestTarget for HitRegion {
465    fn node_id(&self) -> NodeId {
466        self.node_id
467    }
468
469    fn pointer_icon(&self) -> Option<PointerIcon> {
470        self.handlers.pointer_icon().cloned()
471    }
472
473    fn capture_path(&self) -> Vec<NodeId> {
474        self.capture_path.clone()
475    }
476
477    fn dispatch(&self, event: PointerEvent) {
478        self.dispatch_modifier_slices(&self.handlers, event);
479    }
480
481    fn dispatch_with_applier(&self, applier: &mut MemoryApplier, event: PointerEvent) {
482        if let Some(modifier_slices) = self.live_modifier_slices(applier) {
483            self.dispatch_modifier_slices(modifier_slices.as_ref(), event);
484            return;
485        }
486
487        self.diagnostics.record_live_modifier_slice_lookup_miss();
488        self.dispatch_modifier_slices(&self.handlers, event);
489    }
490}
491
492#[derive(Default)]
493struct HitBuffers {
494    hit_clips: Vec<HitClip>,
495    capture_path: Vec<NodeId>,
496}
497
498// The hit targets of a scene's records in draw order, the last drawn at the
499// end, and the storage the next collection of them reuses.
500#[derive(Default)]
501struct HitList {
502    hits: Vec<HitRegion>,
503    buffers: Vec<HitBuffers>,
504    // The draw order index the next pushed target receives.
505    next_z: usize,
506    // Where in `hits` the target of each node lies.
507    node_index: HashMap<NodeId, usize>,
508    // The records changed a target since the list was collected: the next
509    // query collects it again.
510    stale: bool,
511}
512
513impl HitList {
514    // Removes the targets, releases their handlers and keeps their storage.
515    fn clear(&mut self) {
516        self.buffers.clear();
517        for hit in self.hits.drain(..) {
518            let mut buffers = HitBuffers {
519                hit_clips: hit.hit_clips,
520                capture_path: hit.capture_path,
521            };
522            buffers.hit_clips.clear();
523            buffers.capture_path.clear();
524            self.buffers.push(buffers);
525        }
526        self.node_index.clear();
527        self.next_z = 0;
528    }
529}
530
531pub(crate) struct HitTargets<'a> {
532    list: &'a mut HitList,
533    diagnostics: &'a Rc<RenderDiagnostics>,
534    pub(crate) holds: &'a SurfaceHolds,
535}
536
537impl HitTargets<'_> {
538    pub(crate) fn push(
539        &mut self,
540        node_id: NodeId,
541        capture_path: &[NodeId],
542        geometry: HitGeometry<'_>,
543        target: HitTargetSpec<'_>,
544    ) {
545        let HitTargetSpec { shape, handlers } = target;
546        if handlers.pointer_inputs().is_empty() && handlers.pointer_icon().is_none() {
547            return;
548        }
549        let list = &mut *self.list;
550        let mut buffers = list.buffers.pop().unwrap_or_default();
551        buffers.capture_path.extend_from_slice(capture_path);
552
553        let z_index = list.next_z;
554        list.next_z += 1;
555        let hit_index = list.hits.len();
556        list.hits.push(HitRegion::with_diagnostics(HitRegionInit {
557            node_id,
558            capture_path: buffers.capture_path,
559            geometry,
560            clip_buffer: buffers.hit_clips,
561            shape,
562            handlers: Rc::clone(handlers),
563            z_index,
564            diagnostics: Rc::clone(self.diagnostics),
565        }));
566        list.node_index.insert(node_id, hit_index);
567    }
568}
569
570/// The records a window draws together with the hit targets built from them.
571pub struct Scene {
572    store: SceneStore,
573    // Collected from the store when a query first needs them after it
574    // changed: a frame that moves a target and takes no pointer input does
575    // not walk the store for targets.
576    hits: RefCell<HitList>,
577    // Kept through collections of the hit targets.
578    pub(crate) holds: SurfaceHolds,
579    diagnostics: Rc<RenderDiagnostics>,
580    // The updates that moved a layer with no layout pass, and the rebuilds,
581    // which may have.
582    layer_moves: u64,
583    left_nodes: LeftNodes,
584}
585
586/// How many hit targets a [`Scene`] holds and has room for, and the same for
587/// its index of them by node, for debugging memory use.
588#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
589pub struct HitStorage {
590    /// Hit targets held.
591    pub hits_len: usize,
592    /// Room reserved for hit targets.
593    pub hits_capacity: usize,
594    /// Nodes indexed.
595    pub node_index_len: usize,
596    /// Room reserved in the node index.
597    pub node_index_capacity: usize,
598}
599
600impl Scene {
601    /// Creates an empty scene with no records and no hit targets.
602    pub fn new() -> Self {
603        let mut store = SceneStore::new();
604        store.follow(RecordEvents::LEAVES);
605        Self {
606            left_nodes: LeftNodes::default(),
607            store,
608            hits: RefCell::default(),
609            holds: SurfaceHolds::default(),
610            diagnostics: Rc::new(RenderDiagnostics::new()),
611            layer_moves: 0,
612        }
613    }
614
615    /// The diagnostics shared by the scene and its hit targets.
616    pub fn diagnostics(&self) -> &RenderDiagnostics {
617        self.diagnostics.as_ref()
618    }
619
620    /// The records the scene draws.
621    pub fn store(&self) -> &SceneStore {
622        &self.store
623    }
624
625    /// Keeps the changes of the kinds in `events` for the scene's readers
626    /// from the next update on, beside the leaves the scene reads itself;
627    /// see [`SceneStore::follow`].
628    pub fn follow(&mut self, events: RecordEvents) {
629        self.store.follow(events | RecordEvents::LEAVES);
630    }
631
632    /// Works out the reach of the records a change left stale; see
633    /// [`SceneStore::refresh_reach`].
634    #[cfg(feature = "window-damage")]
635    pub fn refresh_reach(&mut self) {
636        self.store.refresh_reach();
637    }
638
639    /// The root record, `None` while the scene is empty.
640    pub fn root_layer(&self) -> Option<LayerRef<'_>> {
641        self.store.root_layer()
642    }
643
644    /// Writes the layer tree `root` describes in place of the scene's
645    /// records. The hit targets follow it.
646    #[cfg(feature = "layer-tree")]
647    pub fn describe(&mut self, root: &LayerNode) {
648        self.store.describe(root);
649        self.hits.get_mut().stale = true;
650        self.layer_moves += 1;
651    }
652
653    /// Runs `edit` on the scene's records in a new update. The hit targets
654    /// follow them.
655    pub fn edit_store(&mut self, edit: impl FnOnce(&mut SceneStore)) {
656        self.store.begin_update();
657        edit(&mut self.store);
658        self.store.finish_update();
659        self.hits.get_mut().stale = true;
660        self.layer_moves += 1;
661    }
662
663    /// Lowers the layout tree below `root` again from the applier, its records
664    /// reusing the scene's storage. The hit targets follow it.
665    pub fn rebuild_from_applier(&mut self, applier: &MemoryApplier, root: NodeId) {
666        self.hits.get_mut().stale = true;
667        self.layer_moves += 1;
668        if crate::scene_builder::rebuild_from_applier(applier, root, &mut self.store) {
669            crate::scene_builder::publish_space(applier, &self.store);
670        }
671    }
672
673    // The hit targets, collected from the records first when they changed since
674    // they were.
675    fn fresh_hits(&self) -> Ref<'_, HitList> {
676        if self.hits.borrow().stale {
677            let mut list = self.hits.borrow_mut();
678            list.clear();
679            list.stale = false;
680            self.holds.collect_again();
681            if let Some(root) = self.store.root_layer() {
682                crate::hit_graph::collect_hits_from_graph(
683                    root,
684                    ProjectiveTransform::identity(),
685                    &mut HitTargets {
686                        list: &mut list,
687                        diagnostics: &self.diagnostics,
688                        holds: &self.holds,
689                    },
690                    None,
691                );
692            }
693        }
694        self.hits.borrow()
695    }
696
697    /// The hit targets in draw order, the last drawn at the end.
698    pub fn hit_targets(&self) -> Vec<HitRegion> {
699        self.fresh_hits().hits.clone()
700    }
701
702    /// How much storage the hit targets take.
703    pub fn hit_storage(&self) -> HitStorage {
704        let list = self.hits.borrow();
705        HitStorage {
706            hits_len: list.hits.len(),
707            hits_capacity: list.hits.capacity(),
708            node_index_len: list.node_index.len(),
709            node_index_capacity: list.node_index.capacity(),
710        }
711    }
712
713    /// Applies content and layer-property changes to the scene's records
714    /// in place and returns `true`, or rebuilds the scene and returns
715    /// `false`: for empty updates, an empty scene or an update that cannot
716    /// be applied in place. The hit targets follow the records when the
717    /// update changed a hit target or the geometry above one: each updated
718    /// layer compares its hit state, and the layers beneath one built again,
719    /// before and after.
720    pub fn update_from_applier(
721        &mut self,
722        applier: &MemoryApplier,
723        root: NodeId,
724        updates: SceneUpdates<'_>,
725    ) -> bool {
726        let report = crate::scene_builder::update_from_applier(applier, &mut self.store, updates);
727        if updates.is_empty() || !report.applied() {
728            self.rebuild_from_applier(applier, root);
729            return false;
730        }
731        crate::scene_builder::publish_space(applier, &self.store);
732        if report.hit_graph_dirty {
733            self.hits.get_mut().stale = true;
734        }
735        self.layer_moves += u64::from(report.layers_moved);
736        true
737    }
738
739    // Adds an interactive target in draw order, ignoring targets that neither
740    // handle a pointer nor name a pointer icon.
741    pub(crate) fn push_hit(
742        &mut self,
743        node_id: NodeId,
744        capture_path: &[NodeId],
745        geometry: HitGeometry<'_>,
746        target: HitTargetSpec<'_>,
747    ) {
748        HitTargets {
749            list: self.hits.get_mut(),
750            diagnostics: &self.diagnostics,
751            holds: &self.holds,
752        }
753        .push(node_id, capture_path, geometry, target);
754    }
755
756    // Removes all hit targets and releases their handlers while retaining
757    // their storage.
758    fn clear_hits(&mut self) {
759        let list = self.hits.get_mut();
760        list.clear();
761        list.stale = false;
762    }
763}
764
765impl Default for Scene {
766    fn default() -> Self {
767        Self::new()
768    }
769}
770
771impl RenderScene for Scene {
772    type HitTarget = HitRegion;
773
774    fn clear(&mut self) {
775        self.store.clear();
776        self.clear_hits();
777    }
778
779    fn trim(&mut self) -> bool {
780        crate::scene_builder::trim_dirty_room();
781        let rebuild = self.store.trim();
782        if rebuild {
783            self.clear();
784            self.store.trim();
785        }
786        rebuild
787    }
788
789    fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget> {
790        let list = self.fresh_hits();
791        let mut hit_indices: Vec<usize> = list
792            .hits
793            .iter()
794            .enumerate()
795            .filter_map(|(index, hit)| hit.contains(x, y).then_some(index))
796            .collect();
797
798        shared_sort::sort_positions(&mut hit_indices, &mut |a, b| {
799            list.hits[b].z_index.cmp(&list.hits[a].z_index)
800        });
801        hit_indices
802            .into_iter()
803            .map(|index| list.hits[index].clone())
804            .collect()
805    }
806
807    fn hit_test_near(&self, x: f32, y: f32) -> Option<Self::HitTarget> {
808        self.fresh_hits()
809            .hits
810            .iter()
811            .filter_map(|hit| hit.reach_distance(x, y).map(|distance| (distance, hit)))
812            .min_by(|(near, hit), (other_near, other)| {
813                near.total_cmp(other_near)
814                    .then_with(|| other.z_index.cmp(&hit.z_index))
815            })
816            .map(|(_, hit)| hit.clone())
817    }
818
819    fn find_target(&self, node_id: NodeId) -> Option<Self::HitTarget> {
820        let list = self.fresh_hits();
821        list.node_index
822            .get(&node_id)
823            .and_then(|&index| list.hits.get(index))
824            .cloned()
825    }
826
827    fn hit_test_ray(&self, scene: NodeId, ray: Ray) -> Vec<Self::HitTarget> {
828        let list = self.fresh_hits();
829        let mut hit: Vec<&HitRegion> = list
830            .hits
831            .iter()
832            .filter(|hit| {
833                hit.surface.as_ref().is_some_and(|surface| {
834                    surface.target.pick.scene() == Some(scene)
835                        && surface
836                            .local_point_along(ray)
837                            .is_some_and(|local| hit.contains_local(local))
838                })
839            })
840            .collect();
841        shared_sort::sort_by(&mut hit, |a, b| b.z_index.cmp(&a.z_index));
842        hit.into_iter().cloned().collect()
843    }
844
845    fn visit_meshes(&self, under: NodeId, visit: &mut dyn FnMut(&crate::space::MeshVisit<'_>)) {
846        let layer = self
847            .store
848            .root_layer()
849            .and_then(|root| crate::space::layer_of_node(root, under));
850        if let Some(layer) = layer {
851            crate::space::visit_meshes(layer, visit);
852        }
853    }
854
855    fn surface_windows(&self, visit: &mut dyn FnMut(NodeId, ProjectiveTransform)) {
856        let Some(root_layer) = self.store.root_layer() else {
857            return;
858        };
859        let root = ProjectiveTransform::identity();
860        crate::space::for_each_window_eye(root_layer, root, &mut |_, view, to_window| {
861            // The owner of a layer drawn on several meshes places it.
862            for seen in view.surfaces.iter().filter(|seen| seen.mesh == 0) {
863                if let (Some(node_id), Some(content)) = (
864                    seen.layer.node_id(),
865                    view.content_to_window(seen, to_window),
866                ) {
867                    visit(node_id, content);
868                }
869            }
870        });
871    }
872
873    fn surface_window_bounds(&self, node_id: NodeId) -> Option<Rect> {
874        let list = self.fresh_hits();
875        let hit = list.hits.get(*list.node_index.get(&node_id)?)?;
876        let surface = hit.surface.as_ref()?;
877        surface
878            .target
879            .window_bounds(&surface.content_to_local, hit.local_bounds)
880    }
881
882    fn node_window_bounds(&self, visit: &mut dyn FnMut(NodeId, Rect)) {
883        let Some(root) = self.store.root_layer() else {
884            return;
885        };
886        let mut surfaces = HashMap::default();
887        self.surface_windows(&mut |node_id, content| {
888            surfaces.insert(node_id, content);
889        });
890        crate::node_window_bounds::for_each_node_window_bounds(
891            root,
892            ProjectiveTransform::identity(),
893            &surfaces,
894            visit,
895        );
896    }
897
898    fn layer_moves(&self) -> u64 {
899        self.layer_moves
900    }
901
902    fn draws(&self, node: NodeId) -> bool {
903        self.store.record_of(node).is_some()
904    }
905
906    fn drawn_parent(&self, node: NodeId) -> Option<NodeId> {
907        self.store.drawn_parent(node)
908    }
909
910    fn read_left_nodes(&mut self, left: &mut Vec<NodeId>) -> bool {
911        self.left_nodes.read(&self.store, left)
912    }
913}
914
915fn point_in_rounded_rect(point: Point, rect: Rect, shape: RoundedCornerShape) -> bool {
916    if !rect.contains(point.x, point.y) {
917        return false;
918    }
919
920    let local_x = point.x - rect.x;
921    let local_y = point.y - rect.y;
922    let radii = shape.resolve(rect.width, rect.height);
923    let tl = radii.top_left;
924    let tr = radii.top_right;
925    let bl = radii.bottom_left;
926    let br = radii.bottom_right;
927
928    if local_x < tl && local_y < tl {
929        let dx = tl - local_x;
930        let dy = tl - local_y;
931        return dx * dx + dy * dy <= tl * tl;
932    }
933
934    if local_x > rect.width - tr && local_y < tr {
935        let dx = local_x - (rect.width - tr);
936        let dy = tr - local_y;
937        return dx * dx + dy * dy <= tr * tr;
938    }
939
940    if local_x < bl && local_y > rect.height - bl {
941        let dx = bl - local_x;
942        let dy = local_y - (rect.height - bl);
943        return dx * dx + dy * dy <= bl * bl;
944    }
945
946    if local_x > rect.width - br && local_y > rect.height - br {
947        let dx = local_x - (rect.width - br);
948        let dy = local_y - (rect.height - br);
949        return dx * dx + dy * dy <= br * br;
950    }
951
952    true
953}
954
955fn point_in_quad(point: Point, quad: [[f32; 2]; 4]) -> bool {
956    point_in_triangle(point, quad[0], quad[1], quad[3])
957        || point_in_triangle(point, quad[0], quad[3], quad[2])
958}
959
960fn point_in_triangle(point: Point, a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
961    let d1 = triangle_sign(point, a, b);
962    let d2 = triangle_sign(point, b, c);
963    let d3 = triangle_sign(point, c, a);
964    let has_negative = d1 < -f32::EPSILON || d2 < -f32::EPSILON || d3 < -f32::EPSILON;
965    let has_positive = d1 > f32::EPSILON || d2 > f32::EPSILON || d3 > f32::EPSILON;
966    !(has_negative && has_positive)
967}
968
969fn triangle_sign(point: Point, a: [f32; 2], b: [f32; 2]) -> f32 {
970    (point.x - b[0]) * (a[1] - b[1]) - (a[0] - b[0]) * (point.y - b[1])
971}
972
973#[cfg(test)]
974#[path = "tests/graph_scene_tests.rs"]
975mod tests;