Skip to main content

cranpose_render_common/
primitive_emit.rs

1use std::sync::Arc;
2
3use cranpose_ui::text::{AnnotatedString, TextStyle, drawn_text_style};
4use cranpose_ui_graphics::{
5    ArcGeometry, BlendMode, Brush, Color, ColorFilter, CornerRadii, DrawPrimitive, GraphicsLayer,
6    ImageBitmap, ImageSampling, LineGeometry, Point, Rect, RoundedCornerShape, ShadowPrimitive,
7    Stroke, TextPrimitive, Trapezoid, arc_band, inflate_rect,
8};
9
10use crate::{
11    graph::quad_bounds,
12    layer_transform::{
13        apply_layer_affine_to_point, apply_layer_affine_to_rect, apply_layer_to_quad,
14        apply_layer_to_rect, layer_uniform_scale,
15    },
16    style_shared::{
17        ResolvedBrush, apply_layer_to_brush, apply_layer_to_color, compose_color_filters,
18        resolve_layer_brush, scale_corner_radii,
19    },
20};
21
22/// The space in which the clip rectangle of a primitive is given.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum PrimitiveClipSpace {
25    /// The clip is in the layer's own space and the layer transform does not apply to it.
26    Local,
27    /// The clip is moved with the layer transform, like the primitive itself.
28    LayerTransformed,
29}
30
31/// A shape ready for a renderer to draw, with the layer transform, paint and clip resolved.
32pub struct ShapeDrawParams {
33    /// Axis-aligned bounds of `quad`.
34    pub rect: Rect,
35    /// The shape's rectangle after the layer's scale and translation, before any rotation.
36    pub local_rect: Rect,
37    /// The shape's rectangle after the full layer transform, as four corners.
38    pub quad: [[f32; 2]; 4],
39    /// Layer-resolved at emit time. Solid — effectively every shape of a
40    /// heavy animated frame — is an inline color; only gradients carry a
41    /// cloned [`Brush`].
42    pub brush: ResolvedBrush,
43    /// Rounded corners of the shape, or `None` for sharp corners.
44    pub shape: Option<RoundedCornerShape>,
45    /// `Some` means "stroke the outline of `local_rect`/`shape`" instead of
46    /// filling it. The width is already in `local_rect` units (the layer scale
47    /// has been applied), and `local_rect`/`quad` have already been inflated by
48    /// half that width so the outer half of the stroke has geometry to land on.
49    pub stroke: Option<Stroke>,
50    /// `Some` replaces the rect geometry entirely with a circular band. The
51    /// center and radii are in `local_rect` units.
52    pub arc: Option<ArcGeometry>,
53    /// `Some` replaces the rect geometry entirely with a stroked segment, its
54    /// ends and width in `local_rect` units.
55    pub line: Option<LineGeometry>,
56    /// `Some` replaces the rect geometry entirely with a slice of a path
57    /// fill, in `local_rect` units; `local_rect` is the rect its brush
58    /// resolves against.
59    pub trapezoid: Option<Trapezoid>,
60    /// Clip rectangle that cuts the shape, or `None` when nothing clips it.
61    pub clip: Option<Rect>,
62    /// How the shape blends onto what lies beneath it.
63    pub blend_mode: BlendMode,
64    /// Whether the shape sits in an animated motion context, where a renderer must not snap it
65    /// to the pixel grid.
66    pub motion_context_animated: bool,
67}
68
69fn stroked_draw_rect(
70    local_rect: Rect,
71    stroke: Option<Stroke>,
72    layer_bounds: Rect,
73    layer: &GraphicsLayer,
74) -> Option<(Rect, Option<Stroke>)> {
75    let draw_rect = local_rect.translate(layer_bounds.x, layer_bounds.y);
76    let Some(stroke) = stroke else {
77        return Some((draw_rect, None));
78    };
79    if !stroke.is_visible() {
80        return None;
81    }
82    let outset = stroke.half_width();
83    Some((
84        inflate_rect(draw_rect, outset),
85        Some(stroke.scaled(layer_uniform_scale(layer))),
86    ))
87}
88
89/// An image ready for a renderer to draw, with the layer transform, opacity and clip resolved.
90pub struct ImageDrawParams {
91    /// Axis-aligned bounds of `quad`.
92    pub rect: Rect,
93    /// The image's rectangle after the layer's scale and translation, before any rotation.
94    pub local_rect: Rect,
95    /// The image's rectangle after the full layer transform, as four corners.
96    pub quad: [[f32; 2]; 4],
97    /// The bitmap to draw.
98    pub image: ImageBitmap,
99    /// Opacity of the image from 0.0 to 1.0.
100    pub alpha: f32,
101    /// Color filter applied to the image, if any.
102    pub color_filter: Option<ColorFilter>,
103    /// How the bitmap is sampled when it is scaled.
104    pub sampling: ImageSampling,
105    /// Clip rectangle that cuts the image, or `None` when nothing clips it.
106    pub clip: Option<Rect>,
107    /// Region of the bitmap to draw, in bitmap pixels, or `None` for the whole bitmap.
108    pub src_rect: Option<Rect>,
109    /// How the image blends onto what lies beneath it.
110    pub blend_mode: BlendMode,
111    /// Whether the image sits in an animated motion context, where a renderer must not snap it
112    /// to the pixel grid.
113    pub motion_context_animated: bool,
114}
115
116/// A `DrawScope` text run, lowered into the vocabulary the text pipeline
117/// already speaks.
118///
119/// The fields line up one-for-one with `CompositorScene::push_text` in both
120/// backends, so a text primitive joins the same glyph atlas, run cache and
121/// shader the `Text` composable uses instead of getting a pipeline of its own.
122pub struct TextDrawParams {
123    /// Layer-transformed block box. Glyphs are laid out from its top-left; the
124    /// draw scope already resolved alignment into it.
125    pub rect: Rect,
126    /// The text to draw.
127    pub text: AnnotatedString,
128    /// The lines and glyphs, from `rect`'s top left corner.
129    pub layout: cranpose_text::TextLayout,
130    /// Color that fills the glyphs.
131    pub color: Color,
132    /// Style the text is drawn with.
133    pub text_style: Arc<TextStyle>,
134    /// `text_style`'s render hash.
135    pub style_hash: u64,
136    /// Font size in logical pixels, before `scale` is applied.
137    pub font_size: f32,
138    /// Uniform layer scale — the factor glyphs are rasterized at.
139    pub scale: f32,
140    /// Clip rectangle that cuts the text, or `None` when nothing clips it.
141    pub clip: Option<Rect>,
142}
143
144/// Receives the draw calls that `emit_draw_primitive` produces from a draw primitive.
145pub trait DrawPrimitiveSink {
146    /// Draws a shape.
147    fn push_shape(&mut self, params: ShapeDrawParams);
148
149    /// Draws an image.
150    fn push_image(&mut self, params: ImageDrawParams);
151
152    /// Emits a shadow without transferring ownership of its caster and cutout.
153    fn push_shadow(
154        &mut self,
155        shadow_primitive: &ShadowPrimitive,
156        layer_bounds: Rect,
157        layer: &GraphicsLayer,
158        clip: Option<Rect>,
159    );
160
161    /// Draws a text run. The default drops it, for sinks that only collect
162    /// geometry (shadow casters, hit testing) and backends with no text
163    /// pipeline.
164    fn push_text(&mut self, params: TextDrawParams) {
165        let _ = params;
166    }
167}
168
169/// Resolves a borrowed shape with the layer transform, paint, and clipping applied.
170pub fn draw_shape_params_for_primitive(
171    primitive: &DrawPrimitive,
172    layer_bounds: Rect,
173    layer: &GraphicsLayer,
174    clip: Option<Rect>,
175    blend_mode: BlendMode,
176) -> Option<ShapeDrawParams> {
177    struct SingleShapeSink {
178        shape: Option<ShapeDrawParams>,
179    }
180
181    impl DrawPrimitiveSink for SingleShapeSink {
182        fn push_shape(&mut self, params: ShapeDrawParams) {
183            if self.shape.is_none() {
184                self.shape = Some(params);
185            }
186        }
187
188        fn push_image(&mut self, _params: ImageDrawParams) {}
189
190        fn push_shadow(
191            &mut self,
192            _shadow_primitive: &ShadowPrimitive,
193            _layer_bounds: Rect,
194            _layer: &GraphicsLayer,
195            _clip: Option<Rect>,
196        ) {
197        }
198    }
199
200    let mut sink = SingleShapeSink { shape: None };
201    emit_draw_primitive(
202        primitive,
203        layer_bounds,
204        layer,
205        clip,
206        &mut sink,
207        Some(blend_mode),
208        false,
209    );
210    sink.shape
211}
212
213/// The clip a node paints within once its own clip meets the clips above
214/// it: `None` only when nothing clips at all. Two clips that do not overlap
215/// resolve to [`Rect::EMPTY`], never to `None` -- a list that has scrolled a
216/// control past its edge has clipped the control away, not set it free.
217pub fn resolve_clip(parent_clip: Option<Rect>, requested_clip: Option<Rect>) -> Option<Rect> {
218    match (parent_clip, requested_clip) {
219        (Some(parent), Some(current)) => Some(parent.intersect(current).unwrap_or(Rect::EMPTY)),
220        (Some(parent), None) => Some(parent),
221        (None, Some(current)) => Some(current),
222        (None, None) => None,
223    }
224}
225
226/// Returns the clip for a primitive: `local_clip` moved to `layer_bounds`, moved with the layer
227/// transform for `PrimitiveClipSpace::LayerTransformed`, and intersected with `parent_clip`.
228/// Returns `parent_clip` when the primitive has no clip of its own.
229pub fn resolve_primitive_clip(
230    local_clip: Option<Rect>,
231    layer_bounds: Rect,
232    layer: &GraphicsLayer,
233    parent_clip: Option<Rect>,
234    clip_space: PrimitiveClipSpace,
235) -> Option<Rect> {
236    let Some(local_clip) = local_clip else {
237        return parent_clip;
238    };
239    let clip_rect = Rect {
240        x: layer_bounds.x + local_clip.x,
241        y: layer_bounds.y + local_clip.y,
242        width: local_clip.width,
243        height: local_clip.height,
244    };
245    let requested_clip = match clip_space {
246        PrimitiveClipSpace::Local => clip_rect,
247        PrimitiveClipSpace::LayerTransformed => apply_layer_to_rect(clip_rect, layer_bounds, layer),
248    };
249    resolve_clip(parent_clip, Some(requested_clip))
250}
251
252// Where a shape lands: the layer that places it, the clip that cuts it and
253// the blend it draws with.
254struct ShapePlacement<'a> {
255    layer_bounds: Rect,
256    layer: &'a GraphicsLayer,
257    clip: Option<Rect>,
258    blend_mode: BlendMode,
259    motion_context_animated: bool,
260}
261
262// What a shape draws over its rect. A shape holds one geometry at a time.
263#[derive(Clone, Copy)]
264enum ShapeGeometry {
265    Rect,
266    Rounded(RoundedCornerShape),
267    Arc(ArcGeometry),
268    Line(LineGeometry),
269    Trapezoid(Trapezoid),
270}
271
272impl ShapePlacement<'_> {
273    // A shape over `draw_rect` with `geometry`, its outline stroked when
274    // `stroke` says so. The builders pass their geometry in, so the shape
275    // is written once in place.
276    fn fill(
277        &self,
278        draw_rect: Rect,
279        brush: &Brush,
280        geometry: ShapeGeometry,
281        stroke: Option<Stroke>,
282    ) -> ShapeDrawParams {
283        let quad = apply_layer_to_quad(draw_rect, self.layer_bounds, self.layer);
284        let mut params = ShapeDrawParams {
285            rect: quad_bounds(quad),
286            local_rect: apply_layer_affine_to_rect(draw_rect, self.layer_bounds, self.layer),
287            quad,
288            brush: resolve_layer_brush(brush, self.layer),
289            shape: None,
290            stroke,
291            arc: None,
292            line: None,
293            trapezoid: None,
294            clip: self.clip,
295            blend_mode: self.blend_mode,
296            motion_context_animated: self.motion_context_animated,
297        };
298        match geometry {
299            ShapeGeometry::Rect => {}
300            ShapeGeometry::Rounded(shape) => params.shape = Some(shape),
301            ShapeGeometry::Arc(arc) => params.arc = Some(arc),
302            ShapeGeometry::Line(line) => params.line = Some(line),
303            ShapeGeometry::Trapezoid(trapezoid) => params.trapezoid = Some(trapezoid),
304        }
305        params
306    }
307
308    fn translate(&self, rect: Rect) -> Rect {
309        rect.translate(self.layer_bounds.x, self.layer_bounds.y)
310    }
311
312    fn place(&self, point: Point) -> Point {
313        apply_layer_affine_to_point(
314            Point::new(point.x + self.layer_bounds.x, point.y + self.layer_bounds.y),
315            self.layer_bounds,
316            self.layer,
317        )
318    }
319}
320
321fn rect_shape_params(
322    local_rect: Rect,
323    brush: &Brush,
324    stroke: Option<Stroke>,
325    placement: &ShapePlacement,
326) -> Option<ShapeDrawParams> {
327    let (draw_rect, stroke) =
328        stroked_draw_rect(local_rect, stroke, placement.layer_bounds, placement.layer)?;
329    Some(placement.fill(draw_rect, brush, ShapeGeometry::Rect, stroke))
330}
331
332fn round_rect_shape_params(
333    local_rect: Rect,
334    brush: &Brush,
335    radii: CornerRadii,
336    stroke: Option<Stroke>,
337    placement: &ShapePlacement,
338) -> Option<ShapeDrawParams> {
339    let (draw_rect, stroke) =
340        stroked_draw_rect(local_rect, stroke, placement.layer_bounds, placement.layer)?;
341    let radii = scale_corner_radii(radii, layer_uniform_scale(placement.layer));
342    let shape = ShapeGeometry::Rounded(RoundedCornerShape::with_radii(radii));
343    Some(placement.fill(draw_rect, brush, shape, stroke))
344}
345
346// `arc` is in scope coordinates and `local_rect` is its tight bounds.
347fn arc_shape_params(
348    local_rect: Rect,
349    brush: &Brush,
350    arc: ArcGeometry,
351    placement: &ShapePlacement,
352) -> Option<ShapeDrawParams> {
353    if arc.is_degenerate() {
354        return None;
355    }
356    let scale = layer_uniform_scale(placement.layer);
357    let arc = ShapeGeometry::Arc(arc.scaled_about(placement.place(arc.center), scale));
358    Some(placement.fill(placement.translate(local_rect), brush, arc, None))
359}
360
361// The segment's ends are placed by the layer's transform and its width is
362// scaled by the layer's uniform scale.
363fn line_shape_params(
364    brush: &Brush,
365    start: Point,
366    end: Point,
367    stroke: Stroke,
368    placement: &ShapePlacement,
369) -> Option<ShapeDrawParams> {
370    let line = LineGeometry::new(start, end, stroke);
371    if line.is_degenerate() {
372        return None;
373    }
374    let scale = layer_uniform_scale(placement.layer);
375    let draw_rect = placement.translate(line.bounds());
376    let line =
377        ShapeGeometry::Line(line.placed(placement.place(start), placement.place(end), scale));
378    Some(placement.fill(draw_rect, brush, line, None))
379}
380
381// The brush rect is placed by the layer's transform as a rect is, and the
382// slice's corners are placed by it as points.
383fn trapezoid_shape_params(
384    brush_rect: Rect,
385    brush: &Brush,
386    trapezoid: Trapezoid,
387    placement: &ShapePlacement,
388) -> Option<ShapeDrawParams> {
389    if trapezoid.right <= trapezoid.left {
390        return None;
391    }
392    let place = |x: f32, y: f32| placement.place(Point::new(x, y));
393    let [top_left, top_right, bottom_left, bottom_right] = [
394        place(trapezoid.left, trapezoid.top[0]),
395        place(trapezoid.right, trapezoid.top[1]),
396        place(trapezoid.left, trapezoid.bottom[0]),
397        place(trapezoid.right, trapezoid.bottom[1]),
398    ];
399    let placed = ShapeGeometry::Trapezoid(Trapezoid {
400        left: top_left.x,
401        right: top_right.x,
402        top: [top_left.y, top_right.y],
403        bottom: [bottom_left.y, bottom_right.y],
404        ..trapezoid
405    });
406    Some(placement.fill(placement.translate(brush_rect), brush, placed, None))
407}
408
409/// Lowers `primitive` to shape, image, shadow and text draw calls on `sink`, with the transform
410/// of `layer` applied at `layer_bounds`. `blend_mode` is the mode inherited from an enclosing
411/// blend primitive, and `motion_context_animated` is passed on to every call. Content and group
412/// markers draw nothing: the scene builder turns groups into layers.
413pub fn emit_draw_primitive<S: DrawPrimitiveSink>(
414    primitive: &DrawPrimitive,
415    layer_bounds: Rect,
416    layer: &GraphicsLayer,
417    clip: Option<Rect>,
418    sink: &mut S,
419    blend_mode: Option<BlendMode>,
420    motion_context_animated: bool,
421) {
422    let placement = ShapePlacement {
423        layer_bounds,
424        layer,
425        clip,
426        blend_mode: blend_mode.unwrap_or(BlendMode::SrcOver),
427        motion_context_animated,
428    };
429    match primitive {
430        DrawPrimitive::Content | DrawPrimitive::Group(_) => {}
431        DrawPrimitive::Blend {
432            primitive,
433            blend_mode: nested,
434        } => emit_draw_primitive(
435            primitive,
436            layer_bounds,
437            layer,
438            clip,
439            sink,
440            blend_mode.or(Some(*nested)),
441            motion_context_animated,
442        ),
443        DrawPrimitive::Rect {
444            rect,
445            brush,
446            stroke,
447        } => {
448            if let Some(params) = rect_shape_params(*rect, brush, *stroke, &placement) {
449                sink.push_shape(params);
450            }
451        }
452        DrawPrimitive::RoundRect {
453            rect,
454            brush,
455            radii,
456            stroke,
457        } => {
458            if let Some(params) = round_rect_shape_params(*rect, brush, *radii, *stroke, &placement)
459            {
460                sink.push_shape(params);
461            }
462        }
463        DrawPrimitive::Arc {
464            rect,
465            brush,
466            center,
467            radius,
468            start_angle,
469            sweep_angle,
470            stroke,
471            inner_radius,
472        } => {
473            let (band_inner, band_outer, cap) = arc_band(*radius, *inner_radius, *stroke);
474            let arc = ArcGeometry::new(
475                *center,
476                band_inner,
477                band_outer,
478                *start_angle,
479                *sweep_angle,
480                cap,
481            );
482            if let Some(params) = arc_shape_params(*rect, brush, arc, &placement) {
483                sink.push_shape(params);
484            }
485        }
486        DrawPrimitive::Line {
487            brush,
488            start,
489            end,
490            stroke,
491            ..
492        } => {
493            if let Some(params) = line_shape_params(brush, *start, *end, *stroke, &placement) {
494                sink.push_shape(params);
495            }
496        }
497        DrawPrimitive::Trapezoid {
498            rect,
499            brush,
500            trapezoid,
501        } => {
502            if let Some(params) = trapezoid_shape_params(*rect, brush, *trapezoid, &placement) {
503                sink.push_shape(params);
504            }
505        }
506        DrawPrimitive::Image {
507            rect: local_rect,
508            image,
509            alpha,
510            color_filter,
511            sampling,
512            src_rect,
513        } => {
514            let draw_rect = local_rect.translate(layer_bounds.x, layer_bounds.y);
515            let local_rect = apply_layer_affine_to_rect(draw_rect, layer_bounds, layer);
516            let quad = apply_layer_to_quad(draw_rect, layer_bounds, layer);
517            sink.push_image(ImageDrawParams {
518                rect: quad_bounds(quad),
519                local_rect,
520                quad,
521                image: image.clone(),
522                alpha: (alpha * layer.alpha).clamp(0.0, 1.0),
523                color_filter: compose_color_filters(
524                    color_filter.as_ref(),
525                    layer.color_filter.as_ref(),
526                ),
527                sampling: *sampling,
528                clip,
529                src_rect: *src_rect,
530                blend_mode: blend_mode.unwrap_or(BlendMode::SrcOver),
531                motion_context_animated,
532            });
533        }
534        DrawPrimitive::Text(text) => {
535            if let Some(params) = text_draw_params((**text).clone(), layer_bounds, layer, clip) {
536                sink.push_text(params);
537            }
538        }
539        DrawPrimitive::Shadow(shadow_primitive) => {
540            sink.push_shadow(shadow_primitive, layer_bounds, layer, clip);
541        }
542    }
543}
544
545fn text_draw_params(
546    text: TextPrimitive,
547    layer_bounds: Rect,
548    layer: &GraphicsLayer,
549    clip: Option<Rect>,
550) -> Option<TextDrawParams> {
551    if text.text.is_empty() {
552        return None;
553    }
554    // A text no text system laid out draws nothing.
555    let layout = cranpose_text::TextLayout::clone(
556        &*text
557            .layout
558            .as_ref()?
559            .downcast::<cranpose_text::TextLayout>()?,
560    );
561    let draw_rect = text.rect.translate(layer_bounds.x, layer_bounds.y);
562    let rect = apply_layer_to_rect(draw_rect, layer_bounds, layer);
563    if !(rect.width > 0.0 && rect.height > 0.0) {
564        return None;
565    }
566    let scale = layer_uniform_scale(layer);
567    if !scale.is_finite() || scale <= 0.0 {
568        return None;
569    }
570    let (mut text_style, mut style_hash) = drawn_text_style(&text.style);
571    // A gradient fills the glyphs through the style's brush, as a `Text`
572    // composable's does, laid over the text's extent.
573    let color = match text.brush {
574        Brush::Solid(color) => apply_layer_to_color(color, layer),
575        gradient => {
576            let gradient = apply_layer_to_brush(gradient, layer);
577            let first = gradient
578                .colors()
579                .first()
580                .copied()
581                .unwrap_or(Color::TRANSPARENT);
582            let style = Arc::make_mut(&mut text_style);
583            style.span_style.brush = Some(gradient);
584            style_hash = style.render_hash();
585            first
586        }
587    };
588    if !text_style
589        .span_style
590        .brush
591        .as_ref()
592        .map_or(color.3 > 0.0, Brush::paints)
593    {
594        return None;
595    }
596
597    Some(TextDrawParams {
598        rect,
599        text: cranpose_ui::text::shared_plain_annotated_string(text.text.as_ref()),
600        layout,
601        color,
602        text_style,
603        style_hash,
604        font_size: text.style.resolved_font_size(),
605        scale,
606        clip,
607    })
608}
609
610#[cfg(test)]
611#[path = "tests/primitive_emit_tests.rs"]
612mod tests;