use std::collections::HashMap;
use crate::curves::Curve2;
use crate::loaders::{TtfError, TtfFont};
#[derive(Clone, Debug, Default)]
pub struct GlyphBitmap {
pub width: u32,
pub height: u32,
pub coverage: Vec<u8>,
pub offset_x: i32,
pub offset_y: i32,
pub advance: f32,
}
impl GlyphBitmap {
pub fn is_blank(&self) -> bool {
self.width == 0 || self.height == 0 || self.coverage.is_empty()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontMetrics {
pub ascent: f32,
pub descent: f32,
pub line_gap: f32,
}
impl FontMetrics {
pub fn line_height(&self) -> f32 {
self.ascent + self.descent + self.line_gap
}
}
enum Face {
Builtin,
Ttf(Box<TtfFont>),
}
pub struct CaptionFont {
face: Face,
cache: HashMap<(u32, u32, u32), GlyphBitmap>,
}
impl Default for CaptionFont {
fn default() -> Self {
Self::builtin()
}
}
impl std::fmt::Debug for CaptionFont {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CaptionFont")
.field(
"face",
&match self.face {
Face::Builtin => "builtin",
Face::Ttf(_) => "truetype",
},
)
.field("cached_glyphs", &self.cache.len())
.finish()
}
}
impl CaptionFont {
pub fn builtin() -> Self {
Self {
face: Face::Builtin,
cache: HashMap::new(),
}
}
pub fn from_ttf(font: TtfFont) -> Self {
Self {
face: Face::Ttf(Box::new(font)),
cache: HashMap::new(),
}
}
pub fn from_ttf_bytes(bytes: &[u8]) -> Result<Self, TtfError> {
Ok(Self::from_ttf(TtfFont::parse(bytes)?))
}
pub fn ui() -> Self {
Self::try_sf_compact().unwrap_or_else(Self::builtin)
}
pub fn try_sf_compact() -> Option<Self> {
#[cfg(target_os = "macos")]
{
const PATHS: &[&str] = &[
"/System/Library/Fonts/SFCompact.ttf",
"/System/Library/Fonts/SFCompactRounded.ttf",
];
for path in PATHS {
let bytes = std::fs::read(path).ok()?;
if let Ok(font) = Self::from_ttf_bytes(&bytes) {
return Some(font);
}
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = ();
}
None
}
pub fn is_builtin(&self) -> bool {
matches!(self.face, Face::Builtin)
}
pub fn clear_cache(&mut self) {
self.cache.clear();
}
pub fn metrics(&self, size: f32) -> FontMetrics {
match &self.face {
Face::Builtin => FontMetrics {
ascent: size * (BUILTIN_ASCENT_ROWS as f32 / BUILTIN_CELL as f32),
descent: size * (1.0 / BUILTIN_CELL as f32),
line_gap: 0.0,
},
Face::Ttf(font) => {
let upem = font.units_per_em.max(1) as f32;
let scale = size / upem;
if font.ascender == 0 && font.descender == 0 {
FontMetrics {
ascent: size * 0.8,
descent: size * 0.2,
line_gap: 0.0,
}
} else {
FontMetrics {
ascent: font.ascender as f32 * scale,
descent: (-(font.descender as f32)) * scale,
line_gap: font.line_gap as f32 * scale,
}
}
}
}
}
pub fn glyph(&mut self, c: char, size: f32) -> &GlyphBitmap {
self.glyph_at(c, size, 0)
}
pub fn glyph_at(&mut self, c: char, size: f32, phase: usize) -> &GlyphBitmap {
let size = size.max(1.0);
let phase = phase % SUBPIXEL_PHASES;
let key = (c as u32, (size * 4.0).round() as u32, phase as u32);
if !self.cache.contains_key(&key) {
let shift = phase as f32 / SUBPIXEL_PHASES as f32;
let bitmap = match &self.face {
Face::Builtin => raster_builtin(c, size, shift),
Face::Ttf(font) => raster_ttf(font, c, size, shift),
};
self.cache.insert(key, bitmap);
}
&self.cache[&key]
}
pub fn kerning(&self, left: char, right: char, size: f32) -> f32 {
let Face::Ttf(font) = &self.face else {
return 0.0;
};
if font.kerning.is_empty() {
return 0.0;
}
let gid = |c: char| font.cmap.get(&(c as u32)).copied().unwrap_or(0);
let units = font.kern(gid(left), gid(right));
if units == 0 {
return 0.0;
}
units as f32 * size.max(1.0) / font.units_per_em.max(1) as f32
}
pub fn has_glyph(&self, c: char) -> bool {
match &self.face {
Face::Builtin => builtin_rows(c).is_some_and(|rows| rows != TOFU),
Face::Ttf(font) => font.cmap.contains_key(&(c as u32)),
}
}
pub fn outline(&self, c: char, size: f32) -> Option<Vec<Vec<Vec<[f32; 2]>>>> {
let Face::Ttf(font) = &self.face else {
return None;
};
let gid = font.cmap.get(&(c as u32)).copied().unwrap_or(0);
let glyph = font.glyphs.get(gid as usize)?;
let scale = size.max(1.0) / font.units_per_em.max(1) as f32;
Some(flatten_curves(glyph, scale))
}
pub fn advance(&mut self, c: char, size: f32) -> f32 {
self.glyph(c, size).advance
}
pub fn measure(&mut self, text: &str, size: f32, letter_spacing: f32) -> f32 {
let mut width = 0.0;
let mut count = 0usize;
let mut previous: Option<char> = None;
for c in text.chars() {
if let Some(p) = previous {
width += self.kerning(p, c, size);
}
width += self.advance(c, size);
previous = Some(c);
count += 1;
}
if count > 1 {
width += letter_spacing * (count - 1) as f32;
}
width
}
}
pub const SUBPIXEL_PHASES: usize = 4;
const BUILTIN_CELL: u32 = 8;
const BUILTIN_ASCENT_ROWS: u32 = 7;
fn raster_builtin(c: char, size: f32, shift: f32) -> GlyphBitmap {
let scale = size / BUILTIN_CELL as f32;
let advance = BUILTIN_CELL as f32 * scale;
let rows = builtin_rows(c);
let Some(rows) = rows else {
return GlyphBitmap {
advance,
..Default::default()
};
};
if rows.iter().all(|&r| r == 0) {
return GlyphBitmap {
advance,
..Default::default()
};
}
let mut min_col = BUILTIN_CELL;
let mut max_col = 0u32;
let mut min_row = BUILTIN_CELL;
let mut max_row = 0u32;
for (y, &bits) in rows.iter().enumerate() {
if bits == 0 {
continue;
}
min_row = min_row.min(y as u32);
max_row = max_row.max(y as u32);
for x in 0..BUILTIN_CELL {
if bits & (1 << x) != 0 {
min_col = min_col.min(x);
max_col = max_col.max(x);
}
}
}
let x0 = min_col as f32 * scale + shift;
let y0 = min_row as f32 * scale;
let px0 = x0.floor() as i32;
let py0 = y0.floor() as i32;
let px1 = ((max_col + 1) as f32 * scale + shift).ceil() as i32;
let py1 = ((max_row + 1) as f32 * scale).ceil() as i32;
let width = (px1 - px0).max(1) as u32;
let height = (py1 - py0).max(1) as u32;
let mut coverage = vec![0u8; (width * height) as usize];
let overlap = |a0: f32, a1: f32, b0: f32, b1: f32| (a1.min(b1) - a0.max(b0)).max(0.0);
for (cy, &bits) in rows.iter().enumerate() {
if bits == 0 {
continue;
}
let cell_top = cy as f32 * scale;
let cell_bottom = cell_top + scale;
let first_row = ((cell_top.floor() as i32) - py0).max(0) as u32;
let last_row = (((cell_bottom.ceil() as i32) - py0).max(0) as u32).min(height);
for cx in 0..BUILTIN_CELL {
if bits & (1 << cx) == 0 {
continue;
}
let cell_left = cx as f32 * scale + shift;
let cell_right = cell_left + scale;
let first_col = ((cell_left.floor() as i32) - px0).max(0) as u32;
let last_col = (((cell_right.ceil() as i32) - px0).max(0) as u32).min(width);
for py in first_row..last_row {
let top = (py0 + py as i32) as f32;
let dy = overlap(top, top + 1.0, cell_top, cell_bottom);
if dy <= 0.0 {
continue;
}
for px in first_col..last_col {
let left = (px0 + px as i32) as f32;
let dx = overlap(left, left + 1.0, cell_left, cell_right);
if dx <= 0.0 {
continue;
}
let slot = &mut coverage[(py * width + px) as usize];
*slot = slot.saturating_add((dx * dy * 255.0).round() as u8);
}
}
}
}
GlyphBitmap {
width,
height,
coverage,
offset_x: px0,
offset_y: py0 - (BUILTIN_ASCENT_ROWS as f32 * scale).round() as i32,
advance,
}
}
fn builtin_rows(c: char) -> Option<[u8; 8]> {
let folded = fold_to_ascii(c);
let code = folded as u32;
if (0x20..=0x7E).contains(&code) {
return Some(FONT8X8[(code - 0x20) as usize]);
}
match code {
0x09 | 0x0A | 0x0D | 0xA0 => Some([0; 8]),
_ => Some(TOFU),
}
}
const TOFU: [u8; 8] = [0x00, 0x3E, 0x22, 0x22, 0x22, 0x22, 0x3E, 0x00];
fn fold_to_ascii(c: char) -> char {
match c {
'À'..='Å' => 'A',
'Æ' => 'A',
'Ç' => 'C',
'È'..='Ë' => 'E',
'Ì'..='Ï' => 'I',
'Ð' => 'D',
'Ñ' => 'N',
'Ò'..='Ö' | 'Ø' => 'O',
'Ù'..='Ü' => 'U',
'Ý' => 'Y',
'ß' => 's',
'à'..='å' => 'a',
'æ' => 'a',
'ç' => 'c',
'è'..='ë' => 'e',
'ì'..='ï' => 'i',
'ñ' => 'n',
'ò'..='ö' | 'ø' => 'o',
'ù'..='ü' => 'u',
'ý' | 'ÿ' => 'y',
'Š' => 'S',
'š' => 's',
'Ž' => 'Z',
'ž' => 'z',
'Œ' => 'O',
'œ' => 'o',
'\u{2018}' | '\u{2019}' => '\'',
'\u{201C}' | '\u{201D}' => '"',
'\u{2013}' | '\u{2014}' => '-',
'\u{2026}' => '.',
_ => c,
}
}
#[rustfmt::skip]
const FONT8X8: [[u8; 8]; 95] = [
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00], [0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00], [0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00], [0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00], [0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00], [0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00], [0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00], [0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00], [0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00], [0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06], [0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00], [0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00], [0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00], [0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00], [0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00], [0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00], [0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00], [0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00], [0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00], [0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00], [0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00], [0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00], [0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00], [0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06], [0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00], [0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00], [0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00], [0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00], [0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00], [0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00], [0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00], [0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00], [0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00], [0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00], [0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00], [0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00], [0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00], [0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], [0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00], [0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00], [0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00], [0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00], [0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00], [0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00], [0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00], [0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00], [0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00], [0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00], [0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], [0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00], [0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00], [0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00], [0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00], [0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00], [0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00], [0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00], [0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00], [0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00], [0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF], [0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00], [0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00], [0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00], [0x38, 0x30, 0x30, 0x3E, 0x33, 0x33, 0x6E, 0x00], [0x00, 0x00, 0x1E, 0x33, 0x3F, 0x03, 0x1E, 0x00], [0x1C, 0x36, 0x06, 0x0F, 0x06, 0x06, 0x0F, 0x00], [0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F], [0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00], [0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], [0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E], [0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00], [0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], [0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00], [0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00], [0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00], [0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F], [0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78], [0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00], [0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00], [0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00], [0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00], [0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00], [0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00], [0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00], [0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F], [0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00], [0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00], [0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00], [0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00], [0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], ];
const SUBSAMPLES: usize = 16;
fn raster_ttf(font: &TtfFont, c: char, size: f32, shift: f32) -> GlyphBitmap {
let upem = font.units_per_em.max(1) as f32;
let scale = size / upem;
let gid = font.cmap.get(&(c as u32)).copied().unwrap_or(0);
let Some(glyph) = font.glyphs.get(gid as usize) else {
return GlyphBitmap::default();
};
let advance = glyph.advance_width as f32 * scale;
let contours = flatten_contours(glyph, scale, shift);
let edges: Vec<Edge> = contours
.iter()
.flat_map(|c| c.windows(2).map(|w| Edge::new(w[0], w[1])))
.filter(|e| e.y0 != e.y1)
.collect();
if edges.is_empty() {
return GlyphBitmap {
advance,
..Default::default()
};
}
let (mut min_x, mut min_y) = (f32::MAX, f32::MAX);
let (mut max_x, mut max_y) = (f32::MIN, f32::MIN);
for e in &edges {
min_x = min_x.min(e.x_at_y0.min(e.x_at_y1));
max_x = max_x.max(e.x_at_y0.max(e.x_at_y1));
min_y = min_y.min(e.y0.min(e.y1));
max_y = max_y.max(e.y0.max(e.y1));
}
let px0 = min_x.floor() as i32;
let py0 = min_y.floor() as i32;
let width = ((max_x.ceil() as i32) - px0).max(1) as u32;
let height = ((max_y.ceil() as i32) - py0).max(1) as u32;
if width > 8192 || height > 8192 {
return GlyphBitmap {
advance,
..Default::default()
};
}
let mut coverage = vec![0u8; (width * height) as usize];
let mut row = vec![0f32; width as usize];
let mut crossings: Vec<(f32, i32)> = Vec::new();
for py in 0..height {
row.iter_mut().for_each(|v| *v = 0.0);
for s in 0..SUBSAMPLES {
let y = (py0 + py as i32) as f32 + (s as f32 + 0.5) / SUBSAMPLES as f32;
crossings.clear();
for e in &edges {
if let Some(x) = e.x_at(y) {
crossings.push((x - px0 as f32, e.winding));
}
}
if crossings.len() < 2 {
continue;
}
crossings.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
let mut winding = 0;
let mut span_start = 0.0f32;
for &(x, dir) in &crossings {
if winding == 0 {
span_start = x;
}
winding += dir;
if winding == 0 {
add_span(&mut row, span_start, x);
}
}
}
for px in 0..width as usize {
let v = (row[px] / SUBSAMPLES as f32 * 255.0).round();
coverage[(py * width) as usize + px] = v.clamp(0.0, 255.0) as u8;
}
}
GlyphBitmap {
width,
height,
coverage,
offset_x: px0,
offset_y: py0,
advance,
}
}
fn add_span(row: &mut [f32], x0: f32, x1: f32) {
let w = row.len() as f32;
let x0 = x0.clamp(0.0, w);
let x1 = x1.clamp(0.0, w);
if x1 <= x0 {
return;
}
let i0 = x0.floor() as usize;
let i1 = x1.floor() as usize;
if i0 >= row.len() {
return;
}
if i0 == i1 {
row[i0] += x1 - x0;
return;
}
row[i0] += (i0 + 1) as f32 - x0;
let full_end = i1.min(row.len());
for cell in row.iter_mut().take(full_end).skip(i0 + 1) {
*cell += 1.0;
}
if i1 < row.len() {
row[i1] += x1 - i1 as f32;
}
}
struct Edge {
y0: f32,
y1: f32,
x_at_y0: f32,
x_at_y1: f32,
winding: i32,
}
impl Edge {
fn new(a: (f32, f32), b: (f32, f32)) -> Self {
Self {
y0: a.1,
y1: b.1,
x_at_y0: a.0,
x_at_y1: b.0,
winding: if b.1 > a.1 { 1 } else { -1 },
}
}
fn x_at(&self, y: f32) -> Option<f32> {
let (top, bottom) = if self.y0 < self.y1 {
(self.y0, self.y1)
} else {
(self.y1, self.y0)
};
if y < top || y >= bottom {
return None;
}
let t = (y - self.y0) / (self.y1 - self.y0);
Some(self.x_at_y0 + t * (self.x_at_y1 - self.x_at_y0))
}
}
fn flatten_contours(
glyph: &crate::loaders::TtfGlyph,
scale: f32,
shift: f32,
) -> Vec<Vec<(f32, f32)>> {
let mut contours: Vec<Vec<(f32, f32)>> = Vec::new();
let mut current: Vec<(f32, f32)> = Vec::new();
let mut last: Option<(f32, f32)> = None;
let to_device = |p: crate::math::Vector2| (p.x * scale + shift, -p.y * scale);
for curve in glyph.shape.outline.curve_path.curves.iter() {
let start = to_device(curve.get_point(0.0));
let end = to_device(curve.get_point(1.0));
let breaks = match last {
Some(prev) => (prev.0 - start.0).abs() > 1e-4 || (prev.1 - start.1).abs() > 1e-4,
None => true,
};
if breaks {
if current.len() > 2 {
close_contour(&mut current);
contours.push(std::mem::take(&mut current));
} else {
current.clear();
}
current.push(start);
}
let steps = if is_straight(curve.as_ref()) {
1
} else {
let span = (end.0 - start.0).abs().max((end.1 - start.1).abs());
(span.sqrt() * 2.0).ceil().clamp(3.0, 24.0) as usize
};
for i in 1..=steps {
current.push(to_device(curve.get_point(i as f32 / steps as f32)));
}
last = Some(end);
}
if current.len() > 2 {
close_contour(&mut current);
contours.push(current);
}
contours
}
fn flatten_curves(glyph: &crate::loaders::TtfGlyph, scale: f32) -> Vec<Vec<Vec<[f32; 2]>>> {
let mut contours: Vec<Vec<Vec<[f32; 2]>>> = Vec::new();
let mut current: Vec<Vec<[f32; 2]>> = Vec::new();
let mut last: Option<[f32; 2]> = None;
let to_device = |p: crate::math::Vector2| [p.x * scale, -p.y * scale];
for curve in glyph.shape.outline.curve_path.curves.iter() {
let start = to_device(curve.get_point(0.0));
let end = to_device(curve.get_point(1.0));
let breaks = match last {
Some(prev) => (prev[0] - start[0]).abs() > 1e-4 || (prev[1] - start[1]).abs() > 1e-4,
None => true,
};
if breaks && !current.is_empty() {
contours.push(std::mem::take(&mut current));
}
let steps = if is_straight(curve.as_ref()) {
1
} else {
let span = (end[0] - start[0]).abs().max((end[1] - start[1]).abs());
(span.sqrt() * 2.0).ceil().clamp(3.0, 24.0) as usize
};
let points: Vec<[f32; 2]> = (0..=steps)
.map(|i| to_device(curve.get_point(i as f32 / steps as f32)))
.collect();
if (end[0] - start[0]).abs() + (end[1] - start[1]).abs() > 1e-6 || steps > 1 {
current.push(points);
}
last = Some(end);
}
if !current.is_empty() {
contours.push(current);
}
contours
}
fn is_straight(curve: &dyn Curve2) -> bool {
let a = curve.get_point(0.0);
let b = curve.get_point(1.0);
let mid = curve.get_point(0.5);
let cx = (a.x + b.x) * 0.5;
let cy = (a.y + b.y) * 0.5;
(mid.x - cx).abs() < 1e-3 && (mid.y - cy).abs() < 1e-3
}
fn close_contour(points: &mut Vec<(f32, f32)>) {
if let Some(&first) = points.first() {
if points.last() != Some(&first) {
points.push(first);
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn kerning_narrows_a_measured_pair() {
let mut builtin = CaptionFont::builtin();
let apart = builtin.advance('A', 20.0) + builtin.advance('V', 20.0);
assert!(
(builtin.measure("AV", 20.0, 0.0) - apart).abs() < 1e-3,
"the built-in face has no pairs to kern"
);
let Ok(bytes) = std::fs::read("/System/Library/Fonts/Supplemental/Arial Bold.ttf") else {
eprintln!("skipping: Arial Bold not installed");
return;
};
let Ok(mut font) = CaptionFont::from_ttf_bytes(&bytes) else {
return;
};
let size = 32.0;
let apart = font.advance('A', size) + font.advance('V', size);
let together = font.measure("AV", size, 0.0);
assert!(
together < apart - 0.5,
"AV measured {together}, no tighter than {apart} apart"
);
let loose = font.advance('o', size) + font.advance('o', size);
assert!(
(font.measure("oo", size, 0.0) - loose).abs() < 1e-3,
"oo should need no adjustment"
);
let expected = font.kerning('A', 'V', size);
assert!(
expected < 0.0,
"AV kerning should be negative, got {expected}"
);
assert!(
((together - apart) - expected).abs() < 1e-3,
"measure applied {} where the pair says {expected}",
together - apart
);
}
#[test]
fn builtin_coverage_conserves_ink_at_any_scale() {
for size in [7.3f32, 11.0, 13.7, 19.5, 31.25] {
let scale = size / BUILTIN_CELL as f32;
let rows = builtin_rows('H').expect("H has a glyph");
let lit: u32 = rows.iter().map(|r| r.count_ones()).sum();
let expected = lit as f32 * scale * scale * 255.0;
let glyph = raster_builtin('H', size, 0.0);
let total: f32 = glyph.coverage.iter().map(|v| *v as f32).sum();
let slack = (glyph.coverage.len() as f32) * 0.5 + 1.0;
assert!(
(total - expected).abs() <= slack,
"size {size}: ink {total} vs exact {expected} (slack {slack})"
);
}
}
#[test]
fn builtin_coverage_is_binary_when_cells_align() {
let glyph = raster_builtin('H', BUILTIN_CELL as f32 * 3.0, 0.0);
for &v in &glyph.coverage {
assert!(
v == 0 || v == 255,
"partial coverage {v} at an integer scale"
);
}
}
#[test]
fn a_phase_shifts_the_glyph_without_changing_its_weight() {
let size = 13.7f32;
let base = raster_builtin('H', size, 0.0);
let base_ink: u32 = base.coverage.iter().map(|v| *v as u32).sum();
let mut differed = false;
for phase in 1..SUBPIXEL_PHASES {
let shifted = raster_builtin('H', size, phase as f32 / SUBPIXEL_PHASES as f32);
let ink: u32 = shifted.coverage.iter().map(|v| *v as u32).sum();
let slack = (base.coverage.len().max(shifted.coverage.len()) as u32) + 255;
assert!(
base_ink.abs_diff(ink) <= slack,
"phase {phase}: ink {ink} vs {base_ink}"
);
if shifted.coverage != base.coverage {
differed = true;
}
}
assert!(
differed,
"no phase changed the raster, so phases do nothing"
);
}
#[test]
fn stepping_the_phase_steps_the_glyph_by_a_quarter_pixel() {
let size = 16.0f32;
let centroid = |phase: usize| {
let g = raster_builtin('H', size, phase as f32 / SUBPIXEL_PHASES as f32);
let mut weight = 0.0f32;
let mut moment = 0.0f32;
for row in 0..g.height {
for col in 0..g.width {
let v = g.coverage[(row * g.width + col) as usize] as f32;
moment += (g.offset_x + col as i32) as f32 * v;
weight += v;
}
}
moment / weight
};
let steps: Vec<f32> = (0..SUBPIXEL_PHASES).map(centroid).collect();
for (i, pair) in steps.windows(2).enumerate() {
let moved = pair[1] - pair[0];
let expected = 1.0 / SUBPIXEL_PHASES as f32;
assert!(
(moved - expected).abs() < 0.06,
"phase {i} to {}: centroid moved {moved}, expected {expected}",
i + 1
);
}
}
#[test]
fn the_glyph_cache_distinguishes_phases() {
let mut font = CaptionFont::builtin();
let a = font.glyph_at('H', 13.7, 0).coverage.clone();
let b = font.glyph_at('H', 13.7, 2).coverage.clone();
let a_again = font.glyph_at('H', 13.7, 0).coverage.clone();
assert_ne!(a, b, "two phases gave the same mask");
assert_eq!(
a, a_again,
"the cache returned something else the second time"
);
}
use super::*;
#[test]
fn builtin_metrics_split_the_cell_at_the_baseline() {
let font = CaptionFont::builtin();
let m = font.metrics(32.0);
assert_eq!(m.ascent, 28.0); assert_eq!(m.descent, 4.0); assert_eq!(m.line_height(), 32.0);
}
#[test]
fn builtin_glyphs_have_ink_and_sit_above_the_baseline() {
let mut font = CaptionFont::builtin();
let a = font.glyph('A', 32.0).clone();
assert!(!a.is_blank());
assert!(a.coverage.iter().any(|&v| v > 200), "expected solid pixels");
assert_eq!(a.advance, 32.0);
assert!(a.offset_y + a.height as i32 <= 1, "offset_y={}", a.offset_y);
let g = font.glyph('g', 32.0).clone();
assert!(g.offset_y + g.height as i32 > 0, "expected a descender");
}
#[test]
fn space_is_blank_but_still_advances() {
let mut font = CaptionFont::builtin();
let space = font.glyph(' ', 24.0).clone();
assert!(space.is_blank());
assert_eq!(space.advance, 24.0);
}
#[test]
fn unmapped_codepoints_draw_a_box_and_accents_fold() {
assert_eq!(fold_to_ascii('é'), 'e');
assert_eq!(fold_to_ascii('Ü'), 'U');
assert_eq!(fold_to_ascii('\u{2019}'), '\'');
assert_eq!(builtin_rows('é'), builtin_rows('e'));
assert_eq!(builtin_rows('\u{4E2D}'), Some(TOFU));
}
#[test]
fn measure_matches_summed_advances_plus_tracking() {
let mut font = CaptionFont::builtin();
assert_eq!(font.measure("abc", 16.0, 0.0), 48.0);
assert_eq!(font.measure("abc", 16.0, 2.0), 48.0 + 4.0);
assert_eq!(font.measure("a", 16.0, 2.0), 16.0);
assert_eq!(font.measure("", 16.0, 2.0), 0.0);
}
#[test]
fn glyphs_are_cached_per_size() {
let mut font = CaptionFont::builtin();
font.glyph('A', 16.0);
font.glyph('A', 16.0);
assert_eq!(font.cache.len(), 1);
font.glyph('A', 32.0);
assert_eq!(font.cache.len(), 2);
font.clear_cache();
assert_eq!(font.cache.len(), 0);
}
#[test]
fn spans_accumulate_exact_fractional_coverage() {
let mut row = vec![0.0f32; 4];
add_span(&mut row, 0.5, 2.25);
assert!((row[0] - 0.5).abs() < 1e-6);
assert!((row[1] - 1.0).abs() < 1e-6);
assert!((row[2] - 0.25).abs() < 1e-6);
assert_eq!(row[3], 0.0);
let mut row = vec![0.0f32; 2];
add_span(&mut row, -3.0, 9.0);
assert!((row[0] - 1.0).abs() < 1e-6);
assert!((row[1] - 1.0).abs() < 1e-6);
add_span(&mut row, 1.0, 1.0);
assert!((row[1] - 1.0).abs() < 1e-6);
}
}