Skip to main content

sim_logic/text/
visual.rs

1use std::{fmt, sync::Arc};
2
3use super::TextRunLimits;
4use bevy_ecs::prelude::Component;
5use sim_engine::{Color, Layer, LogicalScreenPosition, ShapedLine};
6
7use crate::screen::ScreenVisualError;
8
9use super::{TextError, TextFont, TextPreparationSession};
10
11/// Horizontal alignment of a line's typographic advance around its baseline anchor.
12///
13/// This aligns the entire line, not each glyph or its ink bounds. Trailing
14/// whitespace contributes to advance. Alignment never changes shaping direction.
15#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
16pub enum TextAlignment {
17    /// The baseline origin starts at the anchor's x coordinate.
18    #[default]
19    Left,
20    /// Half the line's advance lies on each side of the anchor.
21    Center,
22    /// The line's advance ends at the anchor's x coordinate.
23    Right,
24}
25
26/// Headless single-line metrics returned by Sim;Engine's font shaper.
27///
28/// Every distance is in logical pixels and remains independent of display DPI.
29/// These are typographic metrics, not exact rasterized ink or clipping bounds.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct TextMetrics {
32    advance: f32,
33    ascent: f32,
34    descent: f32,
35    line_height: f32,
36    glyph_count: usize,
37}
38
39impl TextMetrics {
40    /// Returns the horizontal pen advance, including whitespace.
41    pub const fn advance(self) -> f32 {
42        self.advance
43    }
44
45    /// Returns the font ascender above the baseline in logical pixels.
46    pub const fn ascent(self) -> f32 {
47        self.ascent
48    }
49
50    /// Returns the signed font descender, normally negative below the baseline.
51    pub const fn descent(self) -> f32 {
52        self.descent
53    }
54
55    /// Returns the font-recommended baseline spacing, not automatic wrapping.
56    pub const fn line_height(self) -> f32 {
57        self.line_height
58    }
59
60    /// Returns shaped output count including non-drawing whitespace glyphs.
61    /// It may differ from the number of UTF-8 bytes or Unicode characters.
62    pub const fn glyph_count(self) -> usize {
63        self.glyph_count
64    }
65
66    fn from_line(line: &ShapedLine) -> Self {
67        Self {
68            advance: line.advance(),
69            ascent: line.ascent(),
70            descent: line.descent(),
71            line_height: line.line_height(),
72            glyph_count: line.glyphs().len(),
73        }
74    }
75}
76
77struct PreparedText {
78    line: ShapedLine,
79    metrics: TextMetrics,
80    minimum_x: f32,
81    maximum_x: f32,
82    minimum_y: f32,
83    maximum_y: f32,
84}
85
86impl PreparedText {
87    fn new(font: &TextFont, text: &str) -> Result<Self, TextError> {
88        let settings = font.settings();
89        let line =
90            font.face()
91                .shape_line(text, &settings.style(1.0)?, &settings.layout_budget())?;
92        Self::from_line(font, line)
93    }
94
95    fn from_line(font: &TextFont, line: ShapedLine) -> Result<Self, TextError> {
96        let settings = font.settings();
97        line.validate_for(
98            font.face(),
99            &settings.style(1.0)?,
100            &settings.layout_budget(),
101        )?;
102        let metrics = TextMetrics::from_line(&line);
103        let run_budget = settings.atlas_limits().run_budget();
104        let required = metrics
105            .glyph_count
106            .checked_mul(TextRunLimits::RETAINED_BYTES_PER_GLYPH);
107        if metrics.glyph_count > run_budget.max_glyphs()
108            || required.is_none_or(|bytes| bytes > run_budget.max_retained_bytes())
109        {
110            return Err(TextError::RunBudgetExceeded {
111                glyphs: metrics.glyph_count,
112                max_glyphs: run_budget.max_glyphs(),
113                required_bytes: required.unwrap_or(usize::MAX),
114                max_retained_bytes: run_budget.max_retained_bytes(),
115            });
116        }
117        let mut result = Self {
118            line,
119            metrics,
120            minimum_x: metrics.advance.min(0.0),
121            maximum_x: metrics.advance.max(0.0),
122            minimum_y: -metrics.ascent,
123            maximum_y: -metrics.descent,
124        };
125        for glyph in result.line.glyphs() {
126            result.minimum_x = result.minimum_x.min(glyph.logical_x());
127            result.maximum_x = result.maximum_x.max(glyph.logical_x());
128            result.minimum_y = result.minimum_y.min(glyph.logical_y());
129            result.maximum_y = result.maximum_y.max(glyph.logical_y());
130        }
131        Ok(result)
132    }
133}
134
135impl fmt::Debug for PreparedText {
136    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137        // ShapedLine also retains its font; avoid dumping that shared source.
138        formatter
139            .debug_struct("PreparedText")
140            .field("text", &self.line.text())
141            .field("metrics", &self.metrics)
142            .finish_non_exhaustive()
143    }
144}
145
146impl PartialEq for PreparedText {
147    fn eq(&self, other: &Self) -> bool {
148        self.line.text() == other.line.text()
149            && self.line.style() == other.line.style()
150            && self.line.glyphs() == other.line.glyphs()
151            && self.metrics == other.metrics
152            && self.minimum_x == other.minimum_x
153            && self.maximum_x == other.maximum_x
154            && self.minimum_y == other.minimum_y
155            && self.maximum_y == other.maximum_y
156    }
157}
158
159/// One validated single-line label anchored to a logical-screen baseline.
160///
161/// Screen coordinates start at the content area's top-left and increase down
162/// and right. The y coordinate is the baseline, not the upper edge of the
163/// letters. World cameras and fixed-step interpolation do not move this label.
164/// It requires no world Transform and may coexist with other visual components.
165///
166/// Construction and changed text/font setters use Engine's CPU font shaper.
167/// Cloning shares immutable text and font data; moving, tinting, ordering, and
168/// aligning do not shape, rasterize, or upload glyphs. A failed setter leaves
169/// every prior field intact. No old string history is retained by this value.
170/// Clones held elsewhere can of course retain earlier immutable strings.
171///
172/// Extraction excludes disabled entities and validates font provenance before
173/// publishing a complete snapshot. Screen layer, depth, and entity identity
174/// determine painter order; a same-entity rectangle/image/text tie uses that
175/// order. No wrapping, font fallback, hit testing, input capture, or text editing
176/// is implied. Missing glyphs and line separators are errors, not replacements.
177///
178/// Raster size, atlas space, and GPU allocation are checked later by desktop
179/// presentation. CPU validation alone cannot guarantee a glyph fits every DPI
180/// or device. Desktop preparation passes this retained CPU line directly to
181/// Engine at scale 1.0. Other display scales require a DPI-specific line because
182/// Engine's prepared-line provenance includes exact DPI; that line is shaped
183/// only on a changed label or resource rebuild, never for an unchanged run.
184#[derive(Debug, Clone, PartialEq, Component)]
185pub struct ScreenTextVisual {
186    font: TextFont,
187    prepared: Arc<PreparedText>,
188    position: LogicalScreenPosition,
189    alignment: TextAlignment,
190    tint: Color,
191    layer: Layer,
192    draw_order_depth: f32,
193    clip: crate::screen::ScreenClip,
194}
195
196impl ScreenTextVisual {
197    /// Returns the fixed-screen clip; label placement and alignment do not move it.
198    pub const fn clip(&self) -> crate::screen::ScreenClip {
199        self.clip
200    }
201
202    /// Replaces the explicit clip without reshaping or changing typographic metrics.
203    pub fn set_clip(&mut self, clip: crate::screen::ScreenClip) {
204        self.clip = clip;
205    }
206    /// Prepares a left-aligned white label on the default layer at depth zero.
207    ///
208    /// Position is a finite logical-pixel baseline anchor. Negative/offscreen
209    /// positions are valid when aligned bounds remain representable. Empty
210    /// text is valid; whitespace retains advance even if it draws no glyphs.
211    /// No window, rasterization, or GPU operation occurs here.
212    pub fn new(
213        font: TextFont,
214        text: &str,
215        position: LogicalScreenPosition,
216    ) -> Result<Self, TextError> {
217        validate_position(position)?;
218        let prepared = PreparedText::new(&font, text)?;
219        Self::from_prepared(font, prepared, position)
220    }
221
222    /// Creates a label using a caller-owned reusable shaping session.
223    ///
224    /// The session fixes one registered font and logical size at scale 1.0.
225    /// It reuses parsed shaping state, not mutable storage held by older labels.
226    /// The returned value owns its line and does not borrow the session.
227    pub fn new_with_session(
228        session: &mut TextPreparationSession<'_>,
229        text: &str,
230        position: LogicalScreenPosition,
231    ) -> Result<Self, TextError> {
232        validate_position(position)?;
233        let font = session.font().clone();
234        let prepared = PreparedText::from_line(&font, session.shape_line(text)?)?;
235        Self::from_prepared(font, prepared, position)
236    }
237
238    fn from_prepared(
239        font: TextFont,
240        prepared: PreparedText,
241        position: LogicalScreenPosition,
242    ) -> Result<Self, TextError> {
243        let prepared = Arc::new(prepared);
244        let result = Self {
245            font,
246            prepared,
247            position,
248            alignment: TextAlignment::Left,
249            tint: Color::WHITE,
250            layer: Layer::DEFAULT,
251            draw_order_depth: 0.0,
252            clip: crate::screen::ScreenClip::Unclipped,
253        };
254        result.validate()?;
255        Ok(result)
256    }
257
258    /// Returns the opaque application font registration shared by this label.
259    pub const fn font(&self) -> &TextFont {
260        &self.font
261    }
262
263    /// Returns the original UTF-8 single line without allocating or reshaping.
264    pub fn text(&self) -> &str {
265        self.prepared.line.text()
266    }
267
268    /// Returns immutable Engine shaping output, including exact font/style provenance.
269    ///
270    /// Logical labels prepare at scale 1.0. A different-DPI atlas must not consume
271    /// this line as though its style matched; desktop handles that rebuild itself.
272    /// The UTF-8 and glyph metadata are shared with every clone and snapshot.
273    pub fn shaped_line(&self) -> &ShapedLine {
274        &self.prepared.line
275    }
276
277    /// Returns DPI-independent typographic metrics from the latest successful preparation.
278    pub fn metrics(&self) -> TextMetrics {
279        self.prepared.metrics
280    }
281
282    /// Returns shaped glyph count, conservatively including whitespace.
283    pub fn glyph_count(&self) -> usize {
284        self.metrics().glyph_count()
285    }
286
287    /// Returns a conservative upper bound on retained UTF-8 storage in bytes.
288    ///
289    /// Since Engine 0.4 owns the UTF-8 together with glyph metadata, this includes
290    /// both capacities, exactly as [`Self::retained_layout_bytes`]. It no longer
291    /// measures the String allocation alone. Font and fixed metadata are excluded.
292    /// Extraction's text-byte allowance independently counts `text().len()`.
293    pub fn retained_text_bytes(&self) -> usize {
294        self.retained_layout_bytes()
295    }
296
297    /// Returns retained UTF-8 plus shaped-glyph Vec capacity bytes.
298    ///
299    /// This is Engine's actual capacity accounting, shared by clones, excluding
300    /// font storage, allocator overhead and this value's fixed metadata. It is
301    /// not a measurement of desktop atlas or GPU memory.
302    pub fn retained_layout_bytes(&self) -> usize {
303        self.prepared.line.allocation_bytes()
304    }
305
306    /// Returns the logical-pixel baseline anchor before horizontal alignment.
307    pub const fn position(&self) -> LogicalScreenPosition {
308        self.position
309    }
310
311    /// Returns the actual logical baseline origin after horizontal alignment.
312    /// Typographic advance, including trailing spaces, determines the offset.
313    pub fn baseline_origin(&self) -> LogicalScreenPosition {
314        let offset = match self.alignment {
315            TextAlignment::Left => 0.0,
316            TextAlignment::Center => self.metrics().advance() * 0.5,
317            TextAlignment::Right => self.metrics().advance(),
318        };
319        let position = self.position.to_vec2();
320        LogicalScreenPosition::new(position.x() - offset, position.y())
321    }
322
323    /// Returns how the line's advance is aligned around its baseline anchor.
324    pub const fn alignment(&self) -> TextAlignment {
325        self.alignment
326    }
327
328    /// Returns normalized straight-linear RGBA multiplied by glyph coverage.
329    pub const fn tint(&self) -> Color {
330        self.tint
331    }
332
333    /// Returns the primary painter-order layer within screen content.
334    pub const fn layer(&self) -> Layer {
335        self.layer
336    }
337
338    /// Returns finite within-layer ordering depth, not camera projection depth.
339    pub const fn draw_order_depth(&self) -> f32 {
340        self.draw_order_depth
341    }
342
343    /// Replaces the line only after complete bounded shaping and geometry validation.
344    ///
345    /// Exact equal UTF-8 is a no-op. Any failure preserves text, metrics,
346    /// shared storage, and presentation fields. Old storage is released when
347    /// no earlier clone or published snapshot references it.
348    pub fn set_text(&mut self, text: &str) -> Result<(), TextError> {
349        if self.text() == text {
350            return Ok(());
351        }
352        let mut candidate = self.clone();
353        candidate.prepared = Arc::new(PreparedText::new(&self.font, text)?);
354        candidate.validate()?;
355        *self = candidate;
356        Ok(())
357    }
358
359    /// Changes text using reusable shaping state for this exact font registration.
360    ///
361    /// A foreign registration is rejected even when UTF-8 is unchanged. An exact
362    /// text match with the correct session performs no shaping. Any error preserves
363    /// all visual fields and earlier snapshots; session scratch may have changed.
364    /// Successful changes own fresh line storage, so this is not a zero-allocation
365    /// update promise. The borrowed session never becomes part of the component.
366    pub fn set_text_with_session(
367        &mut self,
368        session: &mut TextPreparationSession<'_>,
369        text: &str,
370    ) -> Result<(), TextError> {
371        if session.font() != &self.font {
372            return Err(sim_engine::ShapedLineError::FontMismatch.into());
373        }
374        if self.text() == text {
375            return Ok(());
376        }
377        let prepared = PreparedText::from_line(&self.font, session.shape_line(text)?)?;
378        let mut candidate = self.clone();
379        candidate.prepared = Arc::new(prepared);
380        candidate.validate()?;
381        *self = candidate;
382        Ok(())
383    }
384
385    /// Selects a registered font and reparses the current line before swapping.
386    ///
387    /// The same registration is a no-op. Missing glyphs, budgets, or invalid
388    /// aligned geometry preserve the old font and every other field. Issuing
389    /// application identity is checked by extraction, not by this standalone value.
390    pub fn set_font(&mut self, font: TextFont) -> Result<(), TextError> {
391        if self.font == font {
392            return Ok(());
393        }
394        let mut candidate = self.clone();
395        candidate.prepared = Arc::new(PreparedText::new(&font, self.text())?);
396        candidate.font = font;
397        candidate.validate()?;
398        *self = candidate;
399        Ok(())
400    }
401
402    /// Moves the logical baseline anchor without shaping or changing retained text.
403    /// Non-finite or unrepresentable aligned bounds leave the value unchanged.
404    pub fn set_position(&mut self, position: LogicalScreenPosition) -> Result<(), TextError> {
405        let mut candidate = self.clone();
406        candidate.position = position;
407        candidate.validate()?;
408        *self = candidate;
409        Ok(())
410    }
411
412    /// Changes advance-based alignment without shaping or rasterization.
413    /// An unrepresentable adjusted baseline leaves every field unchanged.
414    pub fn set_alignment(&mut self, alignment: TextAlignment) -> Result<(), TextError> {
415        let mut candidate = self.clone();
416        candidate.alignment = alignment;
417        candidate.validate()?;
418        *self = candidate;
419        Ok(())
420    }
421
422    /// Changes normalized straight-linear RGBA tint atomically, without reshaping.
423    pub fn set_tint(&mut self, tint: Color) -> Result<(), TextError> {
424        if !tint.is_normalized() {
425            return Err(ScreenVisualError::InvalidColor { value: tint }.into());
426        }
427        self.tint = tint;
428        Ok(())
429    }
430
431    /// Replaces the primary screen painter-order layer without preparing text again.
432    pub fn set_layer(&mut self, layer: Layer) {
433        self.layer = layer;
434    }
435
436    /// Replaces finite within-layer painter depth; negative values are allowed.
437    /// Non-finite input preserves the current depth and every other field.
438    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), TextError> {
439        if !depth.is_finite() {
440            return Err(ScreenVisualError::InvalidDrawOrderDepth { value: depth }.into());
441        }
442        self.draw_order_depth = depth;
443        Ok(())
444    }
445
446    pub(crate) fn validate(&self) -> Result<(), TextError> {
447        validate_position(self.position)?;
448        if !self.tint.is_normalized() {
449            return Err(ScreenVisualError::InvalidColor { value: self.tint }.into());
450        }
451        if !self.draw_order_depth.is_finite() {
452            return Err(ScreenVisualError::InvalidDrawOrderDepth {
453                value: self.draw_order_depth,
454            }
455            .into());
456        }
457        let baseline = self.baseline_origin().to_vec2();
458        let p = &self.prepared;
459        if !baseline.is_finite()
460            || !offset_is_representable(baseline.x(), p.minimum_x)
461            || !offset_is_representable(baseline.x(), p.maximum_x)
462            || !offset_is_representable(baseline.y(), p.minimum_y)
463            || !offset_is_representable(baseline.y(), p.maximum_y)
464        {
465            return Err(TextError::InvalidBounds {
466                position: self.position,
467            });
468        }
469        Ok(())
470    }
471}
472
473fn validate_position(position: LogicalScreenPosition) -> Result<(), TextError> {
474    if !position.is_finite() {
475        return Err(ScreenVisualError::InvalidPosition { value: position }.into());
476    }
477    Ok(())
478}
479
480fn offset_is_representable(origin: f32, offset: f32) -> bool {
481    let result = origin + offset;
482    result.is_finite() && (offset == 0.0 || result != origin)
483}