euv-core 0.48.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
use super::*;

/// Finds the topmost interactive scene node containing `point`, respecting z-index and clipping with zero heap allocations.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree after layout.
/// - `Point` - Logical pointer coordinates in root space.
///
/// # Returns
///
/// - `Option<NodeId>` - Topmost matching node handle, if any.
#[must_use]
pub fn hit_test(tree: &SceneTree, point: Point) -> Option<NodeId> {
    let mut visited: usize = 0;
    hit_test_with_cache(tree, point, None, &mut visited)
}

/// Finds the topmost interactive scene node containing `point` using optional spatial `subtree_bounds` pruning.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree after layout.
/// - `Point` - Logical pointer coordinates in root space.
/// - `Option<&SplitLayoutCache>` - Optional synced layout cache providing `subtree_bounds` and `has_nonzero_z_child`.
/// - `&mut usize` - Output counter incremented once per inspected scene node.
///
/// # Returns
///
/// - `Option<NodeId>` - Topmost matching node handle, if any.
#[must_use]
pub(crate) fn hit_test_with_cache(
    tree: &SceneTree,
    point: Point,
    cache: Option<&SplitLayoutCache>,
    visited: &mut usize,
) -> Option<NodeId> {
    let active_cache: Option<&SplitLayoutCache> =
        cache.filter(|c: &&SplitLayoutCache| c.is_synced_with(tree));
    let registered: &[NodeId] = tree.portal_nodes();
    if !registered.is_empty() {
        let root: NodeId = tree.get_root();
        let portal_query: HitTestQuery<'_> = HitTestQuery {
            tree,
            point,
            in_portal_pass: true,
            active_cache,
        };
        let mut stack_portals: [PortalZItem; HIT_TEST_STACK_PORTAL_CAP] =
            [PortalZItem::default(); HIT_TEST_STACK_PORTAL_CAP];
        let mut stack_len: usize = 0;
        let mut overflowed: bool = false;
        for portal_id in registered.iter().copied() {
            if is_active_top_layer_portal(tree, root, portal_id)
                && let Some(node) = tree.get_node(portal_id)
            {
                let item: PortalZItem = PortalZItem {
                    z_index: node.style_ref().get_layout().get_z_index(),
                    node_id: portal_id,
                };
                if stack_len < HIT_TEST_STACK_PORTAL_CAP {
                    stack_portals[stack_len] = item;
                    stack_len += 1;
                } else {
                    overflowed = true;
                    break;
                }
            }
        }
        if overflowed {
            if let Some(hit) = hit_test_overflow_portals(portal_query, root, registered, visited) {
                return Some(hit);
            }
        } else if stack_len == 1 {
            if let Some(hit) = hit_test_subtree(
                portal_query,
                stack_portals[0].node_id,
                Point::new(0.0, 0.0),
                None,
                visited,
            ) {
                return Some(hit);
            }
        } else if stack_len > 1 {
            stack_portals[..stack_len].sort_unstable_by(|a: &PortalZItem, b: &PortalZItem| {
                b.z_index.cmp(&a.z_index).then_with(|| {
                    let (rb, ra): (usize, usize) = tree_order_pair(tree, b.node_id, a.node_id);
                    rb.cmp(&ra)
                })
            });
            for item in stack_portals[..stack_len].iter().copied() {
                if let Some(hit) = hit_test_subtree(
                    portal_query,
                    item.node_id,
                    Point::new(0.0, 0.0),
                    None,
                    visited,
                ) {
                    return Some(hit);
                }
            }
        }
    }
    let root_query: HitTestQuery<'_> = HitTestQuery {
        tree,
        point,
        in_portal_pass: false,
        active_cache,
    };
    hit_test_subtree(
        root_query,
        tree.get_root(),
        Point::new(0.0, 0.0),
        None,
        visited,
    )
}

