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    pub isolation: IsolationReasons,
300    pub cache_policy: CachePolicy,
301    pub cache_hashes: LayerRasterCacheHashes,
302    pub cache_hashes_valid: bool,
303    pub children: Vec<RenderNode>,
304}
305
306impl LayerNode {
307    pub fn clip_rect(&self) -> Option<Rect> {
308        (self.clip_to_bounds || self.graphics_layer.clip).then_some(self.local_bounds)
309    }
310
311    pub fn effect(&self) -> Option<&RenderEffect> {
312        self.graphics_layer.render_effect.as_ref()
313    }
314
315    pub fn backdrop(&self) -> Option<&RenderEffect> {
316        self.graphics_layer.backdrop_effect.as_ref()
317    }
318
319    pub fn opacity(&self) -> f32 {
320        self.graphics_layer.alpha
321    }
322
323    pub fn blend_mode(&self) -> BlendMode {
324        self.graphics_layer.blend_mode
325    }
326
327    pub fn color_filter(&self) -> Option<ColorFilter> {
328        self.graphics_layer.color_filter
329    }
330
331    pub fn target_content_hash(&self) -> u64 {
332        if self.cache_hashes_valid {
333            self.cache_hashes.target_content
334        } else {
335            crate::graph_hash::layer_raster_cache_hashes(self).target_content
336        }
337    }
338
339    pub fn motion_source_content_hash(&self) -> u64 {
340        crate::graph_hash::layer_motion_source_content_hash(self)
341    }
342
343    pub fn effect_hash(&self) -> u64 {
344        if self.cache_hashes_valid {
345            self.cache_hashes.effect
346        } else {
347            crate::graph_hash::layer_raster_cache_hashes(self).effect
348        }
349    }
350
351    pub fn recompute_raster_cache_hashes(&mut self) {
352        crate::graph_hash::recompute_layer_raster_cache_hashes(self);
353    }
354}
355
356#[derive(Clone)]
357pub enum RenderNode {
358    Primitive(PrimitiveEntry),
359    /// A whole draw command's primitives as one node. A heavy canvas records
360    /// thousands of primitives per frame; wrapping each in its own
361    /// [`RenderNode`] made the graph rebuild move every one of them twice and
362    /// free seventeen thousand nodes per frame on a stress scene. The run
363    /// keeps the recorded vector intact — semantically it is exactly that
364    /// many consecutive `Primitive` draw entries with no per-primitive clip.
365    DrawRun(DrawRunNode),
366    Layer(Box<LayerNode>),
367}
368
369/// Stable identity of the draw command a run was recorded from: the layout
370/// node owning the command, the command's index in that node's command list,
371/// and which placement pass produced this run (a `WithContent` command emits
372/// one run per placement, so the pair alone is not unique). Rendering does
373/// not read it yet; it is the key under which retained recording state lives
374/// as retention moves up to the draw-command recorder, and it must survive
375/// recording, graph construction, normalized-scene creation, and renderer
376/// cache lookup unchanged.
377#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
378pub struct DrawCommandId {
379    pub node_id: NodeId,
380    pub command_index: u32,
381    pub placement: DrawPlacement,
382}
383
384#[derive(Clone, Debug, PartialEq)]
385pub struct DrawRunNode {
386    pub phase: PrimitivePhase,
387    /// Which draw command recorded these primitives. `None` only for runs
388    /// with no per-command provenance (hand-built tests).
389    pub command: Option<DrawCommandId>,
390    /// Shared, not owned: the recording registry keyed by [`DrawCommandId`]
391    /// keeps a handle to the same buffer, so its capacity survives this
392    /// node being dropped on the next rebuild and the command re-records
393    /// into it instead of growing a fresh vector. Nothing mutates a run's
394    /// primitives after construction, which is what makes sharing sound.
395    pub primitives: std::rc::Rc<Vec<DrawPrimitive>>,
396    /// Content facts consumers keep asking per frame, answered once at
397    /// construction. Surface planning used to rescan every primitive of
398    /// every run per frame to learn "does it contain text?" — for a
399    /// 17k-primitive game canvas with no text, that was two full walks per
400    /// frame that could never early-exit.
401    pub summary: DrawRunSummary,
402    /// The command's verified retained/dynamic span structure for the frame
403    /// this node was built, in primitive space. A renderer that retains by
404    /// identity draws the run span by span — retained spans from slots
405    /// keyed (command, slot), dynamic spans from `primitives` — instead of
406    /// walking the whole vector. `None` means no verification ran or
407    /// nothing was retained: the run is all ordinary primitives.
408    pub replay: Option<Box<cranpose_ui_graphics::CommandReplayFrame>>,
409}
410
411impl DrawRunNode {
412    pub fn new(phase: PrimitivePhase, primitives: Vec<DrawPrimitive>) -> Self {
413        Self::for_command(phase, None, primitives)
414    }
415
416    pub fn for_command(
417        phase: PrimitivePhase,
418        command: Option<DrawCommandId>,
419        primitives: Vec<DrawPrimitive>,
420    ) -> Self {
421        Self::for_command_shared(phase, command, std::rc::Rc::new(primitives))
422    }
423
424    pub fn for_command_shared(
425        phase: PrimitivePhase,
426        command: Option<DrawCommandId>,
427        primitives: std::rc::Rc<Vec<DrawPrimitive>>,
428    ) -> Self {
429        Self::for_command_replayed(phase, command, primitives, None)
430    }
431
432    pub fn for_command_replayed(
433        phase: PrimitivePhase,
434        command: Option<DrawCommandId>,
435        primitives: std::rc::Rc<Vec<DrawPrimitive>>,
436        replay: Option<Box<cranpose_ui_graphics::CommandReplayFrame>>,
437    ) -> Self {
438        // Fail-closed invariant: a bypassed span has NO primitives — the
439        // frame's own `fallback` recording is the only thing that can ever
440        // draw it, so a frame carrying bypassed spans without one is
441        // unconstructible here. The builder attaches the published handle
442        // to every frame; hand-built frames that bypass must do the same.
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        // Bypassed retained spans have no primitives to scan, but they are
461        // drawable content — only shape records ever retain, never shadows.
462        if replay.as_ref().is_some_and(|frame| {
463            frame
464                .spans
465                .iter()
466                .any(|span| matches!(span, cranpose_ui_graphics::FrameSpan::Retained { .. }))
467        }) {
468            summary.has_non_shadow = true;
469        }
470        Self {
471            phase,
472            command,
473            primitives,
474            summary,
475            replay,
476        }
477    }
478}
479
480/// One-pass discriminant census of a draw run, recursing through `Blend`
481/// wrappers the same way the per-primitive predicates it replaces did.
482#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
483pub struct DrawRunSummary {
484    /// Any `Text` primitive, including inside `Blend` — glyph masks want
485    /// rigid snapping.
486    pub has_text: bool,
487    pub has_shadow: bool,
488    /// Any primitive besides `Shadow` (direct drawable content).
489    pub has_non_shadow: bool,
490    /// Any `Image` or `Text`, including inside `Blend` — content that
491    /// resamples badly on a fractionally offset surface.
492    pub has_pixel_sensitive: bool,
493}
494
495impl DrawRunSummary {
496    pub fn scan(primitives: &[DrawPrimitive]) -> Self {
497        fn unwrap_blend(mut primitive: &DrawPrimitive) -> &DrawPrimitive {
498            while let DrawPrimitive::Blend {
499                primitive: inner, ..
500            } = primitive
501            {
502                primitive = inner;
503            }
504            primitive
505        }
506        let mut summary = Self::default();
507        for primitive in primitives {
508            // Shadow classification looks at the outer discriminant only,
509            // text and pixel sensitivity see through `Blend` — exactly the
510            // split the per-primitive predicates this replaces made.
511            if matches!(primitive, DrawPrimitive::Shadow(_)) {
512                summary.has_shadow = true;
513                continue;
514            }
515            summary.has_non_shadow = true;
516            match unwrap_blend(primitive) {
517                DrawPrimitive::Text(_) => {
518                    summary.has_text = true;
519                    summary.has_pixel_sensitive = true;
520                }
521                DrawPrimitive::Image { .. } => summary.has_pixel_sensitive = true,
522                _ => {}
523            }
524        }
525        summary
526    }
527}
528
529#[derive(Clone)]
530pub struct RenderGraph {
531    pub root: LayerNode,
532}
533
534impl RenderGraph {
535    pub fn new(mut root: LayerNode) -> Self {
536        root.recompute_raster_cache_hashes();
537        Self { root }
538    }
539
540    pub fn node_count(&self) -> usize {
541        fn count_layer(layer: &LayerNode) -> usize {
542            1 + layer
543                .children
544                .iter()
545                .map(|child| match child {
546                    RenderNode::Primitive(_) => 1,
547                    RenderNode::DrawRun(run) => run.primitives.len(),
548                    RenderNode::Layer(child_layer) => count_layer(child_layer),
549                })
550                .sum::<usize>()
551        }
552
553        count_layer(&self.root)
554    }
555
556    pub fn heap_bytes(&self) -> usize {
557        layer_heap_bytes(&self.root)
558    }
559
560    pub fn retained_visual_observation_nodes(&self) -> HashSet<NodeId> {
561        fn collect(layer: &LayerNode, nodes: &mut HashSet<NodeId>) {
562            if let Some(node_id) = layer.node_id {
563                nodes.insert(node_id);
564            }
565            for child in &layer.children {
566                match child {
567                    RenderNode::DrawRun(run) => {
568                        if let Some(command) = run.command {
569                            nodes.insert(command.node_id);
570                        }
571                    }
572                    RenderNode::Layer(child) => collect(child, nodes),
573                    RenderNode::Primitive(_) => {}
574                }
575            }
576        }
577
578        let mut nodes = HashSet::new();
579        collect(&self.root, &mut nodes);
580        nodes
581    }
582}
583
584fn layer_heap_bytes(layer: &LayerNode) -> usize {
585    layer.hit_test.as_ref().map_or(0, hit_test_heap_bytes)
586        + size_of::<RenderNode>() * layer.children.capacity()
587        + layer
588            .children
589            .iter()
590            .map(render_node_heap_bytes)
591            .sum::<usize>()
592}
593
594fn render_node_heap_bytes(node: &RenderNode) -> usize {
595    match node {
596        RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
597        RenderNode::DrawRun(run) => {
598            size_of::<DrawPrimitive>() * run.primitives.capacity()
599                + run
600                    .primitives
601                    .iter()
602                    .map(draw_primitive_heap_bytes)
603                    .sum::<usize>()
604        }
605        RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
606    }
607}
608
609fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
610    match &entry.node {
611        PrimitiveNode::Draw(draw) => draw_primitive_heap_bytes(&draw.primitive),
612        PrimitiveNode::Text(text) => {
613            size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
614        }
615    }
616}
617
618fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
619    match primitive {
620        DrawPrimitive::Content
621        | DrawPrimitive::Rect { .. }
622        | DrawPrimitive::RoundRect { .. }
623        | DrawPrimitive::Arc { .. } => 0,
624        DrawPrimitive::Blend { primitive, .. } => {
625            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
626        }
627        DrawPrimitive::Image { .. } => 0,
628        DrawPrimitive::Text(text) => {
629            size_of::<cranpose_ui_graphics::TextPrimitive>()
630                + text.text.len()
631                + text
632                    .style
633                    .font_family
634                    .as_ref()
635                    .map_or(0, |family| family.capacity())
636        }
637        DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
638    }
639}
640
641fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
642    match shadow {
643        ShadowPrimitive::Drop { shape, .. } => {
644            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
645        }
646        ShadowPrimitive::Inner { fill, cutout, .. } => {
647            size_of::<DrawPrimitive>() * 2
648                + draw_primitive_heap_bytes(fill)
649                + draw_primitive_heap_bytes(cutout)
650        }
651    }
652}
653
654fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
655    text.text.capacity()
656        + text.span_styles.capacity() * size_of::<usize>() * 2
657        + text.paragraph_styles.capacity() * size_of::<usize>() * 2
658        + text.string_annotations.capacity() * size_of::<usize>() * 2
659        + text.link_annotations.capacity() * size_of::<usize>() * 2
660        + text
661            .string_annotations
662            .iter()
663            .map(|annotation| {
664                annotation.item.tag.capacity() + annotation.item.annotation.capacity()
665            })
666            .sum::<usize>()
667        + text
668            .link_annotations
669            .iter()
670            .map(|annotation| match &annotation.item {
671                cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
672                cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
673            })
674            .sum::<usize>()
675}
676
677fn hit_test_heap_bytes(hit_test: &HitTestNode) -> usize {
678    hit_test.click_actions.capacity() * size_of::<Rc<dyn Fn(Point)>>()
679        + hit_test.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>()
680}
681
682pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
683    let mut min_x = f32::INFINITY;
684    let mut min_y = f32::INFINITY;
685    let mut max_x = f32::NEG_INFINITY;
686    let mut max_y = f32::NEG_INFINITY;
687
688    for [x, y] in quad {
689        min_x = min_x.min(x);
690        min_y = min_y.min(y);
691        max_x = max_x.max(x);
692        max_y = max_y.max(y);
693    }
694
695    Rect {
696        x: min_x,
697        y: min_y,
698        width: (max_x - min_x).max(0.0),
699        height: (max_y - min_y).max(0.0),
700    }
701}
702
703fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
704    let mut out = [[0.0; 3]; 3];
705    for row in 0..3 {
706        for col in 0..3 {
707            out[row][col] =
708                lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
709        }
710    }
711    out
712}
713
714fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
715    let mut matrix = [[0.0f32; 9]; 8];
716    for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
717        let row = index * 2;
718        let x = src[0];
719        let y = src[1];
720        let u = dst[0];
721        let v = dst[1];
722
723        matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
724        matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
725    }
726
727    for pivot in 0..8 {
728        let mut pivot_row = pivot;
729        let mut pivot_value = matrix[pivot][pivot].abs();
730        let mut candidate = pivot + 1;
731        while candidate < 8 {
732            let candidate_value = matrix[candidate][pivot].abs();
733            if candidate_value > pivot_value {
734                pivot_row = candidate;
735                pivot_value = candidate_value;
736            }
737            candidate += 1;
738        }
739
740        if pivot_value <= f32::EPSILON {
741            return None;
742        }
743
744        if pivot_row != pivot {
745            matrix.swap(pivot, pivot_row);
746        }
747
748        let divisor = matrix[pivot][pivot];
749        let mut col = pivot;
750        while col < 9 {
751            matrix[pivot][col] /= divisor;
752            col += 1;
753        }
754
755        for row in 0..8 {
756            if row == pivot {
757                continue;
758            }
759            let factor = matrix[row][pivot];
760            if factor.abs() <= f32::EPSILON {
761                continue;
762            }
763            let mut col = pivot;
764            while col < 9 {
765                matrix[row][col] -= factor * matrix[pivot][col];
766                col += 1;
767            }
768        }
769    }
770
771    let mut solution = [0.0f32; 8];
772    for index in 0..8 {
773        solution[index] = matrix[index][8];
774    }
775    Some(solution)
776}
777
778#[cfg(test)]
779mod tests {
780    use cranpose_ui_graphics::{Brush, Color, DrawPrimitive};
781
782    use super::*;
783    use crate::raster_cache::LayerRasterCacheHashes;
784
785    fn test_layer(local_bounds: Rect, children: Vec<RenderNode>) -> LayerNode {
786        LayerNode {
787            node_id: None,
788            local_bounds,
789            transform_to_parent: ProjectiveTransform::identity(),
790            content_offset: Point::default(),
791            motion_context_animated: false,
792            translated_content_context: false,
793            translated_content_offset: Point::default(),
794            scene_children_origin: Point::default(),
795            scene_children_layer_translation: Point::default(),
796            graphics_layer: GraphicsLayer::default(),
797            clip_to_bounds: false,
798            shadow_clip: None,
799            hit_test: None,
800            has_hit_targets: false,
801            isolation: IsolationReasons::default(),
802            cache_policy: CachePolicy::None,
803            cache_hashes: LayerRasterCacheHashes::default(),
804            cache_hashes_valid: false,
805            children,
806        }
807    }
808
809    #[test]
810    fn projective_transform_translation_maps_points() {
811        let transform = ProjectiveTransform::translation(7.0, -3.5);
812        let mapped = transform.map_point(Point { x: 2.0, y: 4.0 });
813        assert!((mapped.x - 9.0).abs() < 1e-6);
814        assert!((mapped.y - 0.5).abs() < 1e-6);
815    }
816
817    #[test]
818    fn projective_transform_then_composes_in_parent_order() {
819        let child = ProjectiveTransform::translation(4.0, 2.0);
820        let parent = ProjectiveTransform::translation(10.0, -1.0);
821        let composed = child.then(parent);
822        let mapped = composed.map_point(Point { x: 1.0, y: 1.0 });
823        assert!((mapped.x - 15.0).abs() < 1e-6);
824        assert!((mapped.y - 2.0).abs() < 1e-6);
825    }
826
827    #[test]
828    fn homography_maps_rect_corners_to_target_quad() {
829        let rect = Rect {
830            x: 0.0,
831            y: 0.0,
832            width: 20.0,
833            height: 10.0,
834        };
835        let quad = [[5.0, 7.0], [25.0, 6.0], [7.0, 20.0], [28.0, 21.0]];
836        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
837        let mapped = transform.map_rect(rect);
838        for (expected, actual) in quad.into_iter().zip(mapped) {
839            assert!((expected[0] - actual[0]).abs() < 1e-4);
840            assert!((expected[1] - actual[1]).abs() < 1e-4);
841        }
842    }
843
844    #[test]
845    fn axis_aligned_rect_to_quad_keeps_exact_affine_matrix() {
846        let rect = Rect {
847            x: 2.0,
848            y: 3.0,
849            width: 20.0,
850            height: 10.0,
851        };
852        let quad = [[12.0, 9.0], [32.0, 9.0], [12.0, 19.0], [32.0, 19.0]];
853        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
854
855        assert_eq!(
856            transform.matrix(),
857            [[1.0, 0.0, 10.0], [0.0, 1.0, 6.0], [0.0, 0.0, 1.0]]
858        );
859    }
860
861    #[test]
862    fn axis_aligned_rect_to_quad_keeps_exact_axis_aligned_scale() {
863        let rect = Rect {
864            x: 4.0,
865            y: 6.0,
866            width: 10.0,
867            height: 8.0,
868        };
869        let quad = [[20.0, 18.0], [50.0, 18.0], [20.0, 42.0], [50.0, 42.0]];
870        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
871
872        assert_eq!(
873            transform.matrix(),
874            [[3.0, 0.0, 8.0], [0.0, 3.0, 0.0], [0.0, 0.0, 1.0]]
875        );
876    }
877
878    #[test]
879    fn retained_visual_observation_nodes_collect_layers_and_command_owners() {
880        let bounds = Rect {
881            x: 0.0,
882            y: 0.0,
883            width: 20.0,
884            height: 20.0,
885        };
886        let command = |node_id| DrawCommandId {
887            node_id,
888            command_index: 0,
889            placement: DrawPlacement::Behind,
890        };
891        let mut child = test_layer(
892            bounds,
893            vec![RenderNode::DrawRun(DrawRunNode::for_command(
894                PrimitivePhase::BeforeChildren,
895                Some(command(17)),
896                Vec::new(),
897            ))],
898        );
899        child.node_id = Some(13);
900        let mut root = test_layer(
901            bounds,
902            vec![
903                RenderNode::DrawRun(DrawRunNode::for_command(
904                    PrimitivePhase::BeforeChildren,
905                    Some(command(9)),
906                    Vec::new(),
907                )),
908                RenderNode::DrawRun(DrawRunNode::new(PrimitivePhase::BeforeChildren, Vec::new())),
909                RenderNode::Layer(Box::new(child)),
910            ],
911        );
912
913        root.node_id = Some(5);
914
915        assert_eq!(
916            RenderGraph::new(root).retained_visual_observation_nodes(),
917            HashSet::from([5, 9, 13, 17])
918        );
919    }
920
921    #[test]
922    fn render_graph_new_recomputes_manual_layer_hashes() {
923        let primitive = PrimitiveEntry {
924            phase: PrimitivePhase::BeforeChildren,
925            node: PrimitiveNode::Draw(DrawPrimitiveNode {
926                primitive: DrawPrimitive::Rect {
927                    rect: Rect {
928                        x: 1.0,
929                        y: 2.0,
930                        width: 8.0,
931                        height: 6.0,
932                    },
933                    brush: Brush::solid(Color::WHITE),
934                    stroke: None,
935                },
936                clip: None,
937            }),
938        };
939        let mut root = test_layer(
940            Rect {
941                x: 0.0,
942                y: 0.0,
943                width: 20.0,
944                height: 20.0,
945            },
946            vec![RenderNode::Primitive(primitive)],
947        );
948        root.graphics_layer.render_effect = Some(RenderEffect::blur(3.0));
949        let mut expected = root.clone();
950        expected.recompute_raster_cache_hashes();
951
952        let graph = RenderGraph::new(root);
953        assert_eq!(
954            graph.root.target_content_hash(),
955            expected.target_content_hash()
956        );
957        assert_eq!(graph.root.effect_hash(), expected.effect_hash());
958    }
959
960    #[test]
961    fn motion_source_content_hash_ignores_translated_content_offset() {
962        let primitive = PrimitiveEntry {
963            phase: PrimitivePhase::BeforeChildren,
964            node: PrimitiveNode::Draw(DrawPrimitiveNode {
965                primitive: DrawPrimitive::Rect {
966                    rect: Rect {
967                        x: 1.0,
968                        y: 2.0,
969                        width: 8.0,
970                        height: 6.0,
971                    },
972                    brush: Brush::solid(Color::WHITE),
973                    stroke: None,
974                },
975                clip: None,
976            }),
977        };
978        let mut base = test_layer(
979            Rect {
980                x: 0.0,
981                y: 0.0,
982                width: 20.0,
983                height: 20.0,
984            },
985            vec![RenderNode::Primitive(primitive)],
986        );
987        base.translated_content_context = true;
988        base.translated_content_offset = Point::new(0.0, -24.0);
989        base.recompute_raster_cache_hashes();
990
991        let mut moved = base.clone();
992        moved.translated_content_offset = Point::new(0.0, -72.0);
993        moved.recompute_raster_cache_hashes();
994
995        assert_ne!(base.target_content_hash(), moved.target_content_hash());
996        assert_eq!(
997            base.motion_source_content_hash(),
998            moved.motion_source_content_hash()
999        );
1000    }
1001}