Skip to main content

sim_engine/renderer/
text.rs

1use super::*;
2use crate::{FontError, FontFace, RasterizedGlyph, ShapedLine, TextLayoutBudget, TextStyle};
3
4mod prepared;
5mod types;
6pub use prepared::PreparedTextError;
7pub use types::{TextAtlasBudget, TextError, TextUpdateReport};
8
9#[derive(Clone, Copy)]
10struct CachedGlyph {
11    id: u16,
12    width: u32,
13    height: u32,
14    bearing_x: i32,
15    bearing_y: i32,
16}
17
18#[derive(Clone, Copy, Default)]
19struct Shelf {
20    x: u32,
21    y: u32,
22    height: u32,
23}
24
25impl Shelf {
26    fn insert(
27        &mut self,
28        width: u32,
29        height: u32,
30        size: (u32, u32),
31    ) -> Result<ImageTexelRect, TextError> {
32        if width > size.0 || height > size.1 {
33            return Err(TextError::AtlasFull);
34        }
35        let mut next = *self;
36        if next.x.checked_add(width).is_none_or(|right| right > size.0) {
37            next.x = 0;
38            next.y = next
39                .y
40                .checked_add(next.height)
41                .ok_or(TextError::AtlasFull)?;
42            next.height = 0;
43        }
44        if next
45            .y
46            .checked_add(height)
47            .is_none_or(|bottom| bottom > size.1)
48        {
49            return Err(TextError::AtlasFull);
50        }
51        let rectangle = ImageTexelRect::new(next.x, next.y, width, height)?;
52        next.x += width;
53        next.height = next.height.max(height);
54        *self = next;
55        Ok(rectangle)
56    }
57}
58
59/// Antialiased font cache for one font, logical EM size, direction and DPI.
60///
61/// Enable the optional `text` feature. Glyphs never move or disappear: the fixed
62/// atlas returns [`TextError::AtlasFull`] instead of evicting live runs. Create a
63/// new atlas and prepare replacement runs before swapping when size or DPI changes.
64/// The input font must be a trusted application asset, not an untrusted-font sandbox.
65///
66/// Draw [`Self::atlas`] and [`TextRun2d::glyph_run`] with [`ImageSampling::Linear`].
67/// Placements are baseline-relative, in logical pixels. Bitmap coverage is cached
68/// at an integer physical baseline; fractional placement uses bilinear filtering,
69/// not per-subpixel hinting. No fonts are discovered or downloaded automatically.
70///
71/// ```no_run
72/// use sim_engine::{
73///     Color, FontFace, FrameBudget, FramePassOptions, ImageBatchPlacement, ImageSampling,
74///     LogicalPixels, LogicalScreenVector, PhysicalPerLogical, TextAtlas2d,
75///     TextAtlasBudget, TextLayoutBudget, TextStyle, WgpuRenderer,
76/// };
77///
78/// fn draw_label(renderer: &mut WgpuRenderer, font: FontFace)
79///     -> Result<(), Box<dyn std::error::Error>>
80/// {
81///     let style = TextStyle::new(
82///         LogicalPixels::new(24.0)?,
83///         PhysicalPerLogical::new(renderer.scale_factor() as f32)?,
84///     )?;
85///     // Keep these two resources between frames in an application.
86///     let mut atlas = TextAtlas2d::new(renderer, font, style, TextAtlasBudget::default())?;
87///     let label = atlas.prepare(renderer, "Hello, world!", TextLayoutBudget::default())?;
88///     let mut frame = renderer.begin_frame(Color::BLACK, FrameBudget::default())?;
89///     frame.draw_glyph_run_placed(
90///         atlas.atlas(), label.glyph_run(),
91///         ImageBatchPlacement::new(LogicalScreenVector::new(24.0, 80.0), Color::WHITE)?,
92///         ImageSampling::Linear, FramePassOptions::new(0),
93///     )?;
94///     let _report = frame.present()?;
95///     Ok(())
96/// }
97/// ```
98pub struct TextAtlas2d {
99    font: FontFace,
100    style: TextStyle,
101    budget: TextAtlasBudget,
102    atlas: GlyphAtlas2d,
103    identity: Arc<()>,
104    cached: Vec<CachedGlyph>,
105    shelf: Shelf,
106}
107
108/// Retained, shaped single-line text and its baseline metrics.
109///
110/// Drawing an unchanged run needs no shaping, rasterization or geometry upload.
111/// Whitespace contributes to [`Self::advance`] but emits no glyph quad. Drawable
112/// bounds include filtering support and are not typographic advance bounds.
113pub struct TextRun2d {
114    run: GlyphRun2d,
115    atlas_identity: Arc<()>,
116    text: String,
117    advance: f32,
118    ascent: f32,
119    descent: f32,
120    line_height: f32,
121}
122
123impl TextRun2d {
124    /// Returns the retained glyph instances for a composed glyph draw.
125    pub const fn glyph_run(&self) -> &GlyphRun2d {
126        &self.run
127    }
128    /// Returns the original UTF-8 text.
129    pub fn text(&self) -> &str {
130        &self.text
131    }
132    /// Returns horizontal advance, including spaces, in logical pixels.
133    pub const fn advance(&self) -> f32 {
134        self.advance
135    }
136    /// Returns the font ascender above the baseline in logical pixels.
137    pub const fn ascent(&self) -> f32 {
138        self.ascent
139    }
140    /// Returns the signed font descender below the baseline in logical pixels.
141    pub const fn descent(&self) -> f32 {
142        self.descent
143    }
144    /// Returns the font-recommended baseline spacing in logical pixels.
145    pub const fn line_height(&self) -> f32 {
146        self.line_height
147    }
148    /// Returns retained UTF-8 and glyph-layout allocation bytes, excluding allocator overhead.
149    pub fn recovery_memory_bytes(&self) -> usize {
150        self.text
151            .capacity()
152            .saturating_add(self.run.recovery_memory_bytes())
153    }
154}
155
156impl TextAtlas2d {
157    /// Creates a fixed-capacity atlas, checking device dimensions before pixel allocation.
158    pub fn new(
159        renderer: &WgpuRenderer,
160        font: FontFace,
161        style: TextStyle,
162        budget: TextAtlasBudget,
163    ) -> Result<Self, TextError> {
164        let image_budget = budget.image_budget()?;
165        let bytes = image::validate_image_shape(
166            budget.width(),
167            budget.height(),
168            image_budget.max_bytes(),
169            image_budget,
170            renderer.device.limits().max_texture_dimension_2d,
171        )?;
172        let mut pixels = reserve_vec(bytes)?;
173        pixels.resize(bytes, 255);
174        for pixel in pixels.chunks_exact_mut(4) {
175            pixel[3] = 0;
176        }
177        // Reserve the bounded metadata once: inserting a successfully uploaded
178        // glyph must not fail later and leave the packing cursor inconsistent.
179        let cached = reserve_vec(budget.max_cached_glyphs())?;
180        let metadata_bytes = budget
181            .max_cached_glyphs()
182            .checked_mul(std::mem::size_of::<GlyphAtlasEntry>())
183            .ok_or(TextError::InvalidBudget)?;
184        let atlas = renderer.create_glyph_atlas(
185            budget.width(),
186            budget.height(),
187            pixels,
188            Vec::new(),
189            GlyphAtlasBudget::new(image_budget, budget.max_cached_glyphs(), metadata_bytes)?,
190        )?;
191        Ok(Self {
192            font,
193            style,
194            budget,
195            atlas,
196            identity: Arc::new(()),
197            cached,
198            shelf: Shelf::default(),
199        })
200    }
201
202    /// Returns the atlas to use with a retained glyph-run draw. Use linear sampling.
203    pub const fn atlas(&self) -> &GlyphAtlas2d {
204        &self.atlas
205    }
206    /// Returns the immutable font/style/DPI configuration.
207    pub const fn style(&self) -> &TextStyle {
208        &self.style
209    }
210    /// Returns the original font, shared cheaply through [`FontFace::clone`].
211    pub const fn font(&self) -> &FontFace {
212        &self.font
213    }
214    /// Returns immutable atlas and run limits.
215    pub const fn budget(&self) -> TextAtlasBudget {
216        self.budget
217    }
218    /// Returns cached glyph count, including non-drawing spacing glyphs.
219    pub fn cached_glyph_count(&self) -> usize {
220        self.cached.len()
221    }
222    /// Returns retained atlas pixels and metadata bytes, excluding shared font data and allocator overhead.
223    pub fn recovery_memory_bytes(&self) -> usize {
224        self.atlas.recovery_memory_bytes().saturating_add(
225            self.cached
226                .capacity()
227                .saturating_mul(std::mem::size_of::<CachedGlyph>()),
228        )
229    }
230    /// Returns retained GPU image allocation bytes; runs own separate instance buffers.
231    pub fn gpu_allocation_bytes(&self) -> usize {
232        self.atlas.gpu_allocation_bytes()
233    }
234
235    /// Shapes a line and rasterizes only glyphs missing from this immutable-style cache.
236    ///
237    /// Font/input/output limits apply to shaping; raster limits apply to cache misses.
238    /// Run capacity is conservatively preflighted for all shaped glyphs, including
239    /// whitespace, before allocating placements or populating the glyph cache.
240    /// A failure preserves all existing drawable runs, but may warm the bounded
241    /// cache with some new glyphs before a later glyph or run allocation fails.
242    /// There is no implicit atlas growth, eviction, font fallback or wrapping.
243    pub fn prepare(
244        &mut self,
245        renderer: &WgpuRenderer,
246        text: &str,
247        layout_budget: TextLayoutBudget,
248    ) -> Result<TextRun2d, TextError> {
249        renderer.validate_image(&self.atlas.image)?;
250        let shaped = self.font.shape_line(text, &self.style, &layout_budget)?;
251        self.prepare_validated(renderer, &shaped, layout_budget)
252    }
253
254    fn prepare_validated(
255        &mut self,
256        renderer: &WgpuRenderer,
257        shaped: &ShapedLine,
258        layout_budget: TextLayoutBudget,
259    ) -> Result<TextRun2d, TextError> {
260        let owned = owned_text(shaped.text())?;
261        let glyphs = self.position_glyphs(renderer, shaped, &layout_budget)?;
262        let run = renderer.create_glyph_run(&self.atlas, glyphs, self.budget.run_budget())?;
263        Ok(TextRun2d {
264            run,
265            atlas_identity: Arc::clone(&self.identity),
266            text: owned,
267            advance: shaped.advance(),
268            ascent: shaped.ascent(),
269            descent: shaped.descent(),
270            line_height: shaped.line_height(),
271        })
272    }
273
274    /// Replaces a line atomically while reusing its instance-buffer capacity.
275    ///
276    /// Exact unchanged UTF-8 returns immediately after resource-identity validation;
277    /// no shaping/raster work occurs, so `layout_budget` is not consumed or rechecked.
278    /// For changed text, a synchronous error preserves the old run/text/metrics,
279    /// but may warm atlas entries as documented by [`Self::prepare`].
280    pub fn update(
281        &mut self,
282        renderer: &WgpuRenderer,
283        run: &mut TextRun2d,
284        text: &str,
285        layout_budget: TextLayoutBudget,
286    ) -> Result<TextUpdateReport, TextError> {
287        self.validate_run(run)?;
288        renderer.validate_glyph_run(&self.atlas, &run.run)?;
289        if run.text == text {
290            return Ok(TextUpdateReport::default());
291        }
292        let shaped = self.font.shape_line(text, &self.style, &layout_budget)?;
293        self.update_validated(renderer, run, &shaped, layout_budget)
294    }
295
296    fn update_validated(
297        &mut self,
298        renderer: &WgpuRenderer,
299        run: &mut TextRun2d,
300        shaped: &ShapedLine,
301        layout_budget: TextLayoutBudget,
302    ) -> Result<TextUpdateReport, TextError> {
303        let owned = owned_text(shaped.text())?;
304        let old_cache_count = self.cached.len();
305        let glyphs = self.position_glyphs(renderer, shaped, &layout_budget)?;
306        let upload = renderer.update_glyph_run(&self.atlas, &mut run.run, &glyphs)?;
307        run.text = owned;
308        run.advance = shaped.advance();
309        run.ascent = shaped.ascent();
310        run.descent = shaped.descent();
311        run.line_height = shaped.line_height();
312        Ok(TextUpdateReport::new(
313            upload.instances().uploaded_instance_bytes(),
314            self.cached.len() - old_cache_count,
315        ))
316    }
317
318    /// Restores exact atlas pixels on a replacement renderer without rerasterizing.
319    ///
320    /// This replaces the atlas only after successful allocation. Restore each live
321    /// run using [`Self::restore_run`] before drawing on the replacement renderer.
322    pub fn restore(&mut self, renderer: &WgpuRenderer) -> Result<(), TextError> {
323        self.atlas = renderer.restore_glyph_atlas(&self.atlas)?;
324        Ok(())
325    }
326
327    /// Restores one live run against this atlas, preserving text and baseline metrics.
328    pub fn restore_run(
329        &self,
330        renderer: &WgpuRenderer,
331        run: &mut TextRun2d,
332    ) -> Result<(), TextError> {
333        self.validate_run(run)?;
334        run.run = renderer.restore_glyph_run(&self.atlas, &run.run)?;
335        Ok(())
336    }
337
338    fn validate_run(&self, run: &TextRun2d) -> Result<(), TextError> {
339        if !Arc::ptr_eq(&self.identity, &run.atlas_identity) {
340            return Err(TextError::AtlasMismatch);
341        }
342        Ok(())
343    }
344
345    fn position_glyphs(
346        &mut self,
347        renderer: &WgpuRenderer,
348        shaped: &ShapedLine,
349        layout_budget: &TextLayoutBudget,
350    ) -> Result<Vec<PositionedGlyph2d>, TextError> {
351        let run_budget = self.budget.run_budget();
352        glyph::validate_glyph_run_budget(shaped.glyphs().len(), run_budget)?;
353        image::preflight_image_batch_capacity(
354            &renderer.device,
355            shaped.glyphs().len(),
356            ImageBatchBudget::new(run_budget.max_glyphs(), run_budget.max_retained_bytes())?,
357        )?;
358        let mut glyphs = reserve_vec(shaped.glyphs().len())?;
359        for glyph in shaped.glyphs() {
360            let cached = self.cache_glyph(renderer, glyph.glyph_id(), layout_budget)?;
361            if cached.width == 0 || cached.height == 0 {
362                continue;
363            }
364            let destination = destination_from_metrics(
365                cached,
366                glyph.logical_x(),
367                glyph.logical_y(),
368                self.style.scale().get(),
369            )?;
370            glyphs.push(PositionedGlyph2d::new(
371                GlyphId::new(u32::from(cached.id)),
372                destination,
373                Color::WHITE,
374            )?);
375        }
376        Ok(glyphs)
377    }
378
379    fn cache_glyph(
380        &mut self,
381        renderer: &WgpuRenderer,
382        id: u16,
383        layout_budget: &TextLayoutBudget,
384    ) -> Result<CachedGlyph, TextError> {
385        let insertion = match self.cached.binary_search_by_key(&id, |glyph| glyph.id) {
386            Ok(index) => return Ok(self.cached[index]),
387            Err(index) => index,
388        };
389        if self.cached.len() == self.budget.max_cached_glyphs() {
390            return Err(TextError::GlyphCacheFull);
391        }
392        let raster = self.font.rasterize_glyph(id, &self.style, layout_budget)?;
393        let cached = CachedGlyph {
394            id,
395            width: raster.width(),
396            height: raster.height(),
397            bearing_x: raster.bearing_x(),
398            bearing_y: raster.bearing_y(),
399        };
400        if raster.width() > 0 && raster.height() > 0 {
401            let width = raster.width().checked_add(4).ok_or(TextError::AtlasFull)?;
402            let height = raster.height().checked_add(4).ok_or(TextError::AtlasFull)?;
403            let mut shelf = self.shelf;
404            let source = shelf.insert(width, height, self.atlas.size())?;
405            let pixels = padded_rgba(&raster)?;
406            renderer.upload_glyph(
407                &mut self.atlas,
408                GlyphAtlasEntry::new(GlyphId::new(u32::from(id)), source),
409                &pixels,
410            )?;
411            self.shelf = shelf;
412        }
413        self.cached.insert(insertion, cached);
414        Ok(cached)
415    }
416}
417
418fn destination_from_metrics(
419    glyph: CachedGlyph,
420    x: f32,
421    y: f32,
422    scale: f32,
423) -> Result<LogicalViewportRegion, TextError> {
424    // Image quads map texel centers to their boundaries. Two transparent border
425    // texels preserve bitmap scale and keep the bilinear halo inside full MSAA
426    // coverage, even when the baseline falls between physical pixels.
427    LogicalViewportRegion::new(
428        LogicalScreenPosition::new(
429            x + (glyph.bearing_x as f32 - 1.5) / scale,
430            y + (glyph.bearing_y as f32 - 1.5) / scale,
431        ),
432        LogicalViewport::new(
433            (glyph.width as f32 + 3.0) / scale,
434            (glyph.height as f32 + 3.0) / scale,
435        )
436        .map_err(|_| TextError::InvalidPlacement)?,
437    )
438    .map_err(|_| TextError::InvalidPlacement)
439}
440
441#[cfg(test)]
442pub(super) fn glyph_destination(
443    raster: &RasterizedGlyph,
444    x: f32,
445    y: f32,
446    scale: f32,
447) -> Result<LogicalViewportRegion, TextError> {
448    destination_from_metrics(
449        CachedGlyph {
450            id: 0,
451            width: raster.width(),
452            height: raster.height(),
453            bearing_x: raster.bearing_x(),
454            bearing_y: raster.bearing_y(),
455        },
456        x,
457        y,
458        scale,
459    )
460}
461
462pub(super) fn padded_rgba(raster: &RasterizedGlyph) -> Result<Vec<u8>, TextError> {
463    let width = raster.width() as usize + 4;
464    let height = raster.height() as usize + 4;
465    let bytes = width
466        .checked_mul(height)
467        .and_then(|area| area.checked_mul(4))
468        .ok_or(TextError::AtlasFull)?;
469    let mut pixels = reserve_vec(bytes)?;
470    pixels.resize(bytes, 255);
471    // White transparent padding avoids dark fringes under straight-alpha sampling.
472    for pixel in pixels.chunks_exact_mut(4) {
473        pixel[3] = 0;
474    }
475    for y in 0..raster.height() as usize {
476        for x in 0..raster.width() as usize {
477            pixels[((y + 2) * width + x + 2) * 4 + 3] =
478                raster.coverage()[y * raster.width() as usize + x];
479        }
480    }
481    Ok(pixels)
482}
483
484fn reserve_vec<T>(count: usize) -> Result<Vec<T>, TextError> {
485    let mut values = Vec::new();
486    values
487        .try_reserve_exact(count)
488        .map_err(|_| TextError::AllocationFailed)?;
489    Ok(values)
490}
491
492fn owned_text(text: &str) -> Result<String, TextError> {
493    let mut owned = String::new();
494    owned
495        .try_reserve_exact(text.len())
496        .map_err(|_| TextError::AllocationFailed)?;
497    owned.push_str(text);
498    Ok(owned)
499}
500
501#[cfg(test)]
502mod tests;