Skip to main content

strata/runtime/
spatial.rs

1//! Spatial acceleration index for hit-testing, point queries, and EntityId resolution.
2
3use std::collections::HashMap;
4use std::rc::Rc;
5use strata_dom::{Event, EventType, NodeBlueprint};
6use strata_layout::tree::LayoutNode;
7use strata_layout::Rect;
8use strata_primitives::EntityId;
9use strata_style::types::{Display, Float, Overflow, PointerEvents, Position, Visibility};
10
11use crate::runtime::AppRuntime;
12
13/// An individual spatial entry for an entity in the layout hierarchy.
14#[derive(Clone)]
15pub struct SpatialEntry {
16    pub entity_id: EntityId,
17    pub bounds: Rect,
18    pub event_listeners: Vec<(EventType, Rc<dyn Fn(Event)>)>,
19    pub z_index: i32,
20    pub order: usize,
21    root_z_key: i64,
22    clip_bounds: Option<Rect>,
23    hittable: bool,
24    layout_path: Vec<usize>,
25}
26
27impl SpatialEntry {
28    #[inline]
29    fn contains_clipped_point(&self, px: f32, py: f32) -> bool {
30        if !self.hittable || !self.bounds.contains_point(px, py) {
31            return false;
32        }
33        match self.clip_bounds {
34            Some(clip) => clip.width >= 0.0 && clip.height >= 0.0 && clip.contains_point(px, py),
35            None => true,
36        }
37    }
38}
39
40impl std::fmt::Debug for SpatialEntry {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("SpatialEntry")
43            .field("entity_id", &self.entity_id)
44            .field("bounds", &self.bounds)
45            .field("listeners_count", &self.event_listeners.len())
46            .field("z_index", &self.z_index)
47            .field("order", &self.order)
48            .finish()
49    }
50}
51
52#[inline]
53fn intersect_clip(existing: Option<Rect>, next: Rect) -> Option<Rect> {
54    match existing {
55        None => Some(next),
56        Some(prev) => {
57            if prev.width < 0.0 || prev.height < 0.0 {
58                return Some(prev);
59            }
60            let x0 = prev.x.max(next.x);
61            let y0 = prev.y.max(next.y);
62            let x1 = (prev.x + prev.width).min(next.x + next.width);
63            let y1 = (prev.y + prev.height).min(next.y + next.height);
64            if x1 < x0 || y1 < y0 {
65                Some(Rect::new(0.0, 0.0, -1.0, -1.0))
66            } else {
67                Some(Rect::new(x0, y0, x1 - x0, y1 - y0))
68            }
69        }
70    }
71}
72
73/// Accelerated spatial index maintaining entity bounding boxes and event listeners.
74#[derive(Default, Clone, Debug)]
75pub struct SpatialIndex {
76    entries: Vec<SpatialEntry>,
77    entity_to_index: HashMap<EntityId, usize>,
78}
79
80impl SpatialIndex {
81    /// Creates a new empty spatial index.
82    pub fn new() -> Self {
83        Self {
84            entries: Vec::new(),
85            entity_to_index: HashMap::new(),
86        }
87    }
88
89    /// Synchronizes cached entry bounding boxes from `layout_root` in O(entries) without
90    /// walking blueprints or reallocating the index (used on high-frequency scroll ticks).
91    pub fn sync_bounds(&mut self, layout_root: &LayoutNode) {
92        if self.entries.is_empty() {
93            return;
94        }
95        for entry in &mut self.entries {
96            let mut cur = layout_root;
97            let mut valid = true;
98            for &idx in &entry.layout_path {
99                if let Some(child) = cur.children.get(idx) {
100                    cur = child;
101                } else {
102                    valid = false;
103                    break;
104                }
105            }
106            if valid {
107                entry.bounds = cur.geometry.border_box;
108            }
109        }
110    }
111
112    /// Synchronizes cached entry bounding boxes only for descendants of `prefix`, avoiding
113    /// unrelated root-to-node layout walks on high-frequency smooth scroll ticks.
114    pub fn sync_bounds_for_prefix(&mut self, layout_root: &LayoutNode, prefix: &[usize]) {
115        if self.entries.is_empty() {
116            return;
117        }
118        if prefix.is_empty() {
119            self.sync_bounds(layout_root);
120            return;
121        }
122        let mut prefix_root = layout_root;
123        for &idx in prefix {
124            if let Some(child) = prefix_root.children.get(idx) {
125                prefix_root = child;
126            } else {
127                return;
128            }
129        }
130        let prefix_len = prefix.len();
131        for entry in &mut self.entries {
132            if entry.layout_path.len() <= prefix_len || !entry.layout_path.starts_with(prefix) {
133                continue;
134            }
135            let mut cur = prefix_root;
136            let mut valid = true;
137            for &idx in &entry.layout_path[prefix_len..] {
138                if let Some(child) = cur.children.get(idx) {
139                    cur = child;
140                } else {
141                    valid = false;
142                    break;
143                }
144            }
145            if valid {
146                entry.bounds = cur.geometry.border_box;
147            }
148        }
149    }
150
151    fn collect_top_layer_portals<'a>(
152        bp: &'a NodeBlueprint,
153        layout: &'a LayoutNode,
154        fallback_bp: &'a NodeBlueprint,
155        current_path: &mut Vec<usize>,
156        out: &mut Vec<(&'a NodeBlueprint, &'a LayoutNode, Vec<usize>)>,
157        depth: usize,
158    ) {
159        if depth >= 256 {
160            return;
161        }
162        for (idx, child_bp, child_layout) in
163            Self::paired_children_with_fallback(bp, layout, fallback_bp)
164        {
165            if child_layout.style.display == Display::None {
166                continue;
167            }
168            current_path.push(idx);
169            if child_layout.is_top_layer {
170                out.push((child_bp, child_layout, current_path.clone()));
171            }
172            if !child_layout.children.is_empty() {
173                Self::collect_top_layer_portals(
174                    child_bp,
175                    child_layout,
176                    fallback_bp,
177                    current_path,
178                    out,
179                    depth + 1,
180                );
181            }
182            current_path.pop();
183        }
184    }
185
186    /// Clears and rebuilds the spatial index from the active blueprint and computed layout hierarchy.
187    pub fn rebuild(&mut self, blueprint: &NodeBlueprint, layout: &LayoutNode) {
188        self.entries.clear();
189        self.entity_to_index.clear();
190
191        let mut order = 0;
192        let mut path = Vec::new();
193        let root_z = layout.style.z_index.unwrap_or(0);
194        Self::collect_stacking_context(
195            blueprint,
196            layout,
197            &mut path,
198            &mut self.entries,
199            &mut order,
200            root_z,
201            i64::MIN,
202            true,
203            &[],
204            0,
205        );
206
207        let fallback_bp = NodeBlueprint::Empty;
208        let mut portals = Vec::new();
209        path.clear();
210        Self::collect_top_layer_portals(
211            blueprint,
212            layout,
213            &fallback_bp,
214            &mut path,
215            &mut portals,
216            0,
217        );
218        for (p_bp, p_layout, mut p_path) in portals {
219            let p_z = p_layout.style.z_index.unwrap_or(0);
220            Self::collect_stacking_context(
221                p_bp,
222                p_layout,
223                &mut p_path,
224                &mut self.entries,
225                &mut order,
226                p_z,
227                i64::MAX,
228                false,
229                &[],
230                1,
231            );
232        }
233
234        for (idx, entry) in self.entries.iter().enumerate() {
235            if entry.entity_id.is_valid() {
236                self.entity_to_index.insert(entry.entity_id, idx);
237            }
238        }
239    }
240
241    #[inline]
242    fn steps_to_clip(steps: &[super::hit_test::HitClipStep]) -> Option<Rect> {
243        let mut acc: Option<Rect> = None;
244        for s in steps {
245            if let Some(r) = s.clip {
246                acc = intersect_clip(acc, r);
247            }
248        }
249        acc
250    }
251
252    #[allow(clippy::too_many_arguments)]
253    fn emit_node_entry(
254        blueprint: &NodeBlueprint,
255        layout: &LayoutNode,
256        layout_path: &[usize],
257        out: &mut Vec<SpatialEntry>,
258        order: &mut usize,
259        effective_z: i32,
260        root_z_key: i64,
261        active_clip: Option<Rect>,
262    ) {
263        let entity_id = layout.entity_id;
264        let bounds = layout.geometry.border_box;
265        let mut listeners = Vec::new();
266
267        if let NodeBlueprint::Element { attributes, .. } = blueprint {
268            for attr in attributes {
269                if let strata_dom::Attribute::EventListener { event, handler } = attr {
270                    listeners.push((*event, Rc::clone(handler)));
271                }
272            }
273        }
274
275        if entity_id.is_valid() || !listeners.is_empty() {
276            let hittable = !matches!(layout.style.visibility, Visibility::Hidden)
277                && !matches!(layout.style.pointer_events, PointerEvents::None);
278            let entry = SpatialEntry {
279                entity_id,
280                bounds,
281                event_listeners: listeners,
282                z_index: effective_z,
283                order: *order,
284                root_z_key,
285                clip_bounds: active_clip,
286                hittable,
287                layout_path: layout_path.to_vec(),
288            };
289            *order += 1;
290            out.push(entry);
291        }
292    }
293
294    fn paired_children_with_fallback<'a>(
295        node_bp: &'a NodeBlueprint,
296        node_layout: &'a LayoutNode,
297        fallback_bp: &'a NodeBlueprint,
298    ) -> Vec<(usize, &'a NodeBlueprint, &'a LayoutNode)> {
299        let mut flat_children = Vec::new();
300        match node_bp {
301            NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
302                for c in children {
303                    AppRuntime::flatten_blueprints(c, &mut flat_children);
304                }
305            }
306            _ => {}
307        }
308
309        let mut out = Vec::with_capacity(node_layout.children.len());
310        for (idx, child_layout) in node_layout.children.iter().enumerate() {
311            let resolved_bp = if child_layout.entity_id.is_valid() {
312                if let Some(&cand) = flat_children.get(idx) {
313                    if cand.entity_id() == Some(child_layout.entity_id) {
314                        cand
315                    } else {
316                        node_bp
317                            .find_by_entity_id(child_layout.entity_id)
318                            .unwrap_or(cand)
319                    }
320                } else {
321                    node_bp
322                        .find_by_entity_id(child_layout.entity_id)
323                        .unwrap_or(fallback_bp)
324                }
325            } else {
326                flat_children.get(idx).copied().unwrap_or(fallback_bp)
327            };
328            out.push((idx, resolved_bp, child_layout));
329        }
330        out
331    }
332
333    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
334    fn collect_hoisted_participants<'a>(
335        bp: &'a NodeBlueprint,
336        layout: &'a LayoutNode,
337        fallback_bp: &'a NodeBlueprint,
338        current_path: &mut Vec<usize>,
339        steps: &[super::hit_test::HitClipStep],
340        negative_z: &mut Vec<(
341            &'a NodeBlueprint,
342            &'a LayoutNode,
343            Vec<usize>,
344            Vec<super::hit_test::HitClipStep>,
345        )>,
346        auto_or_zero_z: &mut Vec<(
347            &'a NodeBlueprint,
348            &'a LayoutNode,
349            Vec<usize>,
350            bool,
351            Vec<super::hit_test::HitClipStep>,
352        )>,
353        positive_z: &mut Vec<(
354            &'a NodeBlueprint,
355            &'a LayoutNode,
356            Vec<usize>,
357            Vec<super::hit_test::HitClipStep>,
358        )>,
359        depth: usize,
360    ) {
361        if depth >= 256 {
362            return;
363        }
364        let parent_display = Some(layout.style.display);
365        for (idx, child_bp, child_layout) in
366            Self::paired_children_with_fallback(bp, layout, fallback_bp)
367        {
368            if child_layout.style.display == Display::None || child_layout.is_top_layer {
369                continue;
370            }
371            current_path.push(idx);
372            if AppRuntime::establishes_stacking_context_in(child_layout, parent_display, false) {
373                let eff_steps = AppRuntime::effective_hit_clip_steps(child_layout, steps).to_vec();
374                let z = child_layout.style.z_index.unwrap_or(0);
375                if z < 0 {
376                    negative_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
377                } else if z > 0 {
378                    positive_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
379                } else {
380                    auto_or_zero_z.push((
381                        child_bp,
382                        child_layout,
383                        current_path.clone(),
384                        true,
385                        eff_steps,
386                    ));
387                }
388            } else {
389                let eff_for_child = AppRuntime::effective_hit_clip_steps(child_layout, steps);
390                if child_layout.style.position != Position::Static {
391                    auto_or_zero_z.push((
392                        child_bp,
393                        child_layout,
394                        current_path.clone(),
395                        false,
396                        eff_for_child.to_vec(),
397                    ));
398                }
399                let mut child_steps = Vec::with_capacity(eff_for_child.len() + 1);
400                child_steps.extend_from_slice(eff_for_child);
401                let step = AppRuntime::hit_clip_step_for(child_layout);
402                if step.clip.is_some() || step.is_abs_cb || step.is_fixed_cb {
403                    child_steps.push(step);
404                }
405                Self::collect_hoisted_participants(
406                    child_bp,
407                    child_layout,
408                    fallback_bp,
409                    current_path,
410                    &child_steps,
411                    negative_z,
412                    auto_or_zero_z,
413                    positive_z,
414                    depth + 1,
415                );
416            }
417            current_path.pop();
418        }
419    }
420
421    #[allow(clippy::too_many_arguments)]
422    fn collect_direct_in_flow_children(
423        bp: &NodeBlueprint,
424        layout: &LayoutNode,
425        current_path: &mut Vec<usize>,
426        out: &mut Vec<SpatialEntry>,
427        order: &mut usize,
428        inherited_z: i32,
429        root_z_key: i64,
430        active_clip: Option<Rect>,
431        depth: usize,
432    ) {
433        let fallback_bp = NodeBlueprint::Empty;
434        let paired = Self::paired_children_with_fallback(bp, layout, &fallback_bp);
435        if paired.is_empty() {
436            return;
437        }
438
439        let parent_display = Some(layout.style.display);
440        let is_in_flow_non_sc = |c: &LayoutNode| {
441            c.style.display != Display::None
442                && !c.is_top_layer
443                && !AppRuntime::establishes_stacking_context_in(c, parent_display, false)
444                && c.style.position == Position::Static
445        };
446        let is_inline_level = |c: &LayoutNode| {
447            matches!(
448                c.style.display,
449                Display::Inline | Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
450            )
451        };
452
453        // Layer 3: In-flow blocks
454        for &(idx, child_bp, child_layout) in &paired {
455            if is_in_flow_non_sc(child_layout)
456                && child_layout.style.float == Float::None
457                && !is_inline_level(child_layout)
458            {
459                current_path.push(idx);
460                Self::collect_in_flow_non_hoisted(
461                    child_bp,
462                    child_layout,
463                    current_path,
464                    out,
465                    order,
466                    inherited_z,
467                    root_z_key,
468                    active_clip,
469                    depth + 1,
470                );
471                current_path.pop();
472            }
473        }
474
475        // Layer 4: Floats
476        for &(idx, child_bp, child_layout) in &paired {
477            if is_in_flow_non_sc(child_layout) && child_layout.style.float != Float::None {
478                current_path.push(idx);
479                Self::collect_in_flow_non_hoisted(
480                    child_bp,
481                    child_layout,
482                    current_path,
483                    out,
484                    order,
485                    inherited_z,
486                    root_z_key,
487                    active_clip,
488                    depth + 1,
489                );
490                current_path.pop();
491            }
492        }
493
494        // Layer 5: In-flow inlines
495        for &(idx, child_bp, child_layout) in &paired {
496            if is_in_flow_non_sc(child_layout)
497                && child_layout.style.float == Float::None
498                && is_inline_level(child_layout)
499            {
500                current_path.push(idx);
501                Self::collect_in_flow_non_hoisted(
502                    child_bp,
503                    child_layout,
504                    current_path,
505                    out,
506                    order,
507                    inherited_z,
508                    root_z_key,
509                    active_clip,
510                    depth + 1,
511                );
512                current_path.pop();
513            }
514        }
515    }
516
517    #[allow(clippy::too_many_arguments)]
518    fn collect_in_flow_non_hoisted(
519        bp: &NodeBlueprint,
520        layout: &LayoutNode,
521        current_path: &mut Vec<usize>,
522        out: &mut Vec<SpatialEntry>,
523        order: &mut usize,
524        inherited_z: i32,
525        root_z_key: i64,
526        active_clip: Option<Rect>,
527        depth: usize,
528    ) {
529        if depth >= 256 || layout.style.display == Display::None {
530            return;
531        }
532        let effective_z = layout.style.z_index.unwrap_or(inherited_z);
533        Self::emit_node_entry(
534            bp,
535            layout,
536            current_path,
537            out,
538            order,
539            effective_z,
540            root_z_key,
541            active_clip,
542        );
543        let child_clip = if layout.style.overflow_x != Overflow::Visible
544            || layout.style.overflow_y != Overflow::Visible
545        {
546            intersect_clip(active_clip, layout.geometry.border_box)
547        } else {
548            active_clip
549        };
550        Self::collect_direct_in_flow_children(
551            bp,
552            layout,
553            current_path,
554            out,
555            order,
556            effective_z,
557            root_z_key,
558            child_clip,
559            depth,
560        );
561    }
562
563    #[allow(clippy::too_many_arguments)]
564    fn collect_stacking_context(
565        bp: &NodeBlueprint,
566        layout: &LayoutNode,
567        current_path: &mut Vec<usize>,
568        out: &mut Vec<SpatialEntry>,
569        order: &mut usize,
570        effective_z: i32,
571        self_root_z_key: i64,
572        is_root: bool,
573        inherited_steps: &[super::hit_test::HitClipStep],
574        depth: usize,
575    ) {
576        if depth >= 256 || layout.style.display == Display::None {
577            return;
578        }
579
580        let eff_inherited = AppRuntime::effective_hit_clip_steps(layout, inherited_steps);
581        let self_clip = Self::steps_to_clip(eff_inherited);
582
583        // Layer 1: Stacking context root element itself
584        Self::emit_node_entry(
585            bp,
586            layout,
587            current_path,
588            out,
589            order,
590            effective_z,
591            self_root_z_key,
592            self_clip,
593        );
594
595        let mut base_steps = Vec::with_capacity(eff_inherited.len() + 1);
596        base_steps.extend_from_slice(eff_inherited);
597        let own_step = AppRuntime::hit_clip_step_for(layout);
598        if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
599            base_steps.push(own_step);
600        }
601        let in_flow_clip = Self::steps_to_clip(&base_steps);
602
603        let fallback_bp = NodeBlueprint::Empty;
604        let mut negative_z = Vec::new();
605        let mut auto_or_zero_z = Vec::new();
606        let mut positive_z = Vec::new();
607        Self::collect_hoisted_participants(
608            bp,
609            layout,
610            &fallback_bp,
611            current_path,
612            &base_steps,
613            &mut negative_z,
614            &mut auto_or_zero_z,
615            &mut positive_z,
616            depth + 1,
617        );
618
619        negative_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
620        positive_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
621
622        // Layer 2: Child stacking contexts with negative z-index (ascending)
623        for (c_bp, c_layout, mut c_path, c_steps) in negative_z {
624            let cz = c_layout.style.z_index.unwrap_or(0);
625            let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
626            Self::collect_stacking_context(
627                c_bp,
628                c_layout,
629                &mut c_path,
630                out,
631                order,
632                cz,
633                child_root_key,
634                false,
635                &c_steps,
636                depth + 1,
637            );
638        }
639
640        // Layers 3, 4, 5: In-flow blocks, floats, and inlines
641        let normal_root_key = if is_root { 0 } else { self_root_z_key };
642        Self::collect_direct_in_flow_children(
643            bp,
644            layout,
645            current_path,
646            out,
647            order,
648            effective_z,
649            normal_root_key,
650            in_flow_clip,
651            depth,
652        );
653
654        // Layer 6: Positioned descendants with z-index: auto and child stacking contexts with z-index: 0
655        for (c_bp, c_layout, mut c_path, is_sc, c_steps) in auto_or_zero_z {
656            if is_sc {
657                let cz = c_layout.style.z_index.unwrap_or(effective_z);
658                Self::collect_stacking_context(
659                    c_bp,
660                    c_layout,
661                    &mut c_path,
662                    out,
663                    order,
664                    cz,
665                    normal_root_key,
666                    false,
667                    &c_steps,
668                    depth + 1,
669                );
670            } else {
671                let eff_c = AppRuntime::effective_hit_clip_steps(c_layout, &c_steps);
672                let c_clip = Self::steps_to_clip(eff_c);
673                Self::collect_in_flow_non_hoisted(
674                    c_bp,
675                    c_layout,
676                    &mut c_path,
677                    out,
678                    order,
679                    effective_z,
680                    normal_root_key,
681                    c_clip,
682                    depth + 1,
683                );
684            }
685        }
686
687        // Layer 7: Child stacking contexts with positive z-index (ascending)
688        for (c_bp, c_layout, mut c_path, c_steps) in positive_z {
689            let cz = c_layout.style.z_index.unwrap_or(0);
690            let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
691            Self::collect_stacking_context(
692                c_bp,
693                c_layout,
694                &mut c_path,
695                out,
696                order,
697                cz,
698                child_root_key,
699                false,
700                &c_steps,
701                depth + 1,
702            );
703        }
704    }
705
706    /// Queries the front-most / deepest EntityId at point (px, py), honoring stacking `z_index` and paint order.
707    pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<EntityId> {
708        let mut best: Option<&SpatialEntry> = None;
709        for entry in self.entries.iter().rev() {
710            if entry.entity_id.is_valid() && entry.contains_clipped_point(px, py) {
711                match best {
712                    None => best = Some(entry),
713                    Some(cur) => {
714                        if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
715                            best = Some(entry);
716                        }
717                    }
718                }
719            }
720        }
721        best.map(|e| e.entity_id)
722    }
723
724    /// Queries the front-most event listener registered for `event_type` at point (px, py),
725    /// honoring stacking `z_index` and paint order.
726    pub fn query_event_at_point(
727        &self,
728        px: f32,
729        py: f32,
730        event_type: EventType,
731    ) -> Option<(EntityId, Rc<dyn Fn(Event)>, Rect)> {
732        let mut best: Option<(&SpatialEntry, &Rc<dyn Fn(Event)>)> = None;
733        for entry in self.entries.iter().rev() {
734            if entry.contains_clipped_point(px, py) {
735                for (ev, handler) in &entry.event_listeners {
736                    if *ev == event_type {
737                        match best {
738                            None => best = Some((entry, handler)),
739                            Some((cur, _)) => {
740                                if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
741                                    best = Some((entry, handler));
742                                }
743                            }
744                        }
745                        break;
746                    }
747                }
748            }
749        }
750        best.map(|(entry, handler)| (entry.entity_id, Rc::clone(handler), entry.bounds))
751    }
752
753    /// Returns the bounding box of an entity if present in the index.
754    pub fn get_bounds(&self, entity_id: EntityId) -> Option<Rect> {
755        let idx = self.entity_to_index.get(&entity_id)?;
756        Some(self.entries[*idx].bounds)
757    }
758
759    /// Returns the total number of indexed spatial entries.
760    pub fn len(&self) -> usize {
761        self.entries.len()
762    }
763
764    /// Returns true if the index has no spatial entries.
765    pub fn is_empty(&self) -> bool {
766        self.entries.is_empty()
767    }
768}