From f2a1716264a84ca38dc64149525f356134a5ff47 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 05:43:23 -0800 Subject: [PATCH] Wave 17B: fix Text3D ear_clip/bridge_hole & caching, TextPlus CLS/CRLF/softness/BorderFill, scene3d shadow VRAM, macro isolation, and runtime font registration --- crates/engine/src/eval/text_3d.rs | 256 +++++++++++---- crates/engine/src/scene3d/mod.rs | 132 +++++++- crates/engine/src/text_engine.rs | 518 ++++++++++++++++++++++++++---- crates/model/src/comp.rs | 4 +- crates/model/src/comp/load.rs | 191 +++++++++-- 5 files changed, 932 insertions(+), 169 deletions(-) diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index a69cce1e951671eb8a48e583c67a073419e2dd98..646246d568c30f6d3f9747f2d18be58d714a2794 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use super::*; use crate::text_engine::{RichTextPlusParams, StyledClsRule}; @@ -33,46 +31,9 @@ struct ResolvedTextInputs { baseline_at_center: bool, } -fn parse_styled_text_cls(comp: &Comp, node: &Node) -> Option<(String, Vec)> { - let src_op = node.connected_node("StyledText")?; - let inputs = comp - .raw_root - .as_ref()? - .get_table("Tools")? - .get_table(src_op)? - .get_table("Inputs")?; - let text = inputs - .get_table("Text") - .and_then(|t| t.get_table("Value").and_then(|v| v.get_str("Value")).or_else(|| t.get_str("Value"))) - .unwrap_or("") - .to_owned(); - let mut rules = Vec::new(); - let array = inputs - .get_table("RightClickHereToAnimateCharacterLevelStyling") - .or_else(|| inputs.get_table("CharacterLevelStyling")) - .and_then(|t| t.get_table("Value")) - .and_then(|v| v.get_table("Array")); - if let Some(arr) = array { - let mut idx = 1i64; - while let Some(model::LuaValue::Table(entry)) = arr.get_index(idx) { - if let Some(param) = entry.get_f64("Parameter") { - rules.push(StyledClsRule { - prop_id: param.round().max(0.0) as u32, - start: entry.get_f64("First").unwrap_or(0.0).max(0.0) as usize, - end: entry.get_f64("Last").unwrap_or(0.0).max(0.0) as usize, - value: entry.get_f64("Value").unwrap_or(0.0) as f32, - text: entry.get_str("String").unwrap_or("").to_owned(), - }); - } - idx += 1; - } - } - Some((text, rules)) -} - fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, expr: &ExprEngine) -> ResolvedTextInputs { - let mut text_str = comp.eval_text(node, "StyledText", time, "", expr); - let mut cls_rules: Vec = comp + let text_str = comp.eval_text(node, "StyledText", time, "", expr); + let cls_rules: Vec = comp .text_cls_entries(node, "StyledText") .iter() .map(|e| StyledClsRule { @@ -80,17 +41,9 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp start: e.start, end: e.end, value: e.value, - text: String::new(), + text: e.text.clone(), }) .collect(); - if let Some((cls_text, rich_rules)) = parse_styled_text_cls(comp, node) { - if text_str.is_empty() { - text_str = cls_text; - } - if !rich_rules.is_empty() { - cls_rules = rich_rules; - } - } let font_family = node.static_str("Font").unwrap_or("Helvetica Neue").to_owned(); let font_style = node.static_str("Style").unwrap_or("Regular").to_owned(); @@ -188,6 +141,41 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp } impl ResolvedTextInputs { + fn geometry_hash(&self, ext_depth: f32, bevel_depth: f32, bevel_width: f32) -> u64 { + let mut h = DefaultHasher::new(); + "Text3DMesh".hash(&mut h); + self.text_str.hash(&mut h); + self.font_family.hash(&mut h); + self.font_style.hash(&mut h); + self.baseline_at_center.hash(&mut h); + for v in [ + self.size_norm, + self.tracking, + self.line_spacing, + self.center[0], + self.center[1], + self.h_lcr, + self.v_tcb, + self.write_start, + self.write_end, + self.shear_x, + ext_depth, + bevel_depth, + bevel_width, + ] { + v.to_bits().hash(&mut h); + } + self.cls_rules.len().hash(&mut h); + for r in &self.cls_rules { + r.prop_id.hash(&mut h); + r.start.hash(&mut h); + r.end.hash(&mut h); + r.value.to_bits().hash(&mut h); + r.text.hash(&mut h); + } + h.finish() + } + fn as_rich_params(&self) -> RichTextPlusParams<'_> { let is_text_outline = self.outline_enabled && self.elem2_shape != 2; let outline_rgba = self.outline_rgba.map(|c| c * self.elem2_opacity); @@ -640,10 +628,10 @@ impl Engine { } } - let br = outline_rgba[0] * elem2_opacity; - let bg = outline_rgba[1] * elem2_opacity; - let bb = outline_rgba[2] * elem2_opacity; - let ba = outline_rgba[3] * elem2_opacity; + let br = outline_rgba[0]; + let bg = outline_rgba[1]; + let bb = outline_rgba[2]; + let ba = outline_rgba[3]; for i in 0..(tw * th) { let cov = box_cov[i]; if cov <= 1e-4 { @@ -823,6 +811,7 @@ impl Engine { let mut pending_displace_tex: Vec> = Vec::with_capacity(mesh_specs.len()); for ms in &mesh_specs { let mut mesh_shape = ms.shape.clone(); + let mut custom_mesh_key = None; let mut diffuse_col = ms.diffuse_col; let tex = if let Some(t3d) = &ms.text3d { let tnode = comp.node(t3d.node_id); @@ -835,11 +824,27 @@ impl Engine { }; if ext_depth.abs() > 1e-4 { let ti = resolve_text_inputs(comp, tnode, time, true, &self.expr); - ti.text_str.hash(&mut h_scene); - ti.size_norm.to_bits().hash(&mut h_scene); - ext_depth.to_bits().hash(&mut h_scene); - let verts = crate::text_engine::build_text3d_mesh(&ti.as_rich_params(), ext_depth); - let custom = crate::scene3d::ShapeKind::CustomMesh(Arc::new(verts)); + let bevel_depth = comp.eval_number( + tnode, + "Extrusion.BevelDepth", + time, + comp.eval_number(tnode, "BevelDepth", time, 0.0, &self.expr), + &self.expr, + ) as f32; + let bevel_width = comp.eval_number( + tnode, + "Extrusion.BevelWidth", + time, + comp.eval_number(tnode, "BevelWidth", time, 0.0, &self.expr), + &self.expr, + ) as f32; + let mesh_key = ti.geometry_hash(ext_depth, bevel_depth, bevel_width); + mesh_key.hash(&mut h_scene); + custom_mesh_key = Some(mesh_key); + let verts = self.scene3d.get_or_build_text3d_mesh(mesh_key, || { + crate::text_engine::build_text3d_mesh(&ti.as_rich_params(), ext_depth) + }); + let custom = crate::scene3d::ShapeKind::CustomMesh(verts); mesh_shape = match &ms.shape { crate::scene3d::ShapeKind::WithMaterialFx { fx, .. } => { crate::scene3d::ShapeKind::WithMaterialFx { inner: Box::new(custom), fx: *fx } @@ -880,6 +885,7 @@ impl Engine { draw_meshes.push(crate::scene3d::DrawMesh { world: ms.world, shape: mesh_shape, + custom_mesh_key, tex, diffuse_col, specular_col: ms.specular_col, @@ -1090,4 +1096,136 @@ Composition { "frame 5 larger Radius must invalidate Renderer3D cache and cover far more pixels (f0={c0}, f5={c5})" ); } + + #[test] + fn extruded_text3d_reuses_mesh_cache_key_arc_and_renderer3d_cache() { + let src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + CamAnim = BezierSpline { + KeyFrames = { + [0] = { 4.0, Flags = { Linear = true } }, + [1] = { 4.5, Flags = { Linear = true } }, + }, + }, + Cam = Camera3D { + Inputs = { + ["Transform3DOp.Translate.Z"] = Input { SourceOp = "CamAnim", Source = "Value", }, + ApertureW = Input { Value = 1.0, }, + ApertureH = Input { Value = 1.0, }, + }, + }, + Txt = Text3D { + Inputs = { + StyledText = Input { Value = "OB", }, + Font = Input { Value = "Liberation Sans", }, + Style = Input { Value = "Regular", }, + Size = Input { Value = 1.0, }, + Extrusion = Input { Value = 1, }, + ["Extrusion.ExtrusionDepth"] = Input { Value = 0.2, }, + }, + }, + M = Merge3D { + Inputs = { + SceneInput1 = Input { SourceOp = "Txt", Source = "Output", }, + SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, + }, + }, + R3D = Renderer3D { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + SceneInput = Input { SourceOp = "M", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse Text3D comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let r3d = comp.find_node("R3D").unwrap(); + let txt = comp.find_node("Txt").unwrap(); + + let (_, s0) = eng.evaluate(&comp, r3d, 0.0); + assert_eq!(s0.cache_misses, 1); + assert_eq!(eng.scene3d.gpu_mesh_count(), 1); + + // Identical second evaluation hits Renderer3D output cache and skips CPU/GPU rebuilds. + let (_, s0_repeat) = eng.evaluate(&comp, r3d, 0.0); + assert_eq!(s0_repeat.cache_hits, 1); + assert_eq!(s0_repeat.cache_misses, 0); + + // Moving the camera invalidates Renderer3D output, yet reuses the exact same Text3D mesh key, + // cached Arc, and GPU mesh LRU entry. + let (_, s1) = eng.evaluate(&comp, r3d, 1.0); + assert_eq!(s1.cache_misses, 1); + assert_eq!(eng.scene3d.gpu_mesh_count(), 1); + + let ti0 = super::resolve_text_inputs(&comp, comp.node(txt), 0.0, true, &eng.expr); + let ti1 = super::resolve_text_inputs(&comp, comp.node(txt), 1.0, true, &eng.expr); + let mk0 = ti0.geometry_hash(0.2, 0.0, 0.0); + let mk1 = ti1.geometry_hash(0.2, 0.0, 0.0); + assert_eq!(mk0, mk1); + let a0 = eng.scene3d.get_or_build_text3d_mesh(mk0, || panic!("mesh must be cached")); + let a1 = eng.scene3d.get_or_build_text3d_mesh(mk1, || panic!("mesh must be cached")); + assert!(std::sync::Arc::ptr_eq(&a0, &a1)); + } + + #[test] + fn border_fill_applies_opacity2_once() { + let src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + T1 = TextPlus { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + StyledText = Input { Value = "I", }, + Size = Input { Value = 0.25, }, + Red1 = Input { Value = 1.0, }, + Green1 = Input { Value = 1.0, }, + Blue1 = Input { Value = 1.0, }, + Alpha1 = Input { Value = 1.0, }, + Enabled2 = Input { Value = 1, }, + ElementShape2 = Input { Value = 2, }, + Red2 = Input { Value = 1.0, }, + Green2 = Input { Value = 0.0, }, + Blue2 = Input { Value = 0.0, }, + Alpha2 = Input { Value = 1.0, }, + Opacity2 = Input { Value = 0.5, }, + ExtendHorizontal2 = Input { Value = 1.0, }, + ExtendVertical2 = Input { Value = 1.0, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse BorderFill comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let t1 = comp.find_node("T1").unwrap(); + let (tex, _) = eng.evaluate(&comp, t1, 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + // Pure red BorderFill margin pixels (outside white glyph 'I') have g=0, b=0, and alpha ~128 + // for Opacity2=0.5 (buggy elem2_opacity^2 gave ~64). + let box_alpha = rgba + .chunks_exact(4) + .filter(|px| px[1] == 0 && px[2] == 0 && px[3] > 0) + .map(|px| px[3]) + .max() + .unwrap_or(0); + assert!( + (118..=138).contains(&box_alpha), + "BorderFill Opacity2=0.5 should yield ~128 alpha, got {box_alpha}" + ); + } } diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index ce6cb9c3801c3d906d5f8a9799cb803b1c451543..c1bc115299c9c9482483c1a2e920f695fe3d1019 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -36,6 +36,8 @@ pub struct Scene3DRenderer { pipelines: [[wgpu::RenderPipeline; 2]; 2], sampler: wgpu::Sampler, meshes: Mutex>>, + /// Memoized CPU `Text3D` extruded meshes keyed by deterministic geometry content hash. + text3d_mesh_cache: Mutex>>>, shadow_pipeline: wgpu::RenderPipeline, /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass. shadow_caster_bgl: wgpu::BindGroupLayout, @@ -71,8 +73,6 @@ struct GpuMesh { vbuf: wgpu::Buffer, ibuf: wgpu::Buffer, idx_count: u32, - /// Keeps a `CustomMesh` allocation alive: `ShapeKind::hash_into` hashes its address. - _shape: ShapeKind, } /// Bounded map evicting the least recently used entry. @@ -87,6 +87,16 @@ impl Lru { Self { cap, tick: 0, entries: HashMap::new() } } + fn get(&mut self, key: K) -> Option { + self.tick += 1; + if let Some((used, v)) = self.entries.get_mut(&key) { + *used = self.tick; + Some(v.clone()) + } else { + None + } + } + fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V { self.tick += 1; if let Some((used, v)) = self.entries.get_mut(&key) { @@ -102,6 +112,11 @@ impl Lru { self.entries.insert(key, (self.tick, v.clone())); v } + + fn clear(&mut self) { + self.entries.clear(); + self.tick = 0; + } } #[derive(Clone)] @@ -283,7 +298,6 @@ impl ShapeKind { ShapeKind::CustomMesh(verts) => { 6u8.hash(h); verts.len().hash(h); - (verts.as_ptr() as usize).hash(h); let step = (verts.len() / 64).max(1); for v in verts.iter().step_by(step) { bytemuck::bytes_of(v).hash(h); @@ -377,6 +391,8 @@ pub struct SceneLights { pub struct DrawMesh { pub world: Mat4, pub shape: ShapeKind, + /// Optional deterministic content key for `ShapeKind::CustomMesh` so GPU mesh LRU avoids pointer hashing. + pub custom_mesh_key: Option, pub tex: Option, pub diffuse_col: [f32; 4], pub specular_col: [f32; 3], @@ -389,9 +405,16 @@ pub struct DrawMesh { pub displace: Option, } -fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey { - use std::hash::{DefaultHasher, Hasher}; +fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option, aspect: f32, wireframe: bool) -> MeshKey { + use std::hash::{DefaultHasher, Hash, Hasher}; let mut h = DefaultHasher::new(); + if matches!(base_shape, ShapeKind::CustomMesh(_)) { + if let Some(ck) = custom_mesh_key { + 6u8.hash(&mut h); + ck.hash(&mut h); + return (h.finish(), 0, wireframe); + } + } base_shape.hash_into(&mut h); let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 }; (h.finish(), aspect_bits, wireframe) @@ -627,6 +650,7 @@ impl Scene3DRenderer { pipelines, sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)), + text3d_mesh_cache: Mutex::new(Lru::new(MESH_CACHE_CAP)), shadow_pipeline, shadow_caster_bgl, shadow_face_bgl, @@ -635,6 +659,41 @@ impl Scene3DRenderer { } } + /// Returns a memoized `Text3D` vertex buffer for `key`, building it on miss. + pub fn get_or_build_text3d_mesh( + &self, + key: u64, + build: impl FnOnce() -> Vec, + ) -> Arc> { + if let Some(hit) = self.text3d_mesh_cache.lock().unwrap().get(key) { + return hit; + } + let built = Arc::new(build()); + self.text3d_mesh_cache + .lock() + .unwrap() + .get_or_insert_with(key, || Arc::clone(&built)) + } + + /// Drops the cached shadow cube-map pool and memoized `Text3D` CPU meshes. + pub fn clear_shadow_targets(&self) { + *self.shadow_targets.lock().unwrap() = None; + self.text3d_mesh_cache.lock().unwrap().clear(); + } + + /// Total GPU VRAM in bytes currently occupied by `shadow_targets` (R32Float layers + Depth32Float). + pub fn shadow_vram_bytes(&self) -> u64 { + self.shadow_targets.lock().unwrap().as_ref().map_or(0, |t| { + let layer_bytes = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4; + layer_bytes * (u64::from(t.layers) + 1) + }) + } + + #[cfg(test)] + pub(crate) fn gpu_mesh_count(&self) -> usize { + self.meshes.lock().unwrap().entries.len() + } + #[allow(clippy::too_many_arguments)] pub fn render_meshes( &self, @@ -818,13 +877,13 @@ impl Scene3DRenderer { mapped_at_creation: false, }); queue.write_buffer(&ibuf, 0, ibytes); - Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, _shape: base_shape.clone() }) + Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32 }) }; // Heightmap contents are not part of the key, so displaced meshes are never cached. let gpu_mesh = if m.displace.is_some() { upload() } else { - let key = mesh_key(base_shape, aspect, fx.wireframe); + let key = mesh_key(base_shape, m.custom_mesh_key, aspect, fx.wireframe); self.meshes.lock().unwrap().get_or_insert_with(key, upload) }; let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else { @@ -1192,6 +1251,7 @@ mod tests { inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }), fx: MaterialFx { wireframe, ..Default::default() }, }, + custom_mesh_key: None, tex: None, diffuse_col: [1.0; 4], specular_col: [1.0; 3], @@ -1365,4 +1425,62 @@ mod tests { assert_eq!(uncast, unreceived, "either flag alone removes the shadow entirely"); assert_eq!(uncast, unreceived_by_material, "a material shader owns the receiver flag"); } + + #[test] + fn shadow_vram_bytes_tracks_pool_and_clear_resets_both_caches() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; + let renderer = Scene3DRenderer::new(&device); + assert_eq!(renderer.shadow_vram_bytes(), 0); + + let _ = renderer.get_or_build_text3d_mesh(42, || vec![Vertex3D { pos: [0.0; 3], normal: [0.0, 0.0, 1.0], uv: [0.0; 2] }]); + assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 1); + + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let dst = CachedTexture::from_texture(tex, [8, 8], 0); + let dummy = dst.clone(); + let mut lights = SceneLights::default(); + lights.points.push(PointLight { + pos: [0.0, 0.0, 2.0], + color: [1.0, 1.0, 1.0], + decay_type: 0.0, + decay_rate: 0.0, + shadow_density: Some(1.0), + }); + let mut enc = device.create_command_encoder(&Default::default()); + renderer.render_meshes( + &device, + &queue, + &mut enc, + &dst, + &dummy, + mat4_identity(), + mat4_identity(), + [0.0, 0.0, 5.0], + 100.0, + lights, + true, + true, + &[], + ); + queue.submit(Some(enc.finish())); + + // 1 shadow light = 6 R32Float layers + 1 Depth32Float texture = 7 * 1024 * 1024 * 4 bytes. + let expected = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4 * 7; + assert_eq!(renderer.shadow_vram_bytes(), expected); + + renderer.clear_shadow_targets(); + assert_eq!(renderer.shadow_vram_bytes(), 0); + assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 0); + } } diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs index 6f0e536a0b2667df5e304b905cec30dc6dddc137..2e46f9eef5883c59533cc636c0bd686c02bb2d04 100644 --- a/crates/engine/src/text_engine.rs +++ b/crates/engine/src/text_engine.rs @@ -4,8 +4,8 @@ use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag}; use rustybuzz::{Face, Feature, UnicodeBuffer, Variation}; -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector}; /// Tried in order when the requested family is not installed. @@ -25,13 +25,17 @@ pub struct Font { impl Font { /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the - /// system fonts, falling back through [`FALLBACK_FAMILIES`] and finally any installed face. + /// system fonts and any fonts registered via [`register_font_bytes`], falling back through + /// [`FALLBACK_FAMILIES`] and finally any installed face. pub fn find(family: &str, style: &str) -> Option> { - static CACHE: OnceLock>>>> = OnceLock::new(); - let mut cache = CACHE.get_or_init(Default::default).lock().unwrap(); + let mut cache = font_cache().lock().unwrap(); cache .entry((family.to_owned(), style.to_owned())) - .or_insert_with(|| resolve(database(), family, style).map(Arc::new)) + .or_insert_with(|| { + let db = database().read().unwrap(); + let aliases = font_aliases().read().unwrap(); + resolve(&db, &aliases, family, style).map(Arc::new) + }) .clone() } @@ -44,15 +48,58 @@ impl Font { } } -fn database() -> &'static fontdb::Database { - static DB: OnceLock = OnceLock::new(); +fn font_cache() -> &'static Mutex>>> { + static CACHE: OnceLock>>>> = OnceLock::new(); + CACHE.get_or_init(Default::default) +} + +fn font_aliases() -> &'static RwLock>> { + static ALIASES: OnceLock>>> = OnceLock::new(); + ALIASES.get_or_init(Default::default) +} + +fn database() -> &'static RwLock { + static DB: OnceLock> = OnceLock::new(); DB.get_or_init(|| { let mut db = fontdb::Database::new(); + #[cfg(not(target_arch = "wasm32"))] db.load_system_fonts(); - db + RwLock::new(db) }) } +/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime +/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache. +pub fn register_font_bytes(bytes: Vec) { + { + let mut db = database().write().unwrap(); + db.load_font_data(bytes); + } + font_cache().lock().unwrap().clear(); +} + +/// Registers font bytes under an explicit family alias in addition to its embedded family names, +/// and clears the resolution cache. +pub fn register_font_bytes_with_name(family: &str, bytes: Vec) { + { + let mut db = database().write().unwrap(); + let before: HashSet = db.faces().map(|f| f.id).collect(); + db.load_font_data(bytes); + if !family.is_empty() { + let added: Vec = db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect(); + if !added.is_empty() { + font_aliases() + .write() + .unwrap() + .entry(family.to_ascii_lowercase()) + .or_default() + .extend(added); + } + } + } + font_cache().lock().unwrap().clear(); +} + /// CSS-style weight and italic flag for a Fusion style name. pub fn parse_style(style: &str) -> (u16, bool) { let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); @@ -94,13 +141,18 @@ fn metric_alias(family: &str) -> Option<&'static str> { } } -fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option { +fn resolve( + db: &fontdb::Database, + aliases: &HashMap>, + family: &str, + style: &str, +) -> Option { let (weight, italic) = parse_style(style); let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); let id = std::iter::once(family) .chain(metric_alias(family)) .chain(FALLBACK_FAMILIES) - .find_map(|name| pick(db, name, &wanted, weight, italic)) + .find_map(|name| pick(db, aliases, name, &wanted, weight, italic)) .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) .or_else(|| db.faces().map(|f| f.id).next())?; let info = db.face(id)?; @@ -112,13 +164,24 @@ fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option { /// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest /// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere. -fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, italic: bool) -> Option { +fn pick( + db: &fontdb::Database, + aliases: &HashMap>, + family: &str, + wanted_style: &str, + weight: u16, + italic: bool, +) -> Option { if family.is_empty() { return None; } + let alias_ids = aliases.get(&family.to_ascii_lowercase()); let mut candidates: Vec<&fontdb::FaceInfo> = db .faces() - .filter(|f| f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family))) + .filter(|f| { + f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family)) + || alias_ids.is_some_and(|ids| ids.contains(&f.id)) + }) .collect(); candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index))); let first = candidates.first()?; @@ -137,13 +200,23 @@ fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, it if let Some(face) = exact { return Some(face.id); } - let name = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family))?.0.as_str(); - db.query(&fontdb::Query { - families: &[fontdb::Family::Name(name)], - weight: fontdb::Weight(weight), - style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, - ..Default::default() - }) + if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) { + return db.query(&fontdb::Query { + families: &[fontdb::Family::Name(name)], + weight: fontdb::Weight(weight), + style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, + ..Default::default() + }); + } + let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }; + candidates + .into_iter() + .min_by_key(|f| { + let style_pen = if f.style == want_style { 0i32 } else { 1000 }; + let weight_diff = (f.weight.0 as i32 - weight as i32).abs(); + (style_pen + weight_diff, &f.post_script_name, f.index) + }) + .map(|f| f.id) } /// Ascent and descent (both positive) in em units, from `hhea`. @@ -415,7 +488,9 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec let mut lines = Vec::new(); let mut char_cursor = 0usize; - for line_str in params.text.split('\n') { + for raw_line in params.text.split('\n') { + let raw_char_len = raw_line.chars().count(); + let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line); let line_chars: Vec = line_str.chars().collect(); let mut shaped_runs: Vec<(usize, usize, Arc, f32, ShapedLine)> = Vec::new(); let mut line_max_size = 0.0_f32; @@ -493,7 +568,7 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec descent: max_desc, top_anchor: max_top_anchor, }); - char_cursor += line_chars.len() + 1; + char_cursor += raw_char_len + 1; } let cx = params.center[0] * wf; @@ -558,8 +633,11 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec } fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec) { - let r = (sigma * 3.0).ceil().min(64.0) as isize; - if r <= 0 || sigma < 0.05 { + if !sigma.is_finite() || sigma < 0.05 { + return (0, vec![1.0]); + } + let r = (sigma * 3.0).ceil().clamp(0.0, 64.0) as isize; + if r <= 0 { return (0, vec![1.0]); } let inv2s2 = 1.0 / (2.0 * sigma * sigma); @@ -652,12 +730,13 @@ pub fn rasterize_text_plus_rich( // Calibrated on Fusion 21.1 (`text_diag` & `text_diag2`): sigma = SoftnessX * (W / 1280). let soft_scale = w as f32 / 1280.0; - let sx1 = (params.soft_fill[0].max(0.0)) * soft_scale; - let sy1 = (params.soft_fill[1].max(0.0)) * soft_scale; - let sx2 = (params.soft_outline[0].max(0.0)) * soft_scale; - let sy2 = (params.soft_outline[1].max(0.0)) * soft_scale; - let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil() as i32; - let eff_pad = dod_pad.max(blur_pad); + let clamp_sigma = |v: f32| if v.is_finite() { (v.max(0.0) * soft_scale).min(64.0 / 3.0) } else { 0.0 }; + let sx1 = clamp_sigma(params.soft_fill[0]); + let sy1 = clamp_sigma(params.soft_fill[1]); + let sx2 = clamp_sigma(params.soft_outline[0]); + let sy2 = clamp_sigma(params.soft_outline[1]); + let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil().clamp(0.0, 64.0) as i32; + let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad); let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); let mut grow = |c: &Coverage, pad: i32| { @@ -736,6 +815,48 @@ pub fn rasterize_text_plus_rich( ([tw as u32, th as u32], [origin_x, origin_y], out) } +const MAX_RING_VERTS: usize = 2048; +const MAX_POLY_VERTS: usize = 4096; +const MAX_TEXT3D_VERTS: usize = 500_000; + +fn same_pt_2d(a: [f32; 2], b: [f32; 2]) -> bool { + (a[0] - b[0]).abs() <= 1e-6 && (a[1] - b[1]).abs() <= 1e-6 +} + +fn is_forward_collinear(a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool { + let ab = [b[0] - a[0], b[1] - a[1]]; + let bc = [c[0] - b[0], c[1] - b[1]]; + let ac = [c[0] - a[0], c[1] - a[1]]; + let ac_len = ac[0].hypot(ac[1]); + if ac_len <= 1e-6 { + return false; + } + let perp = (ab[0] * ac[1] - ab[1] * ac[0]).abs() / ac_len; + let dot = ab[0] * bc[0] + ab[1] * bc[1]; + perp <= 1e-6 && dot >= 0.0 +} + +fn strip_forward_collinear(mut ring: Vec<[f32; 2]>) -> Vec<[f32; 2]> { + let mut changed = true; + while changed && ring.len() >= 3 { + changed = false; + let n = ring.len(); + let mut next = Vec::with_capacity(n); + for i in 0..n { + let a = if next.is_empty() { ring[(i + n - 1) % n] } else { *next.last().unwrap() }; + let b = ring[i]; + let c = ring[(i + 1) % n]; + if is_forward_collinear(a, b, c) && next.len() + (n - 1 - i) >= 3 { + changed = true; + continue; + } + next.push(b); + } + ring = next; + } + ring +} + fn flatten_glyph_rings(commands: &[Command]) -> Vec> { let to_world = |p: Vector| -> [f32; 2] { [(p.x - 1024.0) / 512.0, -(p.y - 512.0) / 512.0] }; let mut rings = Vec::new(); @@ -803,6 +924,13 @@ fn flatten_glyph_rings(commands: &[Command]) -> Vec> { if clean.len() >= 2 && (clean[0][0] - clean.last().unwrap()[0]).hypot(clean[0][1] - clean.last().unwrap()[1]) <= 1e-5 { clean.pop(); } + let mut clean = strip_forward_collinear(clean); + if clean.len() > MAX_RING_VERTS { + let len = clean.len(); + clean = (0..MAX_RING_VERTS) + .map(|i| clean[(i * len) / MAX_RING_VERTS]) + .collect(); + } (clean.len() >= 3 && ring_signed_area(&clean).abs() > 1e-9).then_some(clean) }).collect() } @@ -842,51 +970,95 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) { let Some((m_idx, &m)) = hole .iter() .enumerate() - .max_by(|a, b| a.1[0].total_cmp(&b.1[0])) + .max_by(|a, b| a.1[0].total_cmp(&b.1[0]).then_with(|| a.1[1].total_cmp(&b.1[1]))) else { return; }; + let n_outer = outer.len(); + if n_outer < 3 || hole.len() < 3 { + return; + } let mut best_x = f32::INFINITY; - let mut best_edge = None; - for i in 0..outer.len() { - let a = outer[i]; - let b = outer[(i + 1) % outer.len()]; - if (a[1] <= m[1] && b[1] > m[1]) || (b[1] <= m[1] && a[1] > m[1]) { - let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]); - if x_int >= m[0] - 1e-6 && x_int < best_x { - best_x = x_int; - let p_idx = if a[0] >= b[0] { i } else { (i + 1) % outer.len() }; - best_edge = Some((x_int, p_idx)); - } + let mut best_hit: Option<(usize, bool)> = None; + let consider_hit = |best_x: &mut f32, + best_hit: &mut Option<(usize, bool)>, + x_int: f32, + p_idx: usize, + is_vertex_hit: bool| { + if x_int < m[0] - 1e-6 { + return; + } + let better = x_int < *best_x - 1e-6 + || ((x_int - *best_x).abs() <= 1e-6 && is_vertex_hit && !best_hit.is_some_and(|(_, vh)| vh)); + if better { + *best_x = x_int; + *best_hit = Some((p_idx, is_vertex_hit)); } - } - let Some((x_int, mut p_idx)) = best_edge else { - return; }; - let inter = [x_int, m[1]]; - let mut p_pt = outer[p_idx]; - let mut best_ang = f32::INFINITY; - for (vi, &v) in outer.iter().enumerate() { - if vi == p_idx || (v[0] - p_pt[0]).abs() + (v[1] - p_pt[1]).abs() < 1e-6 { + for i in 0..n_outer { + let j = (i + 1) % n_outer; + let (a, b) = (outer[i], outer[j]); + if (a[1] - m[1]).abs() <= 1e-6 && (b[1] - m[1]).abs() <= 1e-6 { + consider_hit(&mut best_x, &mut best_hit, a[0], i, true); + consider_hit(&mut best_x, &mut best_hit, b[0], j, true); continue; } - let cross = (p_pt[0] - m[0]) * (v[1] - m[1]) - (p_pt[1] - m[1]) * (v[0] - m[0]); - let tri_inside = if (p_pt[1] - m[1]).abs() > 1e-7 { - let orient = p_pt[1] > m[1]; - if orient { - point_in_tri(v, m, inter, p_pt) + // For CCW outer contours, a rightward ray exits across upward edges (`b.y > a.y`). + // Checking `b.y > a.y` also avoids picking the wrong side of an existing bridge. + if a[1] <= m[1] + 1e-6 && b[1] >= m[1] - 1e-6 && b[1] > a[1] + 1e-7 { + if (a[1] - m[1]).abs() <= 1e-6 { + consider_hit(&mut best_x, &mut best_hit, a[0], i, true); + } else if (b[1] - m[1]).abs() <= 1e-6 { + consider_hit(&mut best_x, &mut best_hit, b[0], j, true); } else { - point_in_tri(v, m, p_pt, inter) + let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]); + let p_idx = if a[0] >= b[0] { i } else { j }; + consider_hit(&mut best_x, &mut best_hit, x_int, p_idx, false); } - } else { - false - }; - if tri_inside && cross.abs() > 1e-7 { - let ang = ((v[1] - m[1]).atan2((v[0] - m[0]).max(1e-7))).abs(); - if ang < best_ang { - best_ang = ang; - p_idx = vi; - p_pt = v; + } + } + if best_hit.is_none() { + for i in 0..n_outer { + let j = (i + 1) % n_outer; + let (a, b) = (outer[i], outer[j]); + if (a[1] < m[1] && b[1] > m[1]) || (b[1] < m[1] && a[1] > m[1]) { + let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]); + let p_idx = if a[0] >= b[0] { i } else { j }; + consider_hit(&mut best_x, &mut best_hit, x_int, p_idx, false); + } + } + } + let Some((p_initial_idx, is_vertex_hit)) = best_hit else { + return; + }; + let mut p_idx = p_initial_idx; + if !is_vertex_hit { + let inter = [best_x, m[1]]; + let p_initial = outer[p_initial_idx]; + let mut best_ang = (p_initial[1] - m[1]).abs().atan2((p_initial[0] - m[0]).max(0.0)); + let mut best_dist2 = (p_initial[0] - m[0]).powi(2) + (p_initial[1] - m[1]).powi(2); + let orient = p_initial[1] > m[1]; + for (vi, &v) in outer.iter().enumerate() { + if vi == p_initial_idx || same_pt_2d(v, p_initial) || same_pt_2d(v, m) { + continue; + } + let tri_inside = if (p_initial[1] - m[1]).abs() > 1e-7 { + if orient { + point_in_tri(v, m, inter, p_initial) + } else { + point_in_tri(v, m, p_initial, inter) + } + } else { + false + }; + if tri_inside { + let ang = (v[1] - m[1]).abs().atan2((v[0] - m[0]).max(0.0)); + let dist2 = (v[0] - m[0]).powi(2) + (v[1] - m[1]).powi(2); + if ang < best_ang - 1e-6 || ((ang - best_ang).abs() <= 1e-6 && dist2 < best_dist2) { + best_ang = ang; + best_dist2 = dist2; + p_idx = vi; + } } } } @@ -901,9 +1073,27 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) { } fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> { + if poly.len() < 3 || poly.len() > MAX_POLY_VERTS { + return Vec::new(); + } let mut idx: Vec = (0..poly.len()).collect(); - let mut tris = Vec::with_capacity(poly.len().saturating_sub(2)); - let mut guard = poly.len() * poly.len() + 16; + let mut stripped = true; + while stripped && idx.len() >= 3 { + stripped = false; + let mut i = 0; + while i < idx.len() && idx.len() >= 4 { + let n = idx.len(); + let (a, b, c) = (poly[idx[(i + n - 1) % n]], poly[idx[i]], poly[idx[(i + 1) % n]]); + if is_forward_collinear(a, b, c) { + idx.remove(i); + stripped = true; + } else { + i += 1; + } + } + } + let mut tris = Vec::with_capacity(idx.len().saturating_sub(2)); + let mut guard = idx.len() * idx.len() + 16; while idx.len() >= 3 && guard > 0 { guard -= 1; let n = idx.len(); @@ -916,7 +1106,14 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> { continue; } let has_inside = idx.iter().enumerate().any(|(j, &iv)| { - j != (i + n - 1) % n && j != i && j != (i + 1) % n && point_in_tri(poly[iv], a, b, c) + if j == (i + n - 1) % n || j == i || j == (i + 1) % n { + return false; + } + let p = poly[iv]; + if same_pt_2d(p, a) || same_pt_2d(p, b) || same_pt_2d(p, c) { + return false; + } + point_in_tri(p, a, b, c) }); if !has_inside { tris.push([a, b, c]); @@ -925,6 +1122,30 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> { break; } } + if !clipped { + for i in 0..n { + let (ia, ib, ic) = (idx[(i + n - 1) % n], idx[i], idx[(i + 1) % n]); + let (a, b, c) = (poly[ia], poly[ib], poly[ic]); + let area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + let degenerate = same_pt_2d(a, b) || same_pt_2d(b, c) || same_pt_2d(a, c); + let collinear_empty = area2.abs() <= 1e-7 + && !idx.iter().enumerate().any(|(j, &iv)| { + if j == (i + n - 1) % n || j == i || j == (i + 1) % n { + return false; + } + let p = poly[iv]; + !same_pt_2d(p, a) + && !same_pt_2d(p, b) + && !same_pt_2d(p, c) + && point_in_tri(p, a, b, c) + }); + if degenerate || collinear_empty { + idx.remove(i); + clipped = true; + break; + } + } + } if !clipped { break; } @@ -947,6 +1168,9 @@ pub fn build_text3d_mesh( let z_front = depth; let z_back = 0.0; for g in &glyphs { + if verts.len() >= MAX_TEXT3D_VERTS { + break; + } let mut rings = flatten_glyph_rings(&g.commands); if rings.is_empty() { continue; @@ -1003,6 +1227,9 @@ pub fn build_text3d_mesh( } } for oi in outers { + if verts.len() >= MAX_TEXT3D_VERTS { + break; + } let mut poly = rings[oi].clone(); if let Some(mut his) = hole_groups.remove(&oi) { his.sort_by(|&a, &b| { @@ -1014,6 +1241,9 @@ pub fn build_text3d_mesh( } } for [a, b, c] in ear_clip(&poly) { + if verts.len() + 6 > MAX_TEXT3D_VERTS { + break; + } let nf = [0.0, 0.0, 1.0]; verts.push(Vertex3D { pos: [a[0], a[1], z_front], normal: nf, uv: [0.0, 0.0] }); verts.push(Vertex3D { pos: [b[0], b[1], z_front], normal: nf, uv: [0.0, 0.0] }); @@ -1182,7 +1412,7 @@ mod tests { #[test] fn cls_offsets_move_only_the_styled_characters() { let base = render_bounds(¶ms("HH")).unwrap(); - let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05 }]; + let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05, text: String::new() }]; let mut p = params("HH"); p.cls = &cls; let raised = render_bounds(&p).unwrap(); @@ -1319,4 +1549,154 @@ mod tests { assert!((max_z - 0.15).abs() < 1e-4 && min_z.abs() < 1e-4, "{min_z}..{max_z}"); assert!(verts.iter().any(|v| v.normal[2] == 0.0), "expected extruded side normals"); } + + #[test] + fn ear_clip_and_bridge_hole_triangulate_square_with_hole_exact_area() { + let mut outer = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; + let hole = vec![[0.25, 0.25], [0.25, 0.75], [0.75, 0.75], [0.75, 0.25]]; + bridge_hole(&mut outer, &hole); + let tris = ear_clip(&outer); + assert!(!tris.is_empty()); + let area: f32 = tris + .iter() + .map(|[a, b, c]| 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))) + .sum(); + assert!((area - 0.75).abs() < 1e-5, "expected exact 0.75 area, got {area}"); + } + + #[test] + fn text3d_holed_glyphs_o_and_b_preserve_exact_cap_area() { + for (ch, expected_holes) in [('o', 1usize), ('B', 2usize)] { + let txt = ch.to_string(); + let p = RichTextPlusParams { + text: &txt, + font_family: "Liberation Sans", + font_style: "Regular", + size_norm: 0.25, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0; 4], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [0.0; 4], + outline_thickness_norm: 0.0, + outline_enabled: false, + soft_fill: [0.0; 3], + soft_outline: [0.0; 3], + baseline_at_center: true, + }; + let (glyphs, _) = layout_glyphs([2048, 1024], &p).unwrap(); + assert_eq!(glyphs.len(), 1); + let mut rings = flatten_glyph_rings(&glyphs[0].commands); + let mut depths = vec![0usize; rings.len()]; + for i in 0..rings.len() { + let pt = rings[i][0]; + for j in 0..rings.len() { + if i != j && point_in_ring(pt, &rings[j]) { + depths[i] += 1; + } + } + } + assert_eq!(depths.iter().filter(|&&d| d % 2 == 1).count(), expected_holes, "hole count for {ch}"); + for (i, ring) in rings.iter_mut().enumerate() { + if (depths[i] % 2 == 0) != (ring_signed_area(ring) > 0.0) { + ring.reverse(); + } + } + let expected_area: f32 = rings.iter().map(|r| ring_signed_area(r)).sum(); + + let verts = build_text3d_mesh(&p, 0.0); + assert_eq!(verts.len() % 3, 0); + let cap_area: f32 = verts + .chunks_exact(3) + .map(|t| { + let (a, b, c) = (t[0].pos, t[1].pos, t[2].pos); + 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) + }) + .sum(); + assert!( + (cap_area - expected_area).abs() < 1e-4, + "glyph '{ch}' cap area {cap_area} != ring signed area {expected_area}" + ); + } + } + + #[test] + fn crlf_strips_cr_and_keeps_cls_indices_aligned() { + let cls = [StyledClsRule { + prop_id: 102, + start: 4, + end: 5, + value: 0.24, + text: String::new(), + }]; + let make = |text: &'static str| RichTextPlusParams { + text, + font_family: "Liberation Sans", + font_style: "Regular", + size_norm: 0.08, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0; 4], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &cls, + outline_rgba: [0.0; 4], + outline_thickness_norm: 0.0, + outline_enabled: false, + soft_fill: [0.0; 3], + soft_outline: [0.0; 3], + baseline_at_center: false, + }; + let lf = rasterize_text_plus_rich([320, 180], &make("HH\nHH"), 0); + let crlf = rasterize_text_plus_rich([320, 180], &make("HH\r\nHH"), 0); + assert_eq!(lf, crlf, "CRLF must render identically to LF without .notdef boxes or CLS drift"); + } + + #[test] + fn non_finite_and_huge_softness_values_do_not_overflow() { + let p = RichTextPlusParams { + text: "A", + font_family: "Liberation Sans", + font_style: "Regular", + size_norm: 0.12, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0; 4], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [1.0, 0.0, 0.0, 1.0], + outline_thickness_norm: 0.05, + outline_enabled: true, + soft_fill: [f32::NAN, f32::INFINITY, 0.0], + soft_outline: [1e30, -5.0, 0.0], + baseline_at_center: false, + }; + let (sz, _, rgba) = rasterize_text_plus_rich([160, 90], &p, 0); + assert!(sz[0] <= 480 && sz[1] <= 270 && !rgba.is_empty()); + } + + #[test] + fn runtime_font_registration_resolves_custom_family_alias() { + let base = Font::find("Helvetica", "Regular").expect("system fallback font"); + let bytes = base.data.clone(); + register_font_bytes(bytes.clone()); + register_font_bytes_with_name("FissionRuntimeAliasFont", bytes); + let resolved = Font::find("FissionRuntimeAliasFont", "Regular").expect("registered alias font"); + assert!(resolved.face().glyph_index('A').is_some()); + } } diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index adc4c0c2e3bf31cb288b0cf31c741c44c3553002..a7dbeaa13aee34cd811ee011b1729308e58bf081 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -380,13 +380,15 @@ impl Node { } /// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`). -/// Common Fusion property IDs: `1350` = Character X offset, `1351` = Character Y offset. +/// Common Fusion property IDs: `100` = Font family, `102` = Size, `109` = Font style, +/// `1330` = Character shear X, `1350` = Character X offset, `1351` = Character Y offset. #[derive(Clone, Debug, PartialEq)] pub struct ClsEntry { pub prop_id: u32, pub start: usize, pub end: usize, pub value: f32, + pub text: String, } /// Fusion `Shake` procedural modifier (`Source = "X"` / `"Y"` / `"Value"` / `"Position"`). diff --git a/crates/model/src/comp/load.rs b/crates/model/src/comp/load.rs index 00d82c39d49a6a789b529ee21b84f6ece9aa1219..c16f5916fda4c157ae0780dd8a5ae2b84b9afc52 100644 --- a/crates/model/src/comp/load.rs +++ b/crates/model/src/comp/load.rs @@ -84,6 +84,7 @@ impl Comp { let mut tracker_aliases: Vec<(String, String)> = Vec::new(); let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); + let mut macro_owner: HashMap = HashMap::new(); if let Some(tools) = root.get_table("Tools") { parse_tools_table( @@ -103,6 +104,7 @@ impl Comp { &mut tracker_aliases, &mut macro_defaults, &mut instanced_from, + &mut macro_owner, ); } @@ -113,7 +115,7 @@ impl Comp { } } - let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &node_by_name); + let cross_macro_wires = clear_cross_macro_wires(&mut nodes, ¯o_owner); // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools. for (target_op, target_param, val) in macro_defaults { @@ -298,16 +300,10 @@ impl Comp { /// enclosing macros, its nested macros) or at top level; a name that only exists inside an /// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was /// cleared here so saving keeps the original text. -fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap) -> HashSet<(String, String)> { - let mut owner: HashMap = HashMap::new(); - for m in nodes.iter().filter(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) { - let Some(inner) = m.raw.get_table("Tools") else { continue }; - for (key, _) in &inner.entries { - let LuaKey::Str(child) = key else { continue }; - if let Some(&cid) = node_by_name.get(child).filter(|&&c| nodes[c.0].internal) { - owner.insert(cid, m.id); - } - } +fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap) -> HashSet<(String, String)> { + let mut by_name: HashMap<&str, Vec> = HashMap::new(); + for n in nodes.iter() { + by_name.entry(n.name.as_str()).or_default().push(n.id); } let encloses = |outer: NodeId, mut inner: NodeId| { loop { @@ -320,15 +316,23 @@ fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap bool { + if !nodes[t.0].internal { + return true; + } + owner + .get(&t) + .is_some_and(|&t_scope| encloses(t_scope, n_scope) || encloses(n_scope, t_scope)) + }; let mut cleared = Vec::new(); for n in nodes.iter().filter(|n| n.internal) { let Some(&n_scope) = owner.get(&n.id) else { continue }; for (port, b) in &n.inputs { - let Some(&t) = b.source_op.as_ref().and_then(|s| node_by_name.get(s)) else { continue }; - if let Some(&t_scope) = owner.get(&t) { - if !encloses(t_scope, n_scope) && !encloses(n_scope, t_scope) { - cleared.push((n.id, port.clone())); - } + let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else { + continue; + }; + if !candidates.iter().any(|&t| in_scope(n_scope, t)) { + cleared.push((n.id, port.clone())); } } } @@ -514,6 +518,7 @@ fn parse_tools_table( tracker_aliases: &mut Vec<(String, String)>, macro_defaults: &mut Vec<(String, String, ParamValue)>, instanced_from: &mut Vec<(NodeId, String)>, + macro_owner: &mut HashMap, ) { for (key, val) in &tools.entries { let LuaKey::Str(name) = key else { continue }; @@ -572,31 +577,46 @@ fn parse_tools_table( } if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" { if let Some(in_tbl) = tbl.get_table("Inputs") { - if let Some(txt) = in_tbl - .get_table("Text") - .or_else(|| in_tbl.get_table("StyledText")) - .and_then(|s| s.get_str("Value")) - { - text_modifiers.insert(name.clone(), txt.to_owned()); + if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) { + if let Some(txt) = txt_in + .get_table("Value") + .and_then(|v| v.get_str("Value")) + .or_else(|| txt_in.get_str("Value")) + { + text_modifiers.insert(name.clone(), txt.to_owned()); + } } if let Some(arr) = in_tbl - .get_table("CharacterLevelStyling") + .get_table("RightClickHereToAnimateCharacterLevelStyling") + .or_else(|| in_tbl.get_table("CharacterLevelStyling")) .and_then(|c| c.get_table("Value")) .and_then(|v| v.get_table("Array")) { let mut entries = Vec::new(); for (_, ev) in &arr.entries { let Some(et) = ev.as_table() else { continue }; - let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue }; - let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue }; - let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue }; - let Some(val) = et.get_f64("Value") else { continue }; - entries.push(ClsEntry { - prop_id: pid.round().max(0.0) as u32, - start: s.round().max(0.0) as usize, - end: e.round().max(0.0) as usize, - value: val as f32, - }); + if let Some(param) = et.get_f64("Parameter") { + entries.push(ClsEntry { + prop_id: param.round().max(0.0) as u32, + start: et.get_f64("First").unwrap_or(0.0).round().max(0.0) as usize, + end: et.get_f64("Last").unwrap_or(0.0).round().max(0.0) as usize, + value: et.get_f64("Value").unwrap_or(0.0) as f32, + text: et.get_str("String").unwrap_or("").to_owned(), + }); + } else if let (Some(pid), Some(s), Some(e), Some(val)) = ( + et.get_index(1).and_then(LuaValue::as_f64), + et.get_index(2).and_then(LuaValue::as_f64), + et.get_index(3).and_then(LuaValue::as_f64), + et.get_f64("Value"), + ) { + entries.push(ClsEntry { + prop_id: pid.round().max(0.0) as u32, + start: s.round().max(0.0) as usize, + end: e.round().max(0.0) as usize, + value: val as f32, + text: et.get_str("String").unwrap_or("").to_owned(), + }); + } } if !entries.is_empty() { text_cls.insert(name.clone(), entries); @@ -787,11 +807,13 @@ fn parse_tools_table( tracker_aliases, macro_defaults, instanced_from, + macro_owner, ); } } let mut macro_output = None; + let mut macro_inner_start = None; if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { let mut out_name: Option = None; if let Some(outs) = tbl.get_table("Outputs") { @@ -805,6 +827,7 @@ fn parse_tools_table( } } let inner_start = nodes.len(); + macro_inner_start = Some(inner_start); if let Some(inner_tools) = tbl.get_table("Tools") { parse_tools_table( inner_tools, @@ -823,6 +846,7 @@ fn parse_tools_table( tracker_aliases, macro_defaults, instanced_from, + macro_owner, ); } if let Some(oname) = out_name { @@ -835,6 +859,11 @@ fn parse_tools_table( } let id = NodeId(nodes.len()); + if let Some(inner_start) = macro_inner_start { + for nid_raw in inner_start..id.0 { + macro_owner.entry(NodeId(nid_raw)).or_insert(id); + } + } // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name. if !is_internal || !node_by_name.contains_key(name) { node_by_name.insert(name.clone(), id); @@ -856,3 +885,99 @@ fn parse_tools_table( }); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn styled_text_cls_right_click_rules_parse_inside_macro_operator() { + let src = r#" +Composition { + Tools = ordered() { + MyMacro = MacroOperator { + Outputs = ordered() { + Output1 = InstanceOutput { SourceOp = "Txt1", Source = "Output", }, + }, + Tools = ordered() { + Txt1 = TextPlus { + Inputs = { + StyledText = Input { SourceOp = "CLS1", Source = "Value", }, + }, + }, + CLS1 = StyledTextCLS { + Inputs = { + Text = Input { Value = StyledText { Value = "Hello" }, }, + RightClickHereToAnimateCharacterLevelStyling = Input { + Value = StyledTextCLS_Data { + Array = { + { Parameter = 100, First = 0, Last = 1, String = "Arial", }, + { Parameter = 102, First = 2, Last = 4, Value = 0.25, }, + }, + }, + }, + }, + }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse macro StyledTextCLS"); + let txt = comp.nodes.iter().find(|n| n.name == "Txt1").expect("Txt1"); + assert_eq!(comp.text_modifiers.get("CLS1").map(String::as_str), Some("Hello")); + let entries = comp.text_cls_entries(txt, "StyledText"); + assert_eq!(entries.len(), 2); + assert_eq!(entries[0].prop_id, 100); + assert_eq!(entries[0].text, "Arial"); + assert_eq!(entries[1].prop_id, 102); + assert!((entries[1].value - 0.25).abs() < 1e-6); + } + + #[test] + fn clear_cross_macro_wires_handles_duplicate_internal_names_across_sibling_macros() { + let src = r#" +Composition { + Tools = ordered() { + MacroA = MacroOperator { + Outputs = ordered() { + Output1 = InstanceOutput { SourceOp = "OutA", Source = "Output", }, + }, + Tools = ordered() { + Background1 = Background { }, + OnlyInA = Background { }, + OutA = Merge { + Inputs = { + Background = Input { SourceOp = "Background1", Source = "Output", }, + Foreground = Input { SourceOp = "OnlyInB", Source = "Output", }, + }, + }, + }, + }, + MacroB = MacroOperator { + Outputs = ordered() { + Output1 = InstanceOutput { SourceOp = "OutB", Source = "Output", }, + }, + Tools = ordered() { + Background1 = Background { }, + OnlyInB = Background { }, + OutB = Merge { + Inputs = { + Background = Input { SourceOp = "Background1", Source = "Output", }, + Foreground = Input { SourceOp = "OnlyInA", Source = "Output", }, + }, + }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse sibling macros with duplicate inner names"); + let out_a = comp.nodes.iter().find(|n| n.name == "OutA").expect("OutA"); + let out_b = comp.nodes.iter().find(|n| n.name == "OutB").expect("OutB"); + assert_eq!(out_a.connected_node("Background"), Some("Background1")); + assert_eq!(out_b.connected_node("Background"), Some("Background1")); + assert_eq!(out_a.connected_node("Foreground"), None, "OutA -> OnlyInB must be cleared"); + assert_eq!(out_b.connected_node("Foreground"), None, "OutB -> OnlyInA must be cleared"); + } +} -- 2.54.1