/// Fallback top-layer portal pass using thread-local reusable scratch storage when active portals exceed `HIT_TEST_STACK_PORTAL_CAP`.
///
/// # Arguments
///
/// - `HitTestQuery<'_>` - Immutable top-layer hit-test query context.
/// - `NodeId` - Scene root node handle.
/// - `&[NodeId]` - Registered portal and fixed node handles.
/// - `&mut usize` - Visited node counter.
///
/// # Returns
///
/// - `Option<NodeId>` - Topmost matching portal descendant, if any.
fn hit_test_overflow_portals(
    query: HitTestQuery<'_>,
    root: NodeId,
    registered: &[NodeId],
    visited: &mut usize,
) -> Option<NodeId> {
    let range_opt: Option<(usize, usize)> = HIT_TEST_SCRATCH
        .try_with(|cell: &RefCell<HitTestScratch>| {
            let Ok(mut scratch) = cell.try_borrow_mut() else {
                return None;
            };
            let base: usize = scratch.portals.len();
            for portal_id in registered.iter().copied() {
                if is_active_top_layer_portal(query.tree, root, portal_id)
                    && let Some(node) = query.tree.get_node(portal_id)
                {
                    scratch.portals.push(PortalZItem {
                        z_index: node.style_ref().get_layout().get_z_index(),
                        node_id: portal_id,
                    });
                }
            }
            let end: usize = scratch.portals.len();
            scratch.portals[base..end].sort_unstable_by(|a: &PortalZItem, b: &PortalZItem| {
                b.z_index.cmp(&a.z_index).then_with(|| {
                    let (rb, ra): (usize, usize) =
                        tree_order_pair_stack_only(query.tree, b.node_id, a.node_id);
                    rb.cmp(&ra)
                })
            });
            Some((base, end))
        })
        .ok()
        .flatten();
    let (base, end): (usize, usize) = range_opt?;
    let mut found: Option<NodeId> = None;
    for idx in base..end {
        let portal_id_opt: Option<NodeId> = HIT_TEST_SCRATCH
            .try_with(|cell: &RefCell<HitTestScratch>| {
                cell.try_borrow()
                    .ok()
                    .and_then(|s: Ref<'_, HitTestScratch>| {
                        s.portals.get(idx).map(|p: &PortalZItem| p.node_id)
                    })
            })
            .ok()
            .flatten();
        if let Some(portal_id) = portal_id_opt
            && let Some(hit) =
                hit_test_subtree(query, portal_id, Point::new(0.0, 0.0), None, visited)
        {
            found = Some(hit);
            break;
        }
    }
    let _truncated: bool = HIT_TEST_SCRATCH
        .try_with(|cell: &RefCell<HitTestScratch>| {
            if let Ok(mut scratch) = cell.try_borrow_mut() {
                scratch.portals.truncate(base);
            }
        })
        .is_ok();
    found
}

/// Checks in O(depth) whether `portal_id` is a visible, root-attached top-layer portal not nested inside another portal.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree.
/// - `NodeId` - Root scene node handle.
/// - `NodeId` - Candidate portal or `Position::Fixed` node handle.
///
/// # Returns
///
/// - `bool` - `true` when `portal_id` participates in the top-layer hit-test pass.
fn is_active_top_layer_portal(tree: &SceneTree, root: NodeId, portal_id: NodeId) -> bool {
    let Some(node) = tree.get_node(portal_id) else {
        return false;
    };
    let Style { layout, paint, .. } = node.style_ref();
    if layout.get_display() == Display::None
        || paint.get_pointer_events() == PointerEvents::None
        || paint.get_opacity() <= 0.001
    {
        return false;
    }
    let is_portal: bool =
        matches!(node.get_kind(), NodeKind::Portal) || layout.get_position() == Position::Fixed;
    if !is_portal {
        return false;
    }
    if portal_id == root {
        return true;
    }
    let mut cursor: Option<NodeId> = node.parent_id();
    while let Some(pid) = cursor {
        let Some(pnode) = tree.get_node(pid) else {
            return false;
        };
        let Style {
            layout: playout,
            paint: ppaint,
            ..
        } = pnode.style_ref();
        if playout.get_display() == Display::None
            || ppaint.get_pointer_events() == PointerEvents::None
            || ppaint.get_opacity() <= 0.001
        {
            return false;
        }
        let parent_is_portal: bool = matches!(pnode.get_kind(), NodeKind::Portal)
            || playout.get_position() == Position::Fixed;
        if parent_is_portal {
            return false;
        }
        if pid == root {
            return true;
        }
        cursor = pnode.parent_id();
    }
    false
}

