Skip to main content

cranpose_render_common/
text_paint.rs

1//! What a renderer reads of a text's style and string to draw its glyphs,
2//! worked out once per text node so that drawing a plain text never loads
3//! its style, and drawing a cached run never loads its string.
4
5use std::{cell::OnceCell, hash::Hasher, sync::Arc};
6
7use cranpose_text::SynthesizedStyle;
8use cranpose_ui::{
9    Brush, Color, TextStyle,
10    text::{RangeStyle, SpanStyle, TextDecoration, TextDrawStyle, TextMotion},
11};
12use cranpose_ui_graphics::FxHasher;
13
14use crate::glyph_reach::InkSpread;
15
16/// The paint of a text node's glyphs.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct TextPaint {
19    /// Whether the glyphs in `color` are all the text draws: no background,
20    /// shadow, brush, stroke or decoration, and no span that paints its own
21    /// range.
22    pub plain: bool,
23    /// The style's colour, or its solid brush, times its alpha; white when
24    /// it names neither.
25    pub color: Color,
26    /// How far the style's baseline shift moves the glyphs down.
27    pub baseline_shift: f32,
28    /// The style's [`TextStyle::render_hash`], which keys the glyph caches
29    /// a renderer draws the text from, so no frame hashes the style again.
30    pub style_hash: u64,
31    /// Whether the style's motion is static, so its glyphs stay on whole
32    /// pixels.
33    pub static_motion: bool,
34    /// Whether the style or a span casts a shadow, which spreads past the
35    /// glyphs.
36    pub casts_shadow: bool,
37    /// How far past their outlines the glyphs put ink: a stroke's outer
38    /// half, and the bold or italic a face of the layout synthesizes.
39    pub spread: InkSpread,
40    // The font size and the bold and italic the layout synthesizes, which
41    // a paint shared among texts of one style was worked out at.
42    font_size: f32,
43    synthesized: SynthesizedStyle,
44}
45
46impl TextPaint {
47    /// The paint of a text in `style`, whose [`TextStyle::render_hash`] is
48    /// `style_hash`, with `spans`, at `font_size`, laid out as `layout`.
49    pub fn of(
50        style: &TextStyle,
51        style_hash: u64,
52        spans: &[RangeStyle<SpanStyle>],
53        (font_size, layout): (f32, &cranpose_text::TextLayout),
54    ) -> Self {
55        let span_style = &style.span_style;
56        let span_paint = SpanPaint::of(spans);
57        let plain = span_style.background.is_none()
58            && span_style.shadow.is_none()
59            && span_style.brush.is_none()
60            && !matches!(
61                span_style.draw_style,
62                Some(TextDrawStyle::Stroke { width }) if width.is_finite() && width > 0.0
63            )
64            && !span_paint.foreground
65            && !decorates(span_style.text_decoration)
66            && !span_paint.decoration;
67        Self {
68            plain,
69            color: resolve_text_color_without_gradient_fallback(style, Color::WHITE),
70            baseline_shift: span_style
71                .baseline_shift
72                .filter(|shift| shift.is_specified())
73                .map_or(0.0, |shift| -(shift.0 * font_size)),
74            style_hash,
75            static_motion: style
76                .paragraph_style
77                .text_motion
78                .unwrap_or(TextMotion::Static)
79                == TextMotion::Static,
80            casts_shadow: span_style.shadow.is_some() || span_paint.shadow,
81            // A plain text and its spans draw no stroke, and most cast no
82            // shadow.
83            spread: if plain && !span_paint.shadow {
84                InkSpread::of(0.0, layout.synthesized_style())
85            } else {
86                InkSpread::of_text(style, spans, layout)
87            },
88            font_size,
89            synthesized: layout.synthesized_style(),
90        }
91    }
92
93    // Whether the paint is that of a text without spans in the style whose
94    // render hash is `style_hash`, at `font_size`, with `synthesized`.
95    fn made_at(&self, style_hash: u64, font_size: f32, synthesized: SynthesizedStyle) -> bool {
96        self.style_hash == style_hash
97            && self.font_size.to_bits() == font_size.to_bits()
98            && self.synthesized == synthesized
99    }
100}
101
102// The paint of a text without spans in `style`, whose render hash is
103// `style_hash`, at `font_size`, laid out as `layout`: the one the thread
104// worked out for another text of that style, at that size and with the
105// same bold and italic synthesized, which most labels of a screen share.
106fn shared_paint(
107    style: &TextStyle,
108    style_hash: u64,
109    (font_size, layout): (f32, &cranpose_text::TextLayout),
110) -> Arc<TextPaint> {
111    let synthesized = layout.synthesized_style();
112    let bold = synthesized.bold_size.map_or(0, f32::to_bits);
113    let mut key = FxHasher::default();
114    key.write_u64(style_hash);
115    key.write_u64(u64::from(font_size.to_bits()) << 32 | u64::from(bold));
116    key.write_u8(u8::from(synthesized.italic) | u8::from(synthesized.bold_size.is_some()) << 1);
117    crate::thread_state::with(|state| {
118        state.text_paints.borrow_mut().with(
119            key.finish(),
120            |kept| kept.made_at(style_hash, font_size, synthesized),
121            || Arc::new(TextPaint::of(style, style_hash, &[], (font_size, layout))),
122            Arc::clone,
123        )
124    })
125}
126
127// What the spans of a text paint of their own.
128struct SpanPaint {
129    // A span paints its range with a gradient, an alpha or a draw style.
130    foreground: bool,
131    // A span draws a visible decoration.
132    decoration: bool,
133    // A span casts a shadow.
134    shadow: bool,
135}
136
137impl SpanPaint {
138    // What `spans` paint, found in one pass.
139    fn of(spans: &[RangeStyle<SpanStyle>]) -> Self {
140        let none = Self {
141            foreground: false,
142            decoration: false,
143            shadow: false,
144        };
145        spans.iter().fold(none, |paint, span| Self {
146            foreground: paint.foreground | span_has_foreground_override(&span.item),
147            decoration: paint.decoration | decorates(span.item.text_decoration),
148            shadow: paint.shadow | span.item.shadow.is_some(),
149        })
150    }
151}
152
153// Whether `decoration` draws a line.
154fn decorates(decoration: Option<TextDecoration>) -> bool {
155    decoration.is_some_and(|decoration| decoration != TextDecoration::NONE)
156}
157
158/// A text node's [`TextPaint`], set when the scene builds the node or when a
159/// renderer first asks for it. It is derived data, so two caches always
160/// compare equal.
161#[derive(Clone, Debug, Default)]
162pub struct TextPaintCache(OnceCell<Arc<TextPaint>>);
163
164impl TextPaintCache {
165    /// A cache holding the paint of a text in `style`, whose
166    /// [`TextStyle::render_hash`] is `style_hash`, with `spans`, at
167    /// `font_size`, laid out as `layout`: shared with the other texts the
168    /// thread made in that style when the text has no spans.
169    pub fn of_text(
170        style: &TextStyle,
171        style_hash: u64,
172        spans: &[RangeStyle<SpanStyle>],
173        text: (f32, &cranpose_text::TextLayout),
174    ) -> Self {
175        let paint = if spans.is_empty() {
176            shared_paint(style, style_hash, text)
177        } else {
178            Arc::new(TextPaint::of(style, style_hash, spans, text))
179        };
180        Self(OnceCell::from(paint))
181    }
182
183    /// The cached paint, or the one `compute` returns, which the cache then
184    /// keeps.
185    pub fn get_or(&self, compute: impl FnOnce() -> TextPaint) -> &TextPaint {
186        self.0.get_or_init(|| Arc::new(compute()))
187    }
188}
189
190impl PartialEq for TextPaintCache {
191    fn eq(&self, _other: &Self) -> bool {
192        true
193    }
194}
195
196/// The text colour a style names, its solid brush's colour, or `default`,
197/// times the style's alpha.
198pub fn resolve_text_color_without_gradient_fallback(
199    text_style: &TextStyle,
200    default: Color,
201) -> Color {
202    let mut color = text_style
203        .span_style
204        .color
205        .or(match text_style.span_style.brush.as_ref() {
206            Some(Brush::Solid(color)) => Some(*color),
207            _ => None,
208        })
209        .unwrap_or(default);
210    if let Some(alpha) = text_style.span_style.alpha {
211        color.3 *= alpha.clamp(0.0, 1.0);
212    }
213    color
214}
215
216fn span_has_foreground_override(span_style: &SpanStyle) -> bool {
217    matches!(
218        span_style.brush.as_ref(),
219        Some(
220            Brush::LinearGradient { .. }
221                | Brush::RadialGradient { .. }
222                | Brush::SweepGradient { .. }
223        )
224    ) || span_style.alpha.is_some()
225        || span_style.draw_style.is_some()
226}
227
228/// Whether a span paints its range with a gradient, an alpha or a draw
229/// style of its own.
230pub fn spans_override_foreground(spans: &[RangeStyle<SpanStyle>]) -> bool {
231    spans
232        .iter()
233        .any(|span| span_has_foreground_override(&span.item))
234}
235
236/// Whether a span casts a shadow of its own.
237pub fn spans_cast_shadow(spans: &[RangeStyle<SpanStyle>]) -> bool {
238    spans.iter().any(|span| span.item.shadow.is_some())
239}
240
241/// Whether a span gives its range a colour or a solid brush of its own.
242pub fn spans_override_foreground_color(spans: &[RangeStyle<SpanStyle>]) -> bool {
243    spans
244        .iter()
245        .any(|span| span.item.color.is_some() || matches!(span.item.brush, Some(Brush::Solid(_))))
246}