Skip to main content

cranpose_render_common/
graph.rs

1use std::{collections::HashSet, mem::size_of, rc::Rc};
2
3use cranpose_core::NodeId;
4use cranpose_foundation::PointerEvent;
5use cranpose_ui::{
6    GraphicsLayer, Point, Rect, RenderEffect, RoundedCornerShape, TextLayoutOptions, TextStyle,
7    text::AnnotatedString,
8};
9use cranpose_ui_graphics::{BlendMode, ColorFilter, DrawPrimitive, ShadowPrimitive};
10
11use crate::{raster_cache::LayerRasterCacheHashes, style_shared::DrawPlacement};
12
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct ProjectiveTransform {
15    matrix: [[f32; 3]; 3],
16}
17
18impl ProjectiveTransform {
19    pub const fn identity() -> Self {
20        Self {
21            matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
22        }
23    }
24
25    pub fn translation(tx: f32, ty: f32) -> Self {
26        Self {
27            matrix: [[1.0, 0.0, tx], [0.0, 1.0, ty], [0.0, 0.0, 1.0]],
28        }
29    }
30
31    /// Uniform scale about the origin (device-scale root transform: render
32    /// graphs stay in logical dp; density applies at execution).
33    pub fn uniform_scale(scale: f32) -> Self {
34        Self {
35            matrix: [[scale, 0.0, 0.0], [0.0, scale, 0.0], [0.0, 0.0, 1.0]],
36        }
37    }
38
39    pub fn from_rect_to_quad(rect: Rect, quad: [[f32; 2]; 4]) -> Self {
40        if rect.width.abs() <= f32::EPSILON || rect.height.abs() <= f32::EPSILON {
41            return Self::translation(quad[0][0], quad[0][1]);
42        }
43
44        if let Some(axis_aligned) = axis_aligned_rect_from_quad(quad) {
45            let scale_x = axis_aligned.width / rect.width;
46            let scale_y = axis_aligned.height / rect.height;
47            return Self {
48                matrix: [
49                    [scale_x, 0.0, axis_aligned.x - rect.x * scale_x],
50                    [0.0, scale_y, axis_aligned.y - rect.y * scale_y],
51                    [0.0, 0.0, 1.0],
52                ],
53            };
54        }
55
56        let source = [
57            [rect.x, rect.y],
58            [rect.x + rect.width, rect.y],
59            [rect.x, rect.y + rect.height],
60            [rect.x + rect.width, rect.y + rect.height],
61        ];
62        let Some(coefficients) = solve_homography(source, quad) else {
63            return Self::identity();
64        };
65
66        Self {
67            matrix: [
68                [coefficients[0], coefficients[1], coefficients[2]],
69                [coefficients[3], coefficients[4], coefficients[5]],
70                [coefficients[6], coefficients[7], 1.0],
71            ],
72        }
73    }
74
75    /// Returns the composed transform that applies `self` first and `next` second.
76    pub fn then(self, next: Self) -> Self {
77        Self {
78            matrix: multiply_matrices(next.matrix, self.matrix),
79        }
80    }
81
82    pub fn inverse(self) -> Option<Self> {
83        let m = self.matrix;
84        let a = m[0][0];
85        let b = m[0][1];
86        let c = m[0][2];
87        let d = m[1][0];
88        let e = m[1][1];
89        let f = m[1][2];
90        let g = m[2][0];
91        let h = m[2][1];
92        let i = m[2][2];
93
94        let cofactor00 = e * i - f * h;
95        let cofactor01 = -(d * i - f * g);
96        let cofactor02 = d * h - e * g;
97        let cofactor10 = -(b * i - c * h);
98        let cofactor11 = a * i - c * g;
99        let cofactor12 = -(a * h - b * g);
100        let cofactor20 = b * f - c * e;
101        let cofactor21 = -(a * f - c * d);
102        let cofactor22 = a * e - b * d;
103
104        let determinant = a * cofactor00 + b * cofactor01 + c * cofactor02;
105        if determinant.abs() <= f32::EPSILON {
106            return None;
107        }
108        let inverse_determinant = 1.0 / determinant;
109
110        Some(Self {
111            matrix: [
112                [
113                    cofactor00 * inverse_determinant,
114                    cofactor10 * inverse_determinant,
115                    cofactor20 * inverse_determinant,
116                ],
117                [
118                    cofactor01 * inverse_determinant,
119                    cofactor11 * inverse_determinant,
120                    cofactor21 * inverse_determinant,
121                ],
122                [
123                    cofactor02 * inverse_determinant,
124                    cofactor12 * inverse_determinant,
125                    cofactor22 * inverse_determinant,
126                ],
127            ],
128        })
129    }
130
131    pub fn matrix(self) -> [[f32; 3]; 3] {
132        self.matrix
133    }
134
135    pub fn map_point(self, point: Point) -> Point {
136        let x = point.x;
137        let y = point.y;
138        let w = self.matrix[2][0] * x + self.matrix[2][1] * y + self.matrix[2][2];
139        let safe_w = if w.abs() <= f32::EPSILON { 1.0 } else { w };
140
141        Point {
142            x: (self.matrix[0][0] * x + self.matrix[0][1] * y + self.matrix[0][2]) / safe_w,
143            y: (self.matrix[1][0] * x + self.matrix[1][1] * y + self.matrix[1][2]) / safe_w,
144        }
145    }
146
147    pub fn map_rect(self, rect: Rect) -> [[f32; 2]; 4] {
148        [
149            self.map_point(Point {
150                x: rect.x,
151                y: rect.y,
152            }),
153            self.map_point(Point {
154                x: rect.x + rect.width,
155                y: rect.y,
156            }),
157            self.map_point(Point {
158                x: rect.x,
159                y: rect.y + rect.height,
160            }),
161            self.map_point(Point {
162                x: rect.x + rect.width,
163                y: rect.y + rect.height,
164            }),
165        ]
166        .map(|point| [point.x, point.y])
167    }
168
169    pub fn bounds_for_rect(self, rect: Rect) -> Rect {
170        quad_bounds(self.map_rect(rect))
171    }
172}
173
174fn axis_aligned_rect_from_quad(quad: [[f32; 2]; 4]) -> Option<Rect> {
175    let top_left = quad[0];
176    let top_right = quad[1];
177    let bottom_left = quad[2];
178    let bottom_right = quad[3];
179    let x_epsilon = 1e-4;
180    let y_epsilon = 1e-4;
181
182    if (top_left[1] - top_right[1]).abs() > y_epsilon
183        || (bottom_left[1] - bottom_right[1]).abs() > y_epsilon
184        || (top_left[0] - bottom_left[0]).abs() > x_epsilon
185        || (top_right[0] - bottom_right[0]).abs() > x_epsilon
186    {
187        return None;
188    }
189
190    Some(Rect {
191        x: top_left[0],
192        y: top_left[1],
193        width: top_right[0] - top_left[0],
194        height: bottom_left[1] - top_left[1],
195    })
196}
197
198impl Default for ProjectiveTransform {
199    fn default() -> Self {
200        Self::identity()
201    }
202}
203
204#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
205pub struct IsolationReasons {
206    pub explicit_offscreen: bool,
207    pub shape_clip: bool,
208    pub effect: bool,
209    pub backdrop: bool,
210    pub group_opacity: bool,
211    pub blend_mode: bool,
212}
213
214impl IsolationReasons {
215    pub fn has_any(self) -> bool {
216        self.explicit_offscreen
217            || self.shape_clip
218            || self.effect
219            || self.backdrop
220            || self.group_opacity
221            || self.blend_mode
222    }
223}
224
225#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
226pub enum CachePolicy {
227    #[default]
228    None,
229    Auto,
230}
231
232#[derive(Clone)]
233pub struct HitTestNode {
234    pub shape: Option<RoundedCornerShape>,
235    pub click_actions: Vec<Rc<dyn Fn(Point)>>,
236    pub pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
237    pub clip: Option<Rect>,
238}
239
240#[derive(Clone, Debug, PartialEq)]
241pub struct DrawPrimitiveNode {
242    pub primitive: DrawPrimitive,
243    pub clip: Option<Rect>,
244}
245
246#[derive(Clone, Debug, PartialEq)]
247pub struct TextPrimitiveNode {
248    pub node_id: NodeId,
249    pub rect: Rect,
250    /// Shared so the renderer can hand the same allocation to every draw it
251    /// emits for this node instead of deep-copying the string once per emit.
252    pub text: Rc<AnnotatedString>,
253    pub text_style: TextStyle,
254    pub font_size: f32,
255    pub layout_options: TextLayoutOptions,
256    pub clip: Option<Rect>,
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260pub enum PrimitivePhase {
261    BeforeChildren,
262    AfterChildren,
263}
264
265#[derive(Clone, Debug, PartialEq)]
266pub enum PrimitiveNode {
267    Draw(DrawPrimitiveNode),
268    Text(Box<TextPrimitiveNode>),
269}
270
271#[derive(Clone, Debug, PartialEq)]
272pub struct PrimitiveEntry {
273    pub phase: PrimitivePhase,
274    pub node: PrimitiveNode,
275}
276
277#[derive(Clone)]
278pub struct LayerNode {
279    pub node_id: Option<NodeId>,
280    pub local_bounds: Rect,
281    pub transform_to_parent: ProjectiveTransform,
282    pub content_offset: Point,
283    pub motion_context_animated: bool,
284    pub translated_content_context: bool,
285    pub translated_content_offset: Point,
286    /// Window-space origin this layer's children are placed from, and the
287    /// accumulated ancestor graphics-layer translation, captured during the
288    /// full per-frame scene build. Read back when a dirty subtree is rebuilt in
289    /// isolation (`update_scene_from_applier`) so a scrolling field's window
290    /// origin stays live during a fling even though the ancestor chain is not
291    /// re-walked from the root. Defaults to the identity origin.
292    pub scene_children_origin: Point,
293    pub scene_children_layer_translation: Point,
294    pub graphics_layer: GraphicsLayer,
295    pub clip_to_bounds: bool,
296    pub shadow_clip: Option<Rect>,
297    pub hit_test: Option<HitTestNode>,
298    pub has_hit_targets: bool,
299    /// Whether this subtree publishes live window origins (a text field's
300    /// popup anchor, a scroll container's viewport rect). Those sinks are
301    /// written during a full lowering, so the scroll fast path may translate
302    /// a retained subtree in place only when this is false.
303    pub has_origin_sinks: bool,
304    pub isolation: IsolationReasons,
305    pub cache_policy: CachePolicy,
306    pub cache_hashes: LayerRasterCacheHashes,
307    pub cache_hashes_valid: bool,
308    pub children: Vec<RenderNode>,
309}
310
311impl LayerNode {
312    pub fn clip_rect(&self) -> Option<Rect> {
313        (self.clip_to_bounds || self.graphics_layer.clip).then_some(self.local_bounds)
314    }
315
316    pub fn effect(&self) -> Option<&RenderEffect> {
317        self.graphics_layer.render_effect.as_ref()
318    }
319
320    pub fn backdrop(&self) -> Option<&RenderEffect> {
321        self.graphics_layer.backdrop_effect.as_ref()
322    }
323
324    pub fn opacity(&self) -> f32 {
325        self.graphics_layer.alpha
326    }
327
328    pub fn blend_mode(&self) -> BlendMode {
329        self.graphics_layer.blend_mode
330    }
331
332    pub fn color_filter(&self) -> Option<ColorFilter> {
333        self.graphics_layer.color_filter
334    }
335
336    pub fn target_content_hash(&self) -> u64 {
337        if self.cache_hashes_valid {
338            self.cache_hashes.target_content
339        } else {
340            crate::graph_hash::layer_raster_cache_hashes(self).target_content
341        }
342    }
343
344    pub fn motion_source_content_hash(&self) -> u64 {
345        crate::graph_hash::layer_motion_source_content_hash(self)
346    }
347
348    pub fn effect_hash(&self) -> u64 {
349        if self.cache_hashes_valid {
350            self.cache_hashes.effect
351        } else {
352            crate::graph_hash::layer_raster_cache_hashes(self).effect
353        }
354    }
355
356    pub fn recompute_raster_cache_hashes(&mut self) {
357        crate::graph_hash::recompute_layer_raster_cache_hashes(self);
358    }
359}
360
361#[derive(Clone)]
362pub enum RenderNode {
363    Primitive(PrimitiveEntry),
364    /// A whole draw command's primitives as one node. A heavy canvas records
365    /// thousands of primitives per frame; wrapping each in its own
366    /// [`RenderNode`] made the graph rebuild move every one of them twice and
367    /// free seventeen thousand nodes per frame on a stress scene. The run
368    /// keeps the recorded vector intact — semantically it is exactly that
369    /// many consecutive `Primitive` draw entries with no per-primitive clip.
370    DrawRun(DrawRunNode),
371    Layer(Box<LayerNode>),
372}
373
374/// Stable identity of the draw command a run was recorded from: the layout
375/// node owning the command, the command's index in that node's command list,
376/// and which placement pass produced this run (a `WithContent` command emits
377/// one run per placement, so the pair alone is not unique). Rendering does
378/// not read it yet; it is the key under which retained recording state lives
379/// as retention moves up to the draw-command recorder, and it must survive
380/// recording, graph construction, normalized-scene creation, and renderer
381/// cache lookup unchanged.
382#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
383pub struct DrawCommandId {
384    pub node_id: NodeId,
385    pub command_index: u32,
386    pub placement: DrawPlacement,
387}
388
389#[derive(Clone, Debug, PartialEq)]
390pub struct DrawRunNode {
391    pub phase: PrimitivePhase,
392    /// Which draw command recorded these primitives. `None` only for runs
393    /// with no per-command provenance (hand-built tests).
394    pub command: Option<DrawCommandId>,
395    /// Shared, not owned: the recording registry keyed by [`DrawCommandId`]
396    /// keeps a handle to the same buffer, so its capacity survives this
397    /// node being dropped on the next rebuild and the command re-records
398    /// into it instead of growing a fresh vector. Nothing mutates a run's
399    /// primitives after construction, which is what makes sharing sound.
400    pub primitives: std::rc::Rc<Vec<DrawPrimitive>>,
401    /// Content facts consumers keep asking per frame, answered once at
402    /// construction. Surface planning used to rescan every primitive of
403    /// every run per frame to learn "does it contain text?" — for a
404    /// 17k-primitive game canvas with no text, that was two full walks per
405    /// frame that could never early-exit.
406    pub summary: DrawRunSummary,
407    /// The command's verified retained/dynamic span structure for the frame
408    /// this node was built, in primitive space. A renderer that retains by
409    /// identity draws the run span by span — retained spans from slots
410    /// keyed (command, slot), dynamic spans from `primitives` — instead of
411    /// walking the whole vector. `None` means no verification ran or
412    /// nothing was retained: the run is all ordinary primitives.
413    pub replay: Option<Box<cranpose_ui_graphics::CommandReplayFrame>>,
414}
415
416impl DrawRunNode {
417    pub fn new(phase: PrimitivePhase, primitives: Vec<DrawPrimitive>) -> Self {
418        Self::for_command(phase, None, primitives)
419    }
420
421    pub fn for_command(
422        phase: PrimitivePhase,
423        command: Option<DrawCommandId>,
424        primitives: Vec<DrawPrimitive>,
425    ) -> Self {
426        Self::for_command_shared(phase, command, std::rc::Rc::new(primitives))
427    }
428
429    pub fn for_command_shared(
430        phase: PrimitivePhase,
431        command: Option<DrawCommandId>,
432        primitives: std::rc::Rc<Vec<DrawPrimitive>>,
433    ) -> Self {
434        Self::for_command_replayed(phase, command, primitives, None)
435    }
436
437    pub fn for_command_replayed(
438        phase: PrimitivePhase,
439        command: Option<DrawCommandId>,
440        primitives: std::rc::Rc<Vec<DrawPrimitive>>,
441        replay: Option<Box<cranpose_ui_graphics::CommandReplayFrame>>,
442    ) -> Self {
443        // Fail-closed invariant: a bypassed span has NO primitives — the
444        // frame's own `fallback` recording is the only thing that can ever
445        // draw it, so a frame carrying bypassed spans without one is
446        // unconstructible here. The builder attaches the published handle
447        // to every frame; hand-built frames that bypass must do the same.
448        debug_assert!(
449            replay.as_ref().is_none_or(|frame| {
450                frame.fallback.is_some()
451                    || !frame.spans.iter().any(|span| {
452                        matches!(
453                            span,
454                            cranpose_ui_graphics::FrameSpan::Retained {
455                                capture: false,
456                                range,
457                                ..
458                            } if range.1 <= range.0
459                        )
460                    })
461            }),
462            "a replay frame with bypassed spans must own its fallback recording"
463        );
464        let mut summary = DrawRunSummary::scan(&primitives);
465        // Bypassed retained spans have no primitives to scan, but they are
466        // drawable content — only shape records ever retain, never shadows.
467        if replay.as_ref().is_some_and(|frame| {
468            frame
469                .spans
470                .iter()
471                .any(|span| matches!(span, cranpose_ui_graphics::FrameSpan::Retained { .. }))
472        }) {
473            summary.has_non_shadow = true;
474        }
475        Self {
476            phase,
477            command,
478            primitives,
479            summary,
480            replay,
481        }
482    }
483}
484
485/// One-pass discriminant census of a draw run, recursing through `Blend`
486/// wrappers the same way the per-primitive predicates it replaces did.
487#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
488pub struct DrawRunSummary {
489    /// Any `Text` primitive, including inside `Blend` — glyph masks want
490    /// rigid snapping.
491    pub has_text: bool,
492    pub has_shadow: bool,
493    /// Any primitive besides `Shadow` (direct drawable content).
494    pub has_non_shadow: bool,
495    /// Any `Image` or `Text`, including inside `Blend` — content that
496    /// resamples badly on a fractionally offset surface.
497    pub has_pixel_sensitive: bool,
498}
499
500impl DrawRunSummary {
501    pub fn scan(primitives: &[DrawPrimitive]) -> Self {
502        fn unwrap_blend(mut primitive: &DrawPrimitive) -> &DrawPrimitive {
503            while let DrawPrimitive::Blend {
504                primitive: inner, ..
505            } = primitive
506            {
507                primitive = inner;
508            }
509            primitive
510        }
511        let mut summary = Self::default();
512        for primitive in primitives {
513            // Shadow classification looks at the outer discriminant only,
514            // text and pixel sensitivity see through `Blend` — exactly the
515            // split the per-primitive predicates this replaces made.
516            if matches!(primitive, DrawPrimitive::Shadow(_)) {
517                summary.has_shadow = true;
518                continue;
519            }
520            summary.has_non_shadow = true;
521            match unwrap_blend(primitive) {
522                DrawPrimitive::Text(_) => {
523                    summary.has_text = true;
524                    summary.has_pixel_sensitive = true;
525                }
526                DrawPrimitive::Image { .. } => summary.has_pixel_sensitive = true,
527                _ => {}
528            }
529        }
530        summary
531    }
532}
533
534#[derive(Clone)]
535pub struct RenderGraph {
536    pub root: LayerNode,
537}
538
539impl RenderGraph {
540    pub fn new(mut root: LayerNode) -> Self {
541        root.recompute_raster_cache_hashes();
542        Self { root }
543    }
544
545    pub fn node_count(&self) -> usize {
546        fn count_layer(layer: &LayerNode) -> usize {
547            1 + layer
548                .children
549                .iter()
550                .map(|child| match child {
551                    RenderNode::Primitive(_) => 1,
552                    RenderNode::DrawRun(run) => run.primitives.len(),
553                    RenderNode::Layer(child_layer) => count_layer(child_layer),
554                })
555                .sum::<usize>()
556        }
557
558        count_layer(&self.root)
559    }
560
561    pub fn heap_bytes(&self) -> usize {
562        layer_heap_bytes(&self.root)
563    }
564
565    pub fn retained_visual_observation_nodes(&self) -> HashSet<NodeId> {
566        fn collect(layer: &LayerNode, nodes: &mut HashSet<NodeId>) {
567            if let Some(node_id) = layer.node_id {
568                nodes.insert(node_id);
569            }
570            for child in &layer.children {
571                match child {
572                    RenderNode::DrawRun(run) => {
573                        if let Some(command) = run.command {
574                            nodes.insert(command.node_id);
575                        }
576                    }
577                    RenderNode::Layer(child) => collect(child, nodes),
578                    RenderNode::Primitive(_) => {}
579                }
580            }
581        }
582
583        let mut nodes = HashSet::new();
584        collect(&self.root, &mut nodes);
585        nodes
586    }
587}
588
589fn layer_heap_bytes(layer: &LayerNode) -> usize {
590    layer.hit_test.as_ref().map_or(0, hit_test_heap_bytes)
591        + size_of::<RenderNode>() * layer.children.capacity()
592        + layer
593            .children
594            .iter()
595            .map(render_node_heap_bytes)
596            .sum::<usize>()
597}
598
599fn render_node_heap_bytes(node: &RenderNode) -> usize {
600    match node {
601        RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
602        RenderNode::DrawRun(run) => {
603            size_of::<DrawPrimitive>() * run.primitives.capacity()
604                + run
605                    .primitives
606                    .iter()
607                    .map(draw_primitive_heap_bytes)
608                    .sum::<usize>()
609        }
610        RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
611    }
612}
613
614fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
615    match &entry.node {
616        PrimitiveNode::Draw(draw) => draw_primitive_heap_bytes(&draw.primitive),
617        PrimitiveNode::Text(text) => {
618            size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
619        }
620    }
621}
622
623fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
624    match primitive {
625        DrawPrimitive::Content
626        | DrawPrimitive::Rect { .. }
627        | DrawPrimitive::RoundRect { .. }
628        | DrawPrimitive::Arc { .. } => 0,
629        DrawPrimitive::Blend { primitive, .. } => {
630            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
631        }
632        DrawPrimitive::Image { .. } => 0,
633        DrawPrimitive::Text(text) => {
634            size_of::<cranpose_ui_graphics::TextPrimitive>()
635                + text.text.len()
636                + text
637                    .style
638                    .font_family
639                    .as_ref()
640                    .map_or(0, |family| family.capacity())
641        }
642        DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
643    }
644}
645
646fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
647    match shadow {
648        ShadowPrimitive::Drop { shape, .. } => {
649            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
650        }
651        ShadowPrimitive::Inner { fill, cutout, .. } => {
652            size_of::<DrawPrimitive>() * 2
653                + draw_primitive_heap_bytes(fill)
654                + draw_primitive_heap_bytes(cutout)
655        }
656    }
657}
658
659fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
660    text.text.capacity()
661        + text.span_styles.capacity() * size_of::<usize>() * 2
662        + text.paragraph_styles.capacity() * size_of::<usize>() * 2
663        + text.string_annotations.capacity() * size_of::<usize>() * 2
664        + text.link_annotations.capacity() * size_of::<usize>() * 2
665        + text
666            .string_annotations
667            .iter()
668            .map(|annotation| {
669                annotation.item.tag.capacity() + annotation.item.annotation.capacity()
670            })
671            .sum::<usize>()
672        + text
673            .link_annotations
674            .iter()
675            .map(|annotation| match &annotation.item {
676                cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
677                cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
678            })
679            .sum::<usize>()
680}
681
682fn hit_test_heap_bytes(hit_test: &HitTestNode) -> usize {
683    hit_test.click_actions.capacity() * size_of::<Rc<dyn Fn(Point)>>()
684        + hit_test.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>()
685}
686
687pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
688    let mut min_x = f32::INFINITY;
689    let mut min_y = f32::INFINITY;
690    let mut max_x = f32::NEG_INFINITY;
691    let mut max_y = f32::NEG_INFINITY;
692
693    for [x, y] in quad {
694        min_x = min_x.min(x);
695        min_y = min_y.min(y);
696        max_x = max_x.max(x);
697        max_y = max_y.max(y);
698    }
699
700    Rect {
701        x: min_x,
702        y: min_y,
703        width: (max_x - min_x).max(0.0),
704        height: (max_y - min_y).max(0.0),
705    }
706}
707
708fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
709    let mut out = [[0.0; 3]; 3];
710    for row in 0..3 {
711        for col in 0..3 {
712            out[row][col] =
713                lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
714        }
715    }
716    out
717}
718
719fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
720    let mut matrix = [[0.0f32; 9]; 8];
721    for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
722        let row = index * 2;
723        let x = src[0];
724        let y = src[1];
725        let u = dst[0];
726        let v = dst[1];
727
728        matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
729        matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
730    }
731
732    for pivot in 0..8 {
733        let mut pivot_row = pivot;
734        let mut pivot_value = matrix[pivot][pivot].abs();
735        let mut candidate = pivot + 1;
736        while candidate < 8 {
737            let candidate_value = matrix[candidate][pivot].abs();
738            if candidate_value > pivot_value {
739                pivot_row = candidate;
740                pivot_value = candidate_value;
741            }
742            candidate += 1;
743        }
744
745        if pivot_value <= f32::EPSILON {
746            return None;
747        }
748
749        if pivot_row != pivot {
750            matrix.swap(pivot, pivot_row);
751        }
752
753        let divisor = matrix[pivot][pivot];
754        let mut col = pivot;
755        while col < 9 {
756            matrix[pivot][col] /= divisor;
757            col += 1;
758        }
759
760        for row in 0..8 {
761            if row == pivot {
762                continue;
763            }
764            let factor = matrix[row][pivot];
765            if factor.abs() <= f32::EPSILON {
766                continue;
767            }
768            let mut col = pivot;
769            while col < 9 {
770                matrix[row][col] -= factor * matrix[pivot][col];
771                col += 1;
772            }
773        }
774    }
775
776    let mut solution = [0.0f32; 8];
777    for index in 0..8 {
778        solution[index] = matrix[index][8];
779    }
780    Some(solution)
781}
782
783#[cfg(test)]
784mod tests {
785    use cranpose_ui_graphics::{Brush, Color, DrawPrimitive};
786
787    use super::*;
788    use crate::raster_cache::LayerRasterCacheHashes;
789
790    fn test_layer(local_bounds: Rect, children: Vec<RenderNode>) -> LayerNode {
791        LayerNode {
792            node_id: None,
793            local_bounds,
794            transform_to_parent: ProjectiveTransform::identity(),
795            content_offset: Point::default(),
796            motion_context_animated: false,
797            translated_content_context: false,
798            translated_content_offset: Point::default(),
799            scene_children_origin: Point::default(),
800            scene_children_layer_translation: Point::default(),
801            graphics_layer: GraphicsLayer::default(),
802            clip_to_bounds: false,
803            shadow_clip: None,
804            hit_test: None,
805            has_hit_targets: false,
806            has_origin_sinks: false,
807            isolation: IsolationReasons::default(),
808            cache_policy: CachePolicy::None,
809            cache_hashes: LayerRasterCacheHashes::default(),
810            cache_hashes_valid: false,
811            children,
812        }
813    }
814
815    #[test]
816    fn projective_transform_translation_maps_points() {
817        let transform = ProjectiveTransform::translation(7.0, -3.5);
818        let mapped = transform.map_point(Point { x: 2.0, y: 4.0 });
819        assert!((mapped.x - 9.0).abs() < 1e-6);
820        assert!((mapped.y - 0.5).abs() < 1e-6);
821    }
822
823    #[test]
824    fn projective_transform_then_composes_in_parent_order() {
825        let child = ProjectiveTransform::translation(4.0, 2.0);
826        let parent = ProjectiveTransform::translation(10.0, -1.0);
827        let composed = child.then(parent);
828        let mapped = composed.map_point(Point { x: 1.0, y: 1.0 });
829        assert!((mapped.x - 15.0).abs() < 1e-6);
830        assert!((mapped.y - 2.0).abs() < 1e-6);
831    }
832
833    #[test]
834    fn homography_maps_rect_corners_to_target_quad() {
835        let rect = Rect {
836            x: 0.0,
837            y: 0.0,
838            width: 20.0,
839            height: 10.0,
840        };
841        let quad = [[5.0, 7.0], [25.0, 6.0], [7.0, 20.0], [28.0, 21.0]];
842        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
843        let mapped = transform.map_rect(rect);
844        for (expected, actual) in quad.into_iter().zip(mapped) {
845            assert!((expected[0] - actual[0]).abs() < 1e-4);
846            assert!((expected[1] - actual[1]).abs() < 1e-4);
847        }
848    }
849
850    #[test]
851    fn axis_aligned_rect_to_quad_keeps_exact_affine_matrix() {
852        let rect = Rect {
853            x: 2.0,
854            y: 3.0,
855            width: 20.0,
856            height: 10.0,
857        };
858        let quad = [[12.0, 9.0], [32.0, 9.0], [12.0, 19.0], [32.0, 19.0]];
859        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
860
861        assert_eq!(
862            transform.matrix(),
863            [[1.0, 0.0, 10.0], [0.0, 1.0, 6.0], [0.0, 0.0, 1.0]]
864        );
865    }
866
867    #[test]
868    fn axis_aligned_rect_to_quad_keeps_exact_axis_aligned_scale() {
869        let rect = Rect {
870            x: 4.0,
871            y: 6.0,
872            width: 10.0,
873            height: 8.0,
874        };
875        let quad = [[20.0, 18.0], [50.0, 18.0], [20.0, 42.0], [50.0, 42.0]];
876        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
877
878        assert_eq!(
879            transform.matrix(),
880            [[3.0, 0.0, 8.0], [0.0, 3.0, 0.0], [0.0, 0.0, 1.0]]
881        );
882    }
883
884    #[test]
885    fn retained_visual_observation_nodes_collect_layers_and_command_owners() {
886        let bounds = Rect {
887            x: 0.0,
888            y: 0.0,
889            width: 20.0,
890            height: 20.0,
891        };
892        let command = |node_id| DrawCommandId {
893            node_id,
894            command_index: 0,
895            placement: DrawPlacement::Behind,
896        };
897        let mut child = test_layer(
898            bounds,
899            vec![RenderNode::DrawRun(DrawRunNode::for_command(
900                PrimitivePhase::BeforeChildren,
901                Some(command(17)),
902                Vec::new(),
903            ))],
904        );
905        child.node_id = Some(13);
906        let mut root = test_layer(
907            bounds,
908            vec![
909                RenderNode::DrawRun(DrawRunNode::for_command(
910                    PrimitivePhase::BeforeChildren,
911                    Some(command(9)),
912                    Vec::new(),
913                )),
914                RenderNode::DrawRun(DrawRunNode::new(PrimitivePhase::BeforeChildren, Vec::new())),
915                RenderNode::Layer(Box::new(child)),
916            ],
917        );
918
919        root.node_id = Some(5);
920
921        assert_eq!(
922            RenderGraph::new(root).retained_visual_observation_nodes(),
923            HashSet::from([5, 9, 13, 17])
924        );
925    }
926
927    #[test]
928    fn render_graph_new_recomputes_manual_layer_hashes() {
929        let primitive = PrimitiveEntry {
930            phase: PrimitivePhase::BeforeChildren,
931            node: PrimitiveNode::Draw(DrawPrimitiveNode {
932                primitive: DrawPrimitive::Rect {
933                    rect: Rect {
934                        x: 1.0,
935                        y: 2.0,
936                        width: 8.0,
937                        height: 6.0,
938                    },
939                    brush: Brush::solid(Color::WHITE),
940                    stroke: None,
941                },
942                clip: None,
943            }),
944        };
945        let mut root = test_layer(
946            Rect {
947                x: 0.0,
948                y: 0.0,
949                width: 20.0,
950                height: 20.0,
951            },
952            vec![RenderNode::Primitive(primitive)],
953        );
954        root.graphics_layer.render_effect = Some(RenderEffect::blur(3.0));
955        let mut expected = root.clone();
956        expected.recompute_raster_cache_hashes();
957
958        let graph = RenderGraph::new(root);
959        assert_eq!(
960            graph.root.target_content_hash(),
961            expected.target_content_hash()
962        );
963        assert_eq!(graph.root.effect_hash(), expected.effect_hash());
964    }
965
966    #[test]
967    fn motion_source_content_hash_ignores_translated_content_offset() {
968        let primitive = PrimitiveEntry {
969            phase: PrimitivePhase::BeforeChildren,
970            node: PrimitiveNode::Draw(DrawPrimitiveNode {
971                primitive: DrawPrimitive::Rect {
972                    rect: Rect {
973                        x: 1.0,
974                        y: 2.0,
975                        width: 8.0,
976                        height: 6.0,
977                    },
978                    brush: Brush::solid(Color::WHITE),
979                    stroke: None,
980                },
981                clip: None,
982            }),
983        };
984        let mut base = test_layer(
985            Rect {
986                x: 0.0,
987                y: 0.0,
988                width: 20.0,
989                height: 20.0,
990            },
991            vec![RenderNode::Primitive(primitive)],
992        );
993        base.translated_content_context = true;
994        base.translated_content_offset = Point::new(0.0, -24.0);
995        base.recompute_raster_cache_hashes();
996
997        let mut moved = base.clone();
998        moved.translated_content_offset = Point::new(0.0, -72.0);
999        moved.recompute_raster_cache_hashes();
1000
1001        assert_ne!(base.target_content_hash(), moved.target_content_hash());
1002        assert_eq!(
1003            base.motion_source_content_hash(),
1004            moved.motion_source_content_hash()
1005        );
1006    }
1007}