/// Computes an order-preserving `(rank_a, rank_b)` pair comparing tree preorder of `a` and `b` in O(depth) with zero heap allocation up to `HIT_TEST_STACK_PATH_CAP`.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree.
/// - `NodeId` - First root-attached node handle.
/// - `NodeId` - Second root-attached node handle.
///
/// # Returns
///
/// - `(usize, usize)` - Comparable rank pair where `rank_a < rank_b` iff `a` precedes `b` in preorder.
fn tree_order_pair(tree: &SceneTree, a: NodeId, b: NodeId) -> (usize, usize) {
    if a == b {
        return (0, 0);
    }
    let mut path_a: [NodeId; HIT_TEST_STACK_PATH_CAP] =
        [NodeId::default(); HIT_TEST_STACK_PATH_CAP];
    let mut len_a: usize = 0;
    let mut cur_a: Option<NodeId> = Some(a);
    let mut overflow_a: bool = false;
    while let Some(id) = cur_a {
        if len_a < HIT_TEST_STACK_PATH_CAP {
            path_a[len_a] = id;
            len_a += 1;
        } else {
            overflow_a = true;
            break;
        }
        cur_a = tree.get_node(id).and_then(SceneNode::parent_id);
    }
    let mut path_b: [NodeId; HIT_TEST_STACK_PATH_CAP] =
        [NodeId::default(); HIT_TEST_STACK_PATH_CAP];
    let mut len_b: usize = 0;
    let mut cur_b: Option<NodeId> = Some(b);
    let mut overflow_b: bool = false;
    while let Some(id) = cur_b {
        if len_b < HIT_TEST_STACK_PATH_CAP {
            path_b[len_b] = id;
            len_b += 1;
        } else {
            overflow_b = true;
            break;
        }
        cur_b = tree.get_node(id).and_then(SceneNode::parent_id);
    }
    if !overflow_a && !overflow_b {
        path_a[..len_a].reverse();
        path_b[..len_b].reverse();
        return compare_root_paths(tree, &path_a[..len_a], &path_b[..len_b], a, b);
    }
    HIT_TEST_SCRATCH
        .try_with(|cell: &RefCell<HitTestScratch>| {
            let Ok(mut scratch) = cell.try_borrow_mut() else {
                return (a.as_usize(), b.as_usize());
            };
            scratch.path_a.clear();
            let mut ca: Option<NodeId> = Some(a);
            while let Some(id) = ca {
                scratch.path_a.push(id);
                ca = tree.get_node(id).and_then(SceneNode::parent_id);
            }
            scratch.path_a.reverse();
            scratch.path_b.clear();
            let mut cb: Option<NodeId> = Some(b);
            while let Some(id) = cb {
                scratch.path_b.push(id);
                cb = tree.get_node(id).and_then(SceneNode::parent_id);
            }
            scratch.path_b.reverse();
            let res: (usize, usize) =
                compare_root_paths(tree, &scratch.path_a, &scratch.path_b, a, b);
            scratch.path_a.clear();
            scratch.path_b.clear();
            res
        })
        .unwrap_or((a.as_usize(), b.as_usize()))
}

