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 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
19const SCRATCH_MASKS: usize = 64;
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub enum GlyphInk {
25 #[default]
27 Painted,
28 Hidden,
30}
31
32#[derive(Clone, Copy)]
38pub struct TextRasterRequest<'a> {
39 pub layout: &'a TextLayout,
41 pub text: StyledTextRef<'a>,
43 pub rect: Rect,
45 pub origin: Point,
47 pub style: &'a TextStyle,
49 pub fallback_color: Color,
51 pub layer_paint: &'a LayerPaint,
53 pub scale: f32,
55 pub ink: GlyphInk,
57}
58
59impl<'a> TextRasterRequest<'a> {
60 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 pub fn with_origin(self, origin: Point) -> Self {
85 Self { origin, ..self }
86 }
87
88 pub fn with_layer_paint(self, layer_paint: &'a LayerPaint) -> Self {
90 Self {
91 layer_paint,
92 ..self
93 }
94 }
95
96 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 pub(crate) fn motion(&self) -> TextMotion {
111 self.style
112 .paragraph_style
113 .text_motion
114 .unwrap_or(TextMotion::Static)
115 }
116
117 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
128pub 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
153pub 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
177fn 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 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 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#[inline(never)]
252fn scratch_masks() -> GlyphMaskCache {
253 GlyphMaskCache::with_capacity_at_least_one(SCRATCH_MASKS)
254}
255
256fn 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}