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        debug_assert!(
444            replay.as_ref().is_none_or(|frame| {
445                frame.fallback.is_some()
446                    || !frame.spans.iter().any(|span| {
447                        matches!(
448                            span,
449                            cranpose_ui_graphics::FrameSpan::Retained {
450                                capture: false,
451                                range,
452                                ..
453                            } if range.1 <= range.0
454                        )
455                    })
456            }),
457            "a replay frame with bypassed spans must own its fallback recording"
458        );
459        let mut summary = DrawRunSummary::scan(&primitives);
460        if replay.as_ref().is_some_and(|frame| {
461            frame
462                .spans
463                .iter()
464                .any(|span| matches!(span, cranpose_ui_graphics::FrameSpan::Retained { .. }))
465        }) {
466            summary.has_non_shadow = true;
467        }
468        Self {
469            phase,
470            command,
471            primitives,
472            summary,
473            replay,
474        }
475    }
476}
477
478/// One-pass discriminant census of a draw run, recursing through `Blend`
479/// wrappers the same way the per-primitive predicates it replaces did.
480#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
481pub struct DrawRunSummary {
482    /// Any `Text` primitive, including inside `Blend` — glyph masks want
483    /// rigid snapping.
484    pub has_text: bool,
485    pub has_shadow: bool,
486    /// Any primitive besides `Shadow` (direct drawable content).
487    pub has_non_shadow: bool,
488    /// Any `Image` or `Text`, including inside `Blend` — content that
489    /// resamples badly on a fractionally offset surface.
490    pub has_pixel_sensitive: bool,
491}
492
493impl DrawRunSummary {
494    pub fn scan(primitives: &[DrawPrimitive]) -> Self {
495        fn unwrap_blend(mut primitive: &DrawPrimitive) -> &DrawPrimitive {
496            while let DrawPrimitive::Blend {
497                primitive: inner, ..
498            } = primitive
499            {
500                primitive = inner;
501            }
502            primitive
503        }
504        let mut summary = Self::default();
505        for primitive in primitives {
506            if matches!(primitive, DrawPrimitive::Shadow(_)) {
507                summary.has_shadow = true;
508                continue;
509            }
510            summary.has_non_shadow = true;
511            match unwrap_blend(primitive) {
512                DrawPrimitive::Text(_) => {
513                    summary.has_text = true;
514                    summary.has_pixel_sensitive = true;
515                }
516                DrawPrimitive::Image { .. } => summary.has_pixel_sensitive = true,
517                _ => {}
518            }
519        }
520        summary
521    }
522}
523
524#[derive(Clone)]
525pub struct RenderGraph {
526    pub root: LayerNode,
527}
528
529impl RenderGraph {
530    pub fn new(mut root: LayerNode) -> Self {
531        root.recompute_raster_cache_hashes();
532        Self { root }
533    }
534
535    pub fn node_count(&self) -> usize {
536        fn count_layer(layer: &LayerNode) -> usize {
537            1 + layer
538                .children
539                .iter()
540                .map(|child| match child {
541                    RenderNode::Primitive(_) => 1,
542                    RenderNode::DrawRun(run) => run.primitives.len(),
543                    RenderNode::Layer(child_layer) => count_layer(child_layer),
544                })
545                .sum::<usize>()
546        }
547
548        count_layer(&self.root)
549    }
550
551    pub fn heap_bytes(&self) -> usize {
552        layer_heap_bytes(&self.root)
553    }
554
555    pub fn retained_visual_observation_nodes(&self) -> HashSet<NodeId> {
556        fn collect(layer: &LayerNode, nodes: &mut HashSet<NodeId>) {
557            if let Some(node_id) = layer.node_id {
558                nodes.insert(node_id);
559            }
560            for child in &layer.children {
561                match child {
562                    RenderNode::DrawRun(run) => {
563                        if let Some(command) = run.command {
564                            nodes.insert(command.node_id);
565                        }
566                    }
567                    RenderNode::Layer(child) => collect(child, nodes),
568                    RenderNode::Primitive(_) => {}
569                }
570            }
571        }
572
573        let mut nodes = HashSet::new();
574        collect(&self.root, &mut nodes);
575        nodes
576    }
577}
578
579fn layer_heap_bytes(layer: &LayerNode) -> usize {
580    layer.hit_test.as_ref().map_or(0, hit_test_heap_bytes)
581        + size_of::<RenderNode>() * layer.children.capacity()
582        + layer
583            .children
584            .iter()
585            .map(render_node_heap_bytes)
586            .sum::<usize>()
587}
588
589fn render_node_heap_bytes(node: &RenderNode) -> usize {
590    match node {
591        RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
592        RenderNode::DrawRun(run) => {
593            size_of::<DrawPrimitive>() * run.primitives.capacity()
594                + run
595                    .primitives
596                    .iter()
597                    .map(draw_primitive_heap_bytes)
598                    .sum::<usize>()
599        }
600        RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
601    }
602}
603
604fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
605    match &entry.node {
606        PrimitiveNode::Draw(draw) => draw_primitive_heap_bytes(&draw.primitive),
607        PrimitiveNode::Text(text) => {
608            size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
609        }
610    }
611}
612
613fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
614    match primitive {
615        DrawPrimitive::Content
616        | DrawPrimitive::Rect { .. }
617        | DrawPrimitive::RoundRect { .. }
618        | DrawPrimitive::Arc { .. } => 0,
619        DrawPrimitive::Blend { primitive, .. } => {
620            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
621        }
622        DrawPrimitive::Image { .. } => 0,
623        DrawPrimitive::Text(text) => {
624            size_of::<cranpose_ui_graphics::TextPrimitive>()
625                + text.text.len()
626                + text
627                    .style
628                    .font_family
629                    .as_ref()
630                    .map_or(0, |family| family.capacity())
631        }
632        DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
633    }
634}
635
636fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
637    match shadow {
638        ShadowPrimitive::Drop { shape, .. } => {
639            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
640        }
641        ShadowPrimitive::Inner { fill, cutout, .. } => {
642            size_of::<DrawPrimitive>() * 2
643                + draw_primitive_heap_bytes(fill)
644                + draw_primitive_heap_bytes(cutout)
645        }
646    }
647}
648
649fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
650    text.text.capacity()
651        + text.span_styles.capacity() * size_of::<usize>() * 2
652        + text.paragraph_styles.capacity() * size_of::<usize>() * 2
653        + text.string_annotations.capacity() * size_of::<usize>() * 2
654        + text.link_annotations.capacity() * size_of::<usize>() * 2
655        + text
656            .string_annotations
657            .iter()
658            .map(|annotation| {
659                annotation.item.tag.capacity() + annotation.item.annotation.capacity()
660            })
661            .sum::<usize>()
662        + text
663            .link_annotations
664            .iter()
665            .map(|annotation| match &annotation.item {
666                cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
667                cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
668            })
669            .sum::<usize>()
670}
671
672fn hit_test_heap_bytes(hit_test: &HitTestNode) -> usize {
673    hit_test.click_actions.capacity() * size_of::<Rc<dyn Fn(Point)>>()
674        + hit_test.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>()
675}
676
677pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
678    let mut min_x = f32::INFINITY;
679    let mut min_y = f32::INFINITY;
680    let mut max_x = f32::NEG_INFINITY;
681    let mut max_y = f32::NEG_INFINITY;
682
683    for [x, y] in quad {
684        min_x = min_x.min(x);
685        min_y = min_y.min(y);
686        max_x = max_x.max(x);
687        max_y = max_y.max(y);
688    }
689
690    Rect {
691        x: min_x,
692        y: min_y,
693        width: (max_x - min_x).max(0.0),
694        height: (max_y - min_y).max(0.0),
695    }
696}
697
698fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
699    let mut out = [[0.0; 3]; 3];
700    for row in 0..3 {
701        for col in 0..3 {
702            out[row][col] =
703                lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
704        }
705    }
706    out
707}
708
709fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
710    let mut matrix = [[0.0f32; 9]; 8];
711    for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
712        let row = index * 2;
713        let x = src[0];
714        let y = src[1];
715        let u = dst[0];
716        let v = dst[1];
717
718        matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
719        matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
720    }
721
722    for pivot in 0..8 {
723        let mut pivot_row = pivot;
724        let mut pivot_value = matrix[pivot][pivot].abs();
725        let mut candidate = pivot + 1;
726        while candidate < 8 {
727            let candidate_value = matrix[candidate][pivot].abs();
728            if candidate_value > pivot_value {
729                pivot_row = candidate;
730                pivot_value = candidate_value;
731            }
732            candidate += 1;
733        }
734
735        if pivot_value <= f32::EPSILON {
736            return None;
737        }
738
739        if pivot_row != pivot {
740            matrix.swap(pivot, pivot_row);
741        }
742
743        let divisor = matrix[pivot][pivot];
744        let mut col = pivot;
745        while col < 9 {
746            matrix[pivot][col] /= divisor;
747            col += 1;
748        }
749
750        for row in 0..8 {
751            if row == pivot {
752                continue;
753            }
754            let factor = matrix[row][pivot];
755            if factor.abs() <= f32::EPSILON {
756                continue;
757            }
758            let mut col = pivot;
759            while col < 9 {
760                matrix[row][col] -= factor * matrix[pivot][col];
761                col += 1;
762            }
763        }
764    }
765
766    let mut solution = [0.0f32; 8];
767    for index in 0..8 {
768        solution[index] = matrix[index][8];
769    }
770    Some(solution)
771}
772
773#[cfg(test)]
774mod tests {
775    use cranpose_ui_graphics::{Brush, Color, DrawPrimitive};
776
777    use super::*;
778    use crate::raster_cache::LayerRasterCacheHashes;
779
780    fn test_layer(local_bounds: Rect, children: Vec<RenderNode>) -> LayerNode {
781        LayerNode {
782            node_id: None,
783            local_bounds,
784            transform_to_parent: ProjectiveTransform::identity(),
785            content_offset: Point::default(),
786            motion_context_animated: false,
787            translated_content_context: false,
788            translated_content_offset: Point::default(),
789            scene_children_origin: Point::default(),
790            scene_children_layer_translation: Point::default(),
791            graphics_layer: GraphicsLayer::default(),
792            clip_to_bounds: false,
793            shadow_clip: None,
794            hit_test: None,
795            has_hit_targets: false,
796            has_origin_sinks: false,
797            isolation: IsolationReasons::default(),
798            cache_policy: CachePolicy::None,
799            cache_hashes: LayerRasterCacheHashes::default(),
800            cache_hashes_valid: false,
801            children,
802        }
803    }
804
805    #[test]
806    fn projective_transform_translation_maps_points() {
807        let transform = ProjectiveTransform::translation(7.0, -3.5);
808        let mapped = transform.map_point(Point { x: 2.0, y: 4.0 });
809        assert!((mapped.x - 9.0).abs() < 1e-6);
810        assert!((mapped.y - 0.5).abs() < 1e-6);
811    }
812
813    #[test]
814    fn projective_transform_then_composes_in_parent_order() {
815        let child = ProjectiveTransform::translation(4.0, 2.0);
816        let parent = ProjectiveTransform::translation(10.0, -1.0);
817        let composed = child.then(parent);
818        let mapped = composed.map_point(Point { x: 1.0, y: 1.0 });
819        assert!((mapped.x - 15.0).abs() < 1e-6);
820        assert!((mapped.y - 2.0).abs() < 1e-6);
821    }
822
823    #[test]
824    fn homography_maps_rect_corners_to_target_quad() {
825        let rect = Rect {
826            x: 0.0,
827            y: 0.0,
828            width: 20.0,
829            height: 10.0,
830        };
831        let quad = [[5.0, 7.0], [25.0, 6.0], [7.0, 20.0], [28.0, 21.0]];
832        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
833        let mapped = transform.map_rect(rect);
834        for (expected, actual) in quad.into_iter().zip(mapped) {
835            assert!((expected[0] - actual[0]).abs() < 1e-4);
836            assert!((expected[1] - actual[1]).abs() < 1e-4);
837        }
838    }
839
840    #[test]
841    fn axis_aligned_rect_to_quad_keeps_exact_affine_matrix() {
842        let rect = Rect {
843            x: 2.0,
844            y: 3.0,
845            width: 20.0,
846            height: 10.0,
847        };
848        let quad = [[12.0, 9.0], [32.0, 9.0], [12.0, 19.0], [32.0, 19.0]];
849        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
850
851        assert_eq!(
852            transform.matrix(),
853            [[1.0, 0.0, 10.0], [0.0, 1.0, 6.0], [0.0, 0.0, 1.0]]
854        );
855    }
856
857    #[test]
858    fn axis_aligned_rect_to_quad_keeps_exact_axis_aligned_scale() {
859        let rect = Rect {
860            x: 4.0,
861            y: 6.0,
862            width: 10.0,
863            height: 8.0,
864        };
865        let quad = [[20.0, 18.0], [50.0, 18.0], [20.0, 42.0], [50.0, 42.0]];
866        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
867
868        assert_eq!(
869            transform.matrix(),
870            [[3.0, 0.0, 8.0], [0.0, 3.0, 0.0], [0.0, 0.0, 1.0]]
871        );
872    }
873
874    #[test]
875    fn retained_visual_observation_nodes_collect_layers_and_command_owners() {
876        let bounds = Rect {
877            x: 0.0,
878            y: 0.0,
879            width: 20.0,
880            height: 20.0,
881        };
882        let command = |node_id| DrawCommandId {
883            node_id,
884            command_index: 0,
885            placement: DrawPlacement::Behind,
886        };
887        let mut child = test_layer(
888            bounds,
889            vec![RenderNode::DrawRun(DrawRunNode::for_command(
890                PrimitivePhase::BeforeChildren,
891                Some(command(17)),
892                Vec::new(),
893            ))],
894        );
895        child.node_id = Some(13);
896        let mut root = test_layer(
897            bounds,
898            vec![
899                RenderNode::DrawRun(DrawRunNode::for_command(
900                    PrimitivePhase::BeforeChildren,
901                    Some(command(9)),
902                    Vec::new(),
903                )),
904                RenderNode::DrawRun(DrawRunNode::new(PrimitivePhase::BeforeChildren, Vec::new())),
905                RenderNode::Layer(Box::new(child)),
906            ],
907        );
908
909        root.node_id = Some(5);
910
911        assert_eq!(
912            RenderGraph::new(root).retained_visual_observation_nodes(),
913            HashSet::from([5, 9, 13, 17])
914        );
915    }
916
917    #[test]
918    fn render_graph_new_recomputes_manual_layer_hashes() {
919        let primitive = PrimitiveEntry {
920            phase: PrimitivePhase::BeforeChildren,
921            node: PrimitiveNode::Draw(DrawPrimitiveNode {
922                primitive: DrawPrimitive::Rect {
923                    rect: Rect {
924                        x: 1.0,
925                        y: 2.0,
926                        width: 8.0,
927                        height: 6.0,
928                    },
929                    brush: Brush::solid(Color::WHITE),
930                    stroke: None,
931                },
932                clip: None,
933            }),
934        };
935        let mut root = test_layer(
936            Rect {
937                x: 0.0,
938                y: 0.0,
939                width: 20.0,
940                height: 20.0,
941            },
942            vec![RenderNode::Primitive(primitive)],
943        );
944        root.graphics_layer.render_effect = Some(RenderEffect::blur(3.0));
945        let mut expected = root.clone();
946        expected.recompute_raster_cache_hashes();
947
948        let graph = RenderGraph::new(root);
949        assert_eq!(
950            graph.root.target_content_hash(),
951            expected.target_content_hash()
952        );
953        assert_eq!(graph.root.effect_hash(), expected.effect_hash());
954    }
955
956    #[test]
957    fn motion_source_content_hash_ignores_translated_content_offset() {
958        let primitive = PrimitiveEntry {
959            phase: PrimitivePhase::BeforeChildren,
960            node: PrimitiveNode::Draw(DrawPrimitiveNode {
961                primitive: DrawPrimitive::Rect {
962                    rect: Rect {
963                        x: 1.0,
964                        y: 2.0,
965                        width: 8.0,
966                        height: 6.0,
967                    },
968                    brush: Brush::solid(Color::WHITE),
969                    stroke: None,
970                },
971                clip: None,
972            }),
973        };
974        let mut base = test_layer(
975            Rect {
976                x: 0.0,
977                y: 0.0,
978                width: 20.0,
979                height: 20.0,
980            },
981            vec![RenderNode::Primitive(primitive)],
982        );
983        base.translated_content_context = true;
984        base.translated_content_offset = Point::new(0.0, -24.0);
985        base.recompute_raster_cache_hashes();
986
987        let mut moved = base.clone();
988        moved.translated_content_offset = Point::new(0.0, -72.0);
989        moved.recompute_raster_cache_hashes();
990
991        assert_ne!(base.target_content_hash(), moved.target_content_hash());
992        assert_eq!(
993            base.motion_source_content_hash(),
994            moved.motion_source_content_hash()
995        );
996    }
997}