From 7e410d93b3f38dd92b349c1608fb5eb5ad85479a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:27:47 +0200 Subject: [PATCH] Fonts: TrueType providers and the font picked by text components Every font definition of the resources (and packs) is now loaded, not just font/default.json, and a text component's "font" field picks one: "minecraft:alt" draws the enchanting table's Galactic alphabet, "minecraft:illageralt" the illager runes, a pack's own font its glyphs, and a font that doesn't exist draws every character as the missing glyph (FontManager.getFontSetRaw). - font.rs: one FontSet per font id with its providers in order (space, bitmap, unihex, ttf) and their filters ("uniform", "jp"). Bitmap sheets outside the atlas (another namespace or folder) are copied into the glyph region when first drawn. - TrueTypeGlyphProvider: "ttf" providers (file under font/, size, oversample, shift, skip; CFF fonts refused) rasterized with ab_glyph into the glyph region as rrrr coverage (text_intensity), metrics as GlyphBitmap (bearings over the oversampling, whole-pixel advances). - text::Style gains the font id; it is parsed from JSON and SNBT components, pack descriptions and scoreboard number formats, inherited by children and written back. - Obfuscated text picks its random glyph in the style's font. Fixes #336 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/component.rs | 23 + crates/horizon-client/src/font.rs | 1053 +++++++++++++++++------ crates/horizon-client/src/hud.rs | 11 +- crates/horizon-client/src/packs.rs | 1 + crates/horizon-client/src/scoreboard.rs | 1 + crates/horizon-client/src/text.rs | 16 +- 6 files changed, 835 insertions(+), 270 deletions(-) diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 0e04eab5e..68460054b 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -167,6 +167,7 @@ fn object_style(o: &serde_json::Map) -> Style { style.underlined = flag("underlined"); style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); + style.font = o.get("font").and_then(crate::text::font_id); style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components @@ -266,4 +267,26 @@ mod tests { let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap(); assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab"); } + + #[test] + fn the_font_is_inherited_and_kept() { + let (v, _) = + parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#) + .unwrap(); + let t = to_text(&v, &mut |_| Text::empty()); + let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect(); + let (alt, uniform) = ( + Some("minecraft:alt".into()), + Some("minecraft:uniform".into()), + ); + assert_eq!(fonts, [alt.clone(), alt, uniform]); + // Back to JSON with the field, which a re-read keeps. + let again = to_text(&t.component(), &mut |_| Text::empty()); + let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect(); + assert_eq!(kept, fonts); + // Not an identifier: no font. + let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap(); + let t = to_text(&v, &mut |_| Text::empty()); + assert_eq!(t.spans[0].style.font, None); + } } diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index 3039fdb40..c5e5760f3 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -1,19 +1,27 @@ -//! The default font (FontSet over `font/default.json`): space and bitmap -//! providers from the shared atlas, the unihex (GNU Unifont) fallback whose -//! glyphs are rasterized on demand into a reserved atlas region, vanilla -//! glyph metrics (ascent, oversampling, advances, bold/shadow offsets), -//! styled drawing and StringSplitter-style line wrapping. +//! Fonts (FontManager / FontSet): `font/default.json` and every other font a +//! text component names (`minecraft:alt`, `minecraft:uniform`, a pack's own), +//! each a list of providers tried in order: `space`, `bitmap` (sheets in the +//! shared atlas, or rasterized on demand when a pack's sheet is not in it), +//! `unihex` (GNU Unifont) and `ttf` (TrueTypeGlyphProvider, rasterized with +//! ab_glyph). Glyphs drawn at run time go into a reserved atlas region. +//! Vanilla glyph metrics (ascent, oversampling, advances, bold/shadow +//! offsets), styled drawing and StringSplitter-style line wrapping. use crate::{ hud::Rect, text::{Style, Text}, zip::Zip, }; +use ab_glyph::{Font as _, ScaleFont as _}; use std::{ cell::RefCell, collections::HashMap, path::{Path, PathBuf}, + sync::Arc, }; +/// `FontDescription.DEFAULT`. +pub const DEFAULT: &str = "minecraft:default"; + /// A glyph ready to draw: atlas UVs and its box relative to the pen /// position (GlyphBitmap left/top/right/bottom), in GUI pixels. #[derive(Clone, Copy, Debug)] @@ -24,7 +32,7 @@ pub struct Glyph { pub right: f32, pub bottom: f32, pub advance: f32, - /// Shadow and bold offset (1 for bitmap glyphs, 0.5 for unihex). + /// Shadow and bold offset (1 for bitmap and TrueType glyphs, 0.5 for unihex). pub offset: f32, } /// Pixels to copy into the shared atlas before the next HUD draw. @@ -43,23 +51,77 @@ struct HexGlyph { left: u32, right: u32, } -#[derive(Default)] -struct HexProvider { - glyphs: HashMap, +/// A provider's `filter` (`FontOption.Filter`): the options it needs. +#[derive(Clone, Copy, Default)] +struct Filter { + uniform: Option, + jp: Option, +} +impl Filter { + fn of(provider: &serde_json::Value) -> Self { + let f = &provider["filter"]; + Self { + uniform: f["uniform"].as_bool(), + jp: f["jp"].as_bool(), + } + } + fn passes(self, uniform: bool, japanese: bool) -> bool { + self.uniform.is_none_or(|v| v == uniform) && self.jp.is_none_or(|v| v == japanese) + } +} +/// A bitmap glyph whose sheet is not in the atlas: the cell to copy. +struct SheetCell { + sheet: Arc<(u32, Vec)>, + x: u32, + y: u32, + w: u32, + h: u32, + glyph: Glyph, +} +enum BitmapGlyph { + Atlas(Glyph), + Sheet(SheetCell), +} +/// `TrueTypeGlyphProvider`. +struct TrueType { + font: ab_glyph::FontVec, + ids: HashMap, + /// FT_Set_Pixel_Sizes: `size * oversample` pixels to the em. + scale: ab_glyph::PxScale, + oversample: f32, + /// FT_Set_Transform's delta, in oversampled pixels (y down). + shift: (f32, f32), +} +enum Provider { + Space(HashMap), + Bitmap(Filter, HashMap), + /// The definition, and its glyphs once read. + Unihex(Filter, serde_json::Value, Option>), + TrueType(Filter, Box), +} +/// One font (`FontSet`): its providers and the glyphs resolved so far. +struct FontSet { + providers: Vec, + glyphs: HashMap, + /// `glyphsByWidth` for obfuscated text (built on first use). + by_width: Option>>, +} +/// The atlas region glyphs are rasterized into, filled in rows. +struct Region { + cursor: (u32, u32), + row: u32, + pending: Vec, } struct Cache { - glyphs: HashMap, - cursor: (u32, u32), - pending: Vec, - hex: Option>, - /// `FontSet.glyphsByWidth` for obfuscated text (built on first use). - by_width: Option>>, + /// Every font by id, the default one first (the common lookup). + sets: Vec<(String, FontSet)>, + region: Region, /// `Font.random`: picks obfuscated glyphs. random: horizon_core::random::LegacyRandom, } pub struct Font { - bitmap: HashMap, - space: HashMap, + /// The atlas rects of the sheets under `textures/font`. + sheets: HashMap, missing: Glyph, white: Rect, root: PathBuf, @@ -67,9 +129,9 @@ pub struct Font { atlas: (u32, u32), region: (u32, u32), cache: RefCell, - /// "Force Unicode Font": skip the bitmap providers (font/uniform.json). + /// "Force Unicode Font": the `uniform` filter option. pub uniform: bool, - /// "Japanese Glyph Variants": enable providers filtered on `jp`. + /// "Japanese Glyph Variants": the `jp` filter option. pub japanese: bool, } fn parse_hex_digit(b: u8) -> Option { @@ -178,9 +240,324 @@ fn glyph_rect(x: u32, y: u32, w: u32, h: u32, atlas: (u32, u32)) -> Rect { h, } } +/// The unscaled pixel width of a bitmap cell (`BitmapProvider.getActualGlyphWidth`). +fn used_width(pixels: &[u8], stride: u32, (cx, cy, cw, ch): (u32, u32, u32, u32)) -> u32 { + (0..cw) + .rev() + .find(|&x| { + (0..ch).any(|y| { + pixels + .get((((cy + y) * stride + cx + x) * 4 + 3) as usize) + .is_some_and(|a| *a != 0) + }) + }) + .map_or(0, |x| x + 1) +} +/// `BitmapProvider.Definition.load`: each character's glyph, from the atlas +/// when the sheet is in it (`pixels` its RGBA), else from the sheet's own +/// pixels, copied into the atlas when first drawn. +fn load_bitmap( + root: &Path, + p: &serde_json::Value, + sheets: &HashMap, + pixels: &[u8], + atlas: (u32, u32), +) -> HashMap { + let mut out = HashMap::new(); + let file = p["file"].as_str().unwrap_or(""); + let (ns, name) = file.split_once(':').unwrap_or(("minecraft", file)); + let in_atlas = (ns == "minecraft") + .then(|| sheets.get(name.trim_end_matches(".png")).copied()) + .flatten(); + // The sheet: its size, and its pixels when they are not in the atlas. + let (sw, sh, sheet) = match in_atlas { + Some(rect) => (rect.w, rect.h, None), + None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { + Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), + Err(_) => { + log::warn!("font sheet {file} could not be read"); + return out; + } + }, + }; + let rows: Vec> = p["chars"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r.as_str().map(|s| s.chars().collect())) + .collect(); + if rows.is_empty() || rows[0].is_empty() { + return out; + } + let cell_w = sw / rows[0].len() as u32; + let cell_h = sh / rows.len() as u32; + let height = p["height"].as_f64().unwrap_or(8.0) as f32; + let ascent = p["ascent"].as_f64().unwrap_or(7.0) as f32; + let scale = height / cell_h as f32; + let origin = in_atlas.map_or((0, 0), |rect| { + ( + (rect.u0 * atlas.0 as f32).round() as u32, + (rect.v0 * atlas.1 as f32).round() as u32, + ) + }); + for (r, row) in rows.iter().enumerate() { + for (c, ch) in row.iter().enumerate() { + if *ch == '\0' || out.contains_key(ch) { + continue; + } + let (x, y) = (c as u32 * cell_w, r as u32 * cell_h); + let used = match &sheet { + Some(s) => used_width(&s.1, s.0, (x, y, cell_w, cell_h)), + None => used_width( + pixels, + atlas.0, + (origin.0 + x, origin.1 + y, cell_w, cell_h), + ), + }; + let top = 7.0 - ascent; + let glyph = Glyph { + rect: None, + left: 0.0, + top, + right: cell_w as f32 * scale, + bottom: top + cell_h as f32 * scale, + advance: (0.5 + used as f32 * scale).floor() + 1.0, + offset: 1.0, + }; + let glyph = match &sheet { + None => BitmapGlyph::Atlas(Glyph { + rect: Some(glyph_rect( + origin.0 + x, + origin.1 + y, + cell_w, + cell_h, + atlas, + )), + ..glyph + }), + Some(s) => BitmapGlyph::Sheet(SheetCell { + sheet: s.clone(), + x, + y, + w: cell_w, + h: cell_h, + glyph, + }), + }; + out.insert(*ch, glyph); + } + } + out +} +/// `TrueTypeGlyphProviderDefinition.load`: a TrueType file (not CFF) under +/// `font/`, its Unicode characters but the `skip` ones. +fn load_true_type(root: &Path, p: &serde_json::Value) -> Option { + let file = p["file"].as_str()?; + let data = std::fs::read(root.join(resource_path(file, "font", ""))) + .map_err(|e| log::warn!("font file {file}: {e}")) + .ok()?; + // FT_Get_Font_Format must say TrueType: CFF outlines ("OTTO") are refused. + if data.starts_with(b"OTTO") { + log::warn!("font file {file} is not in TTF format"); + return None; + } + let font = ab_glyph::FontVec::try_from_vec(data) + .map_err(|e| log::warn!("font file {file}: {e}")) + .ok()?; + let size = p["size"].as_f64().unwrap_or(11.0) as f32; + let oversample = p["oversample"].as_f64().unwrap_or(1.0) as f32; + let shift = p["shift"].as_array().map_or((0.0, 0.0), |s| { + let f = |i: usize| s.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0) as f32; + (f(0), f(1)) + }); + let skip: Vec = match &p["skip"] { + serde_json::Value::String(s) => s.chars().collect(), + serde_json::Value::Array(a) => a + .iter() + .filter_map(|v| v.as_str()) + .flat_map(str::chars) + .collect(), + _ => Vec::new(), + }; + let ids = font + .codepoint_ids() + .filter(|(id, c)| id.0 != 0 && !skip.contains(c)) + .map(|(id, c)| (c, id)) + .collect(); + let pixels_per_em = (size * oversample).round(); + // ab_glyph scales by the font's height; FreeType by its em. + let units = font.units_per_em().unwrap_or(1000.0); + let scale = ab_glyph::PxScale::from(pixels_per_em * font.height_unscaled() / units); + Some(TrueType { + font, + ids, + scale, + oversample, + shift: (shift.0 * oversample, shift.1 * oversample), + }) +} +impl TrueType { + /// The advance in GUI pixels: hinted FreeType advances are whole + /// oversampled pixels. + fn advance(&self, id: ab_glyph::GlyphId) -> f32 { + self.font.as_scaled(self.scale).h_advance(id).round() / self.oversample + } + /// `loadGlyph` and its bitmap: the grey coverage as `rrrr` texels + /// (`text_intensity`), below 0.1 cut (its discard). + fn glyph(&self, id: ab_glyph::GlyphId) -> (Glyph, Option<(u32, u32, Vec)>) { + let advance = self.advance(id); + let glyph = + id.with_scale_and_position(self.scale, ab_glyph::point(self.shift.0, self.shift.1)); + let empty = Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance, + offset: 1.0, + }; + let Some(outline) = self.font.outline_glyph(glyph) else { + return (empty, None); + }; + let bounds = outline.px_bounds(); + let (w, h) = (bounds.width() as u32, bounds.height() as u32); + if w == 0 || h == 0 { + return (empty, None); + } + let mut rgba = vec![0u8; (w * h * 4) as usize]; + outline.draw(|x, y, coverage| { + let v = if coverage < 0.1 { + 0 + } else { + (coverage.min(1.0) * 255.0).round() as u8 + }; + let i = ((y * w + x) * 4) as usize; + if let Some(px) = rgba.get_mut(i..i + 4) { + px.copy_from_slice(&[v; 4]); + } + }); + let os = self.oversample; + // GlyphBitmap: bitmap_left / bitmap_top over the oversampling, and + // top = 7 - bearingTop. + let (left, top) = (bounds.min.x / os, 7.0 + bounds.min.y / os); + ( + Glyph { + rect: None, + left, + top, + right: left + w as f32 / os, + bottom: top + h as f32 / os, + advance, + offset: 1.0, + }, + Some((w, h, rgba)), + ) + } +} +fn load_hex(root: &Path, p: &serde_json::Value) -> HashMap { + let mut glyphs = HashMap::new(); + let Some(file) = p["hex_file"].as_str() else { + return glyphs; + }; + let path = root.join(resource_path(file, "", "").replace("//", "/")); + let Ok(zip) = Zip::open(&path) else { + return glyphs; + }; + let names: Vec = zip + .names() + .filter(|n| n.ends_with(".hex")) + .map(str::to_owned) + .collect(); + for name in names { + if let Ok(bytes) = zip.read(&name) { + parse_hex(&bytes, &mut glyphs); + } + } + for o in p["size_overrides"].as_array().into_iter().flatten() { + let bound = |k: &str| { + o[k].as_str() + .and_then(|s| s.chars().next()) + .map_or(0, u32::from) + }; + let (left, right) = ( + o["left"].as_u64().unwrap_or(0) as u32, + o["right"].as_u64().unwrap_or(15) as u32, + ); + for c in bound("from")..=bound("to") { + if let Some(g) = glyphs.get_mut(&c) { + g.left = left; + g.right = right; + } + } + } + glyphs +} +/// The ids of every font definition (`font/**/*.json` of each namespace). +fn font_ids(root: &Path) -> Vec { + fn walk(dir: &Path, prefix: &str, out: &mut Vec) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + if path.is_dir() { + walk(&path, &format!("{prefix}{name}/"), out); + } else if let Some(stem) = name.strip_suffix(".json") { + out.push(format!("{prefix}{stem}")); + } + } + } + let mut ids = Vec::new(); + for ns in std::fs::read_dir(root.join("assets")) + .into_iter() + .flatten() + .flatten() + { + let ns = ns.file_name().to_string_lossy().into_owned(); + walk( + &root.join("assets").join(&ns).join("font"), + &format!("{ns}:"), + &mut ids, + ); + } + ids.sort(); + ids +} +impl Region { + /// Place `w x h` pixels in the region (rows left to right); their atlas + /// position, or none when it is full. + fn place( + &mut self, + w: u32, + h: u32, + rgba: Vec, + atlas: (u32, u32), + region: (u32, u32), + ) -> Option<(u32, u32)> { + let (mut x, mut y) = self.cursor; + if x + w + 1 > atlas.0 { + x = 0; + y += self.row + 1; + self.row = 0; + } + if y + h > region.1 { + return None; + } + let (ax, ay) = (x, region.0 + y); + self.pending.push(Patch { + x: ax, + y: ay, + width: w, + height: h, + rgba, + }); + self.cursor = (x + w + 1, y); + self.row = self.row.max(h); + Some((ax, ay)) + } +} impl Font { - /// Build from the atlas holding the bitmap font sheets. `pixels` is the - /// RGBA atlas (for glyph widths) and `region` the reserved rows. + /// Build from the atlas holding the bitmap font sheets (`sprites`, of + /// `atlas` size) with `region` the reserved rows. pub fn load( root: &Path, sprites: &HashMap, @@ -189,107 +566,33 @@ impl Font { region: (u32, u32), white: Rect, ) -> Self { - let mut bitmap = HashMap::new(); - let mut space = HashMap::new(); - let mut all = Vec::new(); - providers(root, "minecraft:default", 0, &mut all); - for provider in &all { - match provider["type"].as_str() { - Some("space") => { - for (k, v) in provider["advances"].as_object().into_iter().flatten() { - if let (Some(c), Some(a)) = (k.chars().next(), v.as_f64()) { - space.entry(c).or_insert(a as f32); - } - } - } - Some("bitmap") => { - // Only non-uniform bitmap sheets exist in the default font. - let file = provider["file"].as_str().unwrap_or(""); - let name = file - .trim_start_matches("minecraft:") - .trim_end_matches(".png"); - let name = name.to_string(); - let Some(rect) = sprites.get(&name).copied() else { - continue; - }; - let rows: Vec> = provider["chars"] - .as_array() - .into_iter() - .flatten() - .filter_map(|r| r.as_str().map(|s| s.chars().collect())) - .collect(); - if rows.is_empty() || rows[0].is_empty() { - continue; - } - let cell_w = rect.w / rows[0].len() as u32; - let cell_h = rect.h / rows.len() as u32; - let height = provider["height"].as_f64().unwrap_or(8.0) as f32; - let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32; - let scale = height / cell_h as f32; - let (ax, ay) = ( - (rect.u0 * atlas.0 as f32).round() as u32, - (rect.v0 * atlas.1 as f32).round() as u32, - ); - for (r, row) in rows.iter().enumerate() { - for (c, ch) in row.iter().enumerate() { - if *ch == '\0' || bitmap.contains_key(ch) { - continue; - } - let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h); - // BitmapProvider.getActualGlyphWidth. - let mut used = 0; - for x in (0..cell_w).rev() { - if (0..cell_h).any(|y| { - pixels - .get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize) - .is_some_and(|a| *a != 0) - }) { - used = x + 1; - break; - } - } - let top = 7.0 - ascent; - bitmap.insert( - *ch, - Glyph { - rect: Some(glyph_rect(cx, cy, cell_w, cell_h, atlas)), - left: 0.0, - top, - right: cell_w as f32 * scale, - bottom: top + cell_h as f32 * scale, - advance: (0.5 + used as f32 * scale).floor() + 1.0, - offset: 1.0, - }, - ); - } - } - } - _ => {} - } - } - let missing = Glyph { - rect: None, - left: 0.0, - top: 0.0, - right: 5.0, - bottom: 8.0, - advance: 6.0, - offset: 1.0, - }; - Self { - bitmap, - space, - missing, + let sheets = sprites + .iter() + .filter(|(k, _)| k.starts_with("font/")) + .map(|(k, v)| (k.clone(), *v)) + .collect(); + let font = Self { + sheets, + missing: Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 5.0, + bottom: 8.0, + advance: 6.0, + offset: 1.0, + }, white, root: root.to_owned(), atlas, region, cache: RefCell::new(Cache { - glyphs: HashMap::new(), - cursor: (0, 0), - pending: Vec::new(), - hex: None, - by_width: None, + sets: Vec::new(), + region: Region { + cursor: (0, 0), + row: 0, + pending: Vec::new(), + }, random: horizon_core::random::LegacyRandom::new( std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -298,120 +601,161 @@ impl Font { }), uniform: false, japanese: false, - } + }; + // FontManager.prepare: every font definition of the resources. + let mut ids = font_ids(root); + ids.sort_by_key(|id| id != DEFAULT); + let sets = ids + .into_iter() + .map(|id| { + let set = font.load_set(&id, pixels); + (id, set) + }) + .collect(); + font.cache.borrow_mut().sets = sets; + font } - fn load_hex(&self) -> Vec { + /// `FontManager`: a font's providers with references expanded. + fn load_set(&self, id: &str, pixels: &[u8]) -> FontSet { let mut all = Vec::new(); - providers(&self.root, "minecraft:default", 0, &mut all); - let mut out = Vec::new(); - for p in all.iter().filter(|p| p["type"] == "unihex") { - if let Some(filter) = p["filter"].as_object() { - let pass = filter.iter().all(|(k, v)| match k.as_str() { - "jp" => v.as_bool() == Some(self.japanese), - "uniform" => v.as_bool() == Some(self.uniform), - _ => true, - }); - if !pass { - continue; - } - } - let Some(file) = p["hex_file"].as_str() else { - continue; - }; - let path = self - .root - .join(resource_path(file, "", "").replace("//", "/")); - let Ok(zip) = Zip::open(&path) else { continue }; - let mut provider = HexProvider::default(); - let names: Vec = zip - .names() - .filter(|n| n.ends_with(".hex")) - .map(str::to_owned) - .collect(); - for name in names { - if let Ok(bytes) = zip.read(&name) { - parse_hex(&bytes, &mut provider.glyphs); - } - } - for o in p["size_overrides"].as_array().into_iter().flatten() { - let from = o["from"] - .as_str() - .and_then(|s| s.chars().next()) - .map_or(0, u32::from); - let to = o["to"] - .as_str() - .and_then(|s| s.chars().next()) - .map_or(0, u32::from); - let (left, right) = ( - o["left"].as_u64().unwrap_or(0) as u32, - o["right"].as_u64().unwrap_or(15) as u32, - ); - for c in from..=to { - if let Some(g) = provider.glyphs.get_mut(&c) { - g.left = left; - g.right = right; - } - } - } - out.push(provider); + providers(&self.root, id, 0, &mut all); + let providers = all + .iter() + .filter_map(|p| match p["type"].as_str()? { + "space" => Some(Provider::Space( + p["advances"] + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.chars().next()?, v.as_f64()? as f32))) + .collect(), + )), + "bitmap" => Some(Provider::Bitmap( + Filter::of(p), + load_bitmap(&self.root, p, &self.sheets, pixels, self.atlas), + )), + "unihex" => Some(Provider::Unihex(Filter::of(p), p.clone(), None)), + "ttf" => Some(Provider::TrueType( + Filter::of(p), + Box::new(load_true_type(&self.root, p)?), + )), + _ => None, + }) + .collect(); + FontSet { + providers, + glyphs: HashMap::new(), + by_width: None, } - out } - /// Forget rasterized fallback glyphs (after changing font options). + /// Forget rasterized glyphs (after changing font options). pub fn reset_cache(&self) { let mut cache = self.cache.borrow_mut(); - cache.glyphs.clear(); - cache.cursor = (0, 0); - cache.hex = None; - cache.by_width = None; + for (_, set) in &mut cache.sets { + set.glyphs.clear(); + set.by_width = None; + } + cache.region.cursor = (0, 0); + cache.region.row = 0; } - /// The glyph for a character (FontSet.getGlyph). + /// The glyph for a character in the default font (FontSet.getGlyph). pub fn glyph(&self, c: char) -> Glyph { - if let Some(a) = self.space.get(&c) { - return Glyph { - rect: None, - left: 0.0, - top: 0.0, - right: 0.0, - bottom: 0.0, - advance: *a, - offset: 1.0, - }; - } - if !self.uniform - && let Some(g) = self.bitmap.get(&c) - { - return *g; - } - if let Some(g) = self.cache.borrow().glyphs.get(&c) { - return *g; + self.glyph_of(DEFAULT, c) + } + /// The glyph for a character drawn in `style`'s font (its id is + /// already complete, see `text::font_id`). + pub fn glyph_styled(&self, c: char, style: &Style) -> Glyph { + self.glyph_of(style.font.as_deref().unwrap_or(DEFAULT), c) + } + /// The glyph for a character in the font `id` (`alt` is `minecraft:alt`). + pub fn glyph_in(&self, id: &str, c: char) -> Glyph { + if id.contains(':') { + self.glyph_of(id, c) + } else { + self.glyph_of(&format!("minecraft:{id}"), c) } + } + /// The first active provider's glyph, else the missing glyph. + fn glyph_of(&self, id: &str, c: char) -> Glyph { let mut cache = self.cache.borrow_mut(); - if cache.hex.is_none() { - cache.hex = Some(self.load_hex()); - } - let hex = cache.hex.as_ref().and_then(|providers| { - providers - .iter() - .find_map(|p| p.glyphs.get(&u32::from(c)).copied()) - }); - let glyph = match hex { - Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing), - None => self.missing, + let Cache { sets, region, .. } = &mut *cache; + // FontManager.getFontSetRaw: a font that doesn't exist draws every + // character as the missing glyph. + let Some((_, set)) = sets.iter_mut().find(|(k, _)| k == id) else { + return self.missing; }; - cache.glyphs.insert(c, glyph); + if let Some(g) = set.glyphs.get(&c) { + return *g; + } + let glyph = self.resolve(set, region, c).unwrap_or(self.missing); + set.glyphs.insert(c, glyph); glyph } - fn rasterize(&self, cache: &mut Cache, h: HexGlyph) -> Option { + fn resolve(&self, set: &mut FontSet, region: &mut Region, c: char) -> Option { + let (uniform, japanese) = (self.uniform, self.japanese); + for provider in &mut set.providers { + match provider { + Provider::Space(advances) => { + if let Some(a) = advances.get(&c) { + return Some(Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance: *a, + offset: 1.0, + }); + } + } + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + match glyphs.get(&c) { + Some(BitmapGlyph::Atlas(g)) => return Some(*g), + Some(BitmapGlyph::Sheet(cell)) => { + let (stride, pixels) = (&cell.sheet.0, &cell.sheet.1); + let mut rgba = Vec::with_capacity((cell.w * cell.h * 4) as usize); + for y in cell.y..cell.y + cell.h { + let at = ((y * stride + cell.x) * 4) as usize; + rgba.extend_from_slice(&pixels[at..at + (cell.w * 4) as usize]); + } + let (x, y) = + region.place(cell.w, cell.h, rgba, self.atlas, self.region)?; + return Some(Glyph { + rect: Some(glyph_rect(x, y, cell.w, cell.h, self.atlas)), + ..cell.glyph + }); + } + None => {} + } + } + Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => { + let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def)); + if let Some(h) = glyphs.get(&u32::from(c)).copied() { + return self.rasterize_hex(region, h); + } + } + Provider::TrueType(filter, ttf) if filter.passes(uniform, japanese) => { + if let Some(id) = ttf.ids.get(&c) { + let (glyph, bitmap) = ttf.glyph(*id); + return match bitmap { + Some((w, h, rgba)) => { + let (x, y) = region.place(w, h, rgba, self.atlas, self.region)?; + Some(Glyph { + rect: Some(glyph_rect(x, y, w, h, self.atlas)), + ..glyph + }) + } + None => Some(glyph), + }; + } + } + _ => {} + } + } + None + } + fn rasterize_hex(&self, region: &mut Region, h: HexGlyph) -> Option { let width = h.right.saturating_sub(h.left) + 1; - let (mut x, mut y) = cache.cursor; - if x + width + 1 > self.atlas.0 { - x = 0; - y += 17; - } - if y + 16 > self.region.1 { - return None; - } let mut rgba = Vec::with_capacity((width * 16 * 4) as usize); for row in h.rows { for bit in h.left..=h.right { @@ -419,17 +763,9 @@ impl Font { rgba.extend(if set { [255; 4] } else { [0; 4] }); } } - let (ax, ay) = (x, self.region.0 + y); - cache.pending.push(Patch { - x: ax, - y: ay, - width, - height: 16, - rgba, - }); - cache.cursor = (x + width + 1, y); + let (x, y) = region.place(width, 16, rgba, self.atlas, self.region)?; Some(Glyph { - rect: Some(glyph_rect(ax, ay, width, 16, self.atlas)), + rect: Some(glyph_rect(x, y, width, 16, self.atlas)), left: 0.0, top: 0.0, right: width as f32 / 2.0, @@ -439,26 +775,29 @@ impl Font { }) } /// `FontSet.getRandomGlyph`: what an obfuscated character draws, a random - /// glyph as wide as `advance` (rounded up), else the missing glyph. + /// glyph of the font as wide as `advance` (rounded up), else the missing + /// glyph. /// /// Vanilla picks among every glyph of the font set, Unifont's included. /// Those are rasterized into a fixed atlas region on demand, which a /// line of obfuscated text would fill in seconds, so the candidates are - /// the glyphs already in the atlas (the bitmap sheets and spaces), or with - /// "Force Unicode Font" the Unifont glyphs below U+0250. - pub fn random_glyph(&self, advance: f32) -> Glyph { + /// the glyphs already in the atlas (the bitmap sheets there and spaces), + /// or for a font without any (Force Unicode Font, a TrueType font) its + /// glyphs below U+0250. + pub fn random_glyph(&self, style: &Style, advance: f32) -> Glyph { use horizon_core::random::RandomSource; + let id = style.font.as_deref().unwrap_or(DEFAULT); let width = advance.ceil() as u32; let pick = { let mut cache = self.cache.borrow_mut(); - if cache.by_width.is_none() { - let by_width = self.glyphs_by_width(&mut cache); - cache.by_width = Some(by_width); + let Cache { sets, random, .. } = &mut *cache; + let Some((_, set)) = sets.iter_mut().find(|(k, _)| k == id) else { + return self.missing; + }; + if set.by_width.is_none() { + set.by_width = Some(self.glyphs_by_width(set)); } - let Cache { - by_width, random, .. - } = &mut *cache; - by_width + set.by_width .as_ref() .and_then(|m| m.get(&width)) .and_then(|chars| { @@ -466,44 +805,79 @@ impl Font { chars.get(i as usize).copied() }) }; - pick.map_or(self.missing, |c| self.glyph(c)) + pick.map_or(self.missing, |c| self.glyph_of(id, c)) } - fn glyphs_by_width(&self, cache: &mut Cache) -> HashMap> { - let mut chars: Vec<(char, f32)> = self.space.iter().map(|(c, a)| (*c, *a)).collect(); - if self.uniform { - if cache.hex.is_none() { - cache.hex = Some(self.load_hex()); - } - for code in 0..0x250u32 { - let hex = cache.hex.iter().flatten().find_map(|p| p.glyphs.get(&code)); - if let (Some(c), Some(h)) = (char::from_u32(code), hex) - && !self.space.contains_key(&c) - { - let width = h.right.saturating_sub(h.left) + 1; - chars.push((c, (width / 2 + 1) as f32)); + fn glyphs_by_width(&self, set: &mut FontSet) -> HashMap> { + let (uniform, japanese) = (self.uniform, self.japanese); + let mut chars = std::collections::BTreeSet::new(); + let mut in_atlas = false; + for provider in &set.providers { + match provider { + Provider::Space(advances) => chars.extend(advances.keys().copied()), + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + for (c, g) in glyphs { + if matches!(g, BitmapGlyph::Atlas(_)) { + in_atlas = true; + chars.insert(*c); + } + } } + _ => {} } - } else { - chars.extend( - self.bitmap - .iter() - .filter(|(c, _)| !self.space.contains_key(c)) - .map(|(c, g)| (*c, g.advance)), - ); } - chars.sort_by_key(|(c, _)| *c); + if !in_atlas { + // Nothing in the atlas: the glyphs below U+0250, rasterized as used. + chars.extend((0..0x250u32).filter_map(char::from_u32)); + } let mut out: HashMap> = HashMap::new(); - for (c, advance) in chars { - out.entry(advance.ceil() as u32).or_default().push(c); + for c in chars { + if let Some(advance) = self.provider_advance(set, c) { + out.entry(advance.ceil() as u32).or_default().push(c); + } } out } + /// A character's advance in `set` (its first provider that has it), + /// without rasterizing it. + fn provider_advance(&self, set: &mut FontSet, c: char) -> Option { + let (uniform, japanese) = (self.uniform, self.japanese); + for provider in &mut set.providers { + match provider { + Provider::Space(advances) => { + if let Some(a) = advances.get(&c) { + return Some(*a); + } + } + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + match glyphs.get(&c) { + Some(BitmapGlyph::Atlas(g)) => return Some(g.advance), + Some(BitmapGlyph::Sheet(cell)) => return Some(cell.glyph.advance), + None => {} + } + } + Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => { + let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def)); + if let Some(h) = glyphs.get(&u32::from(c)) { + let width = h.right.saturating_sub(h.left) + 1; + return Some((width / 2 + 1) as f32); + } + } + Provider::TrueType(filter, ttf) if filter.passes(uniform, japanese) => { + if let Some(id) = ttf.ids.get(&c) { + return Some(ttf.advance(*id)); + } + } + _ => {} + } + } + None + } /// Atlas pixels rasterized since the last call. pub fn take_patches(&self) -> Vec { - std::mem::take(&mut self.cache.borrow_mut().pending) + std::mem::take(&mut self.cache.borrow_mut().region.pending) } pub fn advance(&self, c: char, style: &Style) -> f32 { - let g = self.glyph(c); + let g = self.glyph_styled(c, style); g.advance + if style.is_bold() { g.offset } else { 0.0 } } /// Font.width of plain text (legacy codes are formatting, not glyphs). @@ -689,4 +1063,155 @@ mod tests { assert_eq!(r.v1, ((y + h) as f32 - 0.01) / 4096.0); } } + + /// A resource root with these font definitions and files. + fn root(name: &str, files: &[(&str, &[u8])]) -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-font-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + for (path, bytes) in files { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + root + } + fn white() -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 0.0, + v1: 0.0, + w: 1, + h: 1, + } + } + fn load(root: &Path) -> Font { + Font::load( + root, + &HashMap::new(), + &[], + (4096, 1024), + (512, 512), + white(), + ) + } + fn png(width: u32, height: u32, opaque: impl Fn(u32, u32) -> bool) -> Vec { + let mut pixels = Vec::new(); + for y in 0..height { + for x in 0..width { + pixels.extend(if opaque(x, y) { [255; 4] } else { [0; 4] }); + } + } + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + out + } + + #[test] + fn true_type_glyphs_are_rasterized_at_the_provider_size() { + let def = br#"{"providers":[{"type":"ttf","file":"minecraft:mono.ttf","size":11,"oversample":2,"shift":[0.5,1],"skip":["B"]}]}"#; + let root = root( + "ttf", + &[ + ("assets/minecraft/font/default.json", def), + ( + "assets/minecraft/font/mono.ttf", + horizon_theme::fonts::GEIST_MONO, + ), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + let a = font.glyph('A'); + let rect = a.rect.expect("A is drawn"); + // Oversampled 2x: the bitmap is twice the glyph's GUI size. + assert_eq!(rect.w as f32 / 2.0, a.right - a.left); + assert_eq!(rect.h as f32 / 2.0, a.bottom - a.top); + // A monospaced font: every advance is the same, in half pixels. + assert_eq!(a.advance, font.glyph('i').advance); + assert_eq!((a.advance * 2.0).fract(), 0.0); + assert!(a.advance > 4.0 && a.advance < 9.0, "{}", a.advance); + // Capitals sit on the baseline at y = 7, shifted down a pixel. + assert!((a.bottom - 8.0).abs() <= 0.5, "{}", a.bottom); + assert_eq!(a.offset, 1.0); + // The space has an advance and nothing to draw. + let space = font.glyph(' '); + assert!(space.rect.is_none() && space.advance > 0.0); + // Skipped characters fall through to the missing glyph. + assert_eq!(font.glyph('B').advance, 6.0); + // Coverage as `rrrr` texels, faint coverage cut. + let patches = font.take_patches(); + assert_eq!(patches.len(), 2); + let texels: Vec<&[u8]> = patches.iter().flat_map(|p| p.rgba.chunks(4)).collect(); + assert!(texels.iter().all(|t| t.iter().all(|v| *v == t[0]))); + assert!(texels.iter().all(|t| t[0] == 0 || t[0] >= 25)); + assert!(texels.iter().any(|t| t[0] == 255)); + } + + #[test] + fn styles_pick_their_font_and_unknown_fonts_draw_missing_glyphs() { + let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x)); + let default = br#"{"providers":[{"type":"space","advances":{" ":4}},{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#; + let alt = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ba"]}]}"#; + let root = root( + "styles", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/font/alt.json", alt), + ("assets/minecraft/textures/font/a.png", &sheet), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + // The sheet is not in this atlas: glyphs are copied in when first drawn. + assert_eq!(font.glyph('a').advance, 3.0); + assert_eq!(font.glyph('b').advance, 7.0); + let alt = Style { + font: Some("minecraft:alt".into()), + ..Style::default() + }; + assert_eq!(font.glyph_styled('a', &alt).advance, 7.0); + assert_eq!(font.glyph_in("alt", 'b').advance, 3.0); + assert!(font.glyph_styled('a', &alt).rect.is_some()); + // Not in alt (no space provider there), or no such font at all. + assert_eq!(font.glyph_styled(' ', &alt).advance, 6.0); + let missing = Style { + font: Some("minecraft:nope".into()), + ..Style::default() + }; + assert_eq!(font.glyph_styled(' ', &missing).advance, 6.0); + assert_eq!(font.advance('a', &alt), 7.0); + let text = Text::literal("ab").with_style(&alt); + assert_eq!(font.width_text(&text), 10.0); + assert_eq!(font.random_glyph(&alt, 7.0).advance, 7.0); + assert!(!font.take_patches().is_empty()); + } + + #[test] + fn provider_filters_follow_the_font_options() { + let sheet = png(8, 8, |x, _| x < 4); + let default = br#"{"providers":[{"type":"reference","id":"minecraft:include/sheet","filter":{"uniform":false}},{"type":"space","advances":{"a":2}}]}"#; + let sheet_def = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/s.png","ascent":7,"chars":["a"]}]}"#; + let root = root( + "filters", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/font/include/sheet.json", sheet_def), + ("assets/minecraft/textures/font/s.png", &sheet), + ], + ); + let mut font = load(&root); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(font.glyph('a').advance, 5.0); + font.uniform = true; + font.reset_cache(); + assert_eq!(font.glyph('a').advance, 2.0); + } } diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 29faf5a2a..3c33ecb18 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -711,11 +711,12 @@ impl HudBatch { let mut glyphs = Vec::new(); let mut cursor = x; for (i, (ch, style)) in text.chars().enumerate() { - let mut g = font.glyph(ch); + // The style's font (`Style.getFont`), the default one unless set. + let mut g = font.glyph_styled(ch, style); // Font.StringRenderOutput.accept: obfuscated characters draw a // random glyph of the same width each frame. if style.obfuscated == Some(true) && ch != ' ' { - g = font.random_glyph(g.advance); + g = font.random_glyph(style, g.advance); } let c = style.color.map_or(color, |rgb| { rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha) @@ -1263,11 +1264,11 @@ mod tests { let (a, b) = (fonts.font.glyph('a').advance, fonts.font.glyph('b').advance); assert_ne!(a, b); for _ in 0..20 { - assert_eq!(fonts.font.random_glyph(a).advance, a); - assert_eq!(fonts.font.random_glyph(b).advance, b); + assert_eq!(fonts.font.random_glyph(&Default::default(), a).advance, a); + assert_eq!(fonts.font.random_glyph(&Default::default(), b).advance, b); } // No glyph that wide: FontSet's missing glyph. - let missing = fonts.font.random_glyph(30.0); + let missing = fonts.font.random_glyph(&Default::default(), 30.0); assert!(missing.rect.is_none() && missing.right == 5.0); } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 7af7518f8..7bd4fd782 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -87,6 +87,7 @@ fn style_of(o: &serde_json::Map) -> Style { underlined: flag("underlined"), strikethrough: flag("strikethrough"), obfuscated: flag("obfuscated"), + font: o.get("font").and_then(crate::text::font_id), ..Style::default() } } diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client/src/scoreboard.rs index e063c6f09..4796be51a 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client/src/scoreboard.rs @@ -118,6 +118,7 @@ pub fn style_from_json(v: &Value) -> Style { s.underlined = flag("underlined"); s.strikethrough = flag("strikethrough"); s.obfuscated = flag("obfuscated"); + s.font = o.get("font").and_then(text::font_id); s } impl NumberFormat { diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 3874efd17..9f39155d1 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -61,6 +61,13 @@ pub struct Style { pub click: Option, /// Hover text. pub hover: Option>, + /// The font (`FontDescription.Resource`), a full id like + /// `minecraft:alt`; the default font when unset. + pub font: Option, +} +/// A style's `font` field: an identifier (`alt` is `minecraft:alt`). +pub fn font_id(v: &Value) -> Option { + crate::command::args::parse_identifier(v.as_str()?) } impl Style { pub fn color(c: u32) -> Self { @@ -83,6 +90,9 @@ impl Style { if self.hover.is_none() { self.hover.clone_from(&base.hover); } + if self.font.is_none() { + self.font.clone_from(&base.font); + } } pub fn is_bold(&self) -> bool { self.bold == Some(true) @@ -451,7 +461,7 @@ impl Text { } /// The style fields of a component's JSON. -const STYLE_KEYS: [&str; 8] = [ +const STYLE_KEYS: [&str; 9] = [ "color", "bold", "italic", @@ -460,6 +470,7 @@ const STYLE_KEYS: [&str; 8] = [ "obfuscated", "click_event", "hover_event", + "font", ]; /// Style.Serializer: the fields a style sets. fn style_json(style: &Style) -> Vec<(String, Value)> { @@ -500,6 +511,9 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { json!({ "action": "show_text", "value": hover.component() }), )); } + if let Some(font) = &style.font { + out.push(("font".to_owned(), font.clone().into())); + } out }