authoravatarclover caruso<git@paperclover.net>2026-12-01 16:13:14-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 16:27:14-08:00
log40ca636e5b89a2ea337f81f7bf69a53369e33f88
treeb055e7376436096eaf34325f6ed0d6f57d68eea2
parent6b08e39c45b70bb37ac6c03d0ed2c5a44f430957
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): harden text_engine font/glyph cache, NGon NaN guard, multiplies_by_mask, and blur_glow select loads


7 files changed, 359 insertions(+), 60 deletions(-)

crates/engine/src/eval/composite.rs+3-3
......@@ -673,13 +673,13 @@ fn roi_from_consumer(
673673 if port != "Input" {
674674 return None;
675675 }
676 if Engine::resolve_effect_mask_id(comp, n).is_some() {
677 return Some(RoiBox::canvas(canvas_size));
678 }
676679 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
677680 if blend <= 1e-6 {
678681 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
679682 }
680 if Engine::resolve_effect_mask_id(comp, n).is_some() {
681 return Some(RoiBox::canvas(canvas_size));
682 }
683683 let amount = comp.eval_number(n, "Amount", time, 0.0, expr);
684684 let amt_x = comp.eval_number(n, "XAmount", time, amount, expr) as f32;
685685 let amt_y = if comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5 {
crates/engine/src/eval/transform.rs+2-2
......@@ -890,7 +890,7 @@ impl Engine {
890890
891891 /// `MultiplyByMask` zeroes outside the EffectMask even when the effect itself is an identity.
892892 pub(super) fn multiplies_by_mask(&self, comp: &Comp, node: &Node, time: f64) -> bool {
893 node.connected_node("EffectMask").is_some()
893 Self::resolve_effect_mask_id(comp, node).is_some()
894894 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5
895895 }
896896
......@@ -1007,7 +1007,7 @@ impl Engine {
10071007 return src;
10081008 }
10091009 let skip = self.process_skip(comp, node, time);
1010 if skip.iter().all(|&s| s > 0.5) {
1010 if skip.iter().all(|&s| s > 0.5) && !self.multiplies_by_mask(comp, node, time) {
10111011 return src;
10121012 }
10131013 let src = self.crop_to_canvas(enc, src);
crates/engine/src/eval/warps.rs+1-1
......@@ -150,7 +150,7 @@ impl Engine {
150150 return src;
151151 }
152152 let skip = self.process_skip(comp, node, time);
153 if skip.iter().all(|&s| s > 0.5) {
153 if skip.iter().all(|&s| s > 0.5) && !mbm_flag {
154154 return src;
155155 }
156156 let src = self.crop_to_canvas(enc, src);
crates/engine/src/particles/raster.rs+61-2
......@@ -641,9 +641,9 @@ fn rasterize_single_band(
641641 let angle = (-dy).atan2(dx) - phase;
642642 let off = angle.rem_euclid(spike_period);
643643 let to_spike = off.min(spike_period - off);
644 let shape_w = (1.0 - to_spike * inv_half_period).powf(sharpness) as f32;
644 let shape_w = (1.0 - to_spike * inv_half_period).max(0.0).powf(sharpness) as f32;
645645 let pa = env_a * shape_w;
646 if pa <= 1e-5 {
646 if !(pa > 1e-5) {
647647 continue;
648648 }
649649 let inv_a = 1.0 - pa;
......@@ -942,3 +942,62 @@ fn draw_bitmap_band(
942942 }
943943 }
944944}
945
946#[cfg(test)]
947mod tests {
948 use super::*;
949
950 #[test]
951 fn ngon_spike_midpoint_non_integer_sharpness_produces_no_nan() {
952 let w = 32usize;
953 let h = 32usize;
954 let mut out = vec![0u8; w * h * 4];
955 let mut accum = vec![0.0_f32; w * h * 4];
956 let cx = 16.5;
957 let cy = 16.5;
958
959 // Test multiple odd/non-power-of-two side counts where inv_half_period = 2 / spike_period
960 // can round up at off == spike_period * 0.5 and make (1.0 - to_spike * inv_half_period) < 0.
961 for &sides in &[3.0_f64, 5.0, 6.0, 7.0, 9.0] {
962 let spike_period = std::f64::consts::TAU / sides;
963 let inv_half_period = 2.0 / spike_period;
964 let sharpness = 4.5 * (3.0 / sides).powf(2.8);
965 // At pixel (17, 16), dx = 1.0, dy = 0.0 -> atan2 = 0.0, so phase = -0.5 * spike_period
966 // forces off = 0.5 * spike_period (exact spike midpoint).
967 let phase = -0.5 * spike_period;
968 let cmds = [
969 DrawCmd {
970 min_x: 8,
971 max_x: 24,
972 min_y: 8,
973 max_y: 24,
974 color: [1.0, 0.5, 0.25, 1.0],
975 shape: DrawShape::NGon {
976 cx,
977 cy,
978 inv_two_sigma_sq: 0.05,
979 inv_half_period,
980 spike_period,
981 phase,
982 sharpness,
983 },
984 },
985 // Blend an opaque point on (17, 16) afterwards; if accum had NaN it would poison dst.
986 DrawCmd {
987 min_x: 17,
988 max_x: 17,
989 min_y: 16,
990 max_y: 16,
991 color: [0.0, 1.0, 0.0, 1.0],
992 shape: DrawShape::Point,
993 },
994 ];
995 out.fill(0);
996 accum.fill(0.0);
997 rasterize_single_band(&mut out, &mut accum, w, 0, h, &cmds, &[]);
998 assert!(accum.iter().all(|v| v.is_finite()), "NaN/Inf leaked into accum for sides={sides}");
999 let idx = (16 * w + 17) * 4;
1000 assert_eq!(&out[idx..idx + 4], &[0, 255, 0, 255], "midpoint pixel poisoned for sides={sides}");
1001 }
1002 }
1003}
crates/engine/src/shaders/blur_glow.wgsl+18-17
......@@ -118,11 +118,12 @@ fn run_blur_pass(gid: vec2<u32>) {
118118 let has_mask = u.p[1].y > 0.5;
119119 let m = clamp(read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x, 0.0, 1.0);
120120 if (u.p[0].w > 1.5) {
121 let orig = select(
122 textureLoad(src_a, vec2<i32>(gid.xy), 0),
123 textureLoad(src_b, vec2<i32>(gid.xy), 0),
124 u.p[2].x > 0.5,
125 );
121 var orig: vec4<f32>;
122 if (u.p[2].x > 0.5) {
123 orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
124 } else {
125 orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
126 }
126127 if (m <= 1e-6) {
127128 store_dst(vec2<i32>(gid.xy), orig);
128129 return;
......@@ -132,11 +133,12 @@ fn run_blur_pass(gid: vec2<u32>) {
132133 return;
133134 }
134135 if (has_mask && m <= 1e-6) {
135 let orig = select(
136 textureLoad(src_a, vec2<i32>(gid.xy), 0),
137 textureLoad(src_b, vec2<i32>(gid.xy), 0),
138 u.p[2].x > 0.5,
139 );
136 var orig: vec4<f32>;
137 if (u.p[2].x > 0.5) {
138 orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
139 } else {
140 orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
141 }
140142 store_dst(vec2<i32>(gid.xy), orig);
141143 return;
142144 }
......@@ -273,15 +275,14 @@ fn run_blur_pass(gid: vec2<u32>) {
273275 }
274276 }
275277
276 if (u.p[1].y < 0.5 && u.p[1].x >= 0.9999) {
278 if (u.p[1].y < 0.5 && u.p[1].x >= 1.0) {
277279 store_dst(vec2<i32>(gid.xy), acc);
278280 return;
279281 }
280 let orig = select(
281 center,
282 textureLoad(src_b, vec2<i32>(gid.xy), 0),
283 u.p[2].x > 0.5,
284 );
282 var orig = center;
283 if (u.p[2].x > 0.5) {
284 orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
285 }
285286 let out_col = mix(orig, acc, m);
286287 store_dst(vec2<i32>(gid.xy), out_col);
287288}
......@@ -492,7 +493,7 @@ fn dir_blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
492493 store_dst(vec2<i32>(gid.xy), unprocessed);
493494 return;
494495 }
495 if (abs(length_v) < 1e-5 && abs(angle) < 1e-5) {
496 if (abs(length_v) < 1e-5 && abs(angle) < 1e-5 && glow <= 1e-4) {
496497 let out_col = select(orig, orig * m, mbm);
497498 store_dst(vec2<i32>(gid.xy), select(out_col, unprocessed, skip));
498499 return;
crates/engine/src/shaders/composite.wgsl+2-2
......@@ -382,8 +382,8 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
382382 let fg = merge_sample_fg(src_b, fg_fu, edges, u.p[4], nearest, size);
383383
384384 // Fast path for the common Normal + Over + Gain=1.0 + no mask + Blend=1.0 case.
385 if (mode == 0 && op == 0 && gain >= 0.9999 && has_mask < 0.5 && blend >= 0.9999 && !mbm && burn_in == 0.0) {
386 let fg_rgb = select(fg.rgb * mix(fg.a, 1.0, sub_add), fg.rgb, sub_add >= 0.9999);
385 if (mode == 0 && op == 0 && gain >= 1.0 && has_mask < 0.5 && blend >= 1.0 && !mbm && burn_in == 0.0) {
386 let fg_rgb = select(fg.rgb * mix(fg.a, 1.0, sub_add), fg.rgb, sub_add >= 1.0);
387387 let out_col = vec4<f32>(fg_rgb + bg.rgb * (1.0 - fg.a), fg.a + bg.a * (1.0 - fg.a));
388388 store_dst(vec2<i32>(gid.xy), out_col);
389389 return;
crates/engine/src/text_engine.rs+272-33
......@@ -36,19 +36,15 @@ impl Font {
3636 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
3737 {
3838 let cache = font_cache().lock().unwrap();
39 if let Some(hit) = cache.get(&(family.to_owned(), style.to_owned())) {
39 if let Some(hit) = cache.1.get(&(family.to_owned(), style.to_owned())) {
4040 return hit.clone();
4141 }
4242 }
43 let resolved = {
43 let (resolved, resolved_gen) = {
4444 let mut reg = registry().write().unwrap();
45 resolve_lazy(&mut reg, family, style).map(Arc::new)
45 (resolve_lazy(&mut reg, family, style).map(Arc::new), reg.generation)
4646 };
47 let mut cache = font_cache().lock().unwrap();
48 let entry = cache
49 .entry((family.to_owned(), style.to_owned()))
50 .or_insert_with(|| resolved.clone());
51 entry.clone()
47 cache_resolved_font(family, style, resolved, resolved_gen)
5248 }
5349
5450 pub fn face(&self) -> Face<'_> {
......@@ -63,6 +59,7 @@ impl Font {
6359struct FontRegistry {
6460 db: fontdb::Database,
6561 aliases: HashMap<String, Vec<fontdb::ID>>,
62 generation: u64,
6663 #[cfg(not(target_arch = "wasm32"))]
6764 system_fonts_loaded: bool,
6865 #[cfg(not(target_arch = "wasm32"))]
......@@ -78,6 +75,7 @@ impl FontRegistry {
7875 Self {
7976 db: fontdb::Database::new(),
8077 aliases: HashMap::new(),
78 generation: 0,
8179 #[cfg(not(target_arch = "wasm32"))]
8280 system_fonts_loaded: false,
8381 #[cfg(not(target_arch = "wasm32"))]
......@@ -98,11 +96,35 @@ impl FontRegistry {
9896 }
9997}
10098
101fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {
102 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();
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();
103103 CACHE.get_or_init(Default::default)
104104}
105105
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
106128fn registry() -> &'static RwLock<FontRegistry> {
107129 static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new();
108130 REG.get_or_init(|| RwLock::new(FontRegistry::new()))
......@@ -207,6 +229,8 @@ fn is_style_suffix(rest: &str) -> bool {
207229 "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy",
208230 "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow",
209231 "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",
210234 ];
211235 rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p))
212236}
......@@ -249,17 +273,23 @@ fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) {
249273/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime
250274/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.
251275pub fn register_font_bytes(bytes: Vec<u8>) {
252 {
276 let new_gen = {
253277 let mut reg = registry().write().unwrap();
254278 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();
255286 }
256 font_cache().lock().unwrap().clear();
257287}
258288
259289/// Registers font bytes under an explicit family alias in addition to its embedded family names,
260290/// and clears the resolution cache.
261291pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
262 {
292 let new_gen = {
263293 let mut reg = registry().write().unwrap();
264294 let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect();
265295 reg.db.load_font_data(bytes);
......@@ -272,8 +302,14 @@ pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
272302 .extend(added);
273303 }
274304 }
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();
275312 }
276 font_cache().lock().unwrap().clear();
277313}
278314
279315/// CSS-style weight and italic flag for a Fusion style name.
......@@ -375,7 +411,15 @@ fn try_pick_family_lazy(
375411 load_family_candidates(reg, &fam_norm);
376412 }
377413 }
378 pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic)
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
379423}
380424
381425fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> {
......@@ -386,7 +430,13 @@ fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Fon
386430 .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic)));
387431
388432 #[cfg(not(target_arch = "wasm32"))]
389 if id.is_none() && !family.is_empty() && !reg.system_fonts_loaded {
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 {
390440 reg.ensure_system_fonts_loaded();
391441 id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic)
392442 .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic)));
......@@ -941,6 +991,7 @@ const GLYPH_BASELINE_ANCHOR: f32 = 256.0;
941991const GLYPH_BASELINE_ANCHOR_I32: i32 = 256;
942992const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;
943993const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024;
994const MAX_GLYPH_COORD: f32 = 8_388_608.0;
944995
945996#[derive(Clone, Copy, PartialEq, Eq, Hash)]
946997struct GlyphCacheKey {
......@@ -960,8 +1011,9 @@ struct CachedGlyphCoverage {
9601011}
9611012
9621013struct GlyphCache {
963 map: HashMap<GlyphCacheKey, Arc<CachedGlyphCoverage>>,
964 order: VecDeque<GlyphCacheKey>,
1014 map: HashMap<GlyphCacheKey, (u64, Arc<CachedGlyphCoverage>)>,
1015 order: VecDeque<(u64, GlyphCacheKey)>,
1016 next_stamp: u64,
9651017 total_bytes: usize,
9661018}
9671019
......@@ -970,29 +1022,58 @@ impl GlyphCache {
9701022 Self {
9711023 map: HashMap::new(),
9721024 order: VecDeque::new(),
1025 next_stamp: 0,
9731026 total_bytes: 0,
9741027 }
9751028 }
9761029
977 fn get(&self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {
978 self.map.get(key).cloned()
1030 fn compact_order(&mut self) {
1031 let mut live: Vec<(u64, GlyphCacheKey)> =
1032 self.map.iter().map(|(k, (s, _))| (*s, *k)).collect();
1033 live.sort_unstable_by_key(|&(s, _)| s);
1034 self.order.clear();
1035 self.order.extend(live);
1036 }
1037
1038 fn get(&mut self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {
1039 let (stamp, val) = self.map.get_mut(key)?;
1040 self.next_stamp += 1;
1041 *stamp = self.next_stamp;
1042 self.order.push_back((self.next_stamp, *key));
1043 let out = Arc::clone(val);
1044 if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 {
1045 self.compact_order();
1046 }
1047 Some(out)
9791048 }
9801049
9811050 fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) {
982 if val.bytes > MAX_GLYPH_CACHE_BYTES || self.map.contains_key(&key) {
1051 if val.bytes > MAX_GLYPH_CACHE_BYTES {
1052 return;
1053 }
1054 if let Some((stamp, _)) = self.map.get_mut(&key) {
1055 self.next_stamp += 1;
1056 *stamp = self.next_stamp;
1057 self.order.push_back((self.next_stamp, key));
1058 if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 {
1059 self.compact_order();
1060 }
9831061 return;
9841062 }
9851063 while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES {
986 let Some(old_key) = self.order.pop_front() else {
1064 let Some((s, old_key)) = self.order.pop_front() else {
9871065 break;
9881066 };
989 if let Some(removed) = self.map.remove(&old_key) {
990 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);
1067 if self.map.get(&old_key).is_some_and(|(cur_s, _)| *cur_s == s) {
1068 if let Some((_, removed)) = self.map.remove(&old_key) {
1069 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);
1070 }
9911071 }
9921072 }
1073 self.next_stamp += 1;
9931074 self.total_bytes += val.bytes;
994 self.order.push_back(key);
995 self.map.insert(key, val);
1075 self.order.push_back((self.next_stamp, key));
1076 self.map.insert(key, (self.next_stamp, val));
9961077 }
9971078}
9981079
......@@ -1001,11 +1082,32 @@ fn glyph_cache() -> &'static Mutex<GlyphCache> {
10011082 CACHE.get_or_init(|| Mutex::new(GlyphCache::new()))
10021083}
10031084
1085fn quantize_subpixel(coord: f32) -> Option<(i32, f32)> {
1086 if !coord.is_finite() || coord.abs() > MAX_GLYPH_COORD {
1087 return None;
1088 }
1089 let mut ix = coord.floor() as i32;
1090 let fx = (coord - ix as f32).clamp(0.0, 1.0);
1091 let mut qx = (fx * 16.0).round() as i32;
1092 if qx >= 16 {
1093 ix += 1;
1094 qx = 0;
1095 }
1096 Some((ix, qx as f32 * (1.0 / 16.0)))
1097}
1098
10041099fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) {
1005 let ix = spec.abs_x.floor() as i32;
1006 let iy = spec.abs_y.floor() as i32;
1007 let fx = spec.abs_x - ix as f32;
1008 let fy = spec.abs_y - iy as f32;
1100 let (Some((ix, fx)), Some((iy, fy))) = (quantize_subpixel(spec.abs_x), quantize_subpixel(spec.abs_y)) else {
1101 return (
1102 0,
1103 0,
1104 Arc::new(CachedGlyphCoverage {
1105 fill: None,
1106 stroke: None,
1107 bytes: 0,
1108 }),
1109 );
1110 };
10091111
10101112 let total_lean = spec.font.lean + spec.shear;
10111113 let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean };
......@@ -1245,8 +1347,8 @@ pub fn rasterize_text_plus_rich(
12451347 let top = c.top.saturating_add(oy);
12461348 min_x = min_x.min(left.saturating_sub(pad));
12471349 min_y = min_y.min(top.saturating_sub(pad));
1248 max_x = max_x.max((left + c.width as i32).saturating_add(pad));
1249 max_y = max_y.max((top + c.height as i32).saturating_add(pad));
1350 max_x = max_x.max(left.saturating_add(c.width as i32).saturating_add(pad));
1351 max_y = max_y.max(top.saturating_add(c.height as i32).saturating_add(pad));
12501352 };
12511353
12521354 let mut placed = Vec::with_capacity(specs.len());
......@@ -2353,7 +2455,8 @@ mod tests {
23532455 let tight_canvas = composite_onto_canvas(tsz, torig, &trgba);
23542456 let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba);
23552457 for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() {
2356 assert!(a.abs_diff(b) <= 4, "legacy parity diff at byte {i}: {a} vs {b}");
2458 // 1/16 px subpixel quantization in `cached_glyph_coverage` can shift x/y by <= 1/32 px each (~16 u8 levels).
2459 assert!(a.abs_diff(b) <= 16, "legacy parity diff at byte {i}: {a} vs {b}");
23572460 }
23582461 let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80);
23592462 assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain));
......@@ -2515,4 +2618,140 @@ mod tests {
25152618 }
25162619 assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}");
25172620 }
2621
2622 #[test]
2623 fn glyph_cache_subpixel_quantization_and_lru_eviction() {
2624 assert_eq!(quantize_subpixel(10.99), Some((11, 0.0)));
2625 assert_eq!(quantize_subpixel(-0.01), Some((0, 0.0)));
2626 assert_eq!(quantize_subpixel(10.01), quantize_subpixel(10.02));
2627
2628 let font = Font::find("Helvetica", "Regular").expect("system font");
2629 let gid = font.face().glyph_index('A').expect("glyph A");
2630 let make_spec = |x: f32, y: f32| GlyphSpec {
2631 font: Arc::clone(&font),
2632 glyph_id: gid,
2633 font_px: 42.0,
2634 abs_x: x,
2635 abs_y: y,
2636 shear: 0.0,
2637 outline_w: 0.0,
2638 };
2639 let (ix1, iy1, cov1) = cached_glyph_coverage(&make_spec(100.01, 200.01), false);
2640 let (ix2, iy2, cov2) = cached_glyph_coverage(&make_spec(100.02, 200.02), false);
2641 assert_eq!((ix1, iy1), (100, 200));
2642 assert_eq!((ix2, iy2), (100, 200));
2643 assert!(Arc::ptr_eq(&cov1, &cov2), "jitter within 1/16 px must share cached coverage");
2644
2645 // Verify LRU eviction (touching key 0 keeps it alive when capacity is exceeded).
2646 let mut cache = GlyphCache::new();
2647 let make_key = |i: u16| GlyphCacheKey {
2648 font_id: 777,
2649 glyph_id: i,
2650 size_bits: 42.0_f32.to_bits(),
2651 lean_bits: 0,
2652 stroke_bits: 0,
2653 sub_x_bits: 0,
2654 sub_y_bits: 0,
2655 };
2656 let make_entry = || {
2657 Arc::new(CachedGlyphCoverage {
2658 fill: Some(Coverage {
2659 left: 0,
2660 top: 0,
2661 width: 4,
2662 height: 4,
2663 data: vec![255; 16],
2664 }),
2665 stroke: None,
2666 bytes: 16,
2667 })
2668 };
2669 for i in 0..MAX_GLYPH_CACHE_ENTRIES {
2670 cache.insert(make_key(i as u16), make_entry());
2671 }
2672 // Touch key 0 so key 1 becomes the least recently used entry.
2673 assert!(cache.get(&make_key(0)).is_some());
2674 cache.insert(make_key(MAX_GLYPH_CACHE_ENTRIES as u16), make_entry());
2675 assert!(cache.get(&make_key(0)).is_some(), "recently touched entry must survive LRU eviction");
2676 assert!(cache.get(&make_key(1)).is_none(), "least recently used entry must be evicted");
2677 }
2678
2679 #[test]
2680 fn register_font_bytes_generation_prevents_stale_cache_poisoning() {
2681 let base = Font::find("Helvetica", "Regular").expect("system fallback font");
2682 let gen0 = registry().read().unwrap().generation;
2683 register_font_bytes_with_name("FissionGenRaceFont", base.data.clone());
2684 let gen1 = registry().read().unwrap().generation;
2685 assert!(gen1 > gen0);
2686
2687 // Simulate a thread that finished resolve_lazy at gen0 before register_font_bytes_with_name ran.
2688 let _ = cache_resolved_font("FissionGenRaceFont", "Regular", None, gen0);
2689 {
2690 let cache = font_cache().lock().unwrap();
2691 assert_eq!(cache.0, gen1);
2692 assert!(
2693 !cache.1.contains_key(&("FissionGenRaceFont".to_owned(), "Regular".to_owned())),
2694 "stale pre-registration result must not poison font_cache"
2695 );
2696 }
2697 assert!(Font::find("FissionGenRaceFont", "Regular").is_some());
2698 }
2699
2700 #[test]
2701 fn extreme_off_canvas_coords_never_overflow_i32() {
2702 for bad in [
2703 f32::NAN,
2704 f32::INFINITY,
2705 f32::NEG_INFINITY,
2706 f32::MAX,
2707 f32::MIN,
2708 1e15,
2709 -1e15,
2710 (i32::MAX as f32) * 2.0,
2711 (i32::MIN as f32) * 2.0,
2712 ] {
2713 assert_eq!(quantize_subpixel(bad), None);
2714 }
2715
2716 let font = Font::find("Helvetica", "Regular").expect("system font");
2717 let gid = font.face().glyph_index('A').expect("glyph A");
2718 for (ax, ay) in [(1e20_f32, 0.0_f32), (0.0, -1e20), (f32::NAN, 10.0), (f32::INFINITY, f32::NEG_INFINITY)] {
2719 let spec = GlyphSpec {
2720 font: Arc::clone(&font),
2721 glyph_id: gid,
2722 font_px: 32.0,
2723 abs_x: ax,
2724 abs_y: ay,
2725 shear: 0.0,
2726 outline_w: 0.0,
2727 };
2728 let (ix, iy, cov) = cached_glyph_coverage(&spec, false);
2729 assert_eq!((ix, iy), (0, 0));
2730 assert!(cov.fill.is_none() && cov.stroke.is_none());
2731 }
2732
2733 let p = RichTextPlusParams {
2734 text: "Far",
2735 font_family: "Helvetica",
2736 font_style: "Regular",
2737 size_norm: 0.08,
2738 tracking: 1.0,
2739 line_spacing: 1.0,
2740 center: [1e12, -1e12],
2741 h_lcr: 0.0,
2742 v_tcb: 0.0,
2743 fill_rgba: [1.0; 4],
2744 write_on_start: 0.0,
2745 write_on_end: 1.0,
2746 shear_x: 0.0,
2747 cls: &[],
2748 outline_rgba: [0.0; 4],
2749 outline_thickness_norm: 0.0,
2750 outline_enabled: false,
2751 soft_fill: [0.0; 3],
2752 soft_outline: [0.0; 3],
2753 baseline_at_center: false,
2754 };
2755 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2756 }
25182757}