/// Stack-only preorder comparison safe to invoke while `HIT_TEST_SCRATCH` is already mutably borrowed.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree.
/// - `NodeId` - First node handle.
/// - `NodeId` - Second node handle.
///
/// # Returns
///
/// - `(usize, usize)` - Comparable preorder rank pair.
fn tree_order_pair_stack_only(tree: &SceneTree, a: NodeId, b: NodeId) -> (usize, usize) {
    if a == b {
        return (0, 0);
    }
    let mut path_a: [NodeId; HIT_TEST_STACK_PATH_CAP] =
        [NodeId::default(); HIT_TEST_STACK_PATH_CAP];
    let mut len_a: usize = 0;
    let mut cur_a: Option<NodeId> = Some(a);
    while let Some(id) = cur_a {
        if len_a == HIT_TEST_STACK_PATH_CAP {
            return (a.as_usize(), b.as_usize());
        }
        path_a[len_a] = id;
        len_a += 1;
        cur_a = tree.get_node(id).and_then(SceneNode::parent_id);
    }
    let mut path_b: [NodeId; HIT_TEST_STACK_PATH_CAP] =
        [NodeId::default(); HIT_TEST_STACK_PATH_CAP];
    let mut len_b: usize = 0;
    let mut cur_b: Option<NodeId> = Some(b);
    while let Some(id) = cur_b {
        if len_b == HIT_TEST_STACK_PATH_CAP {
            return (a.as_usize(), b.as_usize());
        }
        path_b[len_b] = id;
        len_b += 1;
        cur_b = tree.get_node(id).and_then(SceneNode::parent_id);
    }
    path_a[..len_a].reverse();
    path_b[..len_b].reverse();
    compare_root_paths(tree, &path_a[..len_a], &path_b[..len_b], a, b)
}

/// Compares two root-to-node ancestor slices at their lowest common ancestor to determine tree preorder.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree.
/// - `&[NodeId]` - Root-to-`a` ancestor path.
/// - `&[NodeId]` - Root-to-`b` ancestor path.
/// - `NodeId` - First node handle fallback.
/// - `NodeId` - Second node handle fallback.
///
/// # Returns
///
/// - `(usize, usize)` - Comparable rank pair where `rank_a < rank_b` iff `a` precedes `b`.
fn compare_root_paths(
    tree: &SceneTree,
    path_a: &[NodeId],
    path_b: &[NodeId],
    a: NodeId,
    b: NodeId,
) -> (usize, usize) {
    let min_len: usize = path_a.len().min(path_b.len());
    let mut diff_idx: usize = 0;
    while diff_idx < min_len && path_a[diff_idx] == path_b[diff_idx] {
        diff_idx += 1;
    }
    if diff_idx == min_len {
        return (path_a.len(), path_b.len());
    }
    if diff_idx == 0 {
        return (a.as_usize(), b.as_usize());
    }
    let lca: NodeId = path_a[diff_idx - 1];
    let branch_a: NodeId = path_a[diff_idx];
    let branch_b: NodeId = path_b[diff_idx];
    if tree.get_node(lca).is_some() {
        for child_id in tree.children_iter(lca) {
            if child_id == branch_a {
                return (0, 1);
            }
            if child_id == branch_b {
                return (1, 0);
            }
        }
    }
    (a.as_usize(), b.as_usize())
}

/// Computes screen-space node bounds after applying accumulated scroll offset and `Transform2D`.
///
/// # Arguments
///
/// - `Rect` - Node layout border-box bounds.
/// - `Point` - Accumulated ancestor scroll offset.
/// - `Transform2D` - Node paint transform.
///
/// # Returns
///
/// - `Rect` - Transformed and scroll-shifted bounds in root logical coordinates.
#[inline(always)]
pub(crate) fn shifted_node_bounds(
    raw_bounds: Rect,
    scroll_offset: Point,
    transform: Transform2D,
) -> Rect {
    let tx: f32 = transform.get_translate_x();
    let ty: f32 = transform.get_translate_y();
    let sx: f32 = transform.get_scale_x();
    let sy: f32 = transform.get_scale_y();
    if sx == 1.0 && sy == 1.0 {
        Rect::new(
            raw_bounds.get_x() - scroll_offset.get_x() + tx,
            raw_bounds.get_y() - scroll_offset.get_y() + ty,
            raw_bounds.get_width(),
            raw_bounds.get_height(),
        )
    } else {
        let scaled_w: f32 = raw_bounds.get_width() * sx;
        let scaled_h: f32 = raw_bounds.get_height() * sy;
        let scale_dx: f32 = (raw_bounds.get_width() - scaled_w) * 0.5;
        let scale_dy: f32 = (raw_bounds.get_height() - scaled_h) * 0.5;
        Rect::new(
            raw_bounds.get_x() - scroll_offset.get_x() + tx + scale_dx,
            raw_bounds.get_y() - scroll_offset.get_y() + ty + scale_dy,
            scaled_w,
            scaled_h,
        )
    }
}

