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<TtfFace>),
Sdf(std::sync::Arc<SdfGlyphs>),
Bitmap(std::sync::Arc<super::glyphs::BitmapGlyphs>),
}
struct TtfFace {
base: std::sync::Arc<TtfFont>,
source: Option<VariableSource>,
family: Family,
synthetic_bold: bool,
oblique: bool,
style: (u16, bool),
}
#[derive(Clone)]
struct Family {
upright: FamilyFile,
italic: Option<std::sync::Arc<[u8]>>,
}
#[derive(Clone)]
enum FamilyFile {
Bytes(std::sync::Arc<[u8]>),
Parsed(std::sync::Arc<TtfFont>),
}
const OBLIQUE_SKEW: f32 = 0.25;
fn synthetic_bold_outset(size: f32) -> f32 {
let t = ((size - 9.0) / 27.0).clamp(0.0, 1.0);
size * (1.0 / 24.0 + t * (1.0 / 32.0 - 1.0 / 24.0)) * 0.5
}
#[derive(Clone, Copy, Default)]
struct Synthesis {
skew: f32,
outset: f32,
hint: bool,
darken: [f32; 2],
}
fn stem_darkening(size: f32) -> [f32; 2] {
[(0.0105 * (size - 6.5)).clamp(0.0, 0.36), (0.0055 * size + 0.02).min(0.3)]
}
fn dilate_contours(contours: &mut [Vec<(f32, f32)>], amount: [f32; 2]) {
let area = |c: &[(f32, f32)]| c.windows(2).map(|w| w[0].0 * w[1].1 - w[1].0 * w[0].1).sum::<f32>();
let Some(largest) = contours.iter().map(|c| area(c)).max_by(|a, b| a.abs().total_cmp(&b.abs())) else {
return;
};
let out = if largest > 0.0 { 1.0 } else { -1.0 };
let unit = |a: (f32, f32), b: (f32, f32)| {
let d = (b.0 - a.0, b.1 - a.1);
let l = (d.0 * d.0 + d.1 * d.1).sqrt();
if l > 0.0 { (d.0 / l, d.1 / l) } else { (0.0, 0.0) }
};
for c in contours.iter_mut() {
let closed = c.len() > 1 && c.first() == c.last();
let n = if closed { c.len() - 1 } else { c.len() };
if n < 3 {
continue;
}
let pts = c[..n].to_vec();
for i in 0..n {
let (a, b) = (unit(pts[(i + n - 1) % n], pts[i]), unit(pts[i], pts[(i + 1) % n]));
let bis = (a.1 + b.1, -(a.0 + b.0));
let l = (bis.0 * bis.0 + bis.1 * bis.1).sqrt();
if l > 0.0 {
c[i] = (pts[i].0 + out * bis.0 / l * amount[0], pts[i].1 + out * bis.1 / l * amount[1]);
}
}
if closed {
c[n] = c[0];
}
for p in c.iter_mut() {
p.1 -= amount[1];
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Hinting {
#[default]
None,
Slight,
}
#[derive(Debug, Clone, Copy)]
struct BlueZones {
x: Option<(f32, f32)>,
cap: Option<(f32, f32)>,
base_shoot: Option<f32>,
descender: Option<f32>,
ascender: Option<f32>,
}
impl BlueZones {
fn of(font: &TtfFont) -> Self {
let extent = |c: char| -> Option<(f32, f32)> {
let gid = *font.cmap.get(&(c as u32))?;
let g = font.glyphs.get(gid as usize)?;
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
for curve in g.shape.outline.curve_path.curves.iter() {
for k in 0..=8 {
let y = curve.get_point(k as f32 / 8.0).y;
lo = lo.min(y);
hi = hi.max(y);
}
}
(lo <= hi).then_some((lo, hi))
};
let pair = |flat: char, round: char| Some((extent(flat)?.1, extent(round)?.1));
Self {
x: pair('x', 'o'),
cap: pair('H', 'O'),
base_shoot: extent('o').map(|e| e.0),
descender: extent('p').map(|e| e.0),
ascender: extent('h').map(|e| e.1),
}
}
}
struct VerticalWarp {
knots: Vec<(f32, f32)>,
slope: f32,
}
impl VerticalWarp {
fn new(font: &TtfFont, size: f32) -> Self {
let mul_fix = |a: i64, b: i64| -> i64 {
let p = a * b;
if p >= 0 { (p + 0x8000) >> 16 } else { -((-p + 0x8000) >> 16) }
};
let mul_div = |a: i64, b: i64, c: i64| -> i64 {
let p = a * b;
if p >= 0 { (p + c / 2) / c } else { -((-p + c / 2) / c) }
};
let round = |v: i64| (v + 32) & !63;
let upem = font.units_per_em.max(1) as i64;
let ppem = (size * 64.0).round() as i64;
let mut scale = (ppem * 65536 + upem / 2) / upem;
let zones = BlueZones::of(font);
if let Some((_, shoot)) = zones.x {
let scaled = mul_fix(shoot.round() as i64, scale);
let fitted = (scaled + 40) & !63;
if scaled > 0 && fitted > 0 {
scale = mul_div(scale, fitted, scaled);
}
}
let px = |v: i64| v as f32 / 64.0;
let mut knots = vec![(0.0, 0.0)];
let mut zone = |flat: f32, shoot: Option<f32>| {
let r = mul_fix(flat.round() as i64, scale);
let Some(shoot) = shoot.filter(|&s| s != flat) else {
knots.push((flat, px(round(r))));
return;
};
let s = mul_fix(shoot.round() as i64, scale);
let dist = s - r;
if dist.abs() > 48 {
return;
}
let fit = round(r);
let over = match dist.abs() {
d if d < 32 => 0,
d if d < 48 => 32,
_ => 64,
} * dist.signum();
knots.push((flat, px(fit)));
knots.push((shoot, px(fit + over)));
};
if let Some((flat, shoot)) = zones.x {
zone(flat, Some(shoot));
}
if let Some((flat, shoot)) = zones.cap {
zone(flat, Some(shoot));
}
if let Some(a) = zones.ascender {
zone(a, None);
}
if let Some(s) = zones.base_shoot.filter(|&s| s < 0.0) {
zone(0.0, Some(s));
}
if let Some(d) = zones.descender.filter(|&d| d < 0.0) {
zone(d, None);
}
knots.sort_by(|a, b| a.0.total_cmp(&b.0));
knots.dedup_by(|a, b| a.0 == b.0);
for i in 1..knots.len() {
knots[i].1 = knots[i].1.max(knots[i - 1].1);
}
Self { knots, slope: scale as f32 / 65536.0 / 64.0 }
}
fn map(&self, y: f32) -> f32 {
let k = &self.knots;
let (first, last) = (k[0], k[k.len() - 1]);
if y <= first.0 {
return first.1 + (y - first.0) * self.slope;
}
if y >= last.0 {
return last.1 + (y - last.0) * self.slope;
}
let i = k.partition_point(|p| p.0 <= y) - 1;
let (a, b) = (k[i], k[i + 1]);
a.1 + (y - a.0) / (b.0 - a.0) * (b.1 - a.1)
}
}
struct VariableSource {
bytes: std::sync::Arc<[u8]>,
wght: Option<f32>,
opsz: Option<(f32, f32)>,
sized: std::sync::Mutex<HashMap<u32, std::sync::Arc<TtfFont>>>,
}
impl TtfFace {
fn fixed(font: TtfFont) -> Self {
let base = std::sync::Arc::new(font);
let family = Family { upright: FamilyFile::Parsed(base.clone()), italic: None };
Self { base, source: None, family, synthetic_bold: false, oblique: false, style: (400, false) }
}
fn styled(family: &Family, weight: u16, italic: bool) -> Result<Self, TtfError> {
let file = match (&family.italic, italic) {
(Some(bytes), true) => FamilyFile::Bytes(bytes.clone()),
_ => family.upright.clone(),
};
let mut face = match file {
FamilyFile::Bytes(bytes) => Self::variable(bytes, weight)?,
FamilyFile::Parsed(font) => {
Self { base: font, source: None, family: family.clone(), synthetic_bold: false, oblique: false, style: (400, false) }
}
};
face.family = family.clone();
let has_weights = face.source.as_ref().is_some_and(|s| s.wght.is_some());
face.synthetic_bold = weight >= 600 && !has_weights && face.base.weight_class < 600;
face.oblique = italic && family.italic.is_none();
face.style = (weight, italic);
Ok(face)
}
fn synthesis(&self, size: f32) -> Synthesis {
Synthesis {
skew: if self.oblique { OBLIQUE_SKEW } else { 0.0 },
outset: if self.synthetic_bold { synthetic_bold_outset(size) } else { 0.0 },
hint: false,
darken: [0.0; 2],
}
}
fn variable(bytes: std::sync::Arc<[u8]>, weight: u16) -> Result<Self, TtfError> {
let (axes, instances) = TtfFont::variation_info(&bytes);
if axes.is_empty() {
let mut face = Self::fixed(TtfFont::parse(&bytes)?);
face.family.upright = FamilyFile::Bytes(bytes);
face.style = (weight, false);
return Ok(face);
}
let wght = crate::loaders::wght_for_css_weight(&axes, &instances, weight as f32);
let opsz = axes.iter().find(|a| &a.tag == b"opsz").map(|a| (a.min, a.max));
let mut at = Vec::new();
if let Some(w) = wght {
at.push((*b"wght", w));
}
let base = std::sync::Arc::new(TtfFont::parse_variation(&bytes, &at)?);
let family = Family { upright: FamilyFile::Bytes(bytes.clone()), italic: None };
let source = VariableSource { bytes, wght, opsz, sized: Default::default() };
Ok(Self { base, source: Some(source), family, synthetic_bold: false, oblique: false, style: (weight, false) })
}
fn at(&self, size: f32) -> std::sync::Arc<TtfFont> {
let Some(src) = &self.source else { return self.base.clone() };
let Some((lo, hi)) = src.opsz else { return self.base.clone() };
let opsz = size.clamp(lo, hi);
let key = (opsz * 4.0).round() as u32;
let mut sized = src.sized.lock().unwrap_or_else(|e| e.into_inner());
if let Some(f) = sized.get(&key) {
return f.clone();
}
let mut at = vec![(*b"opsz", key as f32 / 4.0)];
if let Some(w) = src.wght {
at.push((*b"wght", w));
}
let font = TtfFont::parse_variation(&src.bytes, &at)
.map(std::sync::Arc::new)
.unwrap_or_else(|_| self.base.clone());
sized.insert(key, font.clone());
font
}
}
#[derive(Debug, Clone, Default)]
pub struct SdfGlyphs {
pub size: f32,
pub buffer: u32,
pub top_origin: f32,
pub glyphs: HashMap<u32, SdfGlyph>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SdfGlyph {
pub width: u32,
pub height: u32,
pub left: i32,
pub top: i32,
pub advance: f32,
pub field: Vec<u8>,
}
fn raster_sdf(set: &SdfGlyphs, c: char, size: f32, shift: f32) -> GlyphBitmap {
let blank = |advance: f32| GlyphBitmap { width: 0, height: 0, coverage: Vec::new(), offset_x: 0, offset_y: 0, advance };
let Some(g) = set.glyphs.get(&(c as u32)) else { return blank(0.0) };
let k = size / set.size.max(1.0);
let advance = g.advance * k;
if g.width == 0 || g.height == 0 {
return blank(advance);
}
let b = set.buffer as f32;
let (fw, fh) = (g.width + 2 * set.buffer, g.height + 2 * set.buffer);
if g.field.len() < (fw * fh) as usize {
return blank(advance);
}
let top = g.top as f32 + set.top_origin;
let x0 = (g.left as f32 * k + shift).floor() as i32 - 1;
let y0 = (-top * k).floor() as i32 - 1;
let w = (g.width as f32 * k).ceil() as u32 + 3;
let h = (g.height as f32 * k).ceil() as u32 + 3;
let sample = |x: f32, y: f32| -> f32 {
let (x, y) = ((x - 0.5).clamp(0.0, fw as f32 - 1.0), (y - 0.5).clamp(0.0, fh as f32 - 1.0));
let (ix, iy) = (x.floor() as u32, y.floor() as u32);
let (fx, fy) = (x - ix as f32, y - iy as f32);
let at = |cx: u32, cy: u32| g.field[(cy.min(fh - 1) * fw + cx.min(fw - 1)) as usize] as f32;
let top_row = at(ix, iy) * (1.0 - fx) + at(ix + 1, iy) * fx;
let bottom_row = at(ix, iy + 1) * (1.0 - fx) + at(ix + 1, iy + 1) * fx;
top_row * (1.0 - fy) + bottom_row * fy
};
let mut coverage = Vec::with_capacity((w * h) as usize);
for oy in 0..h {
for ox in 0..w {
let px = (x0 + ox as i32) as f32 + 0.5 - shift;
let py = (y0 + oy as i32) as f32 + 0.5;
let v = sample(px / k - g.left as f32 + b, py / k + top + b);
let d = (v - 192.0) / 32.0 * k;
coverage.push(((d + 0.5).clamp(0.0, 1.0) * 255.0).round() as u8);
}
}
GlyphBitmap { width: w, height: h, coverage, offset_x: x0, offset_y: y0, advance }
}
pub struct CaptionFont {
face: Face,
cache: HashMap<(u32, u32, u32), GlyphBitmap>,
grown: HashMap<(u32, u32, u32, u32), GlyphBitmap>,
optical_size: Option<f32>,
hinting: Hinting,
font_smoothing: bool,
}
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",
Face::Sdf(_) => "distance fields",
Face::Bitmap(_) => "bitmaps",
},
)
.field("cached_glyphs", &self.cache.len())
.finish()
}
}
impl CaptionFont {
pub fn builtin() -> Self {
Self {
face: Face::Builtin,
cache: HashMap::new(),
grown: HashMap::new(),
optical_size: None,
hinting: Hinting::None,
font_smoothing: false,
}
}
pub fn from_ttf(font: TtfFont) -> Self {
Self {
face: Face::Ttf(Box::new(TtfFace::fixed(font))),
cache: HashMap::new(),
grown: HashMap::new(),
optical_size: None,
hinting: Hinting::None,
font_smoothing: false,
}
}
pub fn from_sdf_glyphs(glyphs: std::sync::Arc<SdfGlyphs>) -> Self {
Self {
face: Face::Sdf(glyphs),
cache: HashMap::new(),
grown: HashMap::new(),
optical_size: None,
hinting: Hinting::None,
font_smoothing: false,
}
}
pub fn from_bitmap_glyphs(glyphs: std::sync::Arc<super::glyphs::BitmapGlyphs>) -> Self {
Self {
face: Face::Bitmap(glyphs),
cache: HashMap::new(),
grown: HashMap::new(),
optical_size: None,
hinting: Hinting::None,
font_smoothing: false,
}
}
pub fn bitmap_glyphs(&self) -> Option<&std::sync::Arc<super::glyphs::BitmapGlyphs>> {
match &self.face {
Face::Bitmap(b) => Some(b),
_ => None,
}
}
pub fn from_ttf_bytes(bytes: &[u8]) -> Result<Self, TtfError> {
Self::from_ttf_bytes_weight(bytes, 400)
}
pub fn from_ttf_bytes_weight(bytes: &[u8], weight: u16) -> Result<Self, TtfError> {
Ok(Self {
face: Face::Ttf(Box::new(TtfFace::variable(bytes.into(), weight)?)),
cache: HashMap::new(),
grown: HashMap::new(),
optical_size: None,
hinting: Hinting::None,
font_smoothing: false,
})
}
pub fn styled(&self, weight: u16, italic: bool) -> Option<Self> {
let Face::Ttf(face) = &self.face else { return None };
Some(Self {
face: Face::Ttf(Box::new(TtfFace::styled(&face.family, weight, italic).ok()?)),
cache: HashMap::new(),
grown: HashMap::new(),
optical_size: self.optical_size,
hinting: self.hinting,
font_smoothing: self.font_smoothing,
})
}
pub fn with_weight(&self, weight: u16) -> Option<Self> {
let (_, italic) = self.style()?;
self.styled(weight, italic)
}
pub fn style(&self) -> Option<(u16, bool)> {
match &self.face {
Face::Ttf(face) => Some(face.style),
_ => None,
}
}
pub fn weight(&self) -> Option<u16> {
self.style().map(|s| s.0)
}
pub fn ui() -> Self {
Self::try_sf_compact().unwrap_or_else(Self::builtin)
}
pub fn try_sf_compact() -> Option<Self> {
Self::try_sf_compact_weight(400)
}
pub fn try_sf_compact_weight(weight: u16) -> Option<Self> {
#[cfg(target_os = "macos")]
{
const PATHS: &[&str] = &[
"/System/Library/Fonts/SFCompact.ttf",
"/System/Library/Fonts/SFCompactRounded.ttf",
];
for path in PATHS {
let Ok(bytes) = std::fs::read(path) else { continue };
if let Ok(mut font) = Self::from_ttf_bytes_weight(&bytes, weight) {
if let (Face::Ttf(face), Ok(italic)) =
(&mut font.face, std::fs::read(path.replace(".ttf", "Italic.ttf")))
{
face.family.italic = Some(italic.into());
}
return Some(font);
}
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = weight;
}
None
}
pub fn is_builtin(&self) -> bool {
matches!(self.face, Face::Builtin)
}
pub fn set_optical_size(&mut self, size: Option<f32>) -> bool {
let has_axis = matches!(&self.face, Face::Ttf(f) if f.source.as_ref().is_some_and(|s| s.opsz.is_some()));
if !has_axis || self.optical_size == size {
return false;
}
self.optical_size = size;
self.clear_cache();
true
}
pub fn set_hinting(&mut self, hinting: Hinting) {
if self.hinting != hinting {
self.hinting = hinting;
self.clear_cache();
}
}
pub fn hinting(&self) -> Hinting {
self.hinting
}
pub fn set_font_smoothing(&mut self, on: bool) {
if self.font_smoothing != on {
self.font_smoothing = on;
self.clear_cache();
}
}
pub fn font_smoothing(&self) -> bool {
self.font_smoothing
}
fn darkening(&self, size: f32) -> [f32; 2] {
if self.font_smoothing { stem_darkening(size) } else { [0.0; 2] }
}
pub fn clear_cache(&mut self) {
self.cache.clear();
self.grown.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::Sdf(_) => FontMetrics {
ascent: size * 0.8,
descent: size * 0.2,
line_gap: 0.0,
},
Face::Bitmap(b) => {
let k = size / b.size.max(1e-6);
FontMetrics { ascent: b.ascent * k, descent: b.descent * k, line_gap: 0.0 }
}
Face::Ttf(face) => {
let font = &face.base;
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 gid = self.gid(c);
self.glyph_of(gid, size, phase)
}
pub fn glyph_of(&mut self, gid: u32, size: f32, phase: usize) -> &GlyphBitmap {
let size = size.max(1.0);
let phase = phase % SUBPIXEL_PHASES;
let key = (gid, (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 c = char::from_u32(gid).unwrap_or('\u{FFFD}');
let bitmap = match &self.face {
Face::Builtin => raster_builtin(c, size, shift),
Face::Ttf(face) => raster_ttf(
&face.at(self.optical_size.unwrap_or(size)),
gid,
size,
shift,
self.optical_size.unwrap_or(size),
Synthesis { hint: self.hinting == Hinting::Slight, darken: self.darkening(size), ..face.synthesis(size) },
),
Face::Sdf(set) => raster_sdf(set, c, size, shift),
Face::Bitmap(set) => set.raster(c, size, shift),
};
self.cache.insert(key, bitmap);
}
&self.cache[&key]
}
pub fn grown_glyph_at(&mut self, c: char, size: f32, phase: usize, radius: f32) -> Option<&GlyphBitmap> {
let gid = self.gid(c);
self.grown_glyph_of(gid, size, phase, radius)
}
pub fn grown_glyph_of(
&mut self,
gid: u32,
size: f32,
phase: usize,
radius: f32,
) -> Option<&GlyphBitmap> {
let Face::Ttf(face) = &self.face else { return None };
let size = size.max(1.0);
let phase = phase % SUBPIXEL_PHASES;
let key = (gid, (size * 4.0).round() as u32, phase as u32, (radius.max(0.0) * 16.0).round() as u32);
if !self.grown.contains_key(&key) {
let font = face.at(self.optical_size.unwrap_or(size));
let shift = phase as f32 / SUBPIXEL_PHASES as f32;
let syn = Synthesis { hint: self.hinting == Hinting::Slight, darken: self.darkening(size), ..face.synthesis(size) };
let mut bitmap = raster_grown(
&font,
gid,
size,
shift + syn.outset,
key.3 as f32 / 16.0 + syn.outset,
self.optical_size.unwrap_or(size),
syn,
);
bitmap.advance += 2.0 * syn.outset;
self.grown.insert(key, bitmap);
}
Some(&self.grown[&key])
}
pub fn kerning(&self, left: char, right: char, size: f32) -> f32 {
self.kerning_of(self.gid(left), self.gid(right), size)
}
#[must_use]
pub fn gid(&self, c: char) -> u32 {
match &self.face {
Face::Ttf(face) => u32::from(
face.base.cmap.get(&(c as u32)).copied().unwrap_or(0),
),
Face::Builtin | Face::Sdf(_) | Face::Bitmap(_) => c as u32,
}
}
#[must_use]
pub fn attachments(&self, glyphs: &[u32], size: f32) -> Vec<crate::loaders::mark::Attachment> {
let blank = || vec![crate::loaders::mark::Attachment::default(); glyphs.len()];
let Face::Ttf(face) = &self.face else { return blank() };
let font = face.at(self.optical_size.unwrap_or(size));
if font.gpos.is_empty() {
return blank();
}
let store = crate::loaders::gdef_store(&font.gdef, &font.coords);
let Some(marks) =
crate::loaders::mark::Marks::parse(&font.gpos, &font.gdef, store.as_ref())
else {
return blank();
};
let ids: Vec<u16> = glyphs.iter().map(|g| u16::try_from(*g).unwrap_or(0)).collect();
let scale = size.max(1.0) / font.units_per_em.max(1) as f32;
marks
.attach(&ids)
.into_iter()
.map(|a| crate::loaders::mark::Attachment {
to: a.to,
dx: a.dx * scale,
dy: a.dy * scale,
})
.collect()
}
#[must_use]
pub fn shape_run(&self, chars: &[char], script: &[u8; 4], size: f32) -> Vec<(u32, usize)> {
let Face::Ttf(face) = &self.face else {
return chars.iter().enumerate().map(|(i, c)| (*c as u32, i)).collect();
};
let font = face.at(self.optical_size.unwrap_or(size));
let gsub = crate::loaders::shape::gsub::Gsub::parse(&font.gsub);
crate::loaders::shape::shape(
|c| Some(font.cmap.get(&(c as u32)).copied().unwrap_or(0)),
gsub.as_ref(),
script,
chars,
)
.into_iter()
.map(|s| (u32::from(s.glyph), s.cluster))
.collect()
}
#[must_use]
pub fn is_shapeable(&self) -> bool {
matches!(&self.face, Face::Ttf(_))
}
pub fn composites_run(&self) -> bool {
match &self.face {
Face::Ttf(f) => f.base.composites_run,
Face::Builtin | Face::Sdf(_) | Face::Bitmap(_) => false,
}
}
pub fn advance_of(&mut self, gid: u32, size: f32) -> f32 {
let size = size.max(1.0);
match &self.face {
Face::Builtin => size,
Face::Ttf(face) => {
let optical = self.optical_size.unwrap_or(size);
let font = face.at(optical);
font.glyphs.get(gid as usize).map_or(0.0, |g| {
(g.advance_width as f32 + font.tracking_at(optical)) * size
/ font.units_per_em.max(1) as f32
+ 2.0 * face.synthesis(size).outset
})
}
Face::Sdf(set) => {
set.glyphs.get(&gid).map_or(0.0, |g| g.advance * size / set.size.max(1.0))
}
Face::Bitmap(set) => {
set.glyphs.get(&gid).map_or(0.0, |g| g.advance * size / set.size.max(1e-6))
}
}
}
pub fn kerning_of(&self, left: u32, right: u32, size: f32) -> f32 {
let Face::Ttf(face) = &self.face else {
return 0.0;
};
let font = face.at(self.optical_size.unwrap_or(size));
if font.kerning.is_empty() && font.gpos_kerning.is_empty() {
return 0.0;
}
let narrow = |g: u32| u16::try_from(g).unwrap_or(0);
let units = font.kern(narrow(left), narrow(right));
if units == 0.0 {
return 0.0;
}
units * 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(face) => face.base.cmap.contains_key(&(c as u32)),
Face::Sdf(set) => set.glyphs.contains_key(&(c as u32)),
Face::Bitmap(set) => set.glyphs.contains_key(&(c as u32)),
}
}
pub fn outline(&self, c: char, size: f32) -> Option<Vec<Vec<Vec<[f32; 2]>>>> {
let Face::Ttf(face) = &self.face else {
return None;
};
let font = face.at(self.optical_size.unwrap_or(size));
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;
let syn = face.synthesis(size);
let mut curves = flatten_curves(glyph, scale, syn.skew);
for p in curves.iter_mut().flatten().flatten() {
p[0] += syn.outset;
}
Some(curves)
}
pub fn synthetic_outset(&self, size: f32) -> f32 {
match &self.face {
Face::Ttf(face) => face.synthesis(size.max(1.0)).outset,
_ => 0.0,
}
}
pub fn advance(&mut self, c: char, size: f32) -> f32 {
let gid = self.gid(c);
self.advance_of(gid, size)
}
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<super::order::Placed> = None;
let run = super::order::visual(text, self, size);
for placed in run {
if let Some(p) = previous {
let (l, r) = super::order::pair(p, placed);
width += self.kerning_of(l, r, size);
}
width += self.advance_of(placed.gid, size);
previous = Some(placed);
count += usize::from(placed.attach.is_none());
}
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, gid: u32, size: f32, shift: f32, optical: f32, syn: Synthesis) -> GlyphBitmap {
if syn.outset > 0.0 {
let mut g = raster_grown(font, gid, size, shift + syn.outset, syn.outset, optical, syn);
g.advance += 2.0 * syn.outset;
return g;
}
let upem = font.units_per_em.max(1) as f32;
let scale = size / upem;
let Some(glyph) = font.glyphs.get(gid as usize) else {
return GlyphBitmap::default();
};
let advance = (glyph.advance_width as f32 + font.tracking_at(optical)) * scale;
let warp = syn.hint.then(|| VerticalWarp::new(font, size));
let mut contours = flatten_contours(glyph, scale, shift, syn.skew, warp.as_ref());
if syn.darken != [0.0; 2] {
dilate_contours(&mut contours, syn.darken);
}
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 raster_grown(font: &TtfFont, gid: u32, size: f32, shift: f32, radius: f32, optical: f32, syn: Synthesis) -> GlyphBitmap {
let scale = size / font.units_per_em.max(1) as f32;
let Some(glyph) = font.glyphs.get(gid as usize) else {
return GlyphBitmap::default();
};
let advance = (glyph.advance_width as f32 + font.tracking_at(optical)) * scale;
let warp = syn.hint.then(|| VerticalWarp::new(font, size));
let mut contours = flatten_contours(glyph, scale, shift, syn.skew, warp.as_ref());
if syn.darken != [0.0; 2] {
dilate_contours(&mut contours, syn.darken);
}
let segments: Vec<((f32, f32), (f32, f32))> = contours
.iter()
.flat_map(|c| c.windows(2).map(|w| (w[0], w[1])))
.filter(|(a, b)| a != b)
.collect();
if segments.is_empty() {
return GlyphBitmap { advance, ..Default::default() };
}
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for &(a, _) in &segments {
min_x = min_x.min(a.0);
max_x = max_x.max(a.0);
min_y = min_y.min(a.1);
max_y = max_y.max(a.1);
}
let reach = radius + 1.0;
let x0 = (min_x - reach).floor() as i32;
let y0 = (min_y - reach).floor() as i32;
let width = ((max_x + reach).ceil() as i32 - x0).max(1) as u32;
let height = ((max_y + reach).ceil() as i32 - y0).max(1) as u32;
if width > 8192 || height > 8192 {
return GlyphBitmap { advance, ..Default::default() };
}
const N: u32 = 2;
let mut acc = vec![0f32; (width * height) as usize];
let mut crossings: Vec<(f32, i32)> = Vec::new();
for sy in 0..height * N {
let y = y0 as f32 + (sy as f32 + 0.5) / N as f32;
crossings.clear();
for &(a, b) in &segments {
if (a.1 <= y) != (b.1 <= y) {
let t = (y - a.1) / (b.1 - a.1);
crossings.push((a.0 + t * (b.0 - a.0), if b.1 > a.1 { 1 } else { -1 }));
}
}
crossings.sort_by(|p, q| p.0.total_cmp(&q.0));
let mut k = 0;
let mut winding = 0;
let near_row: Vec<((f32, f32), (f32, f32))> = segments
.iter()
.copied()
.filter(|(a, b)| a.1.min(b.1) - reach <= y && a.1.max(b.1) + reach >= y)
.collect();
for sx in 0..width * N {
let x = x0 as f32 + (sx as f32 + 0.5) / N as f32;
while k < crossings.len() && crossings[k].0 < x {
winding += crossings[k].1;
k += 1;
}
let mut d2 = f32::MAX;
for &(a, b) in &near_row {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let t = (((x - a.0) * dx + (y - a.1) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0);
let (ex, ey) = (a.0 + t * dx - x, a.1 + t * dy - y);
d2 = d2.min(ex * ex + ey * ey);
}
let d = d2.sqrt();
let signed = if winding != 0 { -d } else { d };
let v = ((radius - signed) * N as f32 + 0.5).clamp(0.0, 1.0);
acc[((sy / N) * width + sx / N) as usize] += v;
}
}
let k = 1.0 / (N * N) as f32;
let coverage = acc.iter().map(|v| (v * k * 255.0).round() as u8).collect();
GlyphBitmap { width, height, coverage, offset_x: x0, offset_y: y0, 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,
skew: f32,
warp: Option<&VerticalWarp>,
) -> 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| {
let y = warp.map_or(p.y * scale, |w| w.map(p.y));
((p.x + skew * p.y) * scale + shift, -y)
};
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, skew: 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 + skew * p.y) * 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 advances_without_rasterizing_match_the_rasters() {
let mut faces = vec![CaptionFont::builtin()];
if let Some(sf) = CaptionFont::try_sf_compact() {
faces.push(sf);
}
for font in &mut faces {
for size in [9.0, 14.0, 19.5, 33.0] {
for c in ['A', 'g', ' ', '7', '\u{2603}'] {
let from_metrics = font.advance(c, size);
let from_raster = font.glyph(c, size).advance;
assert!((from_metrics - from_raster).abs() < 1e-4, "{c:?} at {size}: {from_metrics} against {from_raster}");
}
}
}
}
#[test]
fn an_optical_size_holds_at_any_pixel_size() {
let Some(mut font) = CaptionFont::try_sf_compact() else { return };
let display = font.advance('a', 48.0);
let text = font.advance('a', 14.0) * 48.0 / 14.0;
assert!(text > display + 0.1, "text cut {text}, display cut {display}");
let display_ink: u32 = font.glyph('a', 48.0).coverage.iter().map(|&v| v as u32).sum();
assert!(font.set_optical_size(Some(14.0)));
assert!(!font.set_optical_size(Some(14.0)), "no change the second time");
assert!((font.advance('a', 48.0) - text).abs() < 1e-3);
assert!((font.glyph('a', 48.0).advance - text).abs() < 1e-3);
let text_ink: u32 = font.glyph('a', 48.0).coverage.iter().map(|&v| v as u32).sum();
assert_ne!(text_ink, display_ink, "the text cut's shape");
assert!(!CaptionFont::builtin().set_optical_size(Some(14.0)));
}
fn dejavu() -> CaptionFont {
CaptionFont::from_ttf_bytes(include_bytes!("../openscad/DejaVuSans.ttf")).unwrap()
}
fn ink(g: &GlyphBitmap) -> f32 {
g.coverage.iter().map(|&v| v as f32 / 255.0).sum()
}
fn ink_columns(g: &GlyphBitmap) -> (i32, i32) {
let cols: Vec<u32> = (0..g.width)
.filter(|&x| (0..g.height).any(|y| g.coverage[(y * g.width + x) as usize] > 127))
.collect();
(g.offset_x + cols[0] as i32, g.offset_x + *cols.last().unwrap() as i32)
}
#[test]
fn a_static_face_synthesizes_bold() {
let mut regular = dejavu();
let mut bold = regular.styled(700, false).unwrap();
assert_eq!(bold.style(), Some((700, false)));
let size = 24.0;
let outset = synthetic_bold_outset(size);
assert!((outset - size / 56.0).abs() < size / 200.0, "{outset}");
let (r, b) = (regular.glyph('H', size).clone(), bold.glyph('H', size).clone());
assert!(ink(&b) > ink(&r) * 1.1, "bold {} against {}", ink(&b), ink(&r));
assert!((b.advance - r.advance - 2.0 * outset).abs() < 1e-4);
assert!((bold.advance('H', size) - b.advance).abs() < 1e-4);
assert_eq!(ink_columns(&b).0, ink_columns(&r).0, "the left side bearing stays");
let mut medium = regular.styled(500, false).unwrap();
assert_eq!(ink(medium.glyph('H', size)), ink(&r));
}
#[test]
fn a_bold_face_is_not_emboldened_again() {
let Ok(bytes) = std::fs::read("/System/Library/Fonts/Supplemental/Arial Bold.ttf") else { return };
let mut face = CaptionFont::from_ttf_bytes(&bytes).unwrap();
let mut bold = face.styled(700, false).unwrap();
assert_eq!(ink(face.glyph('H', 24.0)), ink(bold.glyph('H', 24.0)));
}
#[test]
fn a_face_without_an_italic_slants() {
let mut upright = dejavu();
let mut italic = upright.styled(400, true).unwrap();
let size = 40.0;
let (u, i) = (upright.glyph('l', size).clone(), italic.glyph('l', size).clone());
assert_eq!(u.advance, i.advance);
let centre = |g: &GlyphBitmap, row: u32| -> f32 {
let (mut sum, mut w) = (0.0, 0.0);
for x in 0..g.width {
let v = g.coverage[(row * g.width + x) as usize] as f32;
sum += v * x as f32;
w += v;
}
sum / w
};
let (top, foot) = (1, i.height - 2);
let lean = (centre(&i, top) - centre(&i, foot)) / (foot - top) as f32;
assert!((lean - OBLIQUE_SKEW).abs() < 0.03, "lean {lean}");
let upright_lean = (centre(&u, 1) - centre(&u, u.height - 2)) / (u.height - 3) as f32;
assert!(upright_lean.abs() < 0.02, "{upright_lean}");
}
#[test]
fn sf_compact_italic_is_its_own_design() {
let Some(sf) = CaptionFont::try_sf_compact() else { return };
let mut real = sf.styled(400, true).unwrap();
let bytes = std::fs::read("/System/Library/Fonts/SFCompact.ttf").unwrap();
let mut slanted = CaptionFont::from_ttf_bytes(&bytes).unwrap().styled(400, true).unwrap();
let (r, s) = (real.glyph('a', 40.0).clone(), slanted.glyph('a', 40.0).clone());
assert!(r.coverage != s.coverage || r.advance != s.advance);
let mut bold = real.with_weight(700).unwrap();
assert!(ink(bold.glyph('a', 40.0)) > ink(&r) * 1.2);
}
fn solid_rows(g: &GlyphBitmap) -> (i32, i32) {
let rows: Vec<i32> = (0..g.height)
.filter(|&y| (0..g.width).any(|x| g.coverage[(y * g.width + x) as usize] > 128))
.map(|y| y as i32)
.collect();
(-(g.offset_y + rows[0]), -(g.offset_y + rows[rows.len() - 1] + 1))
}
#[test]
fn slight_hinting_matches_freetype_light() {
let mut font = dejavu();
let plain = solid_rows(&font.glyph('x', 15.0).clone());
font.set_hinting(Hinting::Slight);
let freetype: [(u32, [(i32, i32); 4]); 21] = [
(8, [(5, 0), (7, 0), (5, 0), (5, 0)]),
(9, [(5, 0), (7, 0), (5, 0), (5, -2)]),
(10, [(6, 0), (8, 0), (6, 0), (6, -2)]),
(11, [(6, 0), (8, 0), (6, 0), (6, -2)]),
(12, [(7, 0), (9, 0), (7, 0), (7, -3)]),
(13, [(7, 0), (9, 0), (7, 0), (7, -3)]),
(14, [(8, 0), (10, 0), (8, 0), (8, -3)]),
(15, [(9, 0), (12, 0), (9, 0), (9, -3)]),
(16, [(9, 0), (12, 0), (9, 0), (9, -3)]),
(17, [(10, 0), (13, 0), (10, 0), (10, -4)]),
(18, [(10, 0), (13, 0), (10, 0), (10, -4)]),
(19, [(11, 0), (14, 0), (11, 0), (11, -4)]),
(20, [(11, 0), (14, 0), (11, 0), (11, -4)]),
(21, [(12, 0), (16, 0), (12, 0), (12, -4)]),
(22, [(12, 0), (16, 0), (12, 0), (12, -4)]),
(23, [(13, 0), (17, 0), (13, 0), (13, -5)]),
(24, [(14, 0), (18, 0), (14, 0), (14, -5)]),
(25, [(14, 0), (18, 0), (14, 0), (14, -5)]),
(26, [(15, 0), (20, 0), (15, 0), (15, -6)]),
(27, [(15, 0), (20, 0), (15, 0), (15, -6)]),
(28, [(16, 0), (21, 0), (16, 0), (16, -6)]),
];
for (px, expected) in freetype {
for (c, want) in ['x', 'H', 'o', 'p'].into_iter().zip(expected) {
let got = solid_rows(&font.glyph(c, px as f32).clone());
assert_eq!(got, want, "{c} at {px} px");
}
}
assert_eq!(plain.0, 8);
assert_eq!(font.hinting(), Hinting::Slight);
}
#[test]
fn hinting_keeps_the_advances() {
let mut font = dejavu();
let plain: Vec<f32> = "Hamburg".chars().map(|c| font.glyph(c, 13.0).advance).collect();
font.set_hinting(Hinting::Slight);
let hinted: Vec<f32> = "Hamburg".chars().map(|c| font.glyph(c, 13.0).advance).collect();
assert_eq!(plain, hinted);
}
#[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 a_decomposed_accent_measures_as_one_letter() {
let mut font = CaptionFont::builtin();
assert_eq!(font.measure("e\u{0301}", 16.0, 0.0), font.measure("é", 16.0, 0.0));
assert_eq!(font.measure("Noe\u{0308}l", 16.0, 0.0), font.measure("Noël", 16.0, 0.0));
assert_eq!(font.measure("Noe\u{0308}l", 16.0, 2.0), 4.0 * 16.0 + 3.0 * 2.0);
}
#[test]
fn a_right_to_left_line_measures_the_same_either_way() {
let mut font = CaptionFont::builtin();
let hebrew = font.measure("\u{05D0}\u{05D1}\u{05D2}", 16.0, 0.0);
let reversed = font.measure("\u{05D2}\u{05D1}\u{05D0}", 16.0, 0.0);
assert_eq!(hebrew, reversed);
}
#[test]
fn a_mark_with_no_composite_still_measures() {
let mut font = CaptionFont::builtin();
let two = font.measure("q\u{0308}", 16.0, 0.0);
let one = font.measure("q", 16.0, 0.0);
assert!(two > one, "the mark vanished");
}
#[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);
}
}