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
59pub 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
108pub 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 pub const fn glyph_run(&self) -> &GlyphRun2d {
126 &self.run
127 }
128 pub fn text(&self) -> &str {
130 &self.text
131 }
132 pub const fn advance(&self) -> f32 {
134 self.advance
135 }
136 pub const fn ascent(&self) -> f32 {
138 self.ascent
139 }
140 pub const fn descent(&self) -> f32 {
142 self.descent
143 }
144 pub const fn line_height(&self) -> f32 {
146 self.line_height
147 }
148 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 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 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 pub const fn atlas(&self) -> &GlyphAtlas2d {
204 &self.atlas
205 }
206 pub const fn style(&self) -> &TextStyle {
208 &self.style
209 }
210 pub const fn font(&self) -> &FontFace {
212 &self.font
213 }
214 pub const fn budget(&self) -> TextAtlasBudget {
216 self.budget
217 }
218 pub fn cached_glyph_count(&self) -> usize {
220 self.cached.len()
221 }
222 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 pub fn gpu_allocation_bytes(&self) -> usize {
232 self.atlas.gpu_allocation_bytes()
233 }
234
235 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 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 pub fn restore(&mut self, renderer: &WgpuRenderer) -> Result<(), TextError> {
323 self.atlas = renderer.restore_glyph_atlas(&self.atlas)?;
324 Ok(())
325 }
326
327 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 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 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;