Skip to main content

cranpose_render_common/
hit_graph.rs

1use std::rc::Rc;
2
3use cranpose_core::NodeId;
4use cranpose_ui_graphics::{Rect, layer_transform::layer_surface};
5use smallvec::SmallVec;
6
7use crate::{
8    graph::{HitTestNode, ProjectiveTransform, quad_bounds},
9    graph_scene::{
10        HitClip, HitGeometry, HitTargetSpec, HitTargets, Scene, SurfaceGeometry, SurfaceTarget,
11    },
12    primitive_emit::resolve_clip,
13    scene_pick::ScenePick,
14    scene_store::LayerRef,
15};
16
17/// Receives the hit targets that `collect_hits_from_graph` finds in a scene.
18pub trait HitGraphSink {
19    /// Records an interactive node. `capture_path` lists the node first and then its pointer-input
20    /// ancestors from the nearest outward, and `geometry` is in window space.
21    fn push_hit(
22        &mut self,
23        node_id: NodeId,
24        capture_path: &[NodeId],
25        geometry: HitGeometry<'_>,
26        hit: &HitTestNode,
27    );
28}
29
30impl HitGraphSink for Scene {
31    fn push_hit(
32        &mut self,
33        node_id: NodeId,
34        capture_path: &[NodeId],
35        geometry: HitGeometry<'_>,
36        hit: &HitTestNode,
37    ) {
38        Self::push_hit(self, node_id, capture_path, geometry, hit_spec(hit));
39    }
40}
41
42impl HitGraphSink for HitTargets<'_> {
43    fn push_hit(
44        &mut self,
45        node_id: NodeId,
46        capture_path: &[NodeId],
47        geometry: HitGeometry<'_>,
48        hit: &HitTestNode,
49    ) {
50        self.push(node_id, capture_path, geometry, hit_spec(hit));
51    }
52}
53
54fn hit_spec(hit: &HitTestNode) -> HitTargetSpec<'_> {
55    HitTargetSpec {
56        shape: None,
57        handlers: &hit.handlers,
58    }
59}
60
61/// Walks `layer` and the layers beneath it in draw order and pushes to `sink` a hit target for
62/// each node that has a hit test, with its geometry in window space. `parent_transform` maps
63/// the parent layer's space to the window, and `parent_hit_clip` is the clip bounds that the
64/// layers above impose.
65pub fn collect_hits_from_graph<S: HitGraphSink>(
66    layer: LayerRef<'_>,
67    parent_transform: ProjectiveTransform,
68    sink: &mut S,
69    parent_hit_clip: Option<Rect>,
70) {
71    if !layer.has_hit_targets() {
72        return;
73    }
74    let mut walk = HitWalk {
75        sink,
76        hit_clips: Vec::new(),
77        pointer_input_ancestors: Vec::new(),
78        capture_path: SmallVec::new(),
79        surface: None,
80    };
81    walk.visit(
82        layer,
83        parent_transform,
84        parent_hit_clip,
85        &ParentSpace::default(),
86    );
87}
88
89struct HitWalk<'s, S> {
90    sink: &'s mut S,
91    hit_clips: Vec<HitClip>,
92    pointer_input_ancestors: Vec<NodeId>,
93    capture_path: SmallVec<[NodeId; 8]>,
94    surface: Option<SurfaceWalk>,
95}
96
97struct SurfaceWalk {
98    target: Rc<SurfaceTarget>,
99    clips: Vec<HitClip>,
100}
101
102#[derive(Default)]
103struct ParentSpace {
104    scene: Option<Rc<ScenePick>>,
105    scene_clips: (Option<Rect>, usize),
106    content: Option<ProjectiveTransform>,
107    content_clip: Option<Rect>,
108    behind_doorway: bool,
109    unseen: bool,
110}
111
112impl<S: HitGraphSink> HitWalk<'_, S> {
113    fn visit(
114        &mut self,
115        layer: LayerRef<'_>,
116        parent_transform: ProjectiveTransform,
117        parent_hit_clip: Option<Rect>,
118        space: &ParentSpace,
119    ) {
120        if !layer.has_hit_targets() {
121            return;
122        }
123        // Behind a doorway the eye does not see through, nothing takes input.
124        let Some((doorway, unseen)) = Self::seen(layer, space) else {
125            return;
126        };
127        let transform = layer.transform_to_parent().then(parent_transform);
128        // The node's handlers sit on its own rect; its clip, at its layer's
129        // bounds, cuts them as it cuts what the layer holds.
130        let node_rect = layer.node_rect();
131        let transformed_quad = hit_quad(&transform, node_rect);
132        let transformed_rect = quad_bounds(transformed_quad);
133
134        // Inside a scene the camera's pick decides where the surfaces'
135        // content takes input, whatever their flat stand-ins show: an eye
136        // behind a wall still sees what lies through its doorway.
137        let in_scene = space.scene.is_some();
138        if !in_scene && (transformed_rect.width <= 0.0 || transformed_rect.height <= 0.0) {
139            return;
140        }
141        let world_to_local = match transform.inverse() {
142            Some(inverse) => inverse,
143            None if in_scene => ProjectiveTransform::identity(),
144            None => return,
145        };
146
147        let (entered, content, content_clip) = self.enter_content(layer, (space, doorway));
148        let behind_doorway = space.behind_doorway || doorway;
149        let Some((hit_clip_bounds, pushed_clip)) =
150            self.push_window_clip(layer, &transform, (parent_hit_clip, in_scene))
151        else {
152            self.leave(entered, content_clip.pushed);
153            return;
154        };
155
156        if let (Some(node_id), Some(hit), false) = (
157            layer.node_id(),
158            layer.hit_test(),
159            self.hides_targets(unseen, behind_doorway),
160        ) {
161            let geometry = PlacedNode {
162                rect: transformed_rect,
163                quad: transformed_quad,
164                local_bounds: node_rect,
165                world_to_local,
166                hit_clip_bounds,
167                content,
168                content_clip: content_clip.bounds,
169            };
170            self.push_node(node_id, hit, geometry);
171        }
172
173        let pointer_input_ancestor = layer
174            .hit_test()
175            .filter(|hit| !hit.handlers.pointer_inputs().is_empty())
176            .and_then(|_| layer.node_id());
177        if let Some(node_id) = pointer_input_ancestor {
178            self.pointer_input_ancestors.push(node_id);
179        }
180
181        let children_space = ParentSpace {
182            content,
183            content_clip: content_clip.bounds,
184            behind_doorway,
185            unseen,
186            ..self.children_scene(layer, (transform, hit_clip_bounds), space)
187        };
188        for child_layer in layer.children() {
189            self.visit(child_layer, transform, hit_clip_bounds, &children_space);
190        }
191
192        if pointer_input_ancestor.is_some() {
193            let _ = self.pointer_input_ancestors.pop();
194        }
195
196        if pushed_clip {
197            let _ = self.hit_clips.pop();
198        }
199        self.leave(entered, content_clip.pushed);
200    }
201
202    fn push_node(&mut self, node_id: NodeId, hit: &HitTestNode, node: PlacedNode) {
203        self.capture_path.clear();
204        self.capture_path.push(node_id);
205        self.capture_path
206            .extend(self.pointer_input_ancestors.iter().rev().copied());
207        let content_to_local = node.content.and_then(ProjectiveTransform::inverse);
208        let surface =
209            self.surface
210                .as_ref()
211                .zip(content_to_local)
212                .map(|(surface, content_to_local)| SurfaceGeometry {
213                    target: &surface.target,
214                    content_to_local,
215                    clip_bounds: node.content_clip,
216                    clips: &surface.clips,
217                });
218        self.sink.push_hit(
219            node_id,
220            &self.capture_path,
221            HitGeometry {
222                rect: node.rect,
223                quad: node.quad,
224                local_bounds: node.local_bounds,
225                world_to_local: node.world_to_local,
226                hit_clip_bounds: node.hit_clip_bounds,
227                hit_clips: &self.hit_clips,
228                surface,
229            },
230            hit,
231        );
232    }
233
234    fn children_scene(
235        &self,
236        layer: LayerRef<'_>,
237        (transform, hit_clip_bounds): (ProjectiveTransform, Option<Rect>),
238        space: &ParentSpace,
239    ) -> ParentSpace {
240        let through_portal = space
241            .scene
242            .as_ref()
243            .is_some_and(|scene| scene.holds_scene(layer));
244        let shown = match (layer.wraps(), through_portal) {
245            (None, false) => ScenePick::of(layer, transform).map(Rc::new),
246            _ => None,
247        };
248        let (scene, scene_clips) = match shown {
249            Some(pick) => (Some(pick), (hit_clip_bounds, self.hit_clips.len())),
250            None => (space.scene.clone(), space.scene_clips),
251        };
252        ParentSpace {
253            scene,
254            scene_clips,
255            ..ParentSpace::default()
256        }
257    }
258
259    fn enter_surface(
260        &mut self,
261        layer: LayerRef<'_>,
262        space: &ParentSpace,
263    ) -> Option<Option<SurfaceWalk>> {
264        let pick = space.scene.as_ref()?;
265        let index = pick.index_of(layer)?;
266        let (outer_clip_bounds, outer_clip_count) = space.scene_clips;
267        let target = Rc::new(SurfaceTarget {
268            pick: Rc::clone(pick),
269            index,
270            outer_clip_bounds,
271            outer_clips: self.hit_clips[..outer_clip_count.min(self.hit_clips.len())].to_vec(),
272        });
273        Some(self.surface.replace(SurfaceWalk {
274            target,
275            clips: Vec::new(),
276        }))
277    }
278
279    fn doorway(layer: LayerRef<'_>, space: &ParentSpace) -> Option<bool> {
280        let Some(pick) = space.scene.as_ref().filter(|pick| pick.holds_scene(layer)) else {
281            return Some(false);
282        };
283        pick.sees_scene(layer).then_some(true)
284    }
285
286    fn seen(layer: LayerRef<'_>, space: &ParentSpace) -> Option<(bool, bool)> {
287        let doorway = Self::doorway(layer, space)?;
288        let unseen = !doorway && (space.unseen || Self::unseen_surface(layer, space));
289        Some((doorway, unseen))
290    }
291
292    fn hides_targets(&self, unseen: bool, behind_doorway: bool) -> bool {
293        unseen || (behind_doorway && self.surface.is_none())
294    }
295
296    fn unseen_surface(layer: LayerRef<'_>, space: &ParentSpace) -> bool {
297        space.scene.as_ref().is_some_and(|pick| {
298            layer_surface(layer.graphics_layer()).is_some() && pick.index_of(layer).is_none()
299        })
300    }
301
302    fn enter_content(
303        &mut self,
304        layer: LayerRef<'_>,
305        (space, doorway): (&ParentSpace, bool),
306    ) -> (
307        Option<Option<SurfaceWalk>>,
308        Option<ProjectiveTransform>,
309        ContentClip,
310    ) {
311        if doorway {
312            let unclipped = ContentClip {
313                bounds: None,
314                pushed: false,
315            };
316            return (Some(self.surface.take()), None, unclipped);
317        }
318        let entered = self.enter_surface(layer, space);
319        // A surface's content starts a space of its own, which the clips of
320        // the content above do not cut.
321        let (content, above) = match entered {
322            Some(_) => (Some(ProjectiveTransform::identity()), None),
323            None => (
324                space
325                    .content
326                    .map(|parent| layer.transform_to_parent().then(parent)),
327                space.content_clip,
328            ),
329        };
330        let content_clip = self.push_content_clip(layer, content, above);
331        (entered, content, content_clip)
332    }
333
334    fn push_window_clip(
335        &mut self,
336        layer: LayerRef<'_>,
337        transform: &ProjectiveTransform,
338        (parent_hit_clip, in_scene): (Option<Rect>, bool),
339    ) -> Option<(Option<Rect>, bool)> {
340        let Some(local_clip) = layer.clip_rect().filter(|_| !in_scene) else {
341            return Some((parent_hit_clip, false));
342        };
343        let quad = hit_quad(transform, local_clip);
344        let bounds = quad_bounds(quad);
345        let resolved = resolve_clip(parent_hit_clip, Some(bounds));
346        if resolved.is_some_and(|clip| clip.is_empty()) {
347            return None;
348        }
349        self.hit_clips.push(HitClip { quad, bounds });
350        Some((resolved, true))
351    }
352
353    fn push_content_clip(
354        &mut self,
355        layer: LayerRef<'_>,
356        content: Option<ProjectiveTransform>,
357        parent_clip: Option<Rect>,
358    ) -> ContentClip {
359        let unclipped = ContentClip {
360            bounds: parent_clip,
361            pushed: false,
362        };
363        let (Some(surface), Some(content)) = (self.surface.as_mut(), content) else {
364            return unclipped;
365        };
366        let Some(local_clip) = layer.clip_rect() else {
367            return unclipped;
368        };
369        let quad = hit_quad(&content, local_clip);
370        let bounds = quad_bounds(quad);
371        surface.clips.push(HitClip { quad, bounds });
372        ContentClip {
373            bounds: resolve_clip(parent_clip, Some(bounds)),
374            pushed: true,
375        }
376    }
377
378    fn leave(&mut self, entered: Option<Option<SurfaceWalk>>, pushed_content_clip: bool) {
379        if pushed_content_clip && let Some(surface) = self.surface.as_mut() {
380            let _ = surface.clips.pop();
381        }
382        if let Some(previous) = entered {
383            self.surface = previous;
384        }
385    }
386}
387
388struct PlacedNode {
389    rect: Rect,
390    quad: [[f32; 2]; 4],
391    local_bounds: Rect,
392    world_to_local: ProjectiveTransform,
393    hit_clip_bounds: Option<Rect>,
394    content: Option<ProjectiveTransform>,
395    content_clip: Option<Rect>,
396}
397
398struct ContentClip {
399    bounds: Option<Rect>,
400    pushed: bool,
401}
402
403fn hit_quad(transform: &ProjectiveTransform, rect: Rect) -> [[f32; 2]; 4] {
404    if transform.rect_in_front(rect) {
405        return transform.map_rect(rect);
406    }
407    let bounds = transform.bounds_for_rect(rect);
408    let (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
409    [
410        [bounds.x, bounds.y],
411        [right, bounds.y],
412        [bounds.x, bottom],
413        [right, bottom],
414    ]
415}
416
417#[cfg(test)]
418#[path = "tests/hit_graph_tests.rs"]
419mod tests;