From a678c8148d26f205e6fdb7d6684053bcf87c8641 Mon Sep 17 00:00:00 2001 From: meehl <12648828+meehl@users.noreply.github.com> Date: Wed, 26 Aug 2026 14:41:32 +0200 Subject: [PATCH] Clean up glyph rasterization --- src/dpi.rs | 1 - src/fonts.rs | 13 ++-- src/fonts/atlas.rs | 29 ++++++- src/fonts/glyph_key.rs | 24 +++--- src/fonts/layout.rs | 4 +- src/fonts/rasterizer.rs | 165 +++++++++++++++------------------------- 6 files changed, 114 insertions(+), 122 deletions(-) diff --git a/src/dpi.rs b/src/dpi.rs index 31a7377..2f8f453 100644 --- a/src/dpi.rs +++ b/src/dpi.rs @@ -4,7 +4,6 @@ pub struct LogicalScreenSpace; pub struct PhysicalScreenSpace; pub type LogicalPoint = Point; -pub type LogicalVector = Vector; pub type LogicalSize = Size; pub type LogicalRect = Rect; pub type LogicalQuad = Quad; diff --git a/src/fonts.rs b/src/fonts.rs index 1104ca0..4e795c8 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -1,9 +1,12 @@ use crate::{ color::Srgba, - dpi::{LogicalVector, ScaleFactor}, + dpi::ScaleFactor, fonts::{ - atlas::FontAtlas, glyph_key::SubpixelBin, layout::PositionedGlyph, - layout_cache::LayoutCache, rasterizer::GlyphRasterizer, + atlas::FontAtlas, + glyph_key::SubpixelBin, + layout::{LayoutVector, PositionedGlyph}, + layout_cache::LayoutCache, + rasterizer::GlyphRasterizer, }, renderer::image::ImageDelta, util::calculate_hash, @@ -176,7 +179,7 @@ impl Fonts { .rasterize_glyph_run( &mut self.atlas, &run, - LogicalVector::new(horizontal_offset, 0.0), + LayoutVector::new(horizontal_offset, 0.0), ScaleFactor::identity(), ) .for_each(|_| {}); @@ -228,7 +231,7 @@ impl Fonts { parley_layout.break_all_lines(None); // extra offset applied to each glyph to get position relative to layout origin - let mut glyph_offset = LogicalVector::new(0.0, 0.0); + let mut glyph_offset = LayoutVector::new(0.0, 0.0); if let Some(alignment) = job.alignment { let alignment = match alignment { Alignment::Min => parley::Alignment::Start, diff --git a/src/fonts/atlas.rs b/src/fonts/atlas.rs index 2076ef0..ca4effe 100644 --- a/src/fonts/atlas.rs +++ b/src/fonts/atlas.rs @@ -2,6 +2,7 @@ use std::num::NonZeroU32; use crate::{ color::Srgba, + dpi::PhysicalSize, math::{Point, Rect, Scale, Size}, renderer::{ image::{DataOrder, ImageData, ImageDelta}, @@ -74,7 +75,7 @@ impl FontAtlas { } /// Allocates a new glyph - pub fn allocate(&mut self, requested_size: FontAtlasSize) -> AllocatedGlyph<'_> { + fn allocate(&mut self, requested_size: FontAtlasSize) -> AllocatedGlyph<'_> { const PADDING: u32 = 1; let mut idx = self.layers.len() - 1; @@ -150,4 +151,30 @@ impl FontAtlas { TextureOptions::LINEAR, )) } + + pub fn write_mask( + &mut self, + image: &swash::scale::image::Image, + ) -> (PhysicalSize, UvRect, u32) { + debug_assert!(matches!(image.content, swash::scale::image::Content::Mask)); + + let size = Size::new(image.placement.width, image.placement.height); + let mut allocation = self.allocate(size); + + let mut i = 0; + for y in 0..size.height { + for x in 0..size.width { + let a = image.data[i]; + // SAFETY: allocated atlas region and swash image have the same size + unsafe { + allocation + .sub_image + .unsafe_put_pixel(x, y, Srgba::new(255, 255, 255, a).into()) + }; + i += 1; + } + } + + (size.cast_unit(), allocation.uv, allocation.layer_idx) + } } diff --git a/src/fonts/glyph_key.rs b/src/fonts/glyph_key.rs index fcdb94b..d045859 100644 --- a/src/fonts/glyph_key.rs +++ b/src/fonts/glyph_key.rs @@ -1,7 +1,9 @@ use ordered_float::OrderedFloat; -use parley::Glyph; -use crate::{dpi::PhysicalPoint, fonts::style_cache::StyleId}; +use crate::{ + dpi::PhysicalPoint, + fonts::{layout::LayoutPoint, style_cache::StyleId}, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct GlyphKey { @@ -12,25 +14,25 @@ pub struct GlyphKey { } impl GlyphKey { - pub fn from_glyph( - glyph: &Glyph, + pub fn from_position( + position: LayoutPoint, + glyph_id: u32, style_id: StyleId, scale_factor: f32, ) -> (Self, PhysicalPoint) { - // Use subpixel binning for x coordinate - let (x, x_bin) = SubpixelBin::<4>::new(glyph.x * scale_factor); - // No binning for y coordinate, just rounding - let y = (glyph.y * scale_factor).round() as i32; - let glyph_pos = PhysicalPoint::new(x, y); + // x: use subpixel binning so bitmap encodes sub-pixel position + let (x, x_bin) = SubpixelBin::<4>::new(position.x * scale_factor); + // y: just rounded. not much benefit from sub-pixel vertical positioning + let y = (position.y * scale_factor).round() as i32; ( Self { - glyph_id: glyph.id as u16, + glyph_id: glyph_id as u16, style_id, x_bin, scale_factor: OrderedFloat(scale_factor), }, - glyph_pos, + PhysicalPoint::new(x, y), ) } diff --git a/src/fonts/layout.rs b/src/fonts/layout.rs index c622079..2e6e223 100644 --- a/src/fonts/layout.rs +++ b/src/fonts/layout.rs @@ -1,7 +1,7 @@ use crate::{ color::Srgba, dpi::{LogicalPoint, LogicalScreenSpace}, - math::{Rect, Translation}, + math::{Point, Rect, Translation, Vector}, uv::UvRect, }; use ordered_float::OrderedFloat; @@ -10,6 +10,8 @@ use parley::{FontFamily, FontFamilyName}; // All coordinates relative to layout origin pub struct LayoutSpace; +pub type LayoutPoint = Point; +pub type LayoutVector = Vector; pub type LayoutRect = Rect; pub type LayoutToLogical = Translation; diff --git a/src/fonts/rasterizer.rs b/src/fonts/rasterizer.rs index fb48707..4db48b6 100644 --- a/src/fonts/rasterizer.rs +++ b/src/fonts/rasterizer.rs @@ -1,12 +1,15 @@ use crate::{ color::Srgba, - dpi::{LogicalVector, PhysicalPoint, PhysicalRect, PhysicalSize, PhysicalVector, ScaleFactor}, - fonts::{atlas::FontAtlas, glyph_key::GlyphKey, layout::LayoutRect, style_cache::StyleCache}, - math::Size, + dpi::{PhysicalRect, PhysicalSize, PhysicalVector, ScaleFactor}, + fonts::{ + atlas::FontAtlas, + glyph_key::GlyphKey, + layout::{LayoutPoint, LayoutRect, LayoutVector}, + style_cache::StyleCache, + }, uv::UvRect, }; use ahash::HashMap; -use image::GenericImage; use parley::{FontData, GlyphRun}; use swash::zeno; @@ -32,33 +35,12 @@ pub struct RasterizedGlyph { pub color: Srgba, } -impl RasterizedGlyph { - fn from_cached( - cached: CachedGlyph, - position: PhysicalPoint, - color: Srgba, - scale_factor: ScaleFactor, - ) -> Self { - let glyph_rect = PhysicalRect::from_origin_and_size( - position + cached.baseline_offset, - cached.size.cast(), - ); - - RasterizedGlyph { - rect: (glyph_rect.cast() / scale_factor).cast_unit(), - uv: cached.uv, - texture_layer_idx: cached.texture_layer_idx, - color, - } - } -} - pub struct GlyphRasterizer { scale_context: swash::scale::ScaleContext, swash_keys: HashMap<(FontBlobId, FontIndex), (SwashFontOffset, swash::CacheKey)>, style_cache: StyleCache, cached_glyphs: HashMap>, - // scratch image buffer used to write bitmap data into + /// Scratch image buffer used to temporarily write bitmap data into scratch: swash::scale::image::Image, } @@ -93,14 +75,14 @@ impl GlyphRasterizer { } } - /// Rasterizes glyph run and returns the placement and UV for each glyph. - /// Can return `None` if glyph doesn't take up any space (e.g. whitespace). + /// Rasterizes a glyph run and returns the placement and UV for each glyph. + /// Returns `None` for glyphs that doesn't take up visible space (e.g. whitespace). pub fn rasterize_glyph_run<'slf: 'run, 'run, 'atlas>( &'slf mut self, atlas: &'atlas mut FontAtlas, glyph_run: &'run GlyphRun<'_, Srgba>, // additional offset relative to layout origin - glyph_offset: LogicalVector, + layout_offset: LayoutVector, scale_factor: ScaleFactor, ) -> impl Iterator> + use<'slf, 'run, 'atlas> { let run = glyph_run.run(); @@ -128,91 +110,68 @@ impl GlyphRasterizer { let image = &mut self.scratch; let cached_glyphs = &mut self.cached_glyphs; - glyph_run.positioned_glyphs().map(move |mut glyph| { - glyph.x += glyph_offset.x; - glyph.y += glyph_offset.y; - let (glyph_key, glyph_pos) = GlyphKey::from_glyph(&glyph, style_id, scale_factor.get()); + glyph_run.positioned_glyphs().map(move |glyph| { + let layout_position = LayoutPoint::new(glyph.x, glyph.y) + layout_offset; - if let Some(cached_glyph) = cached_glyphs.get(&glyph_key) { - return cached_glyph.map(|cached| { - RasterizedGlyph::from_cached(cached, glyph_pos, color, scale_factor) - }); - } + let (glyph_key, pixel_position) = + GlyphKey::from_position(layout_position, glyph.id, style_id, scale_factor.get()); - let fract_offset = glyph_key.get_fractional_offset(); + let cached = *cached_glyphs.entry(glyph_key).or_insert_with(|| { + rasterize_glyph(&mut scaler, image, atlas, glyph.id, &glyph_key, skew) + }); - image.clear(); - let did_render = swash::scale::Render::new(&[ - swash::scale::Source::ColorOutline(0), - swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit), - swash::scale::Source::Outline, - ]) - .format(zeno::Format::Alpha) - .transform(skew.map(|skew| { - zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO) - })) - .offset(fract_offset) - .render_into(&mut scaler, glyph.id as u16, image); + cached.map(|cached| { + // apply the baseline offset to get the actual bitmap position + let bitmap_top_left = pixel_position + cached.baseline_offset; + let physical_rect = + PhysicalRect::from_origin_and_size(bitmap_top_left, cached.size.cast()); - if !did_render || image.placement.width == 0 || image.placement.height == 0 { - cached_glyphs.insert(glyph_key, None); - return None; - }; - - let (glyph_size, atlas_uv, atlas_layer_idx) = write_to_atlas(image, atlas); - - let cached_glyph = CachedGlyph { - size: glyph_size, - uv: atlas_uv, - texture_layer_idx: atlas_layer_idx, - // swash uses `Origin::BottomLeft` so we need to negate the vertical component - baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top), - }; - cached_glyphs.insert(glyph_key, Some(cached_glyph)); - - Some(RasterizedGlyph::from_cached( - cached_glyph, - glyph_pos, - color, - scale_factor, - )) + RasterizedGlyph { + rect: (physical_rect.cast() / scale_factor).cast_unit(), + uv: cached.uv, + texture_layer_idx: cached.texture_layer_idx, + color, + } + }) }) } } -/// Writes rasterized glyph to atlas and returns the UV coordinates of it -fn write_to_atlas( - image: &swash::scale::image::Image, +/// Renders glyph's bitmap into the atlas +fn rasterize_glyph( + scaler: &mut swash::scale::Scaler, + image: &mut swash::scale::image::Image, atlas: &mut FontAtlas, -) -> (PhysicalSize, UvRect, u32) { - let size = Size::new(image.placement.width, image.placement.height); - let mut allocated_glyph = atlas.allocate(size); + glyph_id: u32, + glyph_key: &GlyphKey, + skew: Option, +) -> Option { + image.clear(); - match image.content { - swash::scale::image::Content::Mask => { - let mut i = 0; - for y in 0..image.placement.height { - for x in 0..image.placement.width { - let a = image.data[i]; - // SAFETY: allocated atlas region and swash image have the same size - unsafe { - allocated_glyph.sub_image.unsafe_put_pixel( - x, - y, - Srgba::new(255, 255, 255, a).into(), - ) - }; - i += 1; - } - } - } - _ => unreachable!(), + let did_render = swash::scale::Render::new(&[ + swash::scale::Source::ColorOutline(0), + swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit), + swash::scale::Source::Outline, + ]) + .format(zeno::Format::Alpha) + .transform( + skew.map(|skew| zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)), + ) + .offset(glyph_key.get_fractional_offset()) + .render_into(scaler, glyph_id as u16, image); + + if !did_render || image.placement.width == 0 || image.placement.height == 0 { + return None; }; - ( - size.cast_unit(), - allocated_glyph.uv, - allocated_glyph.layer_idx, - ) + let (size, uv, layer_idx) = atlas.write_mask(image); + + Some(CachedGlyph { + size, + uv, + texture_layer_idx: layer_idx, + // swash uses `Origin::BottomLeft` so we need to negate the vertical component + baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top), + }) }