/// Recursively hit-tests `node_id` in reverse paint order (topmost z-index first).
///
/// # Arguments
///
/// - `HitTestQuery<'_>` - Immutable hit-test query context.
/// - `NodeId` - Subtree root handle.
/// - `Point` - Accumulated scroll offset from ancestor scroll views.
/// - `Option<Rect>` - Active ancestor clip rectangle.
/// - `&mut usize` - Visited node counter.
///
/// # Returns
///
/// - `Option<NodeId>` - Deepest topmost hit node handle.
fn hit_test_subtree(
    query: HitTestQuery<'_>,
    node_id: NodeId,
    scroll_offset: Point,
    clip_rect: Option<Rect>,
    visited: &mut usize,
) -> Option<NodeId> {
    let node: &SceneNode = query.tree.get_node(node_id)?;
    hit_test_resolved(query, node_id, node, scroll_offset, clip_rect, visited)
}

/// Hit-tests an already-fetched `SceneNode` with inline leaf, spatial `subtree_bounds`, clipped-bounds, and single-child fast paths.
///
/// # Arguments
///
/// - `HitTestQuery<'_>` - Immutable hit-test query context.
/// - `NodeId` - Handle corresponding to `node`.
/// - `&SceneNode` - Live scene node reference.
/// - `Point` - Accumulated ancestor scroll offset.
/// - `Option<Rect>` - Active ancestor clip rectangle already verified to contain `point`.
/// - `&mut usize` - Visited node counter.
///
/// # Returns
///
/// - `Option<NodeId>` - Deepest topmost hit node handle.
#[inline(always)]
fn hit_test_resolved(
    query: HitTestQuery<'_>,
    node_id: NodeId,
    node: &SceneNode,
    scroll_offset: Point,
    clip_rect: Option<Rect>,
    visited: &mut usize,
) -> Option<NodeId> {
    *visited = visited.saturating_add(1);
    let Style { layout, paint, .. } = node.style_ref();
    if layout.get_display() == Display::None
        || paint.get_pointer_events() == PointerEvents::None
        || paint.get_opacity() <= 0.001
    {
        return None;
    }
    let is_portal: bool =
        matches!(node.get_kind(), NodeKind::Portal) || layout.get_position() == Position::Fixed;
    if !query.in_portal_pass && is_portal {
        return None;
    }
    let transform: Transform2D = paint.get_transform();
    let shifted_bounds: Rect =
        shifted_node_bounds(node.get_layout_box().get_bounds(), scroll_offset, transform);
    let is_clipped: bool = matches!(layout.get_overflow(), Overflow::Hidden | Overflow::Scroll);
    let child_count: usize = query.tree.child_count(node_id);
    if child_count == 0 {
        return if shifted_bounds.contains(query.point) {
            Some(node_id)
        } else {
            None
        };
    }
    if is_clipped && !shifted_bounds.contains(query.point) {
        return None;
    }
    if !is_clipped
        && let Some(sc) = query.active_cache
        && let Some(sb) = sc.subtree_bounds_for(node_id)
    {
        let shifted_sb: Rect = Rect::new(
            sb.get_x() - scroll_offset.get_x(),
            sb.get_y() - scroll_offset.get_y(),
            sb.get_width(),
            sb.get_height(),
        );
        if !shifted_sb.contains(query.point) {
            return None;
        }
    }
    let effective_clip: Option<Rect> = if is_clipped {
        match clip_rect {
            Some(parent_clip) => parent_clip.intersect(shifted_bounds),
            None => Some(shifted_bounds),
        }
    } else {
        clip_rect
    };
    if let Some(clip) = effective_clip
        && !clip.contains(query.point)
    {
        return None;
    }
    let node_scroll: Point = node.get_layout_box().get_scroll_offset();
    let child_scroll: Point = Point::new(
        scroll_offset.get_x() + node_scroll.get_x() - transform.get_translate_x(),
        scroll_offset.get_y() + node_scroll.get_y() - transform.get_translate_y(),
    );
    if child_count == 1 {
        if let Some(single_id) = query.tree.first_child(node_id)
            && let Some(single_node) = query.tree.get_node(single_id)
        {
            if !query.tree.has_children(single_id) {
                *visited = visited.saturating_add(1);
                let Style {
                    layout: c_layout,
                    paint: c_paint,
                    ..
                } = single_node.style_ref();
                let c_hidden: bool = c_layout.get_display() == Display::None
                    || c_paint.get_pointer_events() == PointerEvents::None
                    || c_paint.get_opacity() <= 0.001;
                let c_portal: bool = matches!(single_node.get_kind(), NodeKind::Portal)
                    || c_layout.get_position() == Position::Fixed;
                if !c_hidden && (query.in_portal_pass || !c_portal) {
                    let c_bounds: Rect = shifted_node_bounds(
                        single_node.get_layout_box().get_bounds(),
                        child_scroll,
                        c_paint.get_transform(),
                    );
                    if c_bounds.contains(query.point) {
                        return Some(single_id);
                    }
                }
            } else if let Some(hit) = hit_test_resolved(
                query,
                single_id,
                single_node,
                child_scroll,
                effective_clip,
                visited,
            ) {
                return Some(hit);
            }
        }
        return if shifted_bounds.contains(query.point) {
            Some(node_id)
        } else {
            None
        };
    }
    hit_test_multi_children(
        query,
        node_id,
        child_count,
        shifted_bounds,
        child_scroll,
        effective_clip,
        visited,
    )
}

