Skip to main content

cranpose_render_common/
graph.rs

1use std::{mem::size_of, ops::Range, rc::Rc};
2
3use cranpose_core::{NodeId, collections::map::HashSet};
4use cranpose_ui::{
5    GraphicsLayer, ModifierNodeSlices, Point, Rect, RenderEffect, RoundedCornerShape,
6    TextLayoutOptions, TextOverflow, TextStyle,
7    text::{AnnotatedString, RenderString},
8};
9use cranpose_ui_graphics::{
10    BlendMode, ColorFilter, CommandRecording, DrawPrimitive, RecordingSummary, ShadowPrimitive,
11};
12
13use crate::{raster_cache::LayerRasterCacheHashes, style_shared::DrawPlacement};
14
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct ProjectiveTransform {
17    matrix: [[f32; 3]; 3],
18}
19
20impl ProjectiveTransform {
21    pub const fn identity() -> Self {
22        Self {
23            matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
24        }
25    }
26
27    pub fn translation(tx: f32, ty: f32) -> Self {
28        Self {
29            matrix: [[1.0, 0.0, tx], [0.0, 1.0, ty], [0.0, 0.0, 1.0]],
30        }
31    }
32
33    /// Uniform scale about the origin (device-scale root transform: render
34    /// graphs stay in logical dp; density applies at execution).
35    pub fn uniform_scale(scale: f32) -> Self {
36        Self {
37            matrix: [[scale, 0.0, 0.0], [0.0, scale, 0.0], [0.0, 0.0, 1.0]],
38        }
39    }
40
41    pub fn from_rect_to_quad(rect: Rect, quad: [[f32; 2]; 4]) -> Self {
42        if rect.width.abs() <= f32::EPSILON || rect.height.abs() <= f32::EPSILON {
43            return Self::translation(quad[0][0], quad[0][1]);
44        }
45
46        if let Some(axis_aligned) = axis_aligned_rect_from_quad(quad) {
47            let scale_x = axis_aligned.width / rect.width;
48            let scale_y = axis_aligned.height / rect.height;
49            return Self {
50                matrix: [
51                    [scale_x, 0.0, axis_aligned.x - rect.x * scale_x],
52                    [0.0, scale_y, axis_aligned.y - rect.y * scale_y],
53                    [0.0, 0.0, 1.0],
54                ],
55            };
56        }
57
58        let source = [
59            [rect.x, rect.y],
60            [rect.x + rect.width, rect.y],
61            [rect.x, rect.y + rect.height],
62            [rect.x + rect.width, rect.y + rect.height],
63        ];
64        let Some(coefficients) = solve_homography(source, quad) else {
65            return Self::identity();
66        };
67
68        Self {
69            matrix: [
70                [coefficients[0], coefficients[1], coefficients[2]],
71                [coefficients[3], coefficients[4], coefficients[5]],
72                [coefficients[6], coefficients[7], 1.0],
73            ],
74        }
75    }
76
77    /// Returns the composed transform that applies `self` first and `next` second.
78    pub fn then(self, next: Self) -> Self {
79        Self {
80            matrix: multiply_matrices(next.matrix, self.matrix),
81        }
82    }
83
84    pub fn inverse(self) -> Option<Self> {
85        let m = self.matrix;
86        let a = m[0][0];
87        let b = m[0][1];
88        let c = m[0][2];
89        let d = m[1][0];
90        let e = m[1][1];
91        let f = m[1][2];
92        let g = m[2][0];
93        let h = m[2][1];
94        let i = m[2][2];
95
96        let cofactor00 = e * i - f * h;
97        let cofactor01 = -(d * i - f * g);
98        let cofactor02 = d * h - e * g;
99        let cofactor10 = -(b * i - c * h);
100        let cofactor11 = a * i - c * g;
101        let cofactor12 = -(a * h - b * g);
102        let cofactor20 = b * f - c * e;
103        let cofactor21 = -(a * f - c * d);
104        let cofactor22 = a * e - b * d;
105
106        let determinant = a * cofactor00 + b * cofactor01 + c * cofactor02;
107        if determinant.abs() <= f32::EPSILON {
108            return None;
109        }
110        let inverse_determinant = 1.0 / determinant;
111
112        Some(Self {
113            matrix: [
114                [
115                    cofactor00 * inverse_determinant,
116                    cofactor10 * inverse_determinant,
117                    cofactor20 * inverse_determinant,
118                ],
119                [
120                    cofactor01 * inverse_determinant,
121                    cofactor11 * inverse_determinant,
122                    cofactor21 * inverse_determinant,
123                ],
124                [
125                    cofactor02 * inverse_determinant,
126                    cofactor12 * inverse_determinant,
127                    cofactor22 * inverse_determinant,
128                ],
129            ],
130        })
131    }
132
133    pub fn matrix(self) -> [[f32; 3]; 3] {
134        self.matrix
135    }
136
137    pub fn map_point(self, point: Point) -> Point {
138        let x = point.x;
139        let y = point.y;
140        let w = self.matrix[2][0] * x + self.matrix[2][1] * y + self.matrix[2][2];
141        let safe_w = if w.abs() <= f32::EPSILON { 1.0 } else { w };
142
143        Point {
144            x: (self.matrix[0][0] * x + self.matrix[0][1] * y + self.matrix[0][2]) / safe_w,
145            y: (self.matrix[1][0] * x + self.matrix[1][1] * y + self.matrix[1][2]) / safe_w,
146        }
147    }
148
149    pub fn map_rect(self, rect: Rect) -> [[f32; 2]; 4] {
150        [
151            self.map_point(Point {
152                x: rect.x,
153                y: rect.y,
154            }),
155            self.map_point(Point {
156                x: rect.x + rect.width,
157                y: rect.y,
158            }),
159            self.map_point(Point {
160                x: rect.x,
161                y: rect.y + rect.height,
162            }),
163            self.map_point(Point {
164                x: rect.x + rect.width,
165                y: rect.y + rect.height,
166            }),
167        ]
168        .map(|point| [point.x, point.y])
169    }
170
171    pub fn bounds_for_rect(self, rect: Rect) -> Rect {
172        quad_bounds(self.map_rect(rect))
173    }
174}
175
176fn axis_aligned_rect_from_quad(quad: [[f32; 2]; 4]) -> Option<Rect> {
177    let top_left = quad[0];
178    let top_right = quad[1];
179    let bottom_left = quad[2];
180    let bottom_right = quad[3];
181    let x_epsilon = 1e-4;
182    let y_epsilon = 1e-4;
183
184    if (top_left[1] - top_right[1]).abs() > y_epsilon
185        || (bottom_left[1] - bottom_right[1]).abs() > y_epsilon
186        || (top_left[0] - bottom_left[0]).abs() > x_epsilon
187        || (top_right[0] - bottom_right[0]).abs() > x_epsilon
188    {
189        return None;
190    }
191
192    Some(Rect {
193        x: top_left[0],
194        y: top_left[1],
195        width: top_right[0] - top_left[0],
196        height: bottom_left[1] - top_left[1],
197    })
198}
199
200impl Default for ProjectiveTransform {
201    fn default() -> Self {
202        Self::identity()
203    }
204}
205
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207pub struct IsolationReasons {
208    pub explicit_offscreen: bool,
209    pub shape_clip: bool,
210    pub effect: bool,
211    pub backdrop: bool,
212    pub group_opacity: bool,
213    pub blend_mode: bool,
214}
215
216impl IsolationReasons {
217    pub fn has_any(self) -> bool {
218        self.explicit_offscreen
219            || self.shape_clip
220            || self.effect
221            || self.backdrop
222            || self.group_opacity
223            || self.blend_mode
224    }
225}
226
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
228pub enum CachePolicy {
229    #[default]
230    None,
231    Auto,
232}
233
234#[derive(Clone)]
235pub struct HitTestNode {
236    pub shape: Option<RoundedCornerShape>,
237    /// The node's modifier slices, shared rather than copied: they hold its
238    /// pointer inputs and the pointer icon it asks for while hovered. A node
239    /// that only names an icon is still a hit target, which is how a
240    /// decorative panel carries a cursor without handling clicks.
241    pub handlers: Rc<ModifierNodeSlices>,
242    pub clip: Option<Rect>,
243}
244
245#[derive(Clone, Debug, PartialEq)]
246pub struct DrawPrimitiveNode {
247    pub primitive: DrawPrimitive,
248    pub clip: Option<Rect>,
249}
250
251#[derive(Clone, Debug, PartialEq)]
252pub struct TextPrimitiveNode {
253    pub node_id: NodeId,
254    pub rect: Rect,
255    /// Shared so the renderer can hand the same allocation to every draw it
256    /// emits for this node instead of deep-copying the string once per emit.
257    pub text: Rc<AnnotatedString>,
258    /// `text` as the renderer's draws carry it across threads, shared with
259    /// the prepared layout it came from so no frame converts it again.
260    pub render_text: std::sync::Arc<RenderString>,
261    /// Shared so every frame's draws of this text hand over the same style
262    /// instead of copying it.
263    pub text_style: std::sync::Arc<TextStyle>,
264    pub font_size: f32,
265    pub layout_options: TextLayoutOptions,
266    pub clip: Option<Rect>,
267}
268
269impl TextPrimitiveNode {
270    /// Whether the text's glyphs stay inside `bounds`: nothing casts a shadow
271    /// past them and the layout does not let the text overflow its rect.
272    fn draws_within(&self, bounds: Rect) -> bool {
273        self.text_style.span_style.shadow.is_none()
274            && self
275                .text
276                .span_styles
277                .iter()
278                .all(|span| span.item.shadow.is_none())
279            && !matches!(self.layout_options.overflow, TextOverflow::Visible)
280            && rect_within(self.rect, bounds)
281    }
282}
283
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285pub enum PrimitivePhase {
286    BeforeChildren,
287    AfterChildren,
288}
289
290#[derive(Clone, Debug, PartialEq)]
291pub enum PrimitiveNode {
292    Draw(Box<DrawPrimitiveNode>),
293    Text(Box<TextPrimitiveNode>),
294}
295
296#[derive(Clone, Debug, PartialEq)]
297pub struct PrimitiveEntry {
298    pub phase: PrimitivePhase,
299    pub node: PrimitiveNode,
300}
301
302#[derive(Clone)]
303pub struct LayerNode {
304    pub node_id: Option<NodeId>,
305    /// Set on the synthetic layer that holds a node's outer draws, those chained
306    /// before its graphics layer, around that node's own layer. Scene updates
307    /// address the node through this id because the node's layer has none of the
308    /// outer draws and the wrapper has no node id of its own.
309    pub wraps: Option<NodeId>,
310    pub local_bounds: Rect,
311    pub transform_to_parent: ProjectiveTransform,
312    pub content_offset: Point,
313    pub motion_context_animated: bool,
314    pub translated_content_context: bool,
315    pub translated_content_offset: Point,
316    /// Where layout placed this layer within its parent's content, before the
317    /// parent's content offset. Scene updates add these up from the root, with
318    /// each layer's content offset and graphics-layer translation, to find the
319    /// window origin of a subtree they rebuild.
320    pub origin_in_parent: Point,
321    pub graphics_layer: GraphicsLayer,
322    pub clip_to_bounds: bool,
323    pub shadow_clip: Option<Rect>,
324    pub hit_test: Option<HitTestNode>,
325    pub has_hit_targets: bool,
326    /// Whether this subtree publishes live window origins (a text field's
327    /// popup anchor, a scroll container's viewport rect). Those sinks are
328    /// written during a full lowering, so the scroll fast path may translate
329    /// a retained subtree in place only when this is false.
330    pub has_origin_sinks: bool,
331    /// Whether everything this layer and its subtree draw lies within its
332    /// `local_bounds`, give or take [`CONTAINED_DRAW_SLACK`], so a renderer
333    /// may skip the whole subtree where those bounds are clipped away. Scene
334    /// building keeps it current; `false` promises nothing.
335    pub draws_within_bounds: bool,
336    pub isolation: IsolationReasons,
337    pub cache_policy: CachePolicy,
338    pub cache_hashes: LayerRasterCacheHashes,
339    pub cache_hashes_valid: bool,
340    pub children: Vec<RenderNode>,
341}
342
343impl Default for LayerNode {
344    fn default() -> Self {
345        Self {
346            node_id: None,
347            wraps: None,
348            local_bounds: Rect {
349                x: 0.0,
350                y: 0.0,
351                width: 0.0,
352                height: 0.0,
353            },
354            transform_to_parent: ProjectiveTransform::identity(),
355            content_offset: Point::default(),
356            motion_context_animated: false,
357            translated_content_context: false,
358            translated_content_offset: Point::default(),
359            origin_in_parent: Point::default(),
360            graphics_layer: GraphicsLayer::default(),
361            clip_to_bounds: false,
362            shadow_clip: None,
363            hit_test: None,
364            has_hit_targets: false,
365            has_origin_sinks: false,
366            draws_within_bounds: false,
367            isolation: IsolationReasons::default(),
368            cache_policy: CachePolicy::None,
369            cache_hashes: LayerRasterCacheHashes::default(),
370            cache_hashes_valid: false,
371            children: Vec::new(),
372        }
373    }
374}
375
376/// How far past its bounds a layer that draws within them may still put
377/// pixels: glyph and edge antialiasing.
378pub const CONTAINED_DRAW_SLACK: f32 = 1.0;
379
380impl LayerNode {
381    /// Whether this layer's content, as [`LayerNode::draws_within_bounds`]
382    /// describes it, stays within its bounds: it clips to them, or its draws,
383    /// its texts and its children placed where they are all fit inside.
384    pub fn content_draws_within_bounds(&self) -> bool {
385        if self.clip_rect().is_some() {
386            return true;
387        }
388        let bounds = inflate_rect(self.local_bounds, CONTAINED_DRAW_SLACK);
389        self.children.iter().all(|child| match child {
390            RenderNode::DrawRun(run) => run
391                .recording
392                .bounds()
393                .is_none_or(|drawn| rect_within(drawn, bounds)),
394            RenderNode::Primitive(entry) => match &entry.node {
395                PrimitiveNode::Text(text) => text.draws_within(bounds),
396                PrimitiveNode::Draw(_) => false,
397            },
398            RenderNode::Layer(layer) => layer.draws_within_parent(bounds),
399        })
400    }
401
402    /// Whether this layer, drawn as a child, puts nothing outside `bounds`:
403    /// it draws within its own bounds, casts no shadow, applies no effect,
404    /// and its bounds placed in its parent lie inside.
405    fn draws_within_parent(&self, bounds: Rect) -> bool {
406        self.draws_within_bounds
407            && self.graphics_layer.shadow_elevation <= 0.0
408            && self.effect().is_none()
409            && self.backdrop().is_none()
410            && rect_within(
411                quad_bounds(self.transform_to_parent.map_rect(self.local_bounds)),
412                bounds,
413            )
414    }
415
416    pub fn clip_rect(&self) -> Option<Rect> {
417        (self.clip_to_bounds || self.graphics_layer.clip).then_some(self.local_bounds)
418    }
419
420    pub fn effect(&self) -> Option<&RenderEffect> {
421        self.graphics_layer.render_effect.as_ref()
422    }
423
424    pub fn backdrop(&self) -> Option<&RenderEffect> {
425        self.graphics_layer.backdrop_effect.as_ref()
426    }
427
428    pub fn opacity(&self) -> f32 {
429        self.graphics_layer.alpha
430    }
431
432    pub fn blend_mode(&self) -> BlendMode {
433        self.graphics_layer.blend_mode
434    }
435
436    pub fn color_filter(&self) -> Option<ColorFilter> {
437        self.graphics_layer.color_filter
438    }
439
440    pub fn target_content_hash(&self) -> u64 {
441        if self.cache_hashes_valid {
442            self.cache_hashes.target_content
443        } else {
444            crate::graph_hash::layer_raster_cache_hashes(self).target_content
445        }
446    }
447
448    pub fn motion_source_content_hash(&self) -> u64 {
449        crate::graph_hash::layer_motion_source_content_hash(self)
450    }
451
452    pub fn effect_hash(&self) -> u64 {
453        if self.cache_hashes_valid {
454            self.cache_hashes.effect
455        } else {
456            crate::graph_hash::layer_raster_cache_hashes(self).effect
457        }
458    }
459
460    pub fn recompute_raster_cache_hashes(&mut self) {
461        crate::graph_hash::recompute_layer_raster_cache_hashes(self);
462    }
463}
464
465#[derive(Clone)]
466pub enum RenderNode {
467    Primitive(PrimitiveEntry),
468    /// A whole draw command's primitives as one node. A heavy canvas records
469    /// thousands of primitives per frame; wrapping each in its own
470    /// [`RenderNode`] made the graph rebuild move every one of them twice and
471    /// free seventeen thousand nodes per frame on a stress scene. The run
472    /// keeps the recorded vector intact — semantically it is exactly that
473    /// many consecutive `Primitive` draw entries with no per-primitive clip.
474    DrawRun(DrawRunNode),
475    Layer(Box<LayerNode>),
476}
477
478/// Stable identity of the draw command a run was recorded from: the layout
479/// node owning the command, the command's index in that node's command list,
480/// and which placement pass produced this run (a `WithContent` command emits
481/// one run per placement, so the pair alone is not unique). Rendering does
482/// not read it yet; it is the key under which retained recording state lives
483/// as retention moves up to the draw-command recorder, and it must survive
484/// recording, graph construction, normalized-scene creation, and renderer
485/// cache lookup unchanged.
486#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
487pub struct DrawCommandId {
488    pub node_id: NodeId,
489    pub command_index: u32,
490    pub placement: DrawPlacement,
491}
492
493#[derive(Clone, Debug, PartialEq)]
494pub struct DrawRunNode {
495    pub phase: PrimitivePhase,
496    /// Which draw command recorded these primitives. `None` only for runs
497    /// with no per-command provenance (hand-built tests).
498    pub command: Option<DrawCommandId>,
499    /// Shared, not owned: the recording registry keyed by [`DrawCommandId`]
500    /// keeps a handle to the same recording, so its buffers survive this
501    /// node being dropped on the next rebuild and the command re-records
502    /// into them. Nothing mutates a recording after construction, which is
503    /// what makes sharing sound.
504    pub recording: Rc<CommandRecording>,
505    /// The segments of the recording this run draws: one placement's part
506    /// of a with-content command, or the whole recording.
507    pub segments: Range<u32>,
508    /// Content facts consumers keep asking per frame, answered while
509    /// recording and never by rescanning.
510    pub summary: DrawRunSummary,
511}
512
513/// What a run contains, answered while recording.
514pub type DrawRunSummary = RecordingSummary;
515
516impl DrawRunNode {
517    pub fn new(phase: PrimitivePhase, primitives: Vec<DrawPrimitive>) -> Self {
518        Self::for_command(phase, None, primitives)
519    }
520
521    pub fn for_command(
522        phase: PrimitivePhase,
523        command: Option<DrawCommandId>,
524        primitives: Vec<DrawPrimitive>,
525    ) -> Self {
526        let recording = CommandRecording::from_primitives(primitives);
527        let segments = recording.all_segments();
528        Self::for_command_shared(phase, command, Rc::new(recording), segments)
529    }
530
531    pub fn for_command_shared(
532        phase: PrimitivePhase,
533        command: Option<DrawCommandId>,
534        recording: Rc<CommandRecording>,
535        segments: Range<u32>,
536    ) -> Self {
537        let summary = recording.summary_in(&segments);
538        Self {
539            phase,
540            command,
541            recording,
542            segments,
543            summary,
544        }
545    }
546
547    /// The run's primitives, materialised from the recording in order.
548    pub fn primitives(&self) -> impl Iterator<Item = DrawPrimitive> + '_ {
549        self.recording.primitives(self.segments.clone())
550    }
551
552    /// The rect every entry of the run can reach.
553    pub fn coverage_rects(&self) -> impl Iterator<Item = Rect> + '_ {
554        self.recording.coverage_rects(self.segments.clone())
555    }
556
557    pub fn len(&self) -> usize {
558        self.recording.len_in(&self.segments)
559    }
560
561    pub fn is_empty(&self) -> bool {
562        self.recording.is_empty_in(&self.segments)
563    }
564}
565
566#[derive(Clone)]
567pub struct RenderGraph {
568    pub root: LayerNode,
569}
570
571impl RenderGraph {
572    pub fn new(mut root: LayerNode) -> Self {
573        root.recompute_raster_cache_hashes();
574        Self { root }
575    }
576
577    pub fn node_count(&self) -> usize {
578        fn count_layer(layer: &LayerNode) -> usize {
579            1 + layer
580                .children
581                .iter()
582                .map(|child| match child {
583                    RenderNode::Primitive(_) => 1,
584                    RenderNode::DrawRun(run) => run.len(),
585                    RenderNode::Layer(child_layer) => count_layer(child_layer),
586                })
587                .sum::<usize>()
588        }
589
590        count_layer(&self.root)
591    }
592
593    pub fn heap_bytes(&self) -> usize {
594        layer_heap_bytes(&self.root)
595    }
596
597    /// Replaces the set with the graph's visual observation owners, retaining its capacity.
598    pub fn collect_retained_visual_observation_nodes(&self, nodes: &mut HashSet<NodeId>) {
599        fn collect(layer: &LayerNode, nodes: &mut HashSet<NodeId>) {
600            if let Some(node_id) = layer.node_id {
601                nodes.insert(node_id);
602            }
603            for child in &layer.children {
604                match child {
605                    RenderNode::DrawRun(run) => {
606                        if let Some(command) = run.command {
607                            nodes.insert(command.node_id);
608                        }
609                    }
610                    RenderNode::Layer(child) => collect(child, nodes),
611                    RenderNode::Primitive(_) => {}
612                }
613            }
614        }
615
616        nodes.clear();
617        collect(&self.root, nodes);
618    }
619}
620
621fn layer_heap_bytes(layer: &LayerNode) -> usize {
622    size_of::<RenderNode>() * layer.children.capacity()
623        + layer
624            .children
625            .iter()
626            .map(render_node_heap_bytes)
627            .sum::<usize>()
628}
629
630fn render_node_heap_bytes(node: &RenderNode) -> usize {
631    match node {
632        RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
633        RenderNode::DrawRun(run) => {
634            run.recording.pod_heap_bytes()
635                + std::mem::size_of_val(run.recording.others())
636                + run
637                    .recording
638                    .others()
639                    .iter()
640                    .map(draw_primitive_heap_bytes)
641                    .sum::<usize>()
642        }
643        RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
644    }
645}
646
647fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
648    match &entry.node {
649        PrimitiveNode::Draw(draw) => {
650            size_of::<DrawPrimitiveNode>() + draw_primitive_heap_bytes(&draw.primitive)
651        }
652        PrimitiveNode::Text(text) => {
653            size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
654        }
655    }
656}
657
658fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
659    match primitive {
660        DrawPrimitive::Content
661        | DrawPrimitive::Rect { .. }
662        | DrawPrimitive::RoundRect { .. }
663        | DrawPrimitive::Arc { .. } => 0,
664        DrawPrimitive::Blend { primitive, .. } => {
665            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
666        }
667        DrawPrimitive::Image { .. } => 0,
668        DrawPrimitive::Text(text) => {
669            size_of::<cranpose_ui_graphics::TextPrimitive>()
670                + text.text.len()
671                + text
672                    .style
673                    .font_family
674                    .as_ref()
675                    .map_or(0, std::string::String::capacity)
676        }
677        DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
678    }
679}
680
681fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
682    match shadow {
683        ShadowPrimitive::Drop { shape, .. } => {
684            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
685        }
686        ShadowPrimitive::Inner { fill, cutout, .. } => {
687            size_of::<DrawPrimitive>() * 2
688                + draw_primitive_heap_bytes(fill)
689                + draw_primitive_heap_bytes(cutout)
690        }
691    }
692}
693
694fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
695    text.text.capacity()
696        + text.span_styles.capacity() * size_of::<usize>() * 2
697        + text.paragraph_styles.capacity() * size_of::<usize>() * 2
698        + text.string_annotations.capacity() * size_of::<usize>() * 2
699        + text.link_annotations.capacity() * size_of::<usize>() * 2
700        + text
701            .string_annotations
702            .iter()
703            .map(|annotation| {
704                annotation.item.tag.capacity() + annotation.item.annotation.capacity()
705            })
706            .sum::<usize>()
707        + text
708            .link_annotations
709            .iter()
710            .map(|annotation| match &annotation.item {
711                cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
712                cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
713            })
714            .sum::<usize>()
715}
716
717pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
718    let mut min_x = f32::INFINITY;
719    let mut min_y = f32::INFINITY;
720    let mut max_x = f32::NEG_INFINITY;
721    let mut max_y = f32::NEG_INFINITY;
722
723    for [x, y] in quad {
724        min_x = min_x.min(x);
725        min_y = min_y.min(y);
726        max_x = max_x.max(x);
727        max_y = max_y.max(y);
728    }
729
730    Rect {
731        x: min_x,
732        y: min_y,
733        width: (max_x - min_x).max(0.0),
734        height: (max_y - min_y).max(0.0),
735    }
736}
737
738fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
739    let mut out = [[0.0; 3]; 3];
740    for row in 0..3 {
741        for col in 0..3 {
742            out[row][col] =
743                lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
744        }
745    }
746    out
747}
748
749fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
750    let mut matrix = [[0.0f32; 9]; 8];
751    for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
752        let row = index * 2;
753        let x = src[0];
754        let y = src[1];
755        let u = dst[0];
756        let v = dst[1];
757
758        matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
759        matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
760    }
761
762    for pivot in 0..8 {
763        let mut pivot_row = pivot;
764        let mut pivot_value = matrix[pivot][pivot].abs();
765        let mut candidate = pivot + 1;
766        while candidate < 8 {
767            let candidate_value = matrix[candidate][pivot].abs();
768            if candidate_value > pivot_value {
769                pivot_row = candidate;
770                pivot_value = candidate_value;
771            }
772            candidate += 1;
773        }
774
775        if pivot_value <= f32::EPSILON {
776            return None;
777        }
778
779        if pivot_row != pivot {
780            matrix.swap(pivot, pivot_row);
781        }
782
783        let divisor = matrix[pivot][pivot];
784        let mut col = pivot;
785        while col < 9 {
786            matrix[pivot][col] /= divisor;
787            col += 1;
788        }
789
790        for row in 0..8 {
791            if row == pivot {
792                continue;
793            }
794            let factor = matrix[row][pivot];
795            if factor.abs() <= f32::EPSILON {
796                continue;
797            }
798            let mut col = pivot;
799            while col < 9 {
800                matrix[row][col] -= factor * matrix[pivot][col];
801                col += 1;
802            }
803        }
804    }
805
806    let mut solution = [0.0f32; 8];
807    for index in 0..8 {
808        solution[index] = matrix[index][8];
809    }
810    Some(solution)
811}
812
813fn inflate_rect(rect: Rect, by: f32) -> Rect {
814    Rect {
815        x: rect.x - by,
816        y: rect.y - by,
817        width: rect.width + by * 2.0,
818        height: rect.height + by * 2.0,
819    }
820}
821
822fn rect_within(inner: Rect, outer: Rect) -> bool {
823    inner.x >= outer.x
824        && inner.y >= outer.y
825        && inner.x + inner.width <= outer.x + outer.width
826        && inner.y + inner.height <= outer.y + outer.height
827}
828
829#[cfg(test)]
830#[path = "tests/graph_tests.rs"]
831mod tests;