From e20a28fef71e1b9f5da6c20bbc503dea85afc85f Mon Sep 17 00:00:00 2001 From: meehl <12648828+meehl@users.noreply.github.com> Date: Sat, 15 Aug 2026 10:42:03 +0200 Subject: [PATCH] Use layered font atlas. Add layers instead of growing in height as more and more glyphs are added. This allows us to return normalized UV coordinates since the dimensions of each layer stay the same. --- src/app.rs | 3 - src/fonts.rs | 22 +---- src/fonts/atlas.rs | 190 +++++++++++++++++++----------------- src/fonts/rasterizer.rs | 59 ++++++----- src/renderer/tessellator.rs | 11 +-- 5 files changed, 136 insertions(+), 149 deletions(-) diff --git a/src/app.rs b/src/app.rs index d7a075b..67acd61 100644 --- a/src/app.rs +++ b/src/app.rs @@ -102,8 +102,6 @@ impl App { let mode_output = self.current_mode.frame(&mut self.state)?; - let font_atlas_size = self.state.fonts.font_atlas().size(); - if let Some(font_image_delta) = self.state.fonts.font_atlas_delta() { self.state .texture_manager @@ -118,7 +116,6 @@ impl App { } else { let meshes = self.tessellator.convert_clipped_primitives( mode_output.primitives, - font_atlas_size, self.state.window.scale_factor(), ); diff --git a/src/fonts.rs b/src/fonts.rs index 1be51ef..54a9f94 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -15,7 +15,6 @@ use parley::{ }; use std::sync::Arc; -pub use atlas::FontAtlasSize; pub use layout::{Alignment, FontStyle, Layout, LayoutJob}; mod atlas; @@ -64,7 +63,7 @@ impl Fonts { definitions, font_context: FontContext::new(), layout_context: LayoutContext::new(), - atlas: FontAtlas::new(1024), + atlas: FontAtlas::new(1024, 1024), glyph_rasterizer: GlyphRasterizer::new(), layout_cache: LayoutCache::default(), }; @@ -96,10 +95,6 @@ impl Fonts { /// Needs to be called at beginning of each frame. pub fn begin_frame(&mut self) { - // recreate atlas when it becomes too full or overflowed - if self.atlas.capacity() > 0.9 { - self.clear_atlas(); - } self.layout_cache.flush(); } @@ -187,10 +182,6 @@ impl Fonts { } } - pub fn font_atlas(&self) -> &FontAtlas { - &self.atlas - } - pub fn layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Arc { let hash = calculate_hash(&(&job, OrderedFloat(pixels_per_point))); @@ -288,13 +279,6 @@ impl Fonts { layout } - /// Clear atlas and invalidate caches depend on atlas state - fn clear_atlas(&mut self) { - self.atlas.clear(); - self.glyph_rasterizer.clear(); - self.layout_cache.clear(); - } - /// Width of laid out text pub fn get_text_width(&mut self, job: LayoutJob, pixels_per_point: f32) -> i32 { let layout = self.layout(job, pixels_per_point); @@ -352,8 +336,4 @@ impl LayoutCache { .retain(|_key, cached| cached.generation == self.current_generation); self.current_generation = self.current_generation.wrapping_add(1); } - - pub fn clear(&mut self) { - self.cache.clear(); - } } diff --git a/src/fonts/atlas.rs b/src/fonts/atlas.rs index 337ad16..4d034bb 100644 --- a/src/fonts/atlas.rs +++ b/src/fonts/atlas.rs @@ -1,137 +1,149 @@ +use std::num::NonZeroU32; + use crate::{ color::Srgba, - math::{Point, Rect, Size}, + dpi::{Normalize, NormalizedRect}, + math::{Point, Size}, renderer::{ - image::{ImageData, ImageDelta}, + image::{DataOrder, ImageData, ImageDelta}, textures::TextureOptions, }, }; -use image::{GenericImage, RgbaImage, SubImage, imageops}; +use image::{GenericImage, RgbaImage, SubImage}; pub struct FontAtlasSpace; pub type FontAtlasPoint = Point; pub type FontAtlasSize = Size; -pub type FontAtlasRect = Rect; -pub struct FontAtlas { - // max width/height of atlas texture - max_texture_side: u32, +pub struct AllocatedGlyph<'a> { + pub sub_image: SubImage<&'a mut RgbaImage>, + pub layer_idx: u32, + pub uv: NormalizedRect, +} + +struct Layer { image: RgbaImage, // position of next allocation cursor: FontAtlasPoint, current_row_height: u32, +} + +pub struct FontAtlas { + layer_size: FontAtlasSize, + // maximum amount of layers + max_layers: u32, + layers: Vec, // atlas has been altered and needs to be reuploaded to the GPU - // TODO: only mark changed region as dirty and perform partial texture update + // TODO: only mark changed regions as dirty and perform partial texture update dirty: bool, - // atlas has overflowed and needs to be recreated - overflowed: bool, } impl FontAtlas { - pub fn new(max_texture_side: u32) -> Self { - // start out with maximum width and let height grow as needed - let width = max_texture_side; - let initial_height = 256; - + pub fn new(layer_size: u32, max_layers: u32) -> Self { let mut atlas = Self { - max_texture_side, - image: RgbaImage::new(width, initial_height), - cursor: FontAtlasPoint::zero(), - current_row_height: 0, + layer_size: Size::new(layer_size, layer_size), + max_layers, + layers: Vec::new(), dirty: false, - overflowed: false, }; + atlas.push_layer(); atlas.initialize(); atlas } - fn initialize(&mut self) { - // Puts white pixel at (0, 0). - // NOTE: Rendering a solid color shape is done by setting the texture to - // the font atlas and sampling the white pixel at (0, 0). - let mut sub_image = self.allocate(FontAtlasSize::new(1, 1)); - sub_image.put_pixel(0, 0, Srgba::WHITE.into()); + /// Adds a new empty layer + fn push_layer(&mut self) { + self.layers.push(Layer { + image: RgbaImage::new(self.layer_size.width, self.layer_size.height), + cursor: FontAtlasPoint::zero(), + current_row_height: 0, + }); } - // TODO: use an actual bin packing algorithm for tighter packing - /// Returns a mutable view into the atlas of given size. - pub fn allocate(&mut self, size: FontAtlasSize) -> SubImage<&mut RgbaImage> { + /// Initializes the atlas. + /// + /// Puts a white pixel at (0, 0) of layer 0 for solid color texturing. + fn initialize(&mut self) { + let mut allocation = self.allocate(FontAtlasSize::new(1, 1)); + allocation.sub_image.put_pixel(0, 0, Srgba::WHITE.into()); + } + + /// Allocates a new glyph + pub fn allocate(&mut self, requested_size: FontAtlasSize) -> AllocatedGlyph<'_> { const PADDING: u32 = 1; - if self.cursor.x + size.width > self.image.width() { - self.cursor.x = 0; - self.cursor.y += self.current_row_height + PADDING; - self.current_row_height = 0; - } + let mut idx = self.layers.len() - 1; - self.current_row_height = self.current_row_height.max(size.height); + { + let layer = &mut self.layers[idx]; - let required_atlas_height = self.cursor.y + self.current_row_height; - if required_atlas_height > self.max_texture_side { - log::warn!("font atlas overflowed!"); - // start overwriting old glyphs - self.cursor = Point::new(0, self.image.height() / 3); - // setting this flag causes atlas to be recreated next frame - self.overflowed = true; - } else if required_atlas_height > self.image().height() { - // increase height - let mut new_height = self.image.height(); - while new_height < required_atlas_height { - new_height *= 2; + // start new row if new allocation doesn't fit current row + if layer.cursor.x + requested_size.width > self.layer_size.width { + layer.cursor.x = 0; + layer.cursor.y += layer.current_row_height + PADDING; + layer.current_row_height = 0; + } + + // add or evict layer if new allocation doesn't fit on this layer + if layer.cursor.y + requested_size.height > self.layer_size.height { + if (self.layers.len() as u32) < self.max_layers { + self.push_layer(); + idx = self.layers.len() - 1; + } else { + // just choose a sufficiently large layer size and count to + // avoid panic. a more sophisticated approach can be implemented + // later if needed + panic!("font atlas reached maximum size!"); + } } - self.image = extend_image_height(&self.image, new_height, Srgba::TRANSPARENT); } - let pos = self.cursor; - self.cursor.x += size.width + PADDING; - + let layer = &mut self.layers[idx]; + layer.current_row_height = layer.current_row_height.max(requested_size.height); + let pos = layer.cursor; + layer.cursor.x += requested_size.width + PADDING; self.dirty = true; - self.image.sub_image(pos.x, pos.y, size.width, size.height) + AllocatedGlyph { + sub_image: layer.image.sub_image( + pos.x, + pos.y, + requested_size.width, + requested_size.height, + ), + layer_idx: idx as u32, + uv: NormalizedRect::new( + pos.normalize(self.layer_size), + (pos + requested_size.to_vector()).normalize(self.layer_size), + ), + } } pub fn take_delta(&mut self) -> Option { - let dirty = std::mem::replace(&mut self.dirty, false); - if dirty { - Some(ImageDelta::new( - ImageData::from(self.image.clone()), - TextureOptions::LINEAR, - )) - } else { - None + if !std::mem::replace(&mut self.dirty, false) { + return None; } - } - pub fn capacity(&self) -> f32 { - if self.overflowed { - 1.0 - } else { - (self.cursor.y + self.current_row_height) as f32 / self.max_texture_side as f32 + let mut bytes = Vec::with_capacity( + self.layers.len() * (self.layer_size.width * self.layer_size.height * 4) as usize, + ); + + for layer in &self.layers { + bytes.extend_from_slice(layer.image.as_raw()); } - } - pub fn clear(&mut self) { - self.image.fill(0); - self.cursor = FontAtlasPoint::zero(); - self.current_row_height = 0; - self.dirty = false; - self.overflowed = false; - self.initialize(); - } - - pub fn image(&self) -> &RgbaImage { - &self.image - } - - pub fn size(&self) -> FontAtlasSize { - FontAtlasSize::new(self.image.width(), self.image.height()) + Some(ImageDelta::new( + ImageData { + format: wgpu::TextureFormat::Rgba8Unorm, + width: self.layer_size.width, + height: self.layer_size.height, + array_layers: self.layers.len() as u32, + mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"), + data_order: DataOrder::default(), + bytes, + }, + TextureOptions::LINEAR, + )) } } - -fn extend_image_height(image: &RgbaImage, new_height: u32, fill_color: Srgba) -> RgbaImage { - let width = image.width(); - let mut extended_image = RgbaImage::from_pixel(width, new_height, fill_color.into()); - imageops::overlay(&mut extended_image, image, 0, 0); - extended_image -} diff --git a/src/fonts/rasterizer.rs b/src/fonts/rasterizer.rs index 48452a6..e9543a7 100644 --- a/src/fonts/rasterizer.rs +++ b/src/fonts/rasterizer.rs @@ -1,13 +1,11 @@ use crate::{ color::Srgba, dpi::{ - ConvertToLogical, LogicalRect, LogicalVector, PhysicalPoint, PhysicalRect, PhysicalVector, + ConvertToLogical, LogicalRect, LogicalVector, NormalizedRect, PhysicalPoint, PhysicalRect, + PhysicalVector, }, - fonts::{ - atlas::{FontAtlas, FontAtlasRect}, - glyph_key::GlyphKey, - }, - math::{Point, Size}, + fonts::{atlas::FontAtlas, glyph_key::GlyphKey}, + math::Size, }; use ahash::HashMap; use image::GenericImage; @@ -51,10 +49,11 @@ impl<'a> StyleKey<'a> { } } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub struct CachedGlyph { - // absolute uv rect within font atlas - pub uv: FontAtlasRect, + pub rect: PhysicalRect, + pub uv: NormalizedRect, + pub texture_layer_idx: u32, // offset from top/left to baseline pub baseline_offset: PhysicalVector, } @@ -62,7 +61,8 @@ pub struct CachedGlyph { pub struct RasterizedGlyph { // NOTE: this is relative to the layout origin pub rect: LogicalRect, - pub uv: FontAtlasRect, + pub uv: NormalizedRect, + pub texture_layer_idx: u32, pub color: Srgba, } @@ -75,12 +75,13 @@ impl RasterizedGlyph { ) -> Self { let glyph_rect = PhysicalRect::from_origin_and_size( position + cached.baseline_offset, - cached.uv.cast_unit().cast().size(), + cached.rect.cast().size(), ); RasterizedGlyph { rect: glyph_rect.to_logical(pixels_per_point), uv: cached.uv, + texture_layer_idx: cached.texture_layer_idx, color, } } @@ -111,13 +112,6 @@ impl GlyphRasterizer { } } - pub fn clear(&mut self) { - self.swash_keys.clear(); - self.style_ids.clear(); - self.next_style_id = 0; - self.cached_glyphs.clear(); - } - /// Gets a [`swash::FontRef`] from [`FontData`] fn get_font_ref<'a>(&mut self, font: &'a FontData) -> swash::FontRef<'a> { let font_blob_id = font.data.id(); @@ -226,10 +220,12 @@ impl GlyphRasterizer { return None; }; - let atlas_region = write_to_atlas(image, atlas); + let (glyph_rect, atlas_uv, atlas_layer_idx) = write_to_atlas(image, atlas); let cached_glyph = CachedGlyph { - uv: atlas_region, + rect: glyph_rect, + uv: atlas_uv, + texture_layer_idx: atlas_layer_idx, baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top), }; cached_glyphs.insert(glyph_key, Some(cached_glyph)); @@ -244,9 +240,13 @@ impl GlyphRasterizer { } } -/// Writes rasterized glyph to atlas and returns region it wrote into -fn write_to_atlas(image: &swash::scale::image::Image, atlas: &mut FontAtlas) -> FontAtlasRect { - let mut atlas_region = atlas.allocate(Size::new(image.placement.width, image.placement.height)); +/// Writes rasterized glyph to atlas and returns the UV coordinates of it +fn write_to_atlas( + image: &swash::scale::image::Image, + atlas: &mut FontAtlas, +) -> (PhysicalRect, NormalizedRect, u32) { + let mut allocated_glyph = + atlas.allocate(Size::new(image.placement.width, image.placement.height)); match image.content { swash::scale::image::Content::Mask => { @@ -256,7 +256,11 @@ fn write_to_atlas(image: &swash::scale::image::Image, atlas: &mut FontAtlas) -> let a = image.data[i]; // SAFETY: allocated atlas region and swash image have the same size unsafe { - atlas_region.unsafe_put_pixel(x, y, Srgba::new(255, 255, 255, a).into()) + allocated_glyph.sub_image.unsafe_put_pixel( + x, + y, + Srgba::new(255, 255, 255, a).into(), + ) }; i += 1; } @@ -265,8 +269,9 @@ fn write_to_atlas(image: &swash::scale::image::Image, atlas: &mut FontAtlas) -> _ => unreachable!(), }; - FontAtlasRect::from_origin_and_size( - Point::new(atlas_region.offsets().0, atlas_region.offsets().1), - Size::new(image.placement.width, image.placement.height), + ( + PhysicalRect::from_size(Size::new(image.placement.width, image.placement.height)), + allocated_glyph.uv, + allocated_glyph.layer_idx, ) } diff --git a/src/renderer/tessellator.rs b/src/renderer/tessellator.rs index debb9ac..2cac38d 100644 --- a/src/renderer/tessellator.rs +++ b/src/renderer/tessellator.rs @@ -1,6 +1,5 @@ use crate::{ - dpi::{ConvertToLogical, ConvertToPhysical, Normalize, NormalizedQuad, NormalizedRect, Uv}, - fonts::FontAtlasSize, + dpi::{ConvertToLogical, ConvertToPhysical, NormalizedQuad, NormalizedRect, Uv}, renderer::{ mesh::{ClippedMesh, Mesh}, primitives::{ @@ -21,7 +20,6 @@ impl Tessellator { pub fn convert_clipped_primitives( &mut self, clipped_primitives: impl Iterator, - font_atlas_size: FontAtlasSize, pixels_per_point: f32, ) -> Vec { profiling::scope!("convert_primitives"); @@ -31,7 +29,6 @@ impl Tessellator { for clipped_primitive in clipped_primitives { self.convert_clipped_primitive( clipped_primitive, - font_atlas_size, pixels_per_point, &mut clipped_meshes, ); @@ -44,7 +41,6 @@ impl Tessellator { pub fn convert_clipped_primitive( &mut self, clipped_primitive: ClippedPrimitive, - font_atlas_size: FontAtlasSize, pixels_per_point: f32, out_clipped_meshes: &mut Vec, ) { @@ -83,7 +79,6 @@ impl Tessellator { DrawPrimitive::Text(text_primitive) => { self.convert_text_primitive( text_primitive, - font_atlas_size, pixels_per_point, &mut last_clipped_mesh.mesh, ); @@ -140,7 +135,6 @@ impl Tessellator { fn convert_text_primitive( &self, text_primitive: TextPrimitive, - font_atlas_size: FontAtlasSize, pixels_per_point: f32, out: &mut Mesh, ) { @@ -168,8 +162,7 @@ impl Tessellator { for row in &layout.rows { for glyph in &row.glyphs { let rect = glyph.rect.translate(layout_pos.to_vector()); - let normalized_uv = glyph.uv.normalize(font_atlas_size); - out.add_rect(rect, normalized_uv, glyph.color, 0); + out.add_rect(rect, glyph.uv, glyph.color, glyph.texture_layer_idx); } } }