/// Hit-tests a container with two or more children using O(1) `HAS_NONZERO_Z_CHILD` reverse fast paths and stack/scratch z-sorting.
///
/// # Arguments
///
/// - `HitTestQuery<'_>` - Immutable hit-test query context.
/// - `NodeId` - Parent container handle.
/// - `usize` - Number of direct children under `node_id`.
/// - `Rect` - Parent shifted bounds for self-hit fallback.
/// - `Point` - Accumulated child scroll offset.
/// - `Option<Rect>` - Effective clip rectangle already containing `point`.
/// - `&mut usize` - Visited node counter.
///
/// # Returns
///
/// - `Option<NodeId>` - Deepest topmost hit node handle.
fn hit_test_multi_children(
    query: HitTestQuery<'_>,
    node_id: NodeId,
    child_count: usize,
    shifted_bounds: Rect,
    child_scroll: Point,
    effective_clip: Option<Rect>,
    visited: &mut usize,
) -> Option<NodeId> {
    let all_zero_z: bool = !query.tree.has_nonzero_z_child(node_id)
        || query
            .active_cache
            .and_then(|c: &SplitLayoutCache| c.has_nonzero_z_child(node_id))
            == Some(false);
    if all_zero_z {
        for child_id in query.tree.children_iter(node_id).rev() {
            if let Some(child_node) = query.tree.get_node(child_id)
                && let Some(hit) = hit_test_resolved(
                    query,
                    child_id,
                    child_node,
                    child_scroll,
                    effective_clip,
                    visited,
                )
            {
                return Some(hit);
            }
        }
        return if shifted_bounds.contains(query.point) {
            Some(node_id)
        } else {
            None
        };
    }
    if let Some(hit) = hit_test_z_sorted_children(
        query,
        node_id,
        child_count,
        child_scroll,
        effective_clip,
        visited,
    ) {
        return Some(hit);
    }
    if shifted_bounds.contains(query.point) {
        Some(node_id)
    } else {
        None
    }
}

