1//! Deterministic vector text for `TextPlus` / `Text3D`: system font discovery (`fontdb`),
2//! HarfBuzz-compatible shaping (`rustybuzz`), OpenType outlines and analytic `zeno` fill and
3//! stroke. No platform text stack is involved, so glyph coverage depends only on the font file.
4
5use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag};
6use rustybuzz::{Face, Feature, UnicodeBuffer, Variation};
7use std::collections::{HashMap, HashSet, VecDeque};
8#[cfg(not(target_arch = "wasm32"))]
9use std::path::PathBuf;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::{Arc, Mutex, OnceLock, RwLock};
12use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};
13
14/// Tried in order when the requested family is not installed.
15const FALLBACK_FAMILIES: [&str; 6] =
16 ["Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "Open Sans", "DejaVu Sans"];
17
18/// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face.
19const SYNTHETIC_ITALIC: f32 = 0.2126;
20
21static NEXT_FONT_ID: AtomicU64 = AtomicU64::new(1);
22
23/// A resolved font file; `face()` parses it on demand.
24pub struct Font {
25 id: u64,
26 data: Vec<u8>,
27 index: u32,
28 weight: u16,
29 lean: f32,
30}
31
32impl Font {
33 /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the
34 /// system fonts and any fonts registered via [`register_font_bytes`], falling back through
35 /// [`FALLBACK_FAMILIES`] and finally any installed face.
36 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
37 {
38 let cache = font_cache().lock().unwrap();
39 if let Some(hit) = cache.1.get(&(family.to_owned(), style.to_owned())) {
40 return hit.clone();
41 }
42 }
43 let (resolved, resolved_gen) = {
44 let mut reg = registry().write().unwrap();
45 (resolve_lazy(&mut reg, family, style).map(Arc::new), reg.generation)
46 };
47 cache_resolved_font(family, style, resolved, resolved_gen)
48 }
49
50 pub fn face(&self) -> Face<'_> {
51 let mut face = Face::from_slice(&self.data, self.index).expect("font validated on load");
52 if face.is_variable() {
53 face.set_variations(&[Variation { tag: Tag::from_bytes(b"wght"), value: self.weight as f32 }]);
54 }
55 face
56 }
57}
58
59struct FontRegistry {
60 db: fontdb::Database,
61 aliases: HashMap<String, Vec<fontdb::ID>>,
62 generation: u64,
63 #[cfg(not(target_arch = "wasm32"))]
64 system_fonts_loaded: bool,
65 #[cfg(not(target_arch = "wasm32"))]
66 loaded_paths: HashSet<PathBuf>,
67 #[cfg(not(target_arch = "wasm32"))]
68 loaded_families: HashSet<String>,
69 #[cfg(not(target_arch = "wasm32"))]
70 loaded_style_keys: HashSet<(String, String)>,
71}
72
73impl FontRegistry {
74 fn new() -> Self {
75 Self {
76 db: fontdb::Database::new(),
77 aliases: HashMap::new(),
78 generation: 0,
79 #[cfg(not(target_arch = "wasm32"))]
80 system_fonts_loaded: false,
81 #[cfg(not(target_arch = "wasm32"))]
82 loaded_paths: HashSet::new(),
83 #[cfg(not(target_arch = "wasm32"))]
84 loaded_families: HashSet::new(),
85 #[cfg(not(target_arch = "wasm32"))]
86 loaded_style_keys: HashSet::new(),
87 }
88 }
89
90 #[cfg(not(target_arch = "wasm32"))]
91 fn ensure_system_fonts_loaded(&mut self) {
92 if !self.system_fonts_loaded {
93 self.db.load_system_fonts();
94 self.system_fonts_loaded = true;
95 }
96 }
97}
98
99type FontCacheMap = HashMap<(String, String), Option<Arc<Font>>>;
100
101fn font_cache() -> &'static Mutex<(u64, FontCacheMap)> {
102 static CACHE: OnceLock<Mutex<(u64, FontCacheMap)>> = OnceLock::new();
103 CACHE.get_or_init(Default::default)
104}
105
106fn cache_resolved_font(
107 family: &str,
108 style: &str,
109 resolved: Option<Arc<Font>>,
110 resolved_gen: u64,
111) -> Option<Arc<Font>> {
112 let mut cache = font_cache().lock().unwrap();
113 if cache.0 != resolved_gen {
114 if cache.0 < resolved_gen {
115 cache.0 = resolved_gen;
116 cache.1.clear();
117 } else {
118 return resolved;
119 }
120 }
121 let entry = cache
122 .1
123 .entry((family.to_owned(), style.to_owned()))
124 .or_insert_with(|| resolved.clone());
125 entry.clone()
126}
127
128fn registry() -> &'static RwLock<FontRegistry> {
129 static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new();
130 REG.get_or_init(|| RwLock::new(FontRegistry::new()))
131}
132
133#[cfg(not(target_arch = "wasm32"))]
134struct FontFileEntry {
135 path: PathBuf,
136 stem_norm: String,
137}
138
139#[cfg(not(target_arch = "wasm32"))]
140fn norm_alnum(s: &str) -> String {
141 s.chars()
142 .filter(|c| c.is_ascii_alphanumeric())
143 .map(|c| c.to_ascii_lowercase())
144 .collect()
145}
146
147#[cfg(not(target_arch = "wasm32"))]
148fn is_font_extension(path: &std::path::Path) -> bool {
149 path.extension()
150 .and_then(|e| e.to_str())
151 .is_some_and(|ext| {
152 ext.eq_ignore_ascii_case("ttf")
153 || ext.eq_ignore_ascii_case("otf")
154 || ext.eq_ignore_ascii_case("ttc")
155 || ext.eq_ignore_ascii_case("otc")
156 })
157}
158
159#[cfg(not(target_arch = "wasm32"))]
160fn collect_font_dir(dir: &std::path::Path, depth: u8, out: &mut Vec<FontFileEntry>) {
161 let Ok(entries) = std::fs::read_dir(dir) else {
162 return;
163 };
164 for entry in entries.flatten() {
165 let path = entry.path();
166 if path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) {
167 continue;
168 }
169 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
170 || (entry.file_type().map(|ft| ft.is_symlink()).unwrap_or(false) && path.is_dir());
171 if is_dir {
172 if depth > 0 {
173 collect_font_dir(&path, depth - 1, out);
174 }
175 } else if is_font_extension(&path) {
176 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
177 let stem_norm = norm_alnum(stem);
178 if !stem_norm.is_empty() {
179 out.push(FontFileEntry { path, stem_norm });
180 }
181 }
182 }
183 }
184}
185
186#[cfg(not(target_arch = "wasm32"))]
187fn system_font_index() -> &'static [FontFileEntry] {
188 static INDEX: OnceLock<Vec<FontFileEntry>> = OnceLock::new();
189 INDEX.get_or_init(|| {
190 let mut out = Vec::with_capacity(768);
191 let mut dirs: Vec<PathBuf> = Vec::new();
192 #[cfg(target_os = "macos")]
193 {
194 dirs.push(PathBuf::from("/System/Library/Fonts"));
195 dirs.push(PathBuf::from("/Library/Fonts"));
196 if let Some(home) = std::env::var_os("HOME") {
197 dirs.push(PathBuf::from(home).join("Library/Fonts"));
198 }
199 }
200 #[cfg(all(unix, not(target_os = "macos")))]
201 {
202 dirs.push(PathBuf::from("/usr/share/fonts"));
203 dirs.push(PathBuf::from("/usr/local/share/fonts"));
204 if let Some(home) = std::env::var_os("HOME") {
205 let h = PathBuf::from(home);
206 dirs.push(h.join(".local/share/fonts"));
207 dirs.push(h.join(".fonts"));
208 }
209 }
210 #[cfg(target_os = "windows")]
211 {
212 if let Some(win) = std::env::var_os("WINDIR") {
213 dirs.push(PathBuf::from(win).join("Fonts"));
214 }
215 if let Some(local) = std::env::var_os("LOCALAPPDATA") {
216 dirs.push(PathBuf::from(local).join("Microsoft/Windows/Fonts"));
217 }
218 }
219 for d in &dirs {
220 collect_font_dir(d, 4, &mut out);
221 }
222 out
223 })
224}
225
226#[cfg(not(target_arch = "wasm32"))]
227fn is_style_suffix(rest: &str) -> bool {
228 const PREFIXES: &[&str] = &[
229 "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy",
230 "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow",
231 "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps",
232 "b", "i", "z", "l", "sl", "sb", "cond", "display", "text",
233 "100", "200", "300", "400", "500", "600", "700", "800", "900",
234 ];
235 rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p))
236}
237
238#[cfg(not(target_arch = "wasm32"))]
239fn load_style_candidates(reg: &mut FontRegistry, fam_norm: &str, style_key: &str) {
240 if fam_norm.is_empty() || reg.system_fonts_loaded || reg.loaded_families.contains(fam_norm) {
241 return;
242 }
243 let key = (fam_norm.to_owned(), style_key.to_owned());
244 if !reg.loaded_style_keys.insert(key) {
245 return;
246 }
247 let combined_len = fam_norm.len() + style_key.len();
248 for entry in system_font_index() {
249 let exact_match = entry.stem_norm == fam_norm
250 || (entry.stem_norm.len() == combined_len
251 && entry.stem_norm.starts_with(fam_norm)
252 && entry.stem_norm.ends_with(style_key));
253 if exact_match && reg.loaded_paths.insert(entry.path.clone()) {
254 let _ = reg.db.load_font_file(&entry.path);
255 }
256 }
257}
258
259#[cfg(not(target_arch = "wasm32"))]
260fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) {
261 if fam_norm.is_empty() || reg.system_fonts_loaded || !reg.loaded_families.insert(fam_norm.to_owned()) {
262 return;
263 }
264 for entry in system_font_index() {
265 if let Some(rest) = entry.stem_norm.strip_prefix(fam_norm) {
266 if is_style_suffix(rest) && reg.loaded_paths.insert(entry.path.clone()) {
267 let _ = reg.db.load_font_file(&entry.path);
268 }
269 }
270 }
271}
272
273/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime
274/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.
275pub fn register_font_bytes(bytes: Vec<u8>) {
276 let new_gen = {
277 let mut reg = registry().write().unwrap();
278 reg.db.load_font_data(bytes);
279 reg.generation += 1;
280 reg.generation
281 };
282 let mut cache = font_cache().lock().unwrap();
283 if cache.0 < new_gen {
284 cache.0 = new_gen;
285 cache.1.clear();
286 }
287}
288
289/// Registers font bytes under an explicit family alias in addition to its embedded family names,
290/// and clears the resolution cache.
291pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
292 let new_gen = {
293 let mut reg = registry().write().unwrap();
294 let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect();
295 reg.db.load_font_data(bytes);
296 if !family.is_empty() {
297 let added: Vec<fontdb::ID> = reg.db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect();
298 if !added.is_empty() {
299 reg.aliases
300 .entry(family.to_ascii_lowercase())
301 .or_default()
302 .extend(added);
303 }
304 }
305 reg.generation += 1;
306 reg.generation
307 };
308 let mut cache = font_cache().lock().unwrap();
309 if cache.0 < new_gen {
310 cache.0 = new_gen;
311 cache.1.clear();
312 }
313}
314
315/// CSS-style weight and italic flag for a Fusion style name.
316pub fn parse_style(style: &str) -> (u16, bool) {
317 let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
318 let weight = if s.contains("black") || s.contains("heavy") {
319 900
320 } else if s.contains("extrabold") || s.contains("ultrabold") {
321 800
322 } else if s.contains("semibold") || s.contains("demibold") || s.contains("demi") {
323 600
324 } else if s.contains("bold") {
325 700
326 } else if s.contains("medium") {
327 500
328 } else if s.contains("extralight") || s.contains("ultralight") || s.contains("thin") || s.contains("hairline") {
329 200
330 } else if s.contains("light") {
331 300
332 } else {
333 400
334 };
335 (weight, s.contains("italic") || s.contains("oblique"))
336}
337
338fn metric_alias(family: &str) -> Option<&'static str> {
339 if family.eq_ignore_ascii_case("Liberation Sans") {
340 Some("Arial")
341 } else if family.eq_ignore_ascii_case("Arial") {
342 Some("Liberation Sans")
343 } else if family.eq_ignore_ascii_case("Liberation Serif") {
344 Some("Times New Roman")
345 } else if family.eq_ignore_ascii_case("Times New Roman") {
346 Some("Liberation Serif")
347 } else if family.eq_ignore_ascii_case("Liberation Mono") {
348 Some("Courier New")
349 } else if family.eq_ignore_ascii_case("Courier New") {
350 Some("Liberation Mono")
351 } else {
352 None
353 }
354}
355
356#[cfg(not(target_arch = "wasm32"))]
357fn is_exact_face_match(
358 db: &fontdb::Database,
359 id: fontdb::ID,
360 wanted_style: &str,
361 weight: u16,
362 italic: bool,
363) -> bool {
364 if !wanted_style.is_empty() {
365 let matched_name = db
366 .with_face_data(id, |data, index| {
367 let face = ttf_parser::Face::parse(data, index).ok()?;
368 let names = face.names();
369 let name = [17, 2].into_iter().find_map(|nid| {
370 names.into_iter().find(|n| n.name_id == nid && n.is_unicode()).and_then(|n| n.to_string())
371 })?;
372 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
373 })
374 .flatten()
375 .unwrap_or(false);
376 if matched_name {
377 return true;
378 }
379 }
380 let Some(info) = db.face(id) else {
381 return false;
382 };
383 let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal };
384 info.weight.0 == weight && info.style == want_style
385}
386
387fn try_pick_family_lazy(
388 reg: &mut FontRegistry,
389 family: &str,
390 wanted_style: &str,
391 weight: u16,
392 italic: bool,
393) -> Option<fontdb::ID> {
394 if family.is_empty() {
395 return None;
396 }
397 #[cfg(not(target_arch = "wasm32"))]
398 {
399 let fam_norm = norm_alnum(family);
400 let style_key = if wanted_style.is_empty() { "regular" } else { wanted_style };
401 if !reg.system_fonts_loaded
402 && !reg.loaded_families.contains(&fam_norm)
403 && !reg.aliases.contains_key(&family.to_ascii_lowercase())
404 {
405 load_style_candidates(reg, &fam_norm, style_key);
406 if let Some(id) = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic) {
407 if is_exact_face_match(&reg.db, id, wanted_style, weight, italic) {
408 return Some(id);
409 }
410 }
411 load_family_candidates(reg, &fam_norm);
412 }
413 }
414 let picked = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic);
415 #[cfg(not(target_arch = "wasm32"))]
416 if let Some(id) = picked {
417 if !reg.system_fonts_loaded && !is_exact_face_match(&reg.db, id, wanted_style, weight, italic) {
418 reg.ensure_system_fonts_loaded();
419 return pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic);
420 }
421 }
422 picked
423}
424
425fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> {
426 let (weight, italic) = parse_style(style);
427 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
428
429 let mut id = try_pick_family_lazy(reg, family, &wanted, weight, italic)
430 .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic)));
431
432 #[cfg(not(target_arch = "wasm32"))]
433 if !family.is_empty()
434 && !reg.system_fonts_loaded
435 && match id {
436 None => true,
437 Some(found) => !is_exact_face_match(&reg.db, found, &wanted, weight, italic),
438 }
439 {
440 reg.ensure_system_fonts_loaded();
441 id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic)
442 .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic)));
443 }
444
445 if id.is_none() {
446 id = FALLBACK_FAMILIES
447 .iter()
448 .find_map(|fb| try_pick_family_lazy(reg, fb, &wanted, weight, italic));
449 }
450
451 #[cfg(not(target_arch = "wasm32"))]
452 if id.is_none() && !reg.system_fonts_loaded {
453 reg.ensure_system_fonts_loaded();
454 }
455
456 let id = id
457 .or_else(|| reg.db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
458 .or_else(|| reg.db.faces().map(|f| f.id).next())?;
459
460 let info = reg.db.face(id)?;
461 let data = reg.db.with_face_data(id, |data, _| data.to_vec())?;
462 let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 };
463 Face::from_slice(&data, info.index)?;
464 let font_id = NEXT_FONT_ID.fetch_add(1, Ordering::Relaxed);
465 Some(Font { id: font_id, data, index: info.index, weight, lean })
466}
467
468/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest
469/// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere.
470fn pick(
471 db: &fontdb::Database,
472 aliases: &HashMap<String, Vec<fontdb::ID>>,
473 family: &str,
474 wanted_style: &str,
475 weight: u16,
476 italic: bool,
477) -> Option<fontdb::ID> {
478 if family.is_empty() {
479 return None;
480 }
481 let alias_ids = aliases.get(&family.to_ascii_lowercase());
482 let mut candidates: Vec<&fontdb::FaceInfo> = db
483 .faces()
484 .filter(|f| {
485 f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family))
486 || alias_ids.is_some_and(|ids| ids.contains(&f.id))
487 })
488 .collect();
489 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));
490 let first = candidates.first()?;
491 if !wanted_style.is_empty() {
492 let exact = candidates.iter().find(|f| {
493 db.with_face_data(f.id, |data, index| {
494 let face = ttf_parser::Face::parse(data, index).ok()?;
495 let names = face.names();
496 let name = [17, 2].into_iter().find_map(|id| {
497 names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string())
498 })?;
499 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
500 })
501 .flatten()
502 .unwrap_or(false)
503 });
504 if let Some(face) = exact {
505 return Some(face.id);
506 }
507 }
508 if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) {
509 return db.query(&fontdb::Query {
510 families: &[fontdb::Family::Name(name)],
511 weight: fontdb::Weight(weight),
512 style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
513 ..Default::default()
514 });
515 }
516 let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal };
517 candidates
518 .into_iter()
519 .min_by_key(|f| {
520 let style_pen = if f.style == want_style { 0i32 } else { 1000 };
521 let weight_diff = (f.weight.0 as i32 - weight as i32).abs();
522 (style_pen + weight_diff, &f.post_script_name, f.index)
523 })
524 .map(|f| f.id)
525}
526
527/// Ascent and descent (both positive) in em units, from `hhea`.
528pub fn vertical_metrics(face: &Face<'_>) -> (f32, f32) {
529 let upem = face.units_per_em() as f32;
530 (face.ascender() as f32 / upem, -(face.descender() as f32) / upem)
531}
532
533pub struct ShapedGlyph {
534 pub id: GlyphId,
535 /// Pen offset from the line origin in pixels.
536 pub x: f32,
537 pub y: f32,
538 /// Index (in `char`s) of the first source character of the glyph's cluster.
539 pub char_index: usize,
540}
541
542pub struct ShapedLine {
543 pub glyphs: Vec<ShapedGlyph>,
544 /// Advance width in pixels, excluding trailing tracking.
545 pub width: f32,
546}
547
548/// Shapes one line at `px` pixels per em. `tracking_px` is added after every cluster and turns
549/// ligatures off, as ligated glyphs cannot be spaced per character.
550pub fn shape_line(face: &Face<'_>, text: &str, px: f32, tracking_px: f32) -> ShapedLine {
551 let scale = px / face.units_per_em() as f32;
552 let mut buffer = UnicodeBuffer::new();
553 buffer.push_str(text);
554 buffer.guess_segment_properties();
555 let features: &[Feature] = if tracking_px != 0.0 {
556 &[Feature::new(Tag::from_bytes(b"liga"), 0, ..), Feature::new(Tag::from_bytes(b"clig"), 0, ..)]
557 } else {
558 &[]
559 };
560 let shaped = rustybuzz::shape(face, features, buffer);
561
562 let char_starts: Vec<usize> = text.char_indices().map(|(i, _)| i).collect();
563 let mut glyphs = Vec::with_capacity(shaped.len());
564 let (mut pen, mut last_cluster) = (0.0_f32, None);
565 for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
566 if last_cluster.is_some_and(|c| c != info.cluster) {
567 pen += tracking_px;
568 }
569 last_cluster = Some(info.cluster);
570 glyphs.push(ShapedGlyph {
571 id: GlyphId(info.glyph_id as u16),
572 x: pen + pos.x_offset as f32 * scale,
573 y: pos.y_offset as f32 * scale,
574 char_index: char_starts.partition_point(|&s| s < info.cluster as usize),
575 });
576 pen += pos.x_advance as f32 * scale;
577 }
578 ShapedLine { glyphs, width: pen }
579}
580
581struct PathBuilder {
582 commands: Vec<Command>,
583 scale: f32,
584 origin: [f32; 2],
585 /// Horizontal shift per pixel above the baseline.
586 lean: f32,
587}
588
589impl PathBuilder {
590 fn point(&self, x: f32, y: f32) -> Vector {
591 let (px, py) = (x * self.scale, y * self.scale);
592 Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] - py)
593 }
594}
595
596impl OutlineBuilder for PathBuilder {
597 fn move_to(&mut self, x: f32, y: f32) {
598 let p = self.point(x, y);
599 self.commands.push(Command::MoveTo(p));
600 }
601 fn line_to(&mut self, x: f32, y: f32) {
602 let p = self.point(x, y);
603 self.commands.push(Command::LineTo(p));
604 }
605 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
606 let (c, p) = (self.point(x1, y1), self.point(x, y));
607 self.commands.push(Command::QuadTo(c, p));
608 }
609 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
610 let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y));
611 self.commands.push(Command::CurveTo(c1, c2, p));
612 }
613 fn close(&mut self) {
614 self.commands.push(Command::Close);
615 }
616}
617
618/// The glyph's Bézier contours in pixel space (y down) with the baseline pen at `origin`.
619/// `shear` leans the glyph right per pixel of height; the font's own synthetic italic is added.
620pub fn glyph_path(font: &Font, face: &Face<'_>, glyph: GlyphId, px: f32, origin: [f32; 2], shear: f32) -> Vec<Command> {
621 let mut builder = PathBuilder {
622 commands: Vec::new(),
623 scale: px / face.units_per_em() as f32,
624 origin,
625 lean: font.lean + shear,
626 };
627 face.outline_glyph(glyph, &mut builder);
628 builder.commands
629}
630
631/// 8-bit coverage over a tight pixel rectangle.
632pub struct Coverage {
633 pub left: i32,
634 pub top: i32,
635 pub width: u32,
636 pub height: u32,
637 pub data: Vec<u8>,
638}
639
640fn render(mask: &mut Mask<'_, '_, &[Command]>) -> Option<Coverage> {
641 let (data, placement) = mask.render();
642 (placement.width > 0 && placement.height > 0).then_some(Coverage {
643 left: placement.left,
644 top: placement.top,
645 width: placement.width,
646 height: placement.height,
647 data,
648 })
649}
650
651/// Analytic non-zero fill of `path`.
652pub fn fill(path: &[Command]) -> Option<Coverage> {
653 render(Mask::new(path).style(Fill::NonZero))
654}
655
656/// Analytic stroke of `path`, centered on the contour, with round joins and caps.
657pub fn stroke(path: &[Command], width: f32) -> Option<Coverage> {
658 render(Mask::new(path).style(Stroke::new(width).join(Join::Round).cap(Cap::Round)))
659}
660
661/// Per-character styling rule from `StyledTextCLS` or `TextPlus` CLS array.
662#[derive(Clone, Debug, PartialEq)]
663pub struct StyledClsRule {
664 pub prop_id: u32,
665 /// Inclusive Fusion character indices (where `\n` occupies 2 CRLF units).
666 pub start: usize,
667 pub end: usize,
668 pub value: f32,
669 pub text: String,
670}
671
672/// Extended `TextPlus` / `Text3D` rasterization parameters supporting `StyledTextCLS` per-character
673/// size/font/style/shear/offset and Element 1/2 Softness (`SoftnessX`, `SoftnessY`, `SoftnessGlow`).
674pub struct RichTextPlusParams<'a> {
675 pub text: &'a str,
676 pub font_family: &'a str,
677 pub font_style: &'a str,
678 pub size_norm: f32,
679 pub tracking: f32,
680 pub line_spacing: f32,
681 pub center: [f32; 2],
682 pub h_lcr: f32,
683 pub v_tcb: f32,
684 pub fill_rgba: [f32; 4],
685 pub write_on_start: f32,
686 pub write_on_end: f32,
687 pub shear_x: f32,
688 pub cls: &'a [StyledClsRule],
689 pub outline_rgba: [f32; 4],
690 pub outline_thickness_norm: f32,
691 pub outline_enabled: bool,
692 pub soft_fill: [f32; 3],
693 pub soft_outline: [f32; 3],
694 pub baseline_at_center: bool,
695}
696
697#[derive(Clone)]
698struct CharStyle {
699 family: String,
700 style: String,
701 size_norm: f32,
702 shear_x: f32,
703 dx: f32,
704 dy: f32,
705}
706
707/// Maps each Rust char index of `text` to its Fusion CRLF index (`\n` counts as 2 unless preceded by `\r`).
708fn fusion_char_positions(text: &str) -> Vec<usize> {
709 let mut positions = Vec::with_capacity(text.chars().count());
710 let mut pos = 0usize;
711 let mut prev_cr = false;
712 for ch in text.chars() {
713 positions.push(pos);
714 if ch == '\n' && !prev_cr {
715 pos += 2;
716 } else {
717 pos += 1;
718 }
719 prev_cr = ch == '\r';
720 }
721 positions
722}
723
724fn resolve_char_styles(params: &RichTextPlusParams<'_>) -> Vec<CharStyle> {
725 let fusion_pos = fusion_char_positions(params.text);
726 let mut styles = vec![
727 CharStyle {
728 family: params.font_family.to_owned(),
729 style: params.font_style.to_owned(),
730 size_norm: params.size_norm,
731 shear_x: params.shear_x,
732 dx: 0.0,
733 dy: 0.0,
734 };
735 fusion_pos.len()
736 ];
737 for rule in params.cls {
738 for (i, &fp) in fusion_pos.iter().enumerate() {
739 if fp < rule.start || fp > rule.end {
740 continue;
741 }
742 match rule.prop_id {
743 100 if !rule.text.is_empty() => styles[i].family.clone_from(&rule.text),
744 102 => styles[i].size_norm = rule.value.max(1e-4),
745 109 if !rule.text.is_empty() => styles[i].style.clone_from(&rule.text),
746 1330 => styles[i].shear_x = rule.value,
747 1350 => styles[i].dx = rule.value,
748 1351 => styles[i].dy = rule.value,
749 _ => {}
750 }
751 }
752 }
753 styles
754}
755
756struct PlacedGlyph {
757 commands: Vec<Command>,
758}
759
760struct GlyphSpec {
761 font: Arc<Font>,
762 glyph_id: GlyphId,
763 font_px: f32,
764 shear: f32,
765 outline_w: f32,
766 abs_x: f32,
767 abs_y: f32,
768}
769
770struct LayoutSpecLine {
771 glyphs: Vec<GlyphSpec>,
772 width: f32,
773 ascent: f32,
774 descent: f32,
775 top_anchor: f32,
776}
777
778fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f32) {
779 let line_box_px = size_norm * canvas_w * 0.8;
780 let (asc_em, desc_em) = vertical_metrics(face);
781 let font_px = (line_box_px / (asc_em + desc_em).max(0.5)).clamp(1.0, 2048.0);
782 (font_px, asc_em * font_px, desc_em * font_px)
783}
784
785fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<GlyphSpec>, usize)> {
786 let [w, h] = dims;
787 let total_chars = params.text.chars().count();
788 if total_chars == 0 || !params.size_norm.is_finite() || params.size_norm <= 1e-4 {
789 return None;
790 }
791 let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize;
792 let c_end = (params.write_on_end.clamp(0.0, 1.0) * total_chars as f32).ceil() as usize;
793 if c_start >= c_end || c_start >= total_chars {
794 return None;
795 }
796 let wf = w as f32;
797 let hf = h as f32;
798 let base_font = Font::find(params.font_family, params.font_style)?;
799 let base_face = base_font.face();
800
801 let mut lines = Vec::new();
802 let mut char_cursor = 0usize;
803
804 if params.cls.is_empty() {
805 let (font_px, asc, desc) = size_metrics(&base_face, params.size_norm, wf);
806 let top_anchor = (font_px - desc).max(0.0);
807 let extra_track = (params.tracking - 1.0) * params.size_norm * wf;
808 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
809 (params.outline_thickness_norm * params.size_norm * wf).clamp(1.0, 128.0)
810 } else {
811 0.0
812 };
813 for raw_line in params.text.split('\n') {
814 let raw_char_len = raw_line.chars().count();
815 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
816 let mut line_glyphs = Vec::new();
817 let width = if line_str.is_empty() {
818 0.0
819 } else {
820 let shaped = shape_line(&base_face, line_str, font_px, extra_track);
821 line_glyphs.reserve(shaped.glyphs.len());
822 for g in &shaped.glyphs {
823 let idx = char_cursor + g.char_index;
824 if idx < c_start || idx >= c_end {
825 continue;
826 }
827 line_glyphs.push(GlyphSpec {
828 font: Arc::clone(&base_font),
829 glyph_id: g.id,
830 font_px,
831 shear: -params.shear_x,
832 outline_w,
833 abs_x: g.x,
834 abs_y: -g.y,
835 });
836 }
837 shaped.width
838 };
839 lines.push(LayoutSpecLine {
840 glyphs: line_glyphs,
841 width,
842 ascent: asc,
843 descent: desc,
844 top_anchor,
845 });
846 char_cursor += raw_char_len + 1;
847 }
848 } else {
849 let styles = resolve_char_styles(params);
850 for raw_line in params.text.split('\n') {
851 let raw_char_len = raw_line.chars().count();
852 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
853 let line_chars: Vec<char> = line_str.chars().collect();
854 let mut shaped_runs: Vec<(usize, Arc<Font>, f32, ShapedLine)> = Vec::new();
855 let mut max_asc = 0.0_f32;
856 let mut max_desc = 0.0_f32;
857 let mut max_top_anchor = 0.0_f32;
858
859 if line_chars.is_empty() {
860 let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm);
861 let (font_px, asc, desc) = size_metrics(&base_face, st, wf);
862 max_asc = asc;
863 max_desc = desc;
864 max_top_anchor = (font_px - desc).max(0.0);
865 } else {
866 let mut r0 = 0usize;
867 while r0 < line_chars.len() {
868 let st0 = &styles[char_cursor + r0];
869 let mut r1 = r0 + 1;
870 while r1 < line_chars.len() {
871 let st1 = &styles[char_cursor + r1];
872 if st1.family != st0.family
873 || st1.style != st0.style
874 || (st1.size_norm - st0.size_norm).abs() > 1e-5
875 {
876 break;
877 }
878 r1 += 1;
879 }
880 let run_str: String = line_chars[r0..r1].iter().collect();
881 let font = if st0.family == params.font_family && st0.style == params.font_style {
882 Arc::clone(&base_font)
883 } else {
884 Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font))
885 };
886 let face = font.face();
887 let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf);
888 max_asc = max_asc.max(asc);
889 max_desc = max_desc.max(desc);
890 max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0));
891 let extra_track = (params.tracking - 1.0) * st0.size_norm * wf;
892 let shaped = shape_line(&face, &run_str, font_px, extra_track);
893 shaped_runs.push((r0, font, font_px, shaped));
894 r0 = r1;
895 }
896 }
897
898 let mut total_w = 0.0_f32;
899 let mut line_glyphs = Vec::new();
900 for (ri, &(r0, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() {
901 if ri > 0 {
902 let st_prev = &styles[char_cursor + r0 - 1];
903 total_w += (params.tracking - 1.0) * st_prev.size_norm * wf;
904 }
905 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
906 let size_px = styles[char_cursor + r0].size_norm * wf;
907 (params.outline_thickness_norm * size_px).clamp(1.0, 128.0)
908 } else {
909 0.0
910 };
911 for g in &shaped.glyphs {
912 let idx = char_cursor + r0 + g.char_index;
913 if idx < c_start || idx >= c_end {
914 continue;
915 }
916 let st = &styles[idx];
917 line_glyphs.push(GlyphSpec {
918 font: Arc::clone(font),
919 glyph_id: g.id,
920 font_px,
921 shear: -st.shear_x,
922 outline_w,
923 abs_x: total_w + g.x + st.dx * wf,
924 abs_y: -g.y - st.dy * wf,
925 });
926 }
927 total_w += shaped.width;
928 }
929 lines.push(LayoutSpecLine {
930 glyphs: line_glyphs,
931 width: total_w,
932 ascent: max_asc,
933 descent: max_desc,
934 top_anchor: max_top_anchor,
935 });
936 char_cursor += raw_char_len + 1;
937 }
938 }
939
940 let cx = params.center[0] * wf;
941 let cy = (1.0 - params.center[1]) * hf;
942 let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5;
943 let ls = params.line_spacing.max(0.05);
944
945 let mut baselines = Vec::with_capacity(lines.len());
946 let mut y_acc = 0.0_f32;
947 for i in 0..lines.len() {
948 baselines.push(y_acc);
949 if i + 1 < lines.len() {
950 y_acc += (lines[i].descent + lines[i + 1].ascent) * ls;
951 }
952 }
953 let baseline_0 = if params.baseline_at_center {
954 cy
955 } else {
956 let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5;
957 let top_anchor = if lines.len() > 1 && !params.cls.is_empty() {
958 (2.0 * lines[0].ascent + lines[0].top_anchor) / 3.0
959 } else {
960 lines[0].top_anchor
961 };
962 let block_h = y_acc + top_anchor;
963 cy + top_anchor - v_frac * block_h
964 };
965
966 let mut out = Vec::new();
967 for (li, line) in lines.into_iter().enumerate() {
968 let start_x = cx - line.width * h_frac;
969 let base_y = baseline_0 + baselines[li];
970 for mut spec in line.glyphs {
971 spec.abs_x += start_x;
972 spec.abs_y += base_y;
973 out.push(spec);
974 }
975 }
976 Some((out, total_chars))
977}
978
979fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> {
980 let (specs, total_chars) = layout_glyph_specs(dims, params)?;
981 let mut out = Vec::with_capacity(specs.len());
982 for spec in &specs {
983 let face = spec.font.face();
984 let commands = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, [spec.abs_x, spec.abs_y], spec.shear);
985 out.push(PlacedGlyph { commands });
986 }
987 Some((out, total_chars))
988}
989
990/// Parameters for extracting vector `zeno::Command` contours for `sText` in Y-up shape space.
991pub struct TextShapeParams<'a> {
992 pub text: &'a str,
993 pub font_family: &'a str,
994 pub font_style: &'a str,
995 pub size_norm: f32,
996 pub tracking: f32,
997 pub line_spacing: f32,
998 pub h_lcr: f32,
999 pub v_tcb: f32,
1000 pub shear_x: f32,
1001 pub write_on_start: f32,
1002 pub write_on_end: f32,
1003 pub char_size_x: f32,
1004 pub char_size_y: f32,
1005}
1006
1007struct ShapePathBuilder {
1008 commands: Vec<Command>,
1009 scale_x: f32,
1010 scale_y: f32,
1011 origin: [f32; 2],
1012 lean: f32,
1013}
1014
1015impl ShapePathBuilder {
1016 fn point(&self, x: f32, y: f32) -> Vector {
1017 let px = x * self.scale_x;
1018 let py = y * self.scale_y;
1019 Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] + py)
1020 }
1021}
1022
1023impl OutlineBuilder for ShapePathBuilder {
1024 fn move_to(&mut self, x: f32, y: f32) {
1025 let p = self.point(x, y);
1026 self.commands.push(Command::MoveTo(p));
1027 }
1028 fn line_to(&mut self, x: f32, y: f32) {
1029 let p = self.point(x, y);
1030 self.commands.push(Command::LineTo(p));
1031 }
1032 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
1033 let (c, p) = (self.point(x1, y1), self.point(x, y));
1034 self.commands.push(Command::QuadTo(c, p));
1035 }
1036 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
1037 let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y));
1038 self.commands.push(Command::CurveTo(c1, c2, p));
1039 }
1040 fn close(&mut self) {
1041 self.commands.push(Command::Close);
1042 }
1043}
1044
1045/// Extracts Y-up shape-space vector `zeno::Command` contours for `sText` using `rustybuzz` + `ttf-parser`.
1046pub fn layout_text_shape_commands(params: &TextShapeParams<'_>) -> Vec<Command> {
1047 let total_chars = params.text.chars().count();
1048 if total_chars == 0 || !params.size_norm.is_finite() || params.size_norm <= 1e-4 {
1049 return Vec::new();
1050 }
1051 let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize;
1052 let c_end = (params.write_on_end.clamp(0.0, 1.0) * total_chars as f32).ceil() as usize;
1053 if c_start >= c_end || c_start >= total_chars {
1054 return Vec::new();
1055 }
1056 let Some(font) = Font::find(params.font_family, params.font_style) else {
1057 return Vec::new();
1058 };
1059 let face = font.face();
1060 let upem = face.units_per_em() as f32;
1061 if upem <= 0.0 {
1062 return Vec::new();
1063 }
1064
1065 // Use a large reference scale (1000.0) for `shape_line` so integer glyph advance/kerning
1066 // stays exact, then rescale back to normalized shape units (width = 1.0).
1067 let ref_w = 1000.0_f32;
1068 let (font_px, asc, desc) = size_metrics(&face, params.size_norm, ref_w);
1069 let top_anchor = (font_px - desc).max(0.0) / ref_w;
1070 let asc = asc / ref_w;
1071 let desc = desc / ref_w;
1072 let font_em = font_px / ref_w;
1073 let extra_track = (params.tracking - 1.0) * params.size_norm;
1074
1075 struct ShapeLine {
1076 glyphs: Vec<(GlyphId, f32, f32)>,
1077 width: f32,
1078 }
1079 let mut lines: Vec<ShapeLine> = Vec::new();
1080 let mut char_cursor = 0usize;
1081 for raw_line in params.text.split('\n') {
1082 let raw_char_len = raw_line.chars().count();
1083 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
1084 let mut glyphs = Vec::new();
1085 let width = if line_str.is_empty() {
1086 0.0
1087 } else {
1088 let shaped = shape_line(&face, line_str, font_px, extra_track * ref_w);
1089 for g in &shaped.glyphs {
1090 let idx = char_cursor + g.char_index;
1091 if idx < c_start || idx >= c_end {
1092 continue;
1093 }
1094 glyphs.push((g.id, g.x / ref_w * params.char_size_x, g.y / ref_w * params.char_size_y));
1095 }
1096 shaped.width / ref_w * params.char_size_x
1097 };
1098 lines.push(ShapeLine { glyphs, width });
1099 char_cursor += raw_char_len + 1;
1100 }
1101
1102 let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5;
1103 let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5;
1104 let ls = params.line_spacing.max(0.05);
1105 let line_step = (desc + asc) * ls;
1106 let mut baselines = Vec::with_capacity(lines.len());
1107 let mut y_acc = 0.0_f32;
1108 for i in 0..lines.len() {
1109 baselines.push(y_acc);
1110 if i + 1 < lines.len() {
1111 y_acc += line_step;
1112 }
1113 }
1114 let block_h = y_acc + top_anchor;
1115 let baseline_0 = v_frac * block_h - top_anchor;
1116
1117 let mut commands = Vec::new();
1118 let scale_x = (font_em / upem) * params.char_size_x;
1119 let scale_y = (font_em / upem) * params.char_size_y;
1120 let lean = font.lean - params.shear_x;
1121 for (li, line) in lines.into_iter().enumerate() {
1122 let start_x = -line.width * h_frac;
1123 let base_y = baseline_0 - baselines[li];
1124 for (gid, gx, gy) in line.glyphs {
1125 let mut builder = ShapePathBuilder {
1126 commands: Vec::new(),
1127 scale_x,
1128 scale_y,
1129 origin: [start_x + gx, base_y + gy],
1130 lean,
1131 };
1132 face.outline_glyph(gid, &mut builder);
1133 commands.extend(builder.commands);
1134 }
1135 }
1136 commands
1137}
1138
1139const GLYPH_BASELINE_ANCHOR: f32 = 256.0;
1140const GLYPH_BASELINE_ANCHOR_I32: i32 = 256;
1141const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;
1142const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024;
1143const MAX_GLYPH_COORD: f32 = 8_388_608.0;
1144
1145#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1146struct GlyphCacheKey {
1147 font_id: u64,
1148 glyph_id: u16,
1149 size_bits: u32,
1150 lean_bits: u32,
1151 stroke_bits: u32,
1152 sub_x_bits: u32,
1153 sub_y_bits: u32,
1154}
1155
1156struct CachedGlyphCoverage {
1157 fill: Option<Coverage>,
1158 stroke: Option<Coverage>,
1159 bytes: usize,
1160}
1161
1162struct GlyphCache {
1163 map: HashMap<GlyphCacheKey, (u64, Arc<CachedGlyphCoverage>)>,
1164 order: VecDeque<(u64, GlyphCacheKey)>,
1165 next_stamp: u64,
1166 total_bytes: usize,
1167}
1168
1169impl GlyphCache {
1170 fn new() -> Self {
1171 Self {
1172 map: HashMap::new(),
1173 order: VecDeque::new(),
1174 next_stamp: 0,
1175 total_bytes: 0,
1176 }
1177 }
1178
1179 fn compact_order(&mut self) {
1180 let mut live: Vec<(u64, GlyphCacheKey)> =
1181 self.map.iter().map(|(k, (s, _))| (*s, *k)).collect();
1182 live.sort_unstable_by_key(|&(s, _)| s);
1183 self.order.clear();
1184 self.order.extend(live);
1185 }
1186
1187 fn get(&mut self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {
1188 let (stamp, val) = self.map.get_mut(key)?;
1189 self.next_stamp += 1;
1190 *stamp = self.next_stamp;
1191 self.order.push_back((self.next_stamp, *key));
1192 let out = Arc::clone(val);
1193 if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 {
1194 self.compact_order();
1195 }
1196 Some(out)
1197 }
1198
1199 fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) {
1200 if val.bytes > MAX_GLYPH_CACHE_BYTES {
1201 return;
1202 }
1203 if let Some((stamp, _)) = self.map.get_mut(&key) {
1204 self.next_stamp += 1;
1205 *stamp = self.next_stamp;
1206 self.order.push_back((self.next_stamp, key));
1207 if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 {
1208 self.compact_order();
1209 }
1210 return;
1211 }
1212 while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES {
1213 let Some((s, old_key)) = self.order.pop_front() else {
1214 break;
1215 };
1216 if self.map.get(&old_key).is_some_and(|(cur_s, _)| *cur_s == s) {
1217 if let Some((_, removed)) = self.map.remove(&old_key) {
1218 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);
1219 }
1220 }
1221 }
1222 self.next_stamp += 1;
1223 self.total_bytes += val.bytes;
1224 self.order.push_back((self.next_stamp, key));
1225 self.map.insert(key, (self.next_stamp, val));
1226 }
1227}
1228
1229fn glyph_cache() -> &'static Mutex<GlyphCache> {
1230 static CACHE: OnceLock<Mutex<GlyphCache>> = OnceLock::new();
1231 CACHE.get_or_init(|| Mutex::new(GlyphCache::new()))
1232}
1233
1234fn quantize_subpixel(coord: f32) -> Option<(i32, f32)> {
1235 if !coord.is_finite() || coord.abs() > MAX_GLYPH_COORD {
1236 return None;
1237 }
1238 let mut ix = coord.floor() as i32;
1239 let fx = (coord - ix as f32).clamp(0.0, 1.0);
1240 let mut qx = (fx * 16.0).round() as i32;
1241 if qx >= 16 {
1242 ix += 1;
1243 qx = 0;
1244 }
1245 Some((ix, qx as f32 * (1.0 / 16.0)))
1246}
1247
1248fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) {
1249 let (Some((ix, fx)), Some((iy, fy))) = (quantize_subpixel(spec.abs_x), quantize_subpixel(spec.abs_y)) else {
1250 return (
1251 0,
1252 0,
1253 Arc::new(CachedGlyphCoverage {
1254 fill: None,
1255 stroke: None,
1256 bytes: 0,
1257 }),
1258 );
1259 };
1260
1261 let total_lean = spec.font.lean + spec.shear;
1262 let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean };
1263 let stroke_bits = if want_outline {
1264 spec.outline_w.to_bits()
1265 } else {
1266 0
1267 };
1268 let key = GlyphCacheKey {
1269 font_id: spec.font.id,
1270 glyph_id: spec.glyph_id.0,
1271 size_bits: spec.font_px.to_bits(),
1272 lean_bits: lean_norm.to_bits(),
1273 stroke_bits,
1274 sub_x_bits: if fx == 0.0 { 0 } else { fx.to_bits() },
1275 sub_y_bits: if fy == 0.0 { 0 } else { fy.to_bits() },
1276 };
1277
1278 if let Some(hit) = glyph_cache().lock().unwrap().get(&key) {
1279 return (ix, iy, hit);
1280 }
1281
1282 // Anchor outlines near 256px so zeno's flattening precision matches full-canvas rasterization.
1283 let sub_origin = [GLYPH_BASELINE_ANCHOR + fx, GLYPH_BASELINE_ANCHOR + fy];
1284 let face = spec.font.face();
1285 let path = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, sub_origin, spec.shear);
1286 let fill_cov = fill(&path).map(|mut c| {
1287 c.left -= GLYPH_BASELINE_ANCHOR_I32;
1288 c.top -= GLYPH_BASELINE_ANCHOR_I32;
1289 c
1290 });
1291 let stroke_cov = if want_outline {
1292 stroke(&path, spec.outline_w).map(|mut c| {
1293 c.left -= GLYPH_BASELINE_ANCHOR_I32;
1294 c.top -= GLYPH_BASELINE_ANCHOR_I32;
1295 c
1296 })
1297 } else {
1298 None
1299 };
1300 let bytes = fill_cov.as_ref().map_or(0, |c| c.data.len())
1301 + stroke_cov.as_ref().map_or(0, |c| c.data.len());
1302 let entry = Arc::new(CachedGlyphCoverage {
1303 fill: fill_cov,
1304 stroke: stroke_cov,
1305 bytes,
1306 });
1307 glyph_cache().lock().unwrap().insert(key, Arc::clone(&entry));
1308 (ix, iy, entry)
1309}
1310
1311fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {
1312 if !sigma.is_finite() || sigma < 0.05 {
1313 return (0, vec![1.0]);
1314 }
1315 let r = (sigma * 3.0).ceil().clamp(0.0, 64.0) as isize;
1316 if r <= 0 {
1317 return (0, vec![1.0]);
1318 }
1319 let inv2s2 = 1.0 / (2.0 * sigma * sigma);
1320 let mut k = Vec::with_capacity((r * 2 + 1) as usize);
1321 let mut sum = 0.0_f32;
1322 for i in -r..=r {
1323 let w = (-((i * i) as f32) * inv2s2).exp();
1324 k.push(w);
1325 sum += w;
1326 }
1327 for w in &mut k {
1328 *w /= sum;
1329 }
1330 (r, k)
1331}
1332
1333fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32, sigma_y: f32) {
1334 let (rx, kx) = gaussian_kernel_1d(sigma_x);
1335 let (ry, ky) = gaussian_kernel_1d(sigma_y);
1336 if rx <= 0 && ry <= 0 {
1337 return;
1338 }
1339 let mut tmp = vec![0.0_f32; w * h];
1340 let src_is_tmp = if rx > 0 {
1341 let r = rx as usize;
1342 let klen = kx.len();
1343 let mid_end = w.saturating_sub(r);
1344 let left_end = r.min(w);
1345 let right_start = mid_end.max(left_end);
1346 for y in 0..h {
1347 let row = &plane[y * w..(y + 1) * w];
1348 let dst = &mut tmp[y * w..(y + 1) * w];
1349 for x in 0..left_end {
1350 let k_start = r - x;
1351 let k_end = (w + r - x).min(klen);
1352 let s_start = x + k_start - r;
1353 let mut acc = 0.0_f32;
1354 for (&s, &kw) in row[s_start..s_start + (k_end - k_start)].iter().zip(&kx[k_start..k_end]) {
1355 acc += s * kw;
1356 }
1357 dst[x] = acc;
1358 }
1359 for x in left_end..mid_end {
1360 let win = &row[x - r..x + r + 1];
1361 let mut acc = 0.0_f32;
1362 for (&s, &kw) in win.iter().zip(kx.iter()) {
1363 acc += s * kw;
1364 }
1365 dst[x] = acc;
1366 }
1367 for x in right_start..w {
1368 let k_end = w + r - x;
1369 let mut acc = 0.0_f32;
1370 for (&s, &kw) in row[x - r..w].iter().zip(&kx[..k_end]) {
1371 acc += s * kw;
1372 }
1373 dst[x] = acc;
1374 }
1375 }
1376 true
1377 } else {
1378 false
1379 };
1380
1381 if ry > 0 {
1382 let (src_buf, dst_buf): (&[f32], &mut [f32]) = if src_is_tmp {
1383 (&tmp, plane)
1384 } else {
1385 tmp.copy_from_slice(plane);
1386 (&tmp, plane)
1387 };
1388 dst_buf.fill(0.0);
1389 let klen = ky.len() as isize;
1390 for y in 0..h {
1391 let yi = y as isize;
1392 let k_start = (ry - yi).max(0) as usize;
1393 let k_end = ((h as isize + ry - yi).min(klen)).max(0) as usize;
1394 let dst_row = &mut dst_buf[y * w..(y + 1) * w];
1395 for (ki, &kw) in ky[k_start..k_end].iter().enumerate() {
1396 let sy = (yi + (k_start + ki) as isize - ry) as usize;
1397 let src_row = &src_buf[sy * w..(sy + 1) * w];
1398 for (d, &s) in dst_row.iter_mut().zip(src_row.iter()) {
1399 *d += s * kw;
1400 }
1401 }
1402 }
1403 } else if src_is_tmp {
1404 plane.copy_from_slice(&tmp);
1405 }
1406}
1407
1408fn blit_plane_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) {
1409 let c_left = c.left + offset[0];
1410 let c_top = c.top + offset[1];
1411 let cw = c.width as i32;
1412 let ch = c.height as i32;
1413 let x0 = (origin[0] - c_left).max(0);
1414 let y0 = (origin[1] - c_top).max(0);
1415 let x1 = (origin[0] + tw as i32 - c_left).min(cw);
1416 let y1 = (origin[1] + th as i32 - c_top).min(ch);
1417 if x0 >= x1 || y0 >= y1 {
1418 return;
1419 }
1420 let span = (x1 - x0) as usize;
1421 let dst_x0 = (c_left + x0 - origin[0]) as usize;
1422 for y in y0..y1 {
1423 let py = (c_top + y - origin[1]) as usize;
1424 let src_start = y as usize * c.width as usize + x0 as usize;
1425 let src_row = &c.data[src_start..src_start + span];
1426 let dst_start = py * tw + dst_x0;
1427 let dst_row = &mut plane[dst_start..dst_start + span];
1428 for (d, &a) in dst_row.iter_mut().zip(src_row.iter()) {
1429 if a > 0 {
1430 *d = d.max(a as f32 / 255.0);
1431 }
1432 }
1433 }
1434}
1435
1436fn blit_plane_u8_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [u8]) {
1437 let c_left = c.left + offset[0];
1438 let c_top = c.top + offset[1];
1439 let cw = c.width as i32;
1440 let ch = c.height as i32;
1441 let x0 = (origin[0] - c_left).max(0);
1442 let y0 = (origin[1] - c_top).max(0);
1443 let x1 = (origin[0] + tw as i32 - c_left).min(cw);
1444 let y1 = (origin[1] + th as i32 - c_top).min(ch);
1445 if x0 >= x1 || y0 >= y1 {
1446 return;
1447 }
1448 let span = (x1 - x0) as usize;
1449 let dst_x0 = (c_left + x0 - origin[0]) as usize;
1450 for y in y0..y1 {
1451 let py = (c_top + y - origin[1]) as usize;
1452 let src_start = y as usize * c.width as usize + x0 as usize;
1453 let src_row = &c.data[src_start..src_start + span];
1454 let dst_start = py * tw + dst_x0;
1455 let dst_row = &mut plane[dst_start..dst_start + span];
1456 for (d, &a) in dst_row.iter_mut().zip(src_row.iter()) {
1457 *d = (*d).max(a);
1458 }
1459 }
1460}
1461
1462/// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and
1463/// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer.
1464pub fn rasterize_text_plus_rich(
1465 dims: [u32; 2],
1466 params: &RichTextPlusParams<'_>,
1467 dod_pad: i32,
1468) -> ([u32; 2], [i32; 2], Vec<u8>) {
1469 let [w, h] = dims;
1470 let empty = || ([1u32, 1u32], [0i32, 0i32], vec![0u8; 4]);
1471 let has_outline = params.outline_enabled && params.outline_rgba[3] > 0.0;
1472 if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 {
1473 return empty();
1474 }
1475 let Some((specs, _)) = layout_glyph_specs(dims, params) else {
1476 return empty();
1477 };
1478 if specs.is_empty() {
1479 return empty();
1480 }
1481
1482 // Calibrated on Fusion 21.1 (`text_diag` & `text_diag2`): sigma = SoftnessX * (W / 1280).
1483 let soft_scale = w as f32 / 1280.0;
1484 let clamp_sigma = |v: f32| if v.is_finite() { (v.max(0.0) * soft_scale).min(64.0 / 3.0) } else { 0.0 };
1485 let sx1 = clamp_sigma(params.soft_fill[0]);
1486 let sy1 = clamp_sigma(params.soft_fill[1]);
1487 let sx2 = clamp_sigma(params.soft_outline[0]);
1488 let sy2 = clamp_sigma(params.soft_outline[1]);
1489 let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil().clamp(0.0, 64.0) as i32;
1490 // Keep at least a 1px transparent apron around glyphs so GPU bilinear filtering never clamps non-zero edge alpha.
1491 let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1);
1492
1493 let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
1494 let mut grow = |c: &Coverage, ox: i32, oy: i32, pad: i32| {
1495 let left = c.left.saturating_add(ox);
1496 let top = c.top.saturating_add(oy);
1497 min_x = min_x.min(left.saturating_sub(pad));
1498 min_y = min_y.min(top.saturating_sub(pad));
1499 max_x = max_x.max(left.saturating_add(c.width as i32).saturating_add(pad));
1500 max_y = max_y.max(top.saturating_add(c.height as i32).saturating_add(pad));
1501 };
1502
1503 let mut placed = Vec::with_capacity(specs.len());
1504 let mut any_outline = false;
1505 for spec in &specs {
1506 if !spec.abs_x.is_finite() || !spec.abs_y.is_finite() {
1507 continue;
1508 }
1509 let want_outline = has_outline && spec.outline_w > 1e-3;
1510 let (ix, iy, cov) = cached_glyph_coverage(spec, want_outline);
1511 if let Some(c) = &cov.fill {
1512 grow(c, ix, iy, eff_pad);
1513 }
1514 if let Some(c) = &cov.stroke {
1515 any_outline = true;
1516 grow(c, ix, iy, eff_pad);
1517 }
1518 placed.push((ix, iy, cov));
1519 }
1520 if min_x > max_x || min_y > max_y {
1521 return empty();
1522 }
1523
1524 let origin_x = min_x.max(-(w as i32));
1525 let origin_y = min_y.max(-(h as i32));
1526 let end_x = max_x.min((w as i32) * 2);
1527 let end_y = max_y.min((h as i32) * 2);
1528 if end_x <= origin_x || end_y <= origin_y {
1529 return empty();
1530 }
1531 let tw = (end_x - origin_x) as usize;
1532 let th = (end_y - origin_y) as usize;
1533
1534 let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999));
1535 let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999));
1536 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
1537 let mut out = vec![0u8; tw * th * 4];
1538
1539 if !any_outline && sx1 <= 0.05 && sy1 <= 0.05 {
1540 let mut fill_u8 = vec![0u8; tw * th];
1541 for (ix, iy, cov) in &placed {
1542 if let Some(c) = &cov.fill {
1543 blit_plane_u8_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_u8);
1544 }
1545 }
1546 let f_scale = fc[3] * glow1;
1547 let mut lut = [[0u8; 4]; 256];
1548 for (a_u8, entry) in lut.iter_mut().enumerate().skip(1) {
1549 let fa = ((a_u8 as f32 / 255.0) * f_scale).clamp(0.0, 1.0);
1550 if fa > 0.0 {
1551 *entry = [
1552 (fc[0] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1553 (fc[1] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1554 (fc[2] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1555 (fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1556 ];
1557 }
1558 }
1559 for (px, &a) in out.chunks_exact_mut(4).zip(fill_u8.iter()) {
1560 if a != 0 {
1561 px.copy_from_slice(&lut[a as usize]);
1562 }
1563 }
1564 return ([tw as u32, th as u32], [origin_x, origin_y], out);
1565 }
1566
1567 let mut fill_plane = vec![0.0_f32; tw * th];
1568 let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }];
1569 for (ix, iy, cov) in &placed {
1570 if let Some(c) = &cov.fill {
1571 blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_plane);
1572 }
1573 if let Some(c) = &cov.stroke {
1574 blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut line_plane);
1575 }
1576 }
1577
1578 if sx1 > 0.05 || sy1 > 0.05 {
1579 apply_separable_gaussian(&mut fill_plane, tw, th, sx1, sy1);
1580 }
1581 if any_outline && (sx2 > 0.05 || sy2 > 0.05) {
1582 apply_separable_gaussian(&mut line_plane, tw, th, sx2, sy2);
1583 }
1584
1585 if any_outline {
1586 let f_scale = fc[3] * glow1;
1587 let o_scale = oc[3] * glow2;
1588 for (i, px) in out.chunks_exact_mut(4).enumerate() {
1589 let fa = (fill_plane[i] * f_scale).clamp(0.0, 1.0);
1590 let oa = (line_plane[i] * o_scale).clamp(0.0, 1.0);
1591 if fa <= 0.0 && oa <= 0.0 {
1592 continue;
1593 }
1594 let under = 1.0 - fa;
1595 px[0] = ((fc[0] * fa + oc[0] * oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1596 px[1] = ((fc[1] * fa + oc[1] * oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1597 px[2] = ((fc[2] * fa + oc[2] * oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1598 px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1599 }
1600 } else {
1601 let f_scale = fc[3] * glow1;
1602 for (i, px) in out.chunks_exact_mut(4).enumerate() {
1603 let fa = (fill_plane[i] * f_scale).clamp(0.0, 1.0);
1604 if fa <= 0.0 {
1605 continue;
1606 }
1607 px[0] = (fc[0] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1608 px[1] = (fc[1] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1609 px[2] = (fc[2] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1610 px[3] = (fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
1611 }
1612 }
1613 ([tw as u32, th as u32], [origin_x, origin_y], out)
1614}
1615
1616const MAX_RING_VERTS: usize = 2048;
1617const MAX_POLY_VERTS: usize = 4096;
1618const MAX_TEXT3D_VERTS: usize = 500_000;
1619
1620fn same_pt_2d(a: [f32; 2], b: [f32; 2]) -> bool {
1621 (a[0] - b[0]).abs() <= 1e-6 && (a[1] - b[1]).abs() <= 1e-6
1622}
1623
1624fn is_forward_collinear(a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
1625 let ab = [b[0] - a[0], b[1] - a[1]];
1626 let bc = [c[0] - b[0], c[1] - b[1]];
1627 let ac = [c[0] - a[0], c[1] - a[1]];
1628 let ac_len = ac[0].hypot(ac[1]);
1629 if ac_len <= 1e-6 {
1630 return false;
1631 }
1632 let perp = (ab[0] * ac[1] - ab[1] * ac[0]).abs() / ac_len;
1633 let dot = ab[0] * bc[0] + ab[1] * bc[1];
1634 perp <= 1e-6 && dot >= 0.0
1635}
1636
1637fn strip_forward_collinear(mut ring: Vec<[f32; 2]>) -> Vec<[f32; 2]> {
1638 let mut changed = true;
1639 while changed && ring.len() >= 3 {
1640 changed = false;
1641 let n = ring.len();
1642 let mut next = Vec::with_capacity(n);
1643 for i in 0..n {
1644 let a = if next.is_empty() { ring[(i + n - 1) % n] } else { *next.last().unwrap() };
1645 let b = ring[i];
1646 let c = ring[(i + 1) % n];
1647 if is_forward_collinear(a, b, c) && next.len() + (n - 1 - i) >= 3 {
1648 changed = true;
1649 continue;
1650 }
1651 next.push(b);
1652 }
1653 ring = next;
1654 }
1655 ring
1656}
1657
1658fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {
1659 let to_world = |p: Vector| -> [f32; 2] { [(p.x - 1024.0) / 512.0, -(p.y - 512.0) / 512.0] };
1660 let mut rings = Vec::new();
1661 let mut cur = Vec::new();
1662 let mut pen = [0.0_f32; 2];
1663 for &cmd in commands {
1664 match cmd {
1665 Command::MoveTo(p) => {
1666 if cur.len() >= 3 {
1667 rings.push(std::mem::take(&mut cur));
1668 } else {
1669 cur.clear();
1670 }
1671 pen = to_world(p);
1672 cur.push(pen);
1673 }
1674 Command::LineTo(p) => {
1675 pen = to_world(p);
1676 cur.push(pen);
1677 }
1678 Command::QuadTo(c, p) => {
1679 let (p0, c0, p1) = (pen, to_world(c), to_world(p));
1680 for s in 1..=8 {
1681 let t = s as f32 / 8.0;
1682 let u = 1.0 - t;
1683 cur.push([
1684 u * u * p0[0] + 2.0 * u * t * c0[0] + t * t * p1[0],
1685 u * u * p0[1] + 2.0 * u * t * c0[1] + t * t * p1[1],
1686 ]);
1687 }
1688 pen = p1;
1689 }
1690 Command::CurveTo(c1, c2, p) => {
1691 let (p0, b1, b2, p1) = (pen, to_world(c1), to_world(c2), to_world(p));
1692 for s in 1..=12 {
1693 let t = s as f32 / 12.0;
1694 let u = 1.0 - t;
1695 let (u2, t2) = (u * u, t * t);
1696 cur.push([
1697 u2 * u * p0[0] + 3.0 * u2 * t * b1[0] + 3.0 * u * t2 * b2[0] + t2 * t * p1[0],
1698 u2 * u * p0[1] + 3.0 * u2 * t * b1[1] + 3.0 * u * t2 * b2[1] + t2 * t * p1[1],
1699 ]);
1700 }
1701 pen = p1;
1702 }
1703 Command::Close => {
1704 if cur.len() >= 3 {
1705 rings.push(std::mem::take(&mut cur));
1706 } else {
1707 cur.clear();
1708 }
1709 }
1710 }
1711 }
1712 if cur.len() >= 3 {
1713 rings.push(cur);
1714 }
1715 rings.into_iter().filter_map(|ring| {
1716 let mut clean: Vec<[f32; 2]> = Vec::with_capacity(ring.len());
1717 for pt in ring {
1718 if clean.last().is_none_or(|prev| (prev[0] - pt[0]).hypot(prev[1] - pt[1]) > 1e-5) {
1719 clean.push(pt);
1720 }
1721 }
1722 if clean.len() >= 2 && (clean[0][0] - clean.last().unwrap()[0]).hypot(clean[0][1] - clean.last().unwrap()[1]) <= 1e-5 {
1723 clean.pop();
1724 }
1725 let mut clean = strip_forward_collinear(clean);
1726 if clean.len() > MAX_RING_VERTS {
1727 let len = clean.len();
1728 clean = (0..MAX_RING_VERTS)
1729 .map(|i| clean[(i * len) / MAX_RING_VERTS])
1730 .collect();
1731 }
1732 (clean.len() >= 3 && ring_signed_area(&clean).abs() > 1e-9).then_some(clean)
1733 }).collect()
1734}
1735
1736fn ring_signed_area(ring: &[[f32; 2]]) -> f32 {
1737 let mut a = 0.0_f32;
1738 for i in 0..ring.len() {
1739 let p0 = ring[i];
1740 let p1 = ring[(i + 1) % ring.len()];
1741 a += p0[0] * p1[1] - p1[0] * p0[1];
1742 }
1743 0.5 * a
1744}
1745
1746fn point_in_ring(pt: [f32; 2], ring: &[[f32; 2]]) -> bool {
1747 let mut inside = false;
1748 for i in 0..ring.len() {
1749 let a = ring[i];
1750 let b = ring[(i + 1) % ring.len()];
1751 if ((a[1] > pt[1]) != (b[1] > pt[1]))
1752 && (pt[0] < (b[0] - a[0]) * (pt[1] - a[1]) / (b[1] - a[1]) + a[0])
1753 {
1754 inside = !inside;
1755 }
1756 }
1757 inside
1758}
1759
1760fn point_in_tri(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
1761 let c1 = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
1762 let c2 = (c[0] - b[0]) * (p[1] - b[1]) - (c[1] - b[1]) * (p[0] - b[0]);
1763 let c3 = (a[0] - c[0]) * (p[1] - c[1]) - (a[1] - c[1]) * (p[0] - c[0]);
1764 c1 >= -1e-7 && c2 >= -1e-7 && c3 >= -1e-7
1765}
1766
1767fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {
1768 let Some((m_idx, &m)) = hole
1769 .iter()
1770 .enumerate()
1771 .max_by(|a, b| a.1[0].total_cmp(&b.1[0]).then_with(|| a.1[1].total_cmp(&b.1[1])))
1772 else {
1773 return;
1774 };
1775 let n_outer = outer.len();
1776 if n_outer < 3 || hole.len() < 3 {
1777 return;
1778 }
1779 let mut best_x = f32::INFINITY;
1780 let mut best_hit: Option<(usize, bool)> = None;
1781 let consider_hit = |best_x: &mut f32,
1782 best_hit: &mut Option<(usize, bool)>,
1783 x_int: f32,
1784 p_idx: usize,
1785 is_vertex_hit: bool| {
1786 if x_int < m[0] - 1e-6 {
1787 return;
1788 }
1789 let better = x_int < *best_x - 1e-6
1790 || ((x_int - *best_x).abs() <= 1e-6 && is_vertex_hit && !best_hit.is_some_and(|(_, vh)| vh));
1791 if better {
1792 *best_x = x_int;
1793 *best_hit = Some((p_idx, is_vertex_hit));
1794 }
1795 };
1796 for i in 0..n_outer {
1797 let j = (i + 1) % n_outer;
1798 let (a, b) = (outer[i], outer[j]);
1799 if (a[1] - m[1]).abs() <= 1e-6 && (b[1] - m[1]).abs() <= 1e-6 {
1800 consider_hit(&mut best_x, &mut best_hit, a[0], i, true);
1801 consider_hit(&mut best_x, &mut best_hit, b[0], j, true);
1802 continue;
1803 }
1804 // For CCW outer contours, a rightward ray exits across upward edges (`b.y > a.y`).
1805 // Checking `b.y > a.y` also avoids picking the wrong side of an existing bridge.
1806 if a[1] <= m[1] + 1e-6 && b[1] >= m[1] - 1e-6 && b[1] > a[1] + 1e-7 {
1807 if (a[1] - m[1]).abs() <= 1e-6 {
1808 consider_hit(&mut best_x, &mut best_hit, a[0], i, true);
1809 } else if (b[1] - m[1]).abs() <= 1e-6 {
1810 consider_hit(&mut best_x, &mut best_hit, b[0], j, true);
1811 } else {
1812 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
1813 let p_idx = if a[0] >= b[0] { i } else { j };
1814 consider_hit(&mut best_x, &mut best_hit, x_int, p_idx, false);
1815 }
1816 }
1817 }
1818 if best_hit.is_none() {
1819 for i in 0..n_outer {
1820 let j = (i + 1) % n_outer;
1821 let (a, b) = (outer[i], outer[j]);
1822 if (a[1] < m[1] && b[1] > m[1]) || (b[1] < m[1] && a[1] > m[1]) {
1823 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
1824 let p_idx = if a[0] >= b[0] { i } else { j };
1825 consider_hit(&mut best_x, &mut best_hit, x_int, p_idx, false);
1826 }
1827 }
1828 }
1829 let Some((p_initial_idx, is_vertex_hit)) = best_hit else {
1830 return;
1831 };
1832 let mut p_idx = p_initial_idx;
1833 if !is_vertex_hit {
1834 let inter = [best_x, m[1]];
1835 let p_initial = outer[p_initial_idx];
1836 let mut best_ang = (p_initial[1] - m[1]).abs().atan2((p_initial[0] - m[0]).max(0.0));
1837 let mut best_dist2 = (p_initial[0] - m[0]).powi(2) + (p_initial[1] - m[1]).powi(2);
1838 let orient = p_initial[1] > m[1];
1839 for (vi, &v) in outer.iter().enumerate() {
1840 if vi == p_initial_idx || same_pt_2d(v, p_initial) || same_pt_2d(v, m) {
1841 continue;
1842 }
1843 let tri_inside = if (p_initial[1] - m[1]).abs() > 1e-7 {
1844 if orient {
1845 point_in_tri(v, m, inter, p_initial)
1846 } else {
1847 point_in_tri(v, m, p_initial, inter)
1848 }
1849 } else {
1850 false
1851 };
1852 if tri_inside {
1853 let ang = (v[1] - m[1]).abs().atan2((v[0] - m[0]).max(0.0));
1854 let dist2 = (v[0] - m[0]).powi(2) + (v[1] - m[1]).powi(2);
1855 if ang < best_ang - 1e-6 || ((ang - best_ang).abs() <= 1e-6 && dist2 < best_dist2) {
1856 best_ang = ang;
1857 best_dist2 = dist2;
1858 p_idx = vi;
1859 }
1860 }
1861 }
1862 }
1863 let mut spliced = Vec::with_capacity(outer.len() + hole.len() + 2);
1864 spliced.extend_from_slice(&outer[..=p_idx]);
1865 for step in 0..=hole.len() {
1866 spliced.push(hole[(m_idx + step) % hole.len()]);
1867 }
1868 spliced.push(outer[p_idx]);
1869 spliced.extend_from_slice(&outer[p_idx + 1..]);
1870 *outer = spliced;
1871}
1872
1873fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
1874 if poly.len() < 3 || poly.len() > MAX_POLY_VERTS {
1875 return Vec::new();
1876 }
1877 let mut idx: Vec<usize> = (0..poly.len()).collect();
1878 let mut stripped = true;
1879 while stripped && idx.len() >= 3 {
1880 stripped = false;
1881 let mut i = 0;
1882 while i < idx.len() && idx.len() >= 4 {
1883 let n = idx.len();
1884 let (a, b, c) = (poly[idx[(i + n - 1) % n]], poly[idx[i]], poly[idx[(i + 1) % n]]);
1885 if is_forward_collinear(a, b, c) {
1886 idx.remove(i);
1887 stripped = true;
1888 } else {
1889 i += 1;
1890 }
1891 }
1892 }
1893 let mut tris = Vec::with_capacity(idx.len().saturating_sub(2));
1894 let mut guard = idx.len() * idx.len() + 16;
1895 while idx.len() >= 3 && guard > 0 {
1896 guard -= 1;
1897 let n = idx.len();
1898 let mut clipped = false;
1899 for i in 0..n {
1900 let (ia, ib, ic) = (idx[(i + n - 1) % n], idx[i], idx[(i + 1) % n]);
1901 let (a, b, c) = (poly[ia], poly[ib], poly[ic]);
1902 let area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
1903 if area2 <= 1e-8 {
1904 continue;
1905 }
1906 let has_inside = idx.iter().enumerate().any(|(j, &iv)| {
1907 if j == (i + n - 1) % n || j == i || j == (i + 1) % n {
1908 return false;
1909 }
1910 let p = poly[iv];
1911 if same_pt_2d(p, a) || same_pt_2d(p, b) || same_pt_2d(p, c) {
1912 return false;
1913 }
1914 point_in_tri(p, a, b, c)
1915 });
1916 if !has_inside {
1917 tris.push([a, b, c]);
1918 idx.remove(i);
1919 clipped = true;
1920 break;
1921 }
1922 }
1923 if !clipped {
1924 for i in 0..n {
1925 let (ia, ib, ic) = (idx[(i + n - 1) % n], idx[i], idx[(i + 1) % n]);
1926 let (a, b, c) = (poly[ia], poly[ib], poly[ic]);
1927 let area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
1928 let degenerate = same_pt_2d(a, b) || same_pt_2d(b, c) || same_pt_2d(a, c);
1929 let collinear_empty = area2.abs() <= 1e-7
1930 && !idx.iter().enumerate().any(|(j, &iv)| {
1931 if j == (i + n - 1) % n || j == i || j == (i + 1) % n {
1932 return false;
1933 }
1934 let p = poly[iv];
1935 !same_pt_2d(p, a)
1936 && !same_pt_2d(p, b)
1937 && !same_pt_2d(p, c)
1938 && point_in_tri(p, a, b, c)
1939 });
1940 if degenerate || collinear_empty {
1941 idx.remove(i);
1942 clipped = true;
1943 break;
1944 }
1945 }
1946 }
1947 if !clipped {
1948 break;
1949 }
1950 }
1951 tris
1952}
1953
1954/// Builds a 3D extruded mesh for `Text3D` matching Fusion's orthographic/perspective world scale
1955/// (front face at `z = depth`, extruding backward along `-Z` to `z = 0`).
1956pub fn build_text3d_mesh(
1957 params: &RichTextPlusParams<'_>,
1958 depth: f32,
1959) -> Vec<crate::scene3d::Vertex3D> {
1960 use crate::scene3d::Vertex3D;
1961 let Some((glyphs, _)) = layout_glyphs([2048, 1024], params) else {
1962 return Vec::new();
1963 };
1964 let mut verts = Vec::new();
1965 let depth = depth.abs();
1966 let z_front = depth;
1967 let z_back = 0.0;
1968 for g in &glyphs {
1969 if verts.len() >= MAX_TEXT3D_VERTS {
1970 break;
1971 }
1972 let mut rings = flatten_glyph_rings(&g.commands);
1973 if rings.is_empty() {
1974 continue;
1975 }
1976 let mut depths = vec![0usize; rings.len()];
1977 for i in 0..rings.len() {
1978 let pt = rings[i][0];
1979 for j in 0..rings.len() {
1980 if i != j && point_in_ring(pt, &rings[j]) {
1981 depths[i] += 1;
1982 }
1983 }
1984 }
1985 for (i, ring) in rings.iter_mut().enumerate() {
1986 let want_ccw = depths[i] % 2 == 0;
1987 let is_ccw = ring_signed_area(ring) > 0.0;
1988 if want_ccw != is_ccw {
1989 ring.reverse();
1990 }
1991 }
1992 // Emit extruded side walls on unbridged outer + hole rings.
1993 if depth > 1e-4 {
1994 for ring in &rings {
1995 for i in 0..ring.len() {
1996 let p0 = ring[i];
1997 let p1 = ring[(i + 1) % ring.len()];
1998 let (dx, dy) = (p1[0] - p0[0], p1[1] - p0[1]);
1999 let len = dx.hypot(dy);
2000 if len < 1e-6 {
2001 continue;
2002 }
2003 let normal = [dy / len, -dx / len, 0.0];
2004 let a = Vertex3D { pos: [p0[0], p0[1], z_front], normal, uv: [0.0, 0.0] };
2005 let b = Vertex3D { pos: [p0[0], p0[1], z_back], normal, uv: [0.0, 0.0] };
2006 let c = Vertex3D { pos: [p1[0], p1[1], z_back], normal, uv: [0.0, 0.0] };
2007 let d = Vertex3D { pos: [p1[0], p1[1], z_front], normal, uv: [0.0, 0.0] };
2008 verts.extend_from_slice(&[a, b, c, a, c, d]);
2009 }
2010 }
2011 }
2012 // Group holes into their deepest enclosing outer contour and triangulate front & back caps.
2013 let outers: Vec<usize> = (0..rings.len()).filter(|&i| depths[i] % 2 == 0).collect();
2014 let mut hole_groups: HashMap<usize, Vec<usize>> = HashMap::new();
2015 for hi in 0..rings.len() {
2016 if depths[hi] % 2 == 1 {
2017 let pt = rings[hi][0];
2018 if let Some(&oi) = outers
2019 .iter()
2020 .filter(|&&oi| depths[oi] < depths[hi] && point_in_ring(pt, &rings[oi]))
2021 .max_by_key(|&&oi| depths[oi])
2022 {
2023 hole_groups.entry(oi).or_default().push(hi);
2024 }
2025 }
2026 }
2027 for oi in outers {
2028 if verts.len() >= MAX_TEXT3D_VERTS {
2029 break;
2030 }
2031 let mut poly = rings[oi].clone();
2032 if let Some(mut his) = hole_groups.remove(&oi) {
2033 his.sort_by(|&a, &b| {
2034 let max_x = |r: &[[f32; 2]]| r.iter().map(|p| p[0]).fold(f32::NEG_INFINITY, f32::max);
2035 max_x(&rings[b]).total_cmp(&max_x(&rings[a]))
2036 });
2037 for hi in his {
2038 bridge_hole(&mut poly, &rings[hi]);
2039 }
2040 }
2041 for [a, b, c] in ear_clip(&poly) {
2042 if verts.len() + 6 > MAX_TEXT3D_VERTS {
2043 break;
2044 }
2045 let nf = [0.0, 0.0, 1.0];
2046 verts.push(Vertex3D { pos: [a[0], a[1], z_front], normal: nf, uv: [0.0, 0.0] });
2047 verts.push(Vertex3D { pos: [b[0], b[1], z_front], normal: nf, uv: [0.0, 0.0] });
2048 verts.push(Vertex3D { pos: [c[0], c[1], z_front], normal: nf, uv: [0.0, 0.0] });
2049 if depth > 1e-4 {
2050 let nb = [0.0, 0.0, -1.0];
2051 verts.push(Vertex3D { pos: [a[0], a[1], z_back], normal: nb, uv: [0.0, 0.0] });
2052 verts.push(Vertex3D { pos: [c[0], c[1], z_back], normal: nb, uv: [0.0, 0.0] });
2053 verts.push(Vertex3D { pos: [b[0], b[1], z_back], normal: nb, uv: [0.0, 0.0] });
2054 }
2055 }
2056 }
2057 }
2058 verts
2059}
2060
2061#[cfg(test)]
2062mod tests {
2063 use super::*;
2064 use crate::media::{TextPlusParams, rasterize_text_plus};
2065 use model::ClsEntry;
2066
2067 fn params<'a>(text: &'a str) -> TextPlusParams<'a> {
2068 TextPlusParams {
2069 text,
2070 font_family: "Helvetica",
2071 font_style: "Regular",
2072 size_norm: 0.08,
2073 tracking: 1.0,
2074 line_spacing: 1.0,
2075 center: [0.5, 0.5],
2076 h_lcr: 0.0,
2077 v_tcb: 0.0,
2078 fill_rgba: [1.0, 1.0, 1.0, 1.0],
2079 write_on_start: 0.0,
2080 write_on_end: 1.0,
2081 shear_x: 0.0,
2082 cls: &[],
2083 outline_rgba: [0.0; 4],
2084 outline_width_px: 0.0,
2085 }
2086 }
2087
2088 const DIMS: [u32; 2] = [960, 540];
2089
2090 fn alpha_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> Option<[i32; 4]> {
2091 let mut b: Option<[i32; 4]> = None;
2092 for (i, px) in rgba.chunks_exact(4).enumerate() {
2093 if px[3] == 0 {
2094 continue;
2095 }
2096 let (x, y) = ((i as u32 % size[0]) as i32 + origin[0], (i as u32 / size[0]) as i32 + origin[1]);
2097 let b = b.get_or_insert([x, y, x, y]);
2098 *b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];
2099 }
2100 b
2101 }
2102
2103 fn render_bounds(p: &TextPlusParams<'_>) -> Option<[i32; 4]> {
2104 let (size, origin, rgba) = rasterize_text_plus(DIMS, p, 0);
2105 alpha_bounds(size, origin, &rgba)
2106 }
2107
2108 #[test]
2109 fn system_fonts_resolve_with_fallback() {
2110 let font = Font::find("Definitely Not Installed 123", "Regular").expect("fallback font");
2111 let face = font.face();
2112 assert!(face.glyph_index('A').is_some());
2113 let (asc, desc) = vertical_metrics(&face);
2114 assert!(asc > 0.5 && desc > 0.0 && asc + desc < 2.0, "{asc} {desc}");
2115 }
2116
2117 #[test]
2118 fn style_names_map_to_weight_and_slant() {
2119 assert_eq!(parse_style("Regular"), (400, false));
2120 assert_eq!(parse_style("Extra Bold"), (800, false));
2121 assert_eq!(parse_style("Semi Bold Italic"), (600, true));
2122 assert_eq!(parse_style("Light Oblique"), (300, true));
2123 assert_eq!(parse_style("Extra Light"), (200, false));
2124 }
2125
2126 #[test]
2127 fn bold_face_is_heavier_than_regular() {
2128 let ink = |style: &str| {
2129 let mut p = params("HHHH");
2130 p.font_style = style;
2131 let (_, _, rgba) = rasterize_text_plus(DIMS, &p, 0);
2132 rgba.chunks_exact(4).map(|px| px[3] as u64).sum::<u64>()
2133 };
2134 assert!(ink("Bold") > ink("Regular"));
2135 }
2136
2137 #[test]
2138 fn rendering_is_deterministic() {
2139 let mut p = params("Fission 2 \u{2014} fi AV");
2140 p.outline_rgba = [1.0, 0.0, 0.0, 1.0];
2141 p.outline_width_px = 6.0;
2142 assert_eq!(rasterize_text_plus(DIMS, &p, 0), rasterize_text_plus(DIMS, &p, 0));
2143 }
2144
2145 #[test]
2146 fn kerning_tightens_av_pair() {
2147 let font = Font::find("Helvetica", "Regular").unwrap();
2148 let face = font.face();
2149 let solo = |s: &str| shape_line(&face, s, 100.0, 0.0).width;
2150 assert!(solo("AV") < solo("A") + solo("V") - 1.0, "{} vs {}", solo("AV"), solo("A") + solo("V"));
2151 }
2152
2153 #[test]
2154 fn tracking_adds_space_between_clusters_only() {
2155 let font = Font::find("Helvetica", "Regular").unwrap();
2156 let face = font.face();
2157 let plain = shape_line(&face, "HHH", 100.0, 0.0);
2158 let spaced = shape_line(&face, "HHH", 100.0, 10.0);
2159 assert!((spaced.width - plain.width - 20.0).abs() < 1e-3);
2160 assert_eq!(spaced.glyphs.iter().map(|g| g.char_index).collect::<Vec<_>>(), [0, 1, 2]);
2161 }
2162
2163 #[test]
2164 fn outlines_are_true_curves() {
2165 let font = Font::find("Helvetica", "Regular").unwrap();
2166 let face = font.face();
2167 let gid = face.glyph_index('O').unwrap();
2168 let path = glyph_path(&font, &face, gid, 100.0, [0.0, 0.0], 0.0);
2169 assert!(path.iter().any(|c| matches!(c, Command::QuadTo(..) | Command::CurveTo(..))));
2170 let cov = fill(&path).unwrap();
2171 assert!((60..=90).contains(&cov.height), "O cap height {}", cov.height);
2172 let ring = stroke(&path, 10.0).unwrap();
2173 assert!(ring.width >= cov.width + 8, "stroke must extend past the fill");
2174 assert!(cov.data.iter().any(|&a| a > 0 && a < 255), "edges are antialiased");
2175 }
2176
2177 #[test]
2178 fn outline_stroke_grows_the_domain_and_sits_under_the_fill() {
2179 let plain = render_bounds(&params("HI")).unwrap();
2180 let mut p = params("HI");
2181 p.outline_rgba = [1.0, 0.0, 0.0, 1.0];
2182 p.outline_width_px = 12.0;
2183 let outlined = render_bounds(&p).unwrap();
2184 assert!(outlined[0] <= plain[0] - 5 && outlined[2] >= plain[2] + 5, "{outlined:?} vs {plain:?}");
2185 let (size, origin, rgba) = rasterize_text_plus(DIMS, &p, 0);
2186 let at = |x: i32, y: i32| {
2187 let i = (((y - origin[1]) as u32 * size[0] + (x - origin[0]) as u32) * 4) as usize;
2188 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
2189 };
2190 let ring = at(plain[0] - 3, (plain[1] + plain[3]) / 2);
2191 assert!(ring[0] > 200 && ring[1] < 10 && ring[3] > 200, "outline pixel {ring:?}");
2192 }
2193
2194 #[test]
2195 fn write_on_reveals_by_character_without_moving_layout() {
2196 let full = render_bounds(&params("HHHH")).unwrap();
2197 let mut p = params("HHHH");
2198 p.write_on_end = 0.5;
2199 let half = render_bounds(&p).unwrap();
2200 assert_eq!(half[0], full[0], "the first glyph stays put");
2201 assert!(half[2] < (full[0] + full[2]) / 2 + 3, "{half:?} vs {full:?}");
2202 p.write_on_start = 0.5;
2203 p.write_on_end = 1.0;
2204 let tail = render_bounds(&p).unwrap();
2205 assert_eq!(tail[2], full[2], "the last glyph stays put");
2206 p.write_on_start = 1.0;
2207 assert!(render_bounds(&p).is_none());
2208 }
2209
2210 #[test]
2211 fn cls_offsets_move_only_the_styled_characters() {
2212 let base = render_bounds(&params("HH")).unwrap();
2213 let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05, text: String::new() }];
2214 let mut p = params("HH");
2215 p.cls = &cls;
2216 let raised = render_bounds(&p).unwrap();
2217 assert_eq!(raised[0], base[0]);
2218 assert_eq!(raised[2], base[2]);
2219 assert!(raised[1] < base[1] - 30, "{raised:?} vs {base:?}");
2220 }
2221
2222 #[test]
2223 fn character_spacing_widens_lines() {
2224 let width = |t: f32| {
2225 let mut p = params("HHHH");
2226 p.tracking = t;
2227 let b = render_bounds(&p).unwrap();
2228 b[2] - b[0]
2229 };
2230 assert!(width(1.5) > width(1.0) + 20);
2231 }
2232
2233 #[test]
2234 fn justification_anchors_lines() {
2235 let at = |h: f32| {
2236 let mut p = params("HHHH");
2237 p.h_lcr = h;
2238 render_bounds(&p).unwrap()
2239 };
2240 let (left, centre, right) = (at(-1.0), at(0.0), at(1.0));
2241 assert!((left[0] - 480).abs() <= 6, "{left:?}");
2242 assert!((right[2] - 480).abs() <= 6, "{right:?}");
2243 assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}");
2244 }
2245
2246 #[test]
2247 fn liberation_sans_uses_metric_equivalent_and_landscape_scales_with_width() {
2248 let lib_font = Font::find("Liberation Sans", "Regular").expect("Liberation Sans or metric alias");
2249 let arial_font = Font::find("Arial", "Regular").expect("Arial");
2250 let (lib_face, arial_face) = (lib_font.face(), arial_font.face());
2251 let lib_w = shape_line(&lib_face, "Aspect 321", 50.0, 0.0).width;
2252 let arial_w = shape_line(&arial_face, "Aspect 321", 50.0, 0.0).width;
2253 assert!((lib_w - arial_w).abs() < 1.0, "expected Liberation Sans / Arial metric parity: {lib_w} vs {arial_w}");
2254
2255 let span = |dims: [u32; 2]| {
2256 let mut p = params("Aspect 321");
2257 p.font_family = "Liberation Sans";
2258 p.size_norm = 0.18;
2259 let (sz, orig, rgba) = rasterize_text_plus(dims, &p, 0);
2260 let b = alpha_bounds(sz, orig, &rgba).unwrap();
2261 (b[2] - b[0] + 1, b[3] - b[1] + 1, (b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
2262 };
2263 let (lw, lh, lcx, lcy) = span([320, 180]);
2264 let (pw, ph, pcx, pcy) = span([180, 320]);
2265 assert!((lw as f32 / pw as f32 - 320.0 / 180.0).abs() < 0.08, "landscape/portrait width ratio {lw}/{pw}");
2266 assert!((lh as f32 / ph as f32 - 320.0 / 180.0).abs() < 0.12, "landscape/portrait height ratio {lh}/{ph}");
2267 assert!((lcx - 160).abs() <= 8 && (lcy - 90).abs() <= 8, "landscape centered ({lcx}, {lcy})");
2268 assert!((pcx - 90).abs() <= 6 && (pcy - 160).abs() <= 6, "portrait centered ({pcx}, {pcy})");
2269 }
2270
2271 #[test]
2272 fn metric_aliases_map_both_ways() {
2273 for (a, b) in [("Arial", "Liberation Sans"), ("Times New Roman", "Liberation Serif"), ("Courier New", "Liberation Mono")] {
2274 assert_eq!(metric_alias(a), Some(b));
2275 assert_eq!(metric_alias(b), Some(a));
2276 }
2277 }
2278
2279 #[test]
2280 fn rich_cls_crlf_size_and_softness_work() {
2281 let cls = [StyledClsRule {
2282 prop_id: 102,
2283 start: 4,
2284 end: 5,
2285 value: 0.24,
2286 text: String::new(),
2287 }];
2288 let mut p = RichTextPlusParams {
2289 text: "HH\nHH",
2290 font_family: "Liberation Sans",
2291 font_style: "Regular",
2292 size_norm: 0.08,
2293 tracking: 1.0,
2294 line_spacing: 1.0,
2295 center: [0.5, 0.5],
2296 h_lcr: 0.0,
2297 v_tcb: 0.0,
2298 fill_rgba: [1.0; 4],
2299 write_on_start: 0.0,
2300 write_on_end: 1.0,
2301 shear_x: 0.0,
2302 cls: &cls,
2303 outline_rgba: [0.0, 1.0, 1.0, 1.0],
2304 outline_thickness_norm: 0.05,
2305 outline_enabled: true,
2306 soft_fill: [0.0; 3],
2307 soft_outline: [4.0, 4.0, 0.5],
2308 baseline_at_center: false,
2309 };
2310 let (sz, orig, rgba) = rasterize_text_plus_rich([512, 288], &p, 0);
2311 let b = alpha_bounds(sz, orig, &rgba).unwrap();
2312 p.cls = &[];
2313 p.soft_outline = [0.0; 3];
2314 let (sz_base, orig_base, rgba_base) = rasterize_text_plus_rich([512, 288], &p, 0);
2315 let b_base = alpha_bounds(sz_base, orig_base, &rgba_base).unwrap();
2316 assert!(b[2] - b[0] > b_base[2] - b_base[0] + 30, "{b:?} vs {b_base:?}");
2317 }
2318
2319 #[test]
2320 fn text3d_extruded_mesh_builds_caps_and_sides_for_holed_glyphs() {
2321 let p = RichTextPlusParams {
2322 text: "cold",
2323 font_family: "Liberation Sans",
2324 font_style: "Regular",
2325 size_norm: 0.25,
2326 tracking: 1.0,
2327 line_spacing: 1.0,
2328 center: [0.5, 0.5],
2329 h_lcr: 0.0,
2330 v_tcb: 0.0,
2331 fill_rgba: [1.0; 4],
2332 write_on_start: 0.0,
2333 write_on_end: 1.0,
2334 shear_x: 0.0,
2335 cls: &[],
2336 outline_rgba: [0.0; 4],
2337 outline_thickness_norm: 0.0,
2338 outline_enabled: false,
2339 soft_fill: [0.0; 3],
2340 soft_outline: [0.0; 3],
2341 baseline_at_center: true,
2342 };
2343 let verts = build_text3d_mesh(&p, 0.15);
2344 assert!(verts.len() > 200);
2345 let max_z = verts.iter().map(|v| v.pos[2]).fold(f32::NEG_INFINITY, f32::max);
2346 let min_z = verts.iter().map(|v| v.pos[2]).fold(f32::INFINITY, f32::min);
2347 assert!((max_z - 0.15).abs() < 1e-4 && min_z.abs() < 1e-4, "{min_z}..{max_z}");
2348 assert!(verts.iter().any(|v| v.normal[2] == 0.0), "expected extruded side normals");
2349 }
2350
2351 #[test]
2352 fn ear_clip_and_bridge_hole_triangulate_square_with_hole_exact_area() {
2353 let mut outer = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
2354 let hole = vec![[0.25, 0.25], [0.25, 0.75], [0.75, 0.75], [0.75, 0.25]];
2355 bridge_hole(&mut outer, &hole);
2356 let tris = ear_clip(&outer);
2357 assert!(!tris.is_empty());
2358 let area: f32 = tris
2359 .iter()
2360 .map(|[a, b, c]| 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])))
2361 .sum();
2362 assert!((area - 0.75).abs() < 1e-5, "expected exact 0.75 area, got {area}");
2363 }
2364
2365 #[test]
2366 fn text3d_holed_glyphs_o_and_b_preserve_exact_cap_area() {
2367 for (ch, expected_holes) in [('o', 1usize), ('B', 2usize)] {
2368 let txt = ch.to_string();
2369 let p = RichTextPlusParams {
2370 text: &txt,
2371 font_family: "Liberation Sans",
2372 font_style: "Regular",
2373 size_norm: 0.25,
2374 tracking: 1.0,
2375 line_spacing: 1.0,
2376 center: [0.5, 0.5],
2377 h_lcr: 0.0,
2378 v_tcb: 0.0,
2379 fill_rgba: [1.0; 4],
2380 write_on_start: 0.0,
2381 write_on_end: 1.0,
2382 shear_x: 0.0,
2383 cls: &[],
2384 outline_rgba: [0.0; 4],
2385 outline_thickness_norm: 0.0,
2386 outline_enabled: false,
2387 soft_fill: [0.0; 3],
2388 soft_outline: [0.0; 3],
2389 baseline_at_center: true,
2390 };
2391 let (glyphs, _) = layout_glyphs([2048, 1024], &p).unwrap();
2392 assert_eq!(glyphs.len(), 1);
2393 let mut rings = flatten_glyph_rings(&glyphs[0].commands);
2394 let mut depths = vec![0usize; rings.len()];
2395 for i in 0..rings.len() {
2396 let pt = rings[i][0];
2397 for j in 0..rings.len() {
2398 if i != j && point_in_ring(pt, &rings[j]) {
2399 depths[i] += 1;
2400 }
2401 }
2402 }
2403 assert_eq!(depths.iter().filter(|&&d| d % 2 == 1).count(), expected_holes, "hole count for {ch}");
2404 for (i, ring) in rings.iter_mut().enumerate() {
2405 if (depths[i] % 2 == 0) != (ring_signed_area(ring) > 0.0) {
2406 ring.reverse();
2407 }
2408 }
2409 let expected_area: f32 = rings.iter().map(|r| ring_signed_area(r)).sum();
2410
2411 let verts = build_text3d_mesh(&p, 0.0);
2412 assert_eq!(verts.len() % 3, 0);
2413 let cap_area: f32 = verts
2414 .chunks_exact(3)
2415 .map(|t| {
2416 let (a, b, c) = (t[0].pos, t[1].pos, t[2].pos);
2417 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
2418 })
2419 .sum();
2420 assert!(
2421 (cap_area - expected_area).abs() < 1e-4,
2422 "glyph '{ch}' cap area {cap_area} != ring signed area {expected_area}"
2423 );
2424 }
2425 }
2426
2427 #[test]
2428 fn crlf_strips_cr_and_keeps_cls_indices_aligned() {
2429 let cls = [StyledClsRule {
2430 prop_id: 102,
2431 start: 4,
2432 end: 5,
2433 value: 0.24,
2434 text: String::new(),
2435 }];
2436 let make = |text: &'static str| RichTextPlusParams {
2437 text,
2438 font_family: "Liberation Sans",
2439 font_style: "Regular",
2440 size_norm: 0.08,
2441 tracking: 1.0,
2442 line_spacing: 1.0,
2443 center: [0.5, 0.5],
2444 h_lcr: 0.0,
2445 v_tcb: 0.0,
2446 fill_rgba: [1.0; 4],
2447 write_on_start: 0.0,
2448 write_on_end: 1.0,
2449 shear_x: 0.0,
2450 cls: &cls,
2451 outline_rgba: [0.0; 4],
2452 outline_thickness_norm: 0.0,
2453 outline_enabled: false,
2454 soft_fill: [0.0; 3],
2455 soft_outline: [0.0; 3],
2456 baseline_at_center: false,
2457 };
2458 let lf = rasterize_text_plus_rich([320, 180], &make("HH\nHH"), 0);
2459 let crlf = rasterize_text_plus_rich([320, 180], &make("HH\r\nHH"), 0);
2460 assert_eq!(lf, crlf, "CRLF must render identically to LF without .notdef boxes or CLS drift");
2461 }
2462
2463 #[test]
2464 fn non_finite_and_huge_softness_values_do_not_overflow() {
2465 let p = RichTextPlusParams {
2466 text: "A",
2467 font_family: "Liberation Sans",
2468 font_style: "Regular",
2469 size_norm: 0.12,
2470 tracking: 1.0,
2471 line_spacing: 1.0,
2472 center: [0.5, 0.5],
2473 h_lcr: 0.0,
2474 v_tcb: 0.0,
2475 fill_rgba: [1.0; 4],
2476 write_on_start: 0.0,
2477 write_on_end: 1.0,
2478 shear_x: 0.0,
2479 cls: &[],
2480 outline_rgba: [1.0, 0.0, 0.0, 1.0],
2481 outline_thickness_norm: 0.05,
2482 outline_enabled: true,
2483 soft_fill: [f32::NAN, f32::INFINITY, 0.0],
2484 soft_outline: [1e30, -5.0, 0.0],
2485 baseline_at_center: false,
2486 };
2487 let (sz, _, rgba) = rasterize_text_plus_rich([160, 90], &p, 0);
2488 assert!(sz[0] <= 480 && sz[1] <= 270 && !rgba.is_empty());
2489 }
2490
2491 #[test]
2492 fn runtime_font_registration_resolves_custom_family_alias() {
2493 let base = Font::find("Helvetica", "Regular").expect("system fallback font");
2494 let bytes = base.data.clone();
2495 register_font_bytes(bytes.clone());
2496 register_font_bytes_with_name("FissionRuntimeAliasFont", bytes);
2497 let resolved = Font::find("FissionRuntimeAliasFont", "Regular").expect("registered alias font");
2498 assert!(resolved.face().glyph_index('A').is_some());
2499 }
2500
2501 #[test]
2502 fn tight_dod_empty_whitespace_and_zero_alpha_return_1x1_transparent() {
2503 let mut p = RichTextPlusParams {
2504 text: "",
2505 font_family: "Liberation Sans",
2506 font_style: "Regular",
2507 size_norm: 0.08,
2508 tracking: 1.0,
2509 line_spacing: 1.0,
2510 center: [0.5, 0.5],
2511 h_lcr: 0.0,
2512 v_tcb: 0.0,
2513 fill_rgba: [1.0; 4],
2514 write_on_start: 0.0,
2515 write_on_end: 1.0,
2516 shear_x: 0.0,
2517 cls: &[],
2518 outline_rgba: [0.0; 4],
2519 outline_thickness_norm: 0.0,
2520 outline_enabled: false,
2521 soft_fill: [0.0; 3],
2522 soft_outline: [0.0; 3],
2523 baseline_at_center: false,
2524 };
2525 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2526 p.text = " ";
2527 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2528 p.text = "AB";
2529 p.write_on_end = 0.0;
2530 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2531 p.write_on_end = 1.0;
2532 p.fill_rgba[3] = 0.0;
2533 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2534 }
2535
2536 #[test]
2537 fn tight_dod_text_plus_matches_full_canvas_across_cls_outline_and_softness() {
2538 let dims = [640u32, 360u32];
2539 let composite_onto_canvas = |sz: [u32; 2], orig: [i32; 2], rgba: &[u8]| -> Vec<u8> {
2540 let mut canvas = vec![0u8; (dims[0] * dims[1] * 4) as usize];
2541 for y in 0..sz[1] as i32 {
2542 let cy = orig[1] + y;
2543 if cy < 0 || cy >= dims[1] as i32 {
2544 continue;
2545 }
2546 for x in 0..sz[0] as i32 {
2547 let cx = orig[0] + x;
2548 if cx < 0 || cx >= dims[0] as i32 {
2549 continue;
2550 }
2551 let si = ((y as u32 * sz[0] + x as u32) * 4) as usize;
2552 let di = ((cy as u32 * dims[0] + cx as u32) * 4) as usize;
2553 canvas[di..di + 4].copy_from_slice(&rgba[si..si + 4]);
2554 }
2555 }
2556 canvas
2557 };
2558
2559 // 1. Plain + outline vs legacy full-canvas `rasterize_text_plus`.
2560 let p_legacy = TextPlusParams {
2561 text: "Hello",
2562 font_family: "Liberation Sans",
2563 font_style: "Regular",
2564 size_norm: 0.08,
2565 tracking: 1.0,
2566 line_spacing: 1.0,
2567 center: [0.5, 0.5],
2568 h_lcr: 0.0,
2569 v_tcb: 0.0,
2570 fill_rgba: [1.0, 0.9, 0.8, 1.0],
2571 write_on_start: 0.0,
2572 write_on_end: 1.0,
2573 shear_x: 0.0,
2574 cls: &[],
2575 outline_rgba: [0.2, 0.4, 1.0, 0.8],
2576 outline_width_px: (0.04_f32 * 0.08 * 640.0).clamp(1.0, 128.0),
2577 };
2578 let (lsz, lorig, lrgba) = rasterize_text_plus(dims, &p_legacy, 0);
2579 let p_rich = RichTextPlusParams {
2580 text: "Hello",
2581 font_family: "Liberation Sans",
2582 font_style: "Regular",
2583 size_norm: 0.08,
2584 tracking: 1.0,
2585 line_spacing: 1.0,
2586 center: [0.5, 0.5],
2587 h_lcr: 0.0,
2588 v_tcb: 0.0,
2589 fill_rgba: [1.0, 0.9, 0.8, 1.0],
2590 write_on_start: 0.0,
2591 write_on_end: 1.0,
2592 shear_x: 0.0,
2593 cls: &[],
2594 outline_rgba: [0.2, 0.4, 1.0, 0.8],
2595 outline_thickness_norm: 0.04,
2596 outline_enabled: true,
2597 soft_fill: [0.0; 3],
2598 soft_outline: [0.0; 3],
2599 baseline_at_center: false,
2600 };
2601 let (tsz, torig, trgba) = rasterize_text_plus_rich(dims, &p_rich, 0);
2602 assert!(tsz[0] < dims[0] && tsz[1] < dims[1], "expected tight DoD, got {tsz:?}");
2603 assert!(torig[0] > 0 && torig[1] > 0, "expected non-zero tight origin, got {torig:?}");
2604 let tight_canvas = composite_onto_canvas(tsz, torig, &trgba);
2605 let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba);
2606 for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() {
2607 // 1/16 px subpixel quantization in `cached_glyph_coverage` can shift x/y by <= 1/32 px each (~16 u8 levels).
2608 assert!(a.abs_diff(b) <= 16, "legacy parity diff at byte {i}: {a} vs {b}");
2609 }
2610 let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80);
2611 assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain));
2612
2613 // 2. CLS offsets + Softness blur: tight bbox matches full-plane blur pixel-for-pixel.
2614 let cls = [
2615 StyledClsRule { prop_id: 1350, start: 1, end: 1, value: 0.04, text: String::new() },
2616 StyledClsRule { prop_id: 1351, start: 2, end: 2, value: -0.03, text: String::new() },
2617 StyledClsRule { prop_id: 102, start: 3, end: 3, value: 0.12, text: String::new() },
2618 ];
2619 let p_soft = RichTextPlusParams {
2620 cls: &cls,
2621 soft_fill: [3.0, 2.5, 0.25],
2622 soft_outline: [4.0, 3.0, 0.4],
2623 ..p_rich
2624 };
2625 let (ssz, sorig, srgba) = rasterize_text_plus_rich(dims, &p_soft, 0);
2626 assert!(ssz[0] < dims[0] && ssz[1] < dims[1], "expected tight soft DoD, got {ssz:?}");
2627 // Padded extra 40px must yield identical canvas pixels because blur tail already decays to 0 inside 3*sigma.
2628 let (psz, porig, prgba) = rasterize_text_plus_rich(dims, &p_soft, 40);
2629 assert_eq!(
2630 composite_onto_canvas(ssz, sorig, &srgba),
2631 composite_onto_canvas(psz, porig, &prgba)
2632 );
2633 }
2634
2635 #[test]
2636 fn separable_gaussian_fast_path_matches_naive_reference() {
2637 let w = 29usize;
2638 let h = 23usize;
2639 let mut init = vec![0.0_f32; w * h];
2640 for y in 0..h {
2641 for x in 0..w {
2642 init[y * w + x] = (((x * 7 + y * 13) % 19) as f32) / 18.0;
2643 }
2644 }
2645 let naive = |src: &[f32], sx: f32, sy: f32| -> Vec<f32> {
2646 let mut p = src.to_vec();
2647 let (rx, kx) = gaussian_kernel_1d(sx);
2648 if rx > 0 {
2649 let mut tmp = vec![0.0_f32; w * h];
2650 for y in 0..h {
2651 for x in 0..w {
2652 let mut acc = 0.0_f32;
2653 for (ki, &kw) in kx.iter().enumerate() {
2654 let ix = x as isize + ki as isize - rx;
2655 if ix >= 0 && ix < w as isize {
2656 acc += p[y * w + ix as usize] * kw;
2657 }
2658 }
2659 tmp[y * w + x] = acc;
2660 }
2661 }
2662 p = tmp;
2663 }
2664 let (ry, ky) = gaussian_kernel_1d(sy);
2665 if ry > 0 {
2666 let mut tmp = vec![0.0_f32; w * h];
2667 for y in 0..h {
2668 for x in 0..w {
2669 let mut acc = 0.0_f32;
2670 for (ki, &kw) in ky.iter().enumerate() {
2671 let iy = y as isize + ki as isize - ry;
2672 if iy >= 0 && iy < h as isize {
2673 acc += p[iy as usize * w + x] * kw;
2674 }
2675 }
2676 tmp[y * w + x] = acc;
2677 }
2678 }
2679 p = tmp;
2680 }
2681 p
2682 };
2683 for (sx, sy) in [(2.3, 1.7), (3.1, 0.0), (0.0, 2.8)] {
2684 let mut fast = init.clone();
2685 apply_separable_gaussian(&mut fast, w, h, sx, sy);
2686 let ref_buf = naive(&init, sx, sy);
2687 for (a, b) in fast.iter().zip(ref_buf.iter()) {
2688 assert!((a - b).abs() < 1e-6, "mismatch for ({sx}, {sy}): {a} vs {b}");
2689 }
2690 }
2691 }
2692
2693 #[test]
2694 fn glyph_cache_is_deterministic_and_bounded() {
2695 let p = RichTextPlusParams {
2696 text: "Mississippi 1234",
2697 font_family: "Helvetica",
2698 font_style: "Regular",
2699 size_norm: 0.08,
2700 tracking: 1.0,
2701 line_spacing: 1.0,
2702 center: [0.5, 0.5],
2703 h_lcr: 0.0,
2704 v_tcb: 0.0,
2705 fill_rgba: [1.0, 0.85, 0.7, 1.0],
2706 write_on_start: 0.0,
2707 write_on_end: 1.0,
2708 shear_x: 0.0,
2709 cls: &[],
2710 outline_rgba: [0.1, 0.2, 0.3, 0.9],
2711 outline_thickness_norm: 0.03,
2712 outline_enabled: true,
2713 soft_fill: [0.0; 3],
2714 soft_outline: [0.0; 3],
2715 baseline_at_center: false,
2716 };
2717 let first = rasterize_text_plus_rich([960, 540], &p, 0);
2718 let second = rasterize_text_plus_rich([960, 540], &p, 0);
2719 assert_eq!(first, second, "cached glyph rasterization must be bit-identical");
2720
2721 let mut p_plain = p;
2722 p_plain.outline_enabled = false;
2723 let p1 = rasterize_text_plus_rich([960, 540], &p_plain, 0);
2724 let p2 = rasterize_text_plus_rich([960, 540], &p_plain, 0);
2725 assert_eq!(p1, p2, "u8 fast-path glyph rasterization must be bit-identical");
2726
2727 // Verify bounded eviction in GlyphCache.
2728 let mut cache = GlyphCache::new();
2729 for i in 0..(MAX_GLYPH_CACHE_ENTRIES + 64) {
2730 let key = GlyphCacheKey {
2731 font_id: 999,
2732 glyph_id: i as u16,
2733 size_bits: 1000,
2734 lean_bits: 0,
2735 stroke_bits: 0,
2736 sub_x_bits: 0,
2737 sub_y_bits: 0,
2738 };
2739 let entry = Arc::new(CachedGlyphCoverage {
2740 fill: Some(Coverage {
2741 left: 0,
2742 top: 0,
2743 width: 4,
2744 height: 4,
2745 data: vec![255; 16],
2746 }),
2747 stroke: None,
2748 bytes: 16,
2749 });
2750 cache.insert(key, entry);
2751 }
2752 assert!(cache.map.len() <= MAX_GLYPH_CACHE_ENTRIES);
2753 assert!(cache.total_bytes <= MAX_GLYPH_CACHE_BYTES);
2754 }
2755
2756 #[test]
2757 fn lazy_font_lookup_resolves_and_caches() {
2758 let f1 = Font::find("Helvetica Neue", "Regular").expect("Helvetica Neue");
2759 let f2 = Font::find("Helvetica Neue", "Regular").expect("cached Helvetica Neue");
2760 assert_eq!(f1.id, f2.id);
2761 let mut t_sum = std::time::Duration::ZERO;
2762 for _ in 0..20 {
2763 let t0 = std::time::Instant::now();
2764 let f = Font::find("Helvetica Neue", "Regular").unwrap();
2765 t_sum += t0.elapsed();
2766 assert_eq!(f.id, f1.id);
2767 }
2768 assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}");
2769 }
2770
2771 #[test]
2772 fn glyph_cache_subpixel_quantization_and_lru_eviction() {
2773 assert_eq!(quantize_subpixel(10.99), Some((11, 0.0)));
2774 assert_eq!(quantize_subpixel(-0.01), Some((0, 0.0)));
2775 assert_eq!(quantize_subpixel(10.01), quantize_subpixel(10.02));
2776
2777 let font = Font::find("Helvetica", "Regular").expect("system font");
2778 let gid = font.face().glyph_index('A').expect("glyph A");
2779 let make_spec = |x: f32, y: f32| GlyphSpec {
2780 font: Arc::clone(&font),
2781 glyph_id: gid,
2782 font_px: 42.0,
2783 abs_x: x,
2784 abs_y: y,
2785 shear: 0.0,
2786 outline_w: 0.0,
2787 };
2788 let (ix1, iy1, cov1) = cached_glyph_coverage(&make_spec(100.01, 200.01), false);
2789 let (ix2, iy2, cov2) = cached_glyph_coverage(&make_spec(100.02, 200.02), false);
2790 assert_eq!((ix1, iy1), (100, 200));
2791 assert_eq!((ix2, iy2), (100, 200));
2792 assert!(Arc::ptr_eq(&cov1, &cov2), "jitter within 1/16 px must share cached coverage");
2793
2794 // Verify LRU eviction (touching key 0 keeps it alive when capacity is exceeded).
2795 let mut cache = GlyphCache::new();
2796 let make_key = |i: u16| GlyphCacheKey {
2797 font_id: 777,
2798 glyph_id: i,
2799 size_bits: 42.0_f32.to_bits(),
2800 lean_bits: 0,
2801 stroke_bits: 0,
2802 sub_x_bits: 0,
2803 sub_y_bits: 0,
2804 };
2805 let make_entry = || {
2806 Arc::new(CachedGlyphCoverage {
2807 fill: Some(Coverage {
2808 left: 0,
2809 top: 0,
2810 width: 4,
2811 height: 4,
2812 data: vec![255; 16],
2813 }),
2814 stroke: None,
2815 bytes: 16,
2816 })
2817 };
2818 for i in 0..MAX_GLYPH_CACHE_ENTRIES {
2819 cache.insert(make_key(i as u16), make_entry());
2820 }
2821 // Touch key 0 so key 1 becomes the least recently used entry.
2822 assert!(cache.get(&make_key(0)).is_some());
2823 cache.insert(make_key(MAX_GLYPH_CACHE_ENTRIES as u16), make_entry());
2824 assert!(cache.get(&make_key(0)).is_some(), "recently touched entry must survive LRU eviction");
2825 assert!(cache.get(&make_key(1)).is_none(), "least recently used entry must be evicted");
2826 }
2827
2828 #[test]
2829 fn register_font_bytes_generation_prevents_stale_cache_poisoning() {
2830 let base = Font::find("Helvetica", "Regular").expect("system fallback font");
2831 let gen0 = registry().read().unwrap().generation;
2832 register_font_bytes_with_name("FissionGenRaceFont", base.data.clone());
2833 let gen1 = registry().read().unwrap().generation;
2834 assert!(gen1 > gen0);
2835
2836 // Simulate a thread that finished resolve_lazy at gen0 before register_font_bytes_with_name ran.
2837 let _ = cache_resolved_font("FissionGenRaceFont", "Regular", None, gen0);
2838 {
2839 let cache = font_cache().lock().unwrap();
2840 assert_eq!(cache.0, gen1);
2841 assert!(
2842 !cache.1.contains_key(&("FissionGenRaceFont".to_owned(), "Regular".to_owned())),
2843 "stale pre-registration result must not poison font_cache"
2844 );
2845 }
2846 assert!(Font::find("FissionGenRaceFont", "Regular").is_some());
2847 }
2848
2849 #[test]
2850 fn extreme_off_canvas_coords_never_overflow_i32() {
2851 for bad in [
2852 f32::NAN,
2853 f32::INFINITY,
2854 f32::NEG_INFINITY,
2855 f32::MAX,
2856 f32::MIN,
2857 1e15,
2858 -1e15,
2859 (i32::MAX as f32) * 2.0,
2860 (i32::MIN as f32) * 2.0,
2861 ] {
2862 assert_eq!(quantize_subpixel(bad), None);
2863 }
2864
2865 let font = Font::find("Helvetica", "Regular").expect("system font");
2866 let gid = font.face().glyph_index('A').expect("glyph A");
2867 for (ax, ay) in [(1e20_f32, 0.0_f32), (0.0, -1e20), (f32::NAN, 10.0), (f32::INFINITY, f32::NEG_INFINITY)] {
2868 let spec = GlyphSpec {
2869 font: Arc::clone(&font),
2870 glyph_id: gid,
2871 font_px: 32.0,
2872 abs_x: ax,
2873 abs_y: ay,
2874 shear: 0.0,
2875 outline_w: 0.0,
2876 };
2877 let (ix, iy, cov) = cached_glyph_coverage(&spec, false);
2878 assert_eq!((ix, iy), (0, 0));
2879 assert!(cov.fill.is_none() && cov.stroke.is_none());
2880 }
2881
2882 let p = RichTextPlusParams {
2883 text: "Far",
2884 font_family: "Helvetica",
2885 font_style: "Regular",
2886 size_norm: 0.08,
2887 tracking: 1.0,
2888 line_spacing: 1.0,
2889 center: [1e12, -1e12],
2890 h_lcr: 0.0,
2891 v_tcb: 0.0,
2892 fill_rgba: [1.0; 4],
2893 write_on_start: 0.0,
2894 write_on_end: 1.0,
2895 shear_x: 0.0,
2896 cls: &[],
2897 outline_rgba: [0.0; 4],
2898 outline_thickness_norm: 0.0,
2899 outline_enabled: false,
2900 soft_fill: [0.0; 3],
2901 soft_outline: [0.0; 3],
2902 baseline_at_center: false,
2903 };
2904 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2905 }
2906}