Skip to main content

cranpose_render_common/
text_raster.rs

1//! A laid-out text's glyphs rasterized into pixels: an image of the text's
2//! own, or a renderer's pixels painted over directly.
3
4use cranpose_text::TextLayout;
5use cranpose_ui::{
6    Color,
7    text::{TextMotion, TextStyle},
8};
9use cranpose_ui_graphics::{Point, Rect, whole};
10
11use crate::{
12    glyph_mask::GlyphMaskCache,
13    layer_paint::LayerPaint,
14    text_canvas::{CanvasPaint, PlacedMask, SolidInk, TextCanvas, TextPixelWindow, TextPixels},
15    text_glyphs::{SpanPaint, SpanPaints, StyledTextRef, visit_placed_glyphs},
16    text_shadow::shadow_blur_sigma,
17};
18
19// Masks a raster keeps when the renderer's cache is in use elsewhere.
20const SCRATCH_MASKS: usize = 64;
21
22/// Whether a raster paints a text's glyphs, or only the shadows under them.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub enum GlyphInk {
25    /// The glyphs, and the shadows of spans that cast one.
26    #[default]
27    Painted,
28    /// Only the shadows, as the shadow a style casts under its text draws.
29    Hidden,
30}
31
32/// What to rasterize: `layout`, the lines of `text`, its top left corner at
33/// `origin` and its pixels cut to `rect`, both in device pixels, `scale` of
34/// them a layout pixel. Glyphs whose style names no color paint in
35/// `fallback_color`. Every resolved color of the glyphs and their shadows
36/// then takes `layer_paint`.
37#[derive(Clone, Copy)]
38pub struct TextRasterRequest<'a> {
39    /// The lines and glyphs.
40    pub layout: &'a TextLayout,
41    /// The text and its span styles.
42    pub text: StyledTextRef<'a>,
43    /// The part of the text the pixels cover.
44    pub rect: Rect,
45    /// Where the text's top left corner sits.
46    pub origin: Point,
47    /// The style of the whole text, under its span styles.
48    pub style: &'a TextStyle,
49    /// The color of text whose style names none.
50    pub fallback_color: Color,
51    /// The paint of the text's layer, over every resolved color.
52    pub layer_paint: &'a LayerPaint,
53    /// Device pixels per layout pixel.
54    pub scale: f32,
55    /// Whether the glyphs paint or only their shadows.
56    pub ink: GlyphInk,
57}
58
59impl<'a> TextRasterRequest<'a> {
60    /// `layout` of `text` with its top left corner at the corner of `rect`,
61    /// which it covers whole.
62    pub fn new(
63        layout: &'a TextLayout,
64        text: impl Into<StyledTextRef<'a>>,
65        rect: Rect,
66        style: &'a TextStyle,
67        fallback_color: Color,
68        scale: f32,
69    ) -> Self {
70        Self {
71            layout,
72            text: text.into(),
73            rect,
74            origin: Point::new(rect.x, rect.y),
75            style,
76            fallback_color,
77            layer_paint: &LayerPaint::NONE,
78            scale,
79            ink: GlyphInk::Painted,
80        }
81    }
82
83    /// The request with the text's top left corner at `origin`.
84    pub fn with_origin(self, origin: Point) -> Self {
85        Self { origin, ..self }
86    }
87
88    /// The request with its colors under `layer_paint`.
89    pub fn with_layer_paint(self, layer_paint: &'a LayerPaint) -> Self {
90        Self {
91            layer_paint,
92            ..self
93        }
94    }
95
96    /// The request painting with `ink`.
97    pub fn with_ink(self, ink: GlyphInk) -> Self {
98        Self { ink, ..self }
99    }
100
101    pub(crate) fn is_degenerate(&self) -> bool {
102        self.text.is_empty()
103            || self.rect.width <= 0.0
104            || self.rect.height <= 0.0
105            || self.scale <= 0.0
106            || !self.scale.is_finite()
107    }
108
109    // How the glyphs move: kept to whole device pixels when static.
110    pub(crate) fn motion(&self) -> TextMotion {
111        self.style
112            .paragraph_style
113            .text_motion
114            .unwrap_or(TextMotion::Static)
115    }
116
117    // The box a brush is sampled across: the whole layout.
118    fn brush_rect(&self) -> Rect {
119        Rect {
120            x: self.origin.x,
121            y: self.origin.y,
122            width: self.layout.width() * self.scale,
123            height: self.layout.height() * self.scale,
124        }
125    }
126}
127
128/// `request`'s text rasterized into an image of its own covering
129/// `request.rect`, straight alpha. `None` for an empty text or rect.
130pub fn rasterize_text(
131    request: TextRasterRequest<'_>,
132    glyph_cache: Option<&mut GlyphMaskCache>,
133) -> Option<TextPixels> {
134    if request.is_degenerate() {
135        return None;
136    }
137    let mut paints = SpanPaints::default();
138    paints.fill(request);
139    let solid = request.ink == GlyphInk::Painted
140        && paints.all(|paint| paint.solid_color().is_some() && paint.shadow.is_none());
141    let width = whole::to_i32(whole::ceil(request.rect.width)).max(1);
142    let height = whole::to_i32(whole::ceil(request.rect.height)).max(1);
143    let (width, height) = (u32::try_from(width).ok()?, u32::try_from(height).ok()?);
144    let mut canvas = if solid {
145        TextCanvas::solid(width, height)
146    } else {
147        TextCanvas::blended(width, height)
148    };
149    paint_glyphs(request, &paints, glyph_cache, &mut canvas);
150    canvas.into_pixels()
151}
152
153/// Paints `request`'s glyphs straight over `window`, which covers
154/// `request.rect`, as the text's own image would draw there. Returns false,
155/// painting nothing, for a text that needs an image of its own: one in
156/// motion, or one with a gradient or a shadow.
157pub fn paint_text(
158    request: TextRasterRequest<'_>,
159    glyph_cache: Option<&mut GlyphMaskCache>,
160    window: TextPixelWindow<'_>,
161) -> bool {
162    if request.is_degenerate() {
163        return true;
164    }
165    let mut paints = SpanPaints::default();
166    paints.fill(request);
167    if request.motion() != TextMotion::Static
168        || request.ink == GlyphInk::Hidden
169        || !paints.all(|paint| paint.solid_color().is_some() && paint.shadow.is_none())
170    {
171        return false;
172    }
173    paint_glyphs(request, &paints, glyph_cache, &mut TextCanvas::over(window));
174    true
175}
176
177// Paints each glyph of `request` over `canvas`, which covers
178// `request.rect`, its mask from `glyph_cache` or from a cache of the call's
179// own when that is in use.
180fn paint_glyphs<'a>(
181    request: TextRasterRequest<'a>,
182    paints: &'a SpanPaints,
183    glyph_cache: Option<&mut GlyphMaskCache>,
184    canvas: &mut TextCanvas<'_>,
185) {
186    let mut scratch = None;
187    let cache = match glyph_cache {
188        Some(cache) => cache,
189        None => scratch.insert(scratch_masks()),
190    };
191    let motion = request.motion();
192    let (rect, scale) = (request.rect, request.scale);
193    let ink = match request.ink {
194        GlyphInk::Painted => 1.0,
195        GlyphInk::Hidden => 0.0,
196    };
197    let brush_rect = request.brush_rect();
198    let area = (canvas.width, canvas.height);
199    let canvas_paint = |span: &'a SpanPaint| {
200        let alpha = span.alpha * ink;
201        CanvasPaint {
202            brush: &span.brush,
203            alpha,
204            solid: SolidInk::of(&span.brush, alpha),
205            shadow: span.shadow,
206            brush_rect,
207            canvas_origin: Point::new(rect.x, rect.y),
208            scale,
209            static_motion: motion == TextMotion::Static,
210        }
211    };
212    // How far past a glyph's mask its shadow reaches, in pixels.
213    let margin = |span: &SpanPaint| {
214        span.shadow.map_or(0, |shadow| {
215            let reach = shadow.offset.x.abs().max(shadow.offset.y.abs()) * scale;
216            let blur = shadow_blur_sigma((shadow.blur_radius * scale).max(0.0)) * 3.0;
217            whole::to_i32(whole::ceil(reach + blur)) + 1
218        })
219    };
220    // The span paint of the glyph before as the canvas paints it, and its
221    // margin: a text's glyphs mostly share one.
222    let mut last: Option<(&'a SpanPaint, CanvasPaint<'a>, i32)> = None;
223    visit_placed_glyphs(
224        request.layout,
225        paints,
226        (request.origin, scale),
227        motion,
228        |glyph| {
229            let Some(mask) = cache.mask(glyph.typeface, glyph.glyph, glyph.size, glyph.raster)
230            else {
231                return;
232            };
233            let placed = PlacedMask {
234                mask,
235                x: whole::to_i32(whole::round(glyph.x - rect.x)) + mask.left,
236                y: whole::to_i32(whole::round(glyph.y - rect.y)) + mask.top,
237            };
238            let (_, paint, margin) = match &last {
239                Some(found) if std::ptr::eq(found.0, glyph.paint) => found,
240                _ => &*last.insert((glyph.paint, canvas_paint(glyph.paint), margin(glyph.paint))),
241            };
242            if overlaps(placed, area, *margin) {
243                canvas.paint(placed, paint);
244            }
245        },
246    );
247}
248
249// The cache of a raster made while the renderer's is in use elsewhere. Out
250// of line, as a raster mostly has the renderer's.
251#[inline(never)]
252fn scratch_masks() -> GlyphMaskCache {
253    GlyphMaskCache::with_capacity_at_least_one(SCRATCH_MASKS)
254}
255
256// Whether `placed`, grown by `margin` pixels, overlaps a canvas `area`.
257fn overlaps(placed: PlacedMask<'_>, (width, height): (u32, u32), margin: i32) -> bool {
258    let size = |value: usize| i32::try_from(value).unwrap_or(i32::MAX);
259    let extent = |value: u32| i32::try_from(value).unwrap_or(i32::MAX);
260    placed.x - margin < extent(width)
261        && placed.y - margin < extent(height)
262        && placed.x + size(placed.mask.width) + margin > 0
263        && placed.y + size(placed.mask.height) + margin > 0
264}