1use 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 text_canvas::{CanvasPaint, PlacedMask, SolidInk, TextCanvas, TextPixelWindow, TextPixels},
14 text_glyphs::{SpanPaint, SpanPaints, StyledTextRef, visit_placed_glyphs},
15 text_shadow::shadow_blur_sigma,
16};
17
18const SCRATCH_MASKS: usize = 64;
20
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum GlyphInk {
24 #[default]
26 Painted,
27 Hidden,
29}
30
31#[derive(Clone, Copy)]
36pub struct TextRasterRequest<'a> {
37 pub layout: &'a TextLayout,
39 pub text: StyledTextRef<'a>,
41 pub rect: Rect,
43 pub origin: Point,
45 pub style: &'a TextStyle,
47 pub fallback_color: Color,
49 pub scale: f32,
51 pub ink: GlyphInk,
53}
54
55impl<'a> TextRasterRequest<'a> {
56 pub fn new(
59 layout: &'a TextLayout,
60 text: impl Into<StyledTextRef<'a>>,
61 rect: Rect,
62 style: &'a TextStyle,
63 fallback_color: Color,
64 scale: f32,
65 ) -> Self {
66 Self {
67 layout,
68 text: text.into(),
69 rect,
70 origin: Point::new(rect.x, rect.y),
71 style,
72 fallback_color,
73 scale,
74 ink: GlyphInk::Painted,
75 }
76 }
77
78 pub fn with_origin(self, origin: Point) -> Self {
80 Self { origin, ..self }
81 }
82
83 pub fn with_ink(self, ink: GlyphInk) -> Self {
85 Self { ink, ..self }
86 }
87
88 pub(crate) fn is_degenerate(&self) -> bool {
89 self.text.is_empty()
90 || self.rect.width <= 0.0
91 || self.rect.height <= 0.0
92 || self.scale <= 0.0
93 || !self.scale.is_finite()
94 }
95
96 pub(crate) fn motion(&self) -> TextMotion {
98 self.style
99 .paragraph_style
100 .text_motion
101 .unwrap_or(TextMotion::Static)
102 }
103
104 fn brush_rect(&self) -> Rect {
106 Rect {
107 x: self.origin.x,
108 y: self.origin.y,
109 width: self.layout.width() * self.scale,
110 height: self.layout.height() * self.scale,
111 }
112 }
113}
114
115pub fn rasterize_text(
118 request: TextRasterRequest<'_>,
119 glyph_cache: Option<&mut GlyphMaskCache>,
120) -> Option<TextPixels> {
121 if request.is_degenerate() {
122 return None;
123 }
124 let mut paints = SpanPaints::default();
125 paints.fill(request.text, request.style, request.fallback_color);
126 let solid = request.ink == GlyphInk::Painted
127 && paints.all(|paint| paint.solid_color().is_some() && paint.shadow.is_none());
128 let width = whole::to_i32(whole::ceil(request.rect.width)).max(1);
129 let height = whole::to_i32(whole::ceil(request.rect.height)).max(1);
130 let (width, height) = (u32::try_from(width).ok()?, u32::try_from(height).ok()?);
131 let mut canvas = if solid {
132 TextCanvas::solid(width, height)
133 } else {
134 TextCanvas::blended(width, height)
135 };
136 paint_glyphs(request, &paints, glyph_cache, &mut canvas);
137 canvas.into_pixels()
138}
139
140pub fn paint_text(
145 request: TextRasterRequest<'_>,
146 glyph_cache: Option<&mut GlyphMaskCache>,
147 window: TextPixelWindow<'_>,
148) -> bool {
149 if request.is_degenerate() {
150 return true;
151 }
152 let mut paints = SpanPaints::default();
153 paints.fill(request.text, request.style, request.fallback_color);
154 if request.motion() != TextMotion::Static
155 || request.ink == GlyphInk::Hidden
156 || !paints.all(|paint| paint.solid_color().is_some() && paint.shadow.is_none())
157 {
158 return false;
159 }
160 paint_glyphs(request, &paints, glyph_cache, &mut TextCanvas::over(window));
161 true
162}
163
164fn paint_glyphs<'a>(
168 request: TextRasterRequest<'a>,
169 paints: &'a SpanPaints,
170 glyph_cache: Option<&mut GlyphMaskCache>,
171 canvas: &mut TextCanvas<'_>,
172) {
173 let mut scratch = None;
174 let cache = match glyph_cache {
175 Some(cache) => cache,
176 None => scratch.insert(scratch_masks()),
177 };
178 let motion = request.motion();
179 let (rect, scale) = (request.rect, request.scale);
180 let ink = match request.ink {
181 GlyphInk::Painted => 1.0,
182 GlyphInk::Hidden => 0.0,
183 };
184 let brush_rect = request.brush_rect();
185 let area = (canvas.width, canvas.height);
186 let canvas_paint = |span: &'a SpanPaint| {
187 let alpha = span.alpha * ink;
188 CanvasPaint {
189 brush: &span.brush,
190 alpha,
191 solid: SolidInk::of(&span.brush, alpha),
192 shadow: span.shadow,
193 brush_rect,
194 canvas_origin: Point::new(rect.x, rect.y),
195 scale,
196 static_motion: motion == TextMotion::Static,
197 }
198 };
199 let margin = |span: &SpanPaint| {
201 span.shadow.map_or(0, |shadow| {
202 let reach = shadow.offset.x.abs().max(shadow.offset.y.abs()) * scale;
203 let blur = shadow_blur_sigma((shadow.blur_radius * scale).max(0.0)) * 3.0;
204 whole::to_i32(whole::ceil(reach + blur)) + 1
205 })
206 };
207 let mut last: Option<(&'a SpanPaint, CanvasPaint<'a>, i32)> = None;
210 visit_placed_glyphs(
211 request.layout,
212 paints,
213 (request.origin, scale),
214 motion,
215 |glyph| {
216 let Some(mask) = cache.mask(glyph.typeface, glyph.glyph, glyph.size, glyph.raster)
217 else {
218 return;
219 };
220 let placed = PlacedMask {
221 mask,
222 x: whole::to_i32(whole::round(glyph.x - rect.x)) + mask.left,
223 y: whole::to_i32(whole::round(glyph.y - rect.y)) + mask.top,
224 };
225 let (_, paint, margin) = match &last {
226 Some(found) if std::ptr::eq(found.0, glyph.paint) => found,
227 _ => &*last.insert((glyph.paint, canvas_paint(glyph.paint), margin(glyph.paint))),
228 };
229 if overlaps(placed, area, *margin) {
230 canvas.paint(placed, paint);
231 }
232 },
233 );
234}
235
236#[inline(never)]
239fn scratch_masks() -> GlyphMaskCache {
240 GlyphMaskCache::with_capacity_at_least_one(SCRATCH_MASKS)
241}
242
243fn overlaps(placed: PlacedMask<'_>, (width, height): (u32, u32), margin: i32) -> bool {
245 let size = |value: usize| i32::try_from(value).unwrap_or(i32::MAX);
246 let extent = |value: u32| i32::try_from(value).unwrap_or(i32::MAX);
247 placed.x - margin < extent(width)
248 && placed.y - margin < extent(height)
249 && placed.x + size(placed.mask.width) + margin > 0
250 && placed.y + size(placed.mask.height) + margin > 0
251}