/// Sorts all children by descending `(z_index, order)` using stack storage up to `HIT_TEST_STACK_Z_CAP` and reusable scratch beyond.
///
/// # Arguments
///
/// - `HitTestQuery<'_>` - Immutable hit-test query context.
/// - `NodeId` - Parent container handle.
/// - `usize` - Number of direct children under `node_id`.
/// - `Point` - Accumulated child scroll offset.
/// - `Option<Rect>` - Effective clip rectangle.
/// - `&mut usize` - Visited node counter.
///
/// # Returns
///
/// - `Option<NodeId>` - Topmost child hit, if any.
fn hit_test_z_sorted_children(
    query: HitTestQuery<'_>,
    node_id: NodeId,
    child_count: usize,
    child_scroll: Point,
    effective_clip: Option<Rect>,
    visited: &mut usize,
) -> Option<NodeId> {
    if child_count <= HIT_TEST_STACK_Z_CAP {
        let mut stack_items: [ZItem; HIT_TEST_STACK_Z_CAP] =
            [ZItem::default(); HIT_TEST_STACK_Z_CAP];
        let mut stack_len: usize = 0;
        for (order, cid) in query.tree.children_iter(node_id).enumerate() {
            if let Some(child_node) = query.tree.get_node(cid) {
                stack_items[stack_len] = ZItem {
                    z_index: child_node.style_ref().get_layout().get_z_index(),
                    order,
                    node_id: cid,
                };
                stack_len += 1;
            }
        }
        stack_items[..stack_len].sort_unstable_by(|a: &ZItem, b: &ZItem| {
            b.z_index
                .cmp(&a.z_index)
                .then_with(|| b.order.cmp(&a.order))
        });
        for item in stack_items[..stack_len].iter().copied() {
            if let Some(hit) =
                hit_test_subtree(query, item.node_id, child_scroll, effective_clip, visited)
            {
                return Some(hit);
            }
        }
        return None;
    }
    hit_test_z_sorted_scratch(query, node_id, child_scroll, effective_clip, visited)
}

/// Recursion-safe overflow z-sorting via the thread-local reusable flat stack `HIT_TEST_SCRATCH::z_items`.
///
/// # Arguments
///
/// - `HitTestQuery<'_>` - Immutable hit-test query context.
/// - `NodeId` - Parent container handle whose children will be sorted.
/// - `Point` - Accumulated child scroll offset.
/// - `Option<Rect>` - Effective clip rectangle.
/// - `&mut usize` - Visited node counter.
///
/// # Returns
///
/// - `Option<NodeId>` - Topmost child hit, if any.
fn hit_test_z_sorted_scratch(
    query: HitTestQuery<'_>,
    node_id: NodeId,
    child_scroll: Point,
    effective_clip: Option<Rect>,
    visited: &mut usize,
) -> Option<NodeId> {
    let range_opt: Option<(usize, usize)> = HIT_TEST_SCRATCH
        .try_with(|cell: &RefCell<HitTestScratch>| {
            let Ok(mut scratch) = cell.try_borrow_mut() else {
                return None;
            };
            let base: usize = scratch.z_items.len();
            for (order, cid) in query.tree.children_iter(node_id).enumerate() {
                if let Some(child_node) = query.tree.get_node(cid) {
                    let z: i32 = child_node.style_ref().get_layout().get_z_index();
                    scratch.z_items.push(ZItem {
                        z_index: z,
                        order,
                        node_id: cid,
                    });
                }
            }
            let end: usize = scratch.z_items.len();
            scratch.z_items[base..end].sort_unstable_by(|a: &ZItem, b: &ZItem| {
                b.z_index
                    .cmp(&a.z_index)
                    .then_with(|| b.order.cmp(&a.order))
            });
            Some((base, end))
        })
        .ok()
        .flatten();
    let (base, end): (usize, usize) = range_opt?;
    let mut found: Option<NodeId> = None;
    for idx in base..end {
        let child_id_opt: Option<NodeId> = HIT_TEST_SCRATCH
            .try_with(|cell: &RefCell<HitTestScratch>| {
                cell.try_borrow()
                    .ok()
                    .and_then(|s: Ref<'_, HitTestScratch>| {
                        s.z_items.get(idx).map(|z: &ZItem| z.node_id)
                    })
            })
            .ok()
            .flatten();
        if let Some(child_id) = child_id_opt
            && let Some(hit) =
                hit_test_subtree(query, child_id, child_scroll, effective_clip, visited)
        {
            found = Some(hit);
            break;
        }
    }
    let _truncated: bool = HIT_TEST_SCRATCH
        .try_with(|cell: &RefCell<HitTestScratch>| {
            if let Ok(mut scratch) = cell.try_borrow_mut() {
                scratch.z_items.truncate(base);
            }
        })
        .is_ok();
    found
}