Skip to main content

sim_engine/renderer/glyph_batch/
mod.rs

1//! Ordered snapshots of already prepared glyph runs sharing one atlas.
2
3use super::{
4    Color, GlyphAtlas2d, GlyphError, GlyphRun2d, ImageBatch2d, ImageBatchBudget,
5    ImageBatchPlacement, ImageBatchUploadReport, ImageSprite2d, LogicalScreenPosition,
6    LogicalViewportRegion, ScreenClipRect, WgpuRenderer, image,
7};
8
9#[cfg(test)]
10mod tests;
11#[cfg(test)]
12pub(super) use tests::verify_glyph_batches;
13
14/// One prepared run's placement in an ordered atlas batch.
15///
16/// Translation uses local logical pixels and tint multiplies the per-glyph tint.
17/// The optional clip is relative to the drawing viewport, is not translated with
18/// the run, and intersects the frame item's clip. No shaping or rasterization is
19/// performed. A batch snapshots this input; later changes to the source run do
20/// not alter the batch until [`WgpuRenderer::update_glyph_batch`] is called.
21#[derive(Clone, Copy)]
22pub struct GlyphRunPlacement2d<'run> {
23    run: &'run GlyphRun2d,
24    placement: ImageBatchPlacement,
25    clip: Option<ScreenClipRect>,
26}
27
28impl<'run> GlyphRunPlacement2d<'run> {
29    /// Places an already prepared run without changing its source layout.
30    pub const fn new(run: &'run GlyphRun2d, placement: ImageBatchPlacement) -> Self {
31        Self {
32            run,
33            placement,
34            clip: None,
35        }
36    }
37
38    /// Sets a validated viewport-local clip, independent of the translation.
39    pub const fn with_clip(mut self, clip: ScreenClipRect) -> Self {
40        self.clip = Some(clip);
41        self
42    }
43
44    /// Returns the prepared source run.
45    pub const fn run(self) -> &'run GlyphRun2d {
46        self.run
47    }
48
49    /// Returns the run's local logical translation and normalized tint.
50    pub const fn placement(self) -> ImageBatchPlacement {
51        self.placement
52    }
53
54    /// Returns the optional viewport-local logical clip.
55    pub const fn clip(self) -> Option<ScreenClipRect> {
56        self.clip
57    }
58}
59
60/// Explicit limits for a retained many-placement glyph batch.
61///
62/// Retained bytes cover sprite descriptions, reusable instance conversion
63/// storage, and clip spans. Atlas storage, input runs and backend allocations are
64/// separate. GPU capacity remains bounded by the glyph count and device limit.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct GlyphBatchBudget {
67    max_placements: usize,
68    max_glyphs: usize,
69    max_retained_bytes: usize,
70}
71
72impl GlyphBatchBudget {
73    /// CPU bytes required by one glyph-capacity slot, excluding clip spans.
74    pub const RETAINED_BYTES_PER_GLYPH: usize = ImageBatchBudget::RETAINED_BYTES_PER_SPRITE;
75    /// Maximum additional CPU bytes for one non-empty placement's clip span.
76    pub const RETAINED_BYTES_PER_PLACEMENT: usize = std::mem::size_of::<GlyphBatchSpan>();
77
78    /// Creates non-zero limits sufficient for one glyph and one clip span.
79    pub fn new(
80        max_placements: usize,
81        max_glyphs: usize,
82        max_retained_bytes: usize,
83    ) -> Result<Self, GlyphError> {
84        if max_placements == 0
85            || max_glyphs == 0
86            || max_retained_bytes
87                < Self::RETAINED_BYTES_PER_GLYPH + Self::RETAINED_BYTES_PER_PLACEMENT
88        {
89            return Err(GlyphError::InvalidBudget);
90        }
91        Ok(Self {
92            max_placements,
93            max_glyphs,
94            max_retained_bytes,
95        })
96    }
97
98    /// Returns the maximum submitted placements, including empty runs.
99    pub const fn max_placements(self) -> usize {
100        self.max_placements
101    }
102    /// Returns the maximum sum of glyphs across all placements.
103    pub const fn max_glyphs(self) -> usize {
104        self.max_glyphs
105    }
106    /// Returns the retained CPU allocation ceiling, including reusable capacity.
107    pub const fn max_retained_bytes(self) -> usize {
108        self.max_retained_bytes
109    }
110}
111
112impl Default for GlyphBatchBudget {
113    fn default() -> Self {
114        Self {
115            max_placements: 16_384,
116            max_glyphs: 100_000,
117            max_retained_bytes: 32 * 1024 * 1024,
118        }
119    }
120}
121
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub(in crate::renderer) struct GlyphBatchSpan {
124    pub(in crate::renderer) first: u32,
125    pub(in crate::renderer) end: u32,
126    pub(in crate::renderer) clip: Option<ScreenClipRect>,
127}
128
129/// A retained, ordered snapshot of prepared glyph placements sharing one atlas.
130///
131/// One instance buffer holds all glyphs. Only adjacent placements with identical
132/// clips are merged; glyphs are never reordered. A shared clip therefore needs
133/// at most one draw, while distinct adjacent clips require separate scissor
134/// draws. The entire batch is one frame item and cannot interleave other frame
135/// sources inside it. Use separate batches at painter-order boundaries.
136///
137/// Updates reuse CPU/GPU capacity and equal sprite input causes no upload. A
138/// frame reuses exact sprite geometry proofs at an unchanged viewport. Device
139/// restoration clears proofs and requires the restored original atlas.
140pub struct GlyphBatch2d {
141    pub(in crate::renderer) batch: ImageBatch2d,
142    pub(in crate::renderer) spans: Vec<GlyphBatchSpan>,
143    placement_count: usize,
144    budget: GlyphBatchBudget,
145}
146
147impl GlyphBatch2d {
148    /// Returns the number of submitted placements, including empty source runs.
149    pub const fn placement_count(&self) -> usize {
150        self.placement_count
151    }
152    /// Returns the total retained glyph count across all placements.
153    pub fn glyph_count(&self) -> usize {
154        self.batch.sprite_count()
155    }
156    /// Returns the conservative draw count before viewport clipping.
157    pub fn draw_count(&self) -> usize {
158        self.spans.len()
159    }
160    /// Returns reusable glyph storage capacity, excluding clip metadata.
161    pub fn capacity(&self) -> usize {
162        self.batch.capacity()
163    }
164    /// Returns the limits retained for updates and device restoration.
165    pub const fn budget(&self) -> GlyphBatchBudget {
166        self.budget
167    }
168    /// Returns CPU recovery/conversion/clip capacity bytes, excluding source runs.
169    pub fn recovery_memory_bytes(&self) -> usize {
170        self.batch
171            .recovery_memory_bytes()
172            .saturating_add(span_bytes(self.spans.capacity()))
173    }
174    /// Returns actual GPU instance-buffer allocation bytes, including spare capacity.
175    pub fn gpu_allocation_bytes(&self) -> usize {
176        self.batch.gpu_allocation_bytes()
177    }
178}
179
180/// Allocation and upload outcome of a transactional glyph-batch update.
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
182pub struct GlyphBatchUploadReport {
183    instances: ImageBatchUploadReport,
184    placements: usize,
185    draws: usize,
186    retained_bytes: usize,
187    peak_retained_bytes: usize,
188}
189
190impl GlyphBatchUploadReport {
191    /// Returns exact instance-upload bytes and GPU allocation/growth counters.
192    pub const fn instances(self) -> ImageBatchUploadReport {
193        self.instances
194    }
195    /// Returns accepted source placement count, including empty runs.
196    pub const fn placement_count(self) -> usize {
197        self.placements
198    }
199    /// Returns the conservative ordered scissor draw count.
200    pub const fn draw_count(self) -> usize {
201        self.draws
202    }
203    /// Returns final retained CPU capacity bytes.
204    pub const fn retained_bytes(self) -> usize {
205        self.retained_bytes
206    }
207    /// Returns conservative old/new overlapping CPU storage during the update.
208    pub const fn peak_retained_bytes(self) -> usize {
209        self.peak_retained_bytes
210    }
211}
212
213impl WgpuRenderer {
214    /// Snapshots same-atlas prepared placements without shaping or font work.
215    ///
216    /// Foreign atlases/runs, overflowing destinations and count/byte/device-limit
217    /// excess are rejected before GPU allocation. Input order is painter order.
218    pub fn create_glyph_batch(
219        &self,
220        atlas: &GlyphAtlas2d,
221        placements: &[GlyphRunPlacement2d<'_>],
222        budget: GlyphBatchBudget,
223    ) -> Result<GlyphBatch2d, GlyphError> {
224        self.validate_image(&atlas.image)?;
225        create_resources(
226            &self.device,
227            &self.queue,
228            std::sync::Arc::clone(&self.renderer_identity),
229            &atlas.image,
230            placements,
231            budget,
232        )
233    }
234
235    /// Atomically replaces the snapshot, reusing CPU arrays and GPU capacity.
236    ///
237    /// All runs must belong to the same current atlas. Synchronous validation or
238    /// allocation failure preserves the old drawable batch. Source run mutations
239    /// are not observed until this call. Clip-only changes do not upload glyphs;
240    /// translation/tint changes update instance data without redoing text layout.
241    /// Shrinking retains reusable capacity. GPU/device failure is not a rollback
242    /// of queue work already submitted.
243    pub fn update_glyph_batch(
244        &self,
245        atlas: &GlyphAtlas2d,
246        batch: &mut GlyphBatch2d,
247        placements: &[GlyphRunPlacement2d<'_>],
248    ) -> Result<GlyphBatchUploadReport, GlyphError> {
249        self.validate_image_batch(&atlas.image, &batch.batch)?;
250        update_resources(&self.device, &self.queue, &atlas.image, batch, placements)
251    }
252
253    /// Restores a snapshot against the restored copy of its original atlas.
254    ///
255    /// The original runs need not remain alive. Translation, tint, clips and
256    /// painter order are preserved. Another atlas, even with identical pixels,
257    /// is rejected. The restored batch has no viewport-dependent cached proof.
258    pub fn restore_glyph_batch(
259        &self,
260        atlas: &GlyphAtlas2d,
261        source: &GlyphBatch2d,
262    ) -> Result<GlyphBatch2d, GlyphError> {
263        self.validate_image(&atlas.image)?;
264        restore_resources(
265            &self.device,
266            &self.queue,
267            std::sync::Arc::clone(&self.renderer_identity),
268            &atlas.image,
269            source,
270        )
271    }
272}
273
274fn restore_resources(
275    device: &wgpu::Device,
276    queue: &wgpu::Queue,
277    renderer_identity: std::sync::Arc<()>,
278    image: &super::Image2d,
279    source: &GlyphBatch2d,
280) -> Result<GlyphBatch2d, GlyphError> {
281    if !std::sync::Arc::ptr_eq(
282        &image.recovery_identity,
283        &source.batch.image_recovery_identity,
284    ) {
285        return Err(super::ImageError::RecoverySourceMismatch.into());
286    }
287    image::preflight_image_batch_capacity(device, source.glyph_count(), source.batch.budget())?;
288    let mut spans = reserve_spans(source.spans.len())?;
289    spans.extend_from_slice(&source.spans);
290    let restored_budget = image_budget(source.budget, spans.capacity())?;
291    let batch = image::restore_image_batch_resources(
292        device,
293        queue,
294        renderer_identity,
295        image,
296        &source.batch,
297        restored_budget,
298    )?;
299    Ok(GlyphBatch2d {
300        batch,
301        spans,
302        placement_count: source.placement_count,
303        budget: source.budget,
304    })
305}
306
307fn span_bytes(count: usize) -> usize {
308    count.saturating_mul(std::mem::size_of::<GlyphBatchSpan>())
309}
310
311fn reserve_spans(count: usize) -> Result<Vec<GlyphBatchSpan>, GlyphError> {
312    let mut spans = Vec::new();
313    spans
314        .try_reserve_exact(count)
315        .map_err(|_| GlyphError::AllocationFailed {
316            requested_bytes: span_bytes(count),
317        })?;
318    Ok(spans)
319}
320
321fn placed_sprite(
322    sprite: ImageSprite2d,
323    placement: ImageBatchPlacement,
324) -> Result<ImageSprite2d, GlyphError> {
325    let sprite = translated_sprite(sprite, placement)?;
326    if !image::logical_image_region_is_portable(sprite.destination()) {
327        return Err(GlyphError::InvalidGlyph);
328    }
329    Ok(sprite)
330}
331
332// The shared image updater performs the exact portable-coordinate proof once,
333// before publication. Its second iterator traversal only needs this inexpensive
334// transformation; do not repeat the interval proof during instance emission.
335fn translated_sprite(
336    sprite: ImageSprite2d,
337    placement: ImageBatchPlacement,
338) -> Result<ImageSprite2d, GlyphError> {
339    let origin = sprite.destination().origin().to_vec2() + placement.translation().to_vec2();
340    let destination = LogicalViewportRegion::new(
341        LogicalScreenPosition::from_vec2(origin),
342        sprite.destination().viewport(),
343    )
344    .map_err(|_| GlyphError::InvalidGlyph)?;
345    let first = sprite.tint().to_array();
346    let second = placement.tint().to_array();
347    Ok(ImageSprite2d::new(
348        sprite.source(),
349        destination,
350        Color::rgba(
351            first[0] * second[0],
352            first[1] * second[1],
353            first[2] * second[2],
354            first[3] * second[3],
355        ),
356    )?)
357}
358
359fn validate_placements(
360    image: &super::Image2d,
361    placements: &[GlyphRunPlacement2d<'_>],
362    budget: GlyphBatchBudget,
363) -> Result<(usize, usize), GlyphError> {
364    if placements.len() > budget.max_placements {
365        return Err(GlyphError::EntryBudgetExceeded {
366            limit: budget.max_placements,
367            actual: placements.len(),
368        });
369    }
370    let mut glyphs = 0_usize;
371    let mut spans = 0;
372    let mut previous_clip = None;
373    for entry in placements {
374        image::validate_batch_image(image, &entry.run.batch)?;
375        glyphs =
376            glyphs
377                .checked_add(entry.run.glyph_count())
378                .ok_or(GlyphError::EntryBudgetExceeded {
379                    limit: budget.max_glyphs,
380                    actual: usize::MAX,
381                })?;
382        if glyphs > budget.max_glyphs {
383            return Err(GlyphError::EntryBudgetExceeded {
384                limit: budget.max_glyphs,
385                actual: glyphs,
386            });
387        }
388        if entry.run.glyph_count() != 0 {
389            if previous_clip != Some(entry.clip) {
390                spans += 1;
391            }
392            previous_clip = Some(entry.clip);
393        }
394    }
395    Ok((glyphs, spans))
396}
397
398fn image_budget(
399    budget: GlyphBatchBudget,
400    span_capacity: usize,
401) -> Result<ImageBatchBudget, GlyphError> {
402    let remaining = budget
403        .max_retained_bytes
404        .checked_sub(span_bytes(span_capacity))
405        .ok_or(GlyphError::MetadataBudgetExceeded {
406            limit: budget.max_retained_bytes,
407            actual: span_bytes(span_capacity),
408        })?;
409    if remaining < ImageBatchBudget::RETAINED_BYTES_PER_SPRITE {
410        return Err(GlyphError::MetadataBudgetExceeded {
411            limit: budget.max_retained_bytes,
412            actual: span_bytes(span_capacity)
413                .saturating_add(ImageBatchBudget::RETAINED_BYTES_PER_SPRITE),
414        });
415    }
416    Ok(ImageBatchBudget::new(budget.max_glyphs, remaining)?)
417}
418
419fn fill_spans(spans: &mut Vec<GlyphBatchSpan>, placements: &[GlyphRunPlacement2d<'_>]) {
420    spans.clear();
421    let mut first = 0_u32;
422    for entry in placements {
423        let count = entry.run.glyph_count() as u32;
424        if count == 0 {
425            continue;
426        }
427        let end = first + count;
428        if let Some(last) = spans.last_mut()
429            && last.clip == entry.clip
430        {
431            last.end = end;
432        } else {
433            spans.push(GlyphBatchSpan {
434                first,
435                end,
436                clip: entry.clip,
437            });
438        }
439        first = end;
440    }
441}
442
443fn create_resources(
444    device: &wgpu::Device,
445    queue: &wgpu::Queue,
446    renderer_identity: std::sync::Arc<()>,
447    image: &super::Image2d,
448    placements: &[GlyphRunPlacement2d<'_>],
449    budget: GlyphBatchBudget,
450) -> Result<GlyphBatch2d, GlyphError> {
451    let (count, span_count) = validate_placements(image, placements, budget)?;
452    image::preflight_image_batch_capacity(device, count, image_budget(budget, span_count)?)?;
453    let mut spans = reserve_spans(span_count)?;
454    let image_budget = image_budget(budget, spans.capacity())?;
455    image::preflight_image_batch_capacity(device, count, image_budget)?;
456    let mut sprites = Vec::new();
457    sprites
458        .try_reserve_exact(count)
459        .map_err(|_| GlyphError::AllocationFailed {
460            requested_bytes: count.saturating_mul(std::mem::size_of::<ImageSprite2d>()),
461        })?;
462    for entry in placements {
463        for sprite in entry.run.batch.sprites() {
464            sprites.push(placed_sprite(*sprite, entry.placement)?);
465        }
466    }
467    let batch = image::create_image_batch_resources(
468        device,
469        queue,
470        renderer_identity,
471        image,
472        sprites,
473        image_budget,
474    )?;
475    fill_spans(&mut spans, placements);
476    Ok(GlyphBatch2d {
477        batch,
478        spans,
479        placement_count: placements.len(),
480        budget,
481    })
482}
483
484fn update_resources(
485    device: &wgpu::Device,
486    queue: &wgpu::Queue,
487    image: &super::Image2d,
488    batch: &mut GlyphBatch2d,
489    placements: &[GlyphRunPlacement2d<'_>],
490) -> Result<GlyphBatchUploadReport, GlyphError> {
491    image::validate_batch_image(image, &batch.batch)?;
492    let (count, span_count) = validate_placements(image, placements, batch.budget)?;
493    image::preflight_image_batch_capacity(device, count, image_budget(batch.budget, span_count)?)?;
494    let old_span_bytes = span_bytes(batch.spans.capacity());
495    let replacement = (span_count > batch.spans.capacity())
496        .then(|| reserve_spans(span_count))
497        .transpose()?;
498    let span_capacity = replacement
499        .as_ref()
500        .map_or(batch.spans.capacity(), Vec::capacity);
501    let budget = image_budget(batch.budget, span_capacity)?;
502    // The common updater validates each transformed sprite exactly once, and
503    // verifies the full count before any publication. A failed transformation
504    // removes an entry here, so count validation rejects the entire update.
505    let sprites = placements.iter().flat_map(|entry| {
506        entry
507            .run
508            .batch
509            .sprites()
510            .iter()
511            .filter_map(move |sprite| translated_sprite(*sprite, entry.placement).ok())
512    });
513    let instances = image::update_image_batch_resources(
514        device,
515        queue,
516        image,
517        &mut batch.batch,
518        sprites,
519        count,
520        budget,
521    )
522    .map_err(|error| match error {
523        super::ImageError::InvalidSprite => GlyphError::InvalidGlyph,
524        error => GlyphError::Image(error),
525    })?;
526    let peak_retained_bytes = instances
527        .peak_retained_bytes()
528        .saturating_add(old_span_bytes)
529        .saturating_add(if replacement.is_some() {
530            span_bytes(span_capacity)
531        } else {
532            0
533        });
534    if let Some(spans) = replacement {
535        batch.spans = spans;
536    }
537    fill_spans(&mut batch.spans, placements);
538    batch.placement_count = placements.len();
539    Ok(GlyphBatchUploadReport {
540        instances,
541        placements: placements.len(),
542        draws: batch.spans.len(),
543        retained_bytes: batch.recovery_memory_bytes(),
544        peak_retained_bytes,
545    })
546}