authoravatarclover caruso<git@paperclover.net>2026-12-01 05:43:23-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 06:26:56-08:00
logf2a1716264a84ca38dc64149525f356134a5ff47
tree4660fc9a93776087f033ab978029384e29941458
parentad3803502cce6b4ea710d670c1fffa194b407e57
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Wave 17B: fix Text3D ear_clip/bridge_hole & caching, TextPlus CLS/CRLF/softness/BorderFill, scene3d shadow VRAM, macro isolation, and runtime font registration


5 files changed, 932 insertions(+), 169 deletions(-)

crates/engine/src/eval/text_3d.rs+197-59
......@@ -1,5 +1,3 @@
1use std::sync::Arc;
2
31use super::*;
42use crate::text_engine::{RichTextPlusParams, StyledClsRule};
53
......@@ -33,46 +31,9 @@ struct ResolvedTextInputs {
3331 baseline_at_center: bool,
3432}
3533
36fn parse_styled_text_cls(comp: &Comp, node: &Node) -> Option<(String, Vec<StyledClsRule>)> {
37 let src_op = node.connected_node("StyledText")?;
38 let inputs = comp
39 .raw_root
40 .as_ref()?
41 .get_table("Tools")?
42 .get_table(src_op)?
43 .get_table("Inputs")?;
44 let text = inputs
45 .get_table("Text")
46 .and_then(|t| t.get_table("Value").and_then(|v| v.get_str("Value")).or_else(|| t.get_str("Value")))
47 .unwrap_or("")
48 .to_owned();
49 let mut rules = Vec::new();
50 let array = inputs
51 .get_table("RightClickHereToAnimateCharacterLevelStyling")
52 .or_else(|| inputs.get_table("CharacterLevelStyling"))
53 .and_then(|t| t.get_table("Value"))
54 .and_then(|v| v.get_table("Array"));
55 if let Some(arr) = array {
56 let mut idx = 1i64;
57 while let Some(model::LuaValue::Table(entry)) = arr.get_index(idx) {
58 if let Some(param) = entry.get_f64("Parameter") {
59 rules.push(StyledClsRule {
60 prop_id: param.round().max(0.0) as u32,
61 start: entry.get_f64("First").unwrap_or(0.0).max(0.0) as usize,
62 end: entry.get_f64("Last").unwrap_or(0.0).max(0.0) as usize,
63 value: entry.get_f64("Value").unwrap_or(0.0) as f32,
64 text: entry.get_str("String").unwrap_or("").to_owned(),
65 });
66 }
67 idx += 1;
68 }
69 }
70 Some((text, rules))
71}
72
7334fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, expr: &ExprEngine) -> ResolvedTextInputs {
74 let mut text_str = comp.eval_text(node, "StyledText", time, "", expr);
75 let mut cls_rules: Vec<StyledClsRule> = comp
35 let text_str = comp.eval_text(node, "StyledText", time, "", expr);
36 let cls_rules: Vec<StyledClsRule> = comp
7637 .text_cls_entries(node, "StyledText")
7738 .iter()
7839 .map(|e| StyledClsRule {
......@@ -80,17 +41,9 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp
8041 start: e.start,
8142 end: e.end,
8243 value: e.value,
83 text: String::new(),
44 text: e.text.clone(),
8445 })
8546 .collect();
86 if let Some((cls_text, rich_rules)) = parse_styled_text_cls(comp, node) {
87 if text_str.is_empty() {
88 text_str = cls_text;
89 }
90 if !rich_rules.is_empty() {
91 cls_rules = rich_rules;
92 }
93 }
9447
9548 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue").to_owned();
9649 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
188141}
189142
190143impl ResolvedTextInputs {
144 fn geometry_hash(&self, ext_depth: f32, bevel_depth: f32, bevel_width: f32) -> u64 {
145 let mut h = DefaultHasher::new();
146 "Text3DMesh".hash(&mut h);
147 self.text_str.hash(&mut h);
148 self.font_family.hash(&mut h);
149 self.font_style.hash(&mut h);
150 self.baseline_at_center.hash(&mut h);
151 for v in [
152 self.size_norm,
153 self.tracking,
154 self.line_spacing,
155 self.center[0],
156 self.center[1],
157 self.h_lcr,
158 self.v_tcb,
159 self.write_start,
160 self.write_end,
161 self.shear_x,
162 ext_depth,
163 bevel_depth,
164 bevel_width,
165 ] {
166 v.to_bits().hash(&mut h);
167 }
168 self.cls_rules.len().hash(&mut h);
169 for r in &self.cls_rules {
170 r.prop_id.hash(&mut h);
171 r.start.hash(&mut h);
172 r.end.hash(&mut h);
173 r.value.to_bits().hash(&mut h);
174 r.text.hash(&mut h);
175 }
176 h.finish()
177 }
178
191179 fn as_rich_params(&self) -> RichTextPlusParams<'_> {
192180 let is_text_outline = self.outline_enabled && self.elem2_shape != 2;
193181 let outline_rgba = self.outline_rgba.map(|c| c * self.elem2_opacity);
......@@ -640,10 +628,10 @@ impl Engine {
640628 }
641629 }
642630
643 let br = outline_rgba[0] * elem2_opacity;
644 let bg = outline_rgba[1] * elem2_opacity;
645 let bb = outline_rgba[2] * elem2_opacity;
646 let ba = outline_rgba[3] * elem2_opacity;
631 let br = outline_rgba[0];
632 let bg = outline_rgba[1];
633 let bb = outline_rgba[2];
634 let ba = outline_rgba[3];
647635 for i in 0..(tw * th) {
648636 let cov = box_cov[i];
649637 if cov <= 1e-4 {
......@@ -823,6 +811,7 @@ impl Engine {
823811 let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len());
824812 for ms in &mesh_specs {
825813 let mut mesh_shape = ms.shape.clone();
814 let mut custom_mesh_key = None;
826815 let mut diffuse_col = ms.diffuse_col;
827816 let tex = if let Some(t3d) = &ms.text3d {
828817 let tnode = comp.node(t3d.node_id);
......@@ -835,11 +824,27 @@ impl Engine {
835824 };
836825 if ext_depth.abs() > 1e-4 {
837826 let ti = resolve_text_inputs(comp, tnode, time, true, &self.expr);
838 ti.text_str.hash(&mut h_scene);
839 ti.size_norm.to_bits().hash(&mut h_scene);
840 ext_depth.to_bits().hash(&mut h_scene);
841 let verts = crate::text_engine::build_text3d_mesh(&ti.as_rich_params(), ext_depth);
842 let custom = crate::scene3d::ShapeKind::CustomMesh(Arc::new(verts));
827 let bevel_depth = comp.eval_number(
828 tnode,
829 "Extrusion.BevelDepth",
830 time,
831 comp.eval_number(tnode, "BevelDepth", time, 0.0, &self.expr),
832 &self.expr,
833 ) as f32;
834 let bevel_width = comp.eval_number(
835 tnode,
836 "Extrusion.BevelWidth",
837 time,
838 comp.eval_number(tnode, "BevelWidth", time, 0.0, &self.expr),
839 &self.expr,
840 ) as f32;
841 let mesh_key = ti.geometry_hash(ext_depth, bevel_depth, bevel_width);
842 mesh_key.hash(&mut h_scene);
843 custom_mesh_key = Some(mesh_key);
844 let verts = self.scene3d.get_or_build_text3d_mesh(mesh_key, || {
845 crate::text_engine::build_text3d_mesh(&ti.as_rich_params(), ext_depth)
846 });
847 let custom = crate::scene3d::ShapeKind::CustomMesh(verts);
843848 mesh_shape = match &ms.shape {
844849 crate::scene3d::ShapeKind::WithMaterialFx { fx, .. } => {
845850 crate::scene3d::ShapeKind::WithMaterialFx { inner: Box::new(custom), fx: *fx }
......@@ -880,6 +885,7 @@ impl Engine {
880885 draw_meshes.push(crate::scene3d::DrawMesh {
881886 world: ms.world,
882887 shape: mesh_shape,
888 custom_mesh_key,
883889 tex,
884890 diffuse_col,
885891 specular_col: ms.specular_col,
......@@ -1090,4 +1096,136 @@ Composition {
10901096 "frame 5 larger Radius must invalidate Renderer3D cache and cover far more pixels (f0={c0}, f5={c5})"
10911097 );
10921098 }
1099
1100 #[test]
1101 fn extruded_text3d_reuses_mesh_cache_key_arc_and_renderer3d_cache() {
1102 let src = r#"
1103Composition {
1104 CurrentTime = 0,
1105 RenderRange = { 0, 10 },
1106 GlobalRange = { 0, 10 },
1107 Tools = ordered() {
1108 CamAnim = BezierSpline {
1109 KeyFrames = {
1110 [0] = { 4.0, Flags = { Linear = true } },
1111 [1] = { 4.5, Flags = { Linear = true } },
1112 },
1113 },
1114 Cam = Camera3D {
1115 Inputs = {
1116 ["Transform3DOp.Translate.Z"] = Input { SourceOp = "CamAnim", Source = "Value", },
1117 ApertureW = Input { Value = 1.0, },
1118 ApertureH = Input { Value = 1.0, },
1119 },
1120 },
1121 Txt = Text3D {
1122 Inputs = {
1123 StyledText = Input { Value = "OB", },
1124 Font = Input { Value = "Liberation Sans", },
1125 Style = Input { Value = "Regular", },
1126 Size = Input { Value = 1.0, },
1127 Extrusion = Input { Value = 1, },
1128 ["Extrusion.ExtrusionDepth"] = Input { Value = 0.2, },
1129 },
1130 },
1131 M = Merge3D {
1132 Inputs = {
1133 SceneInput1 = Input { SourceOp = "Txt", Source = "Output", },
1134 SceneInput2 = Input { SourceOp = "Cam", Source = "Output", },
1135 },
1136 },
1137 R3D = Renderer3D {
1138 Inputs = {
1139 Width = Input { Value = 64, },
1140 Height = Input { Value = 64, },
1141 SceneInput = Input { SourceOp = "M", Source = "Output", },
1142 },
1143 },
1144 },
1145}
1146"#;
1147 let comp = Comp::from_fusion_str(src).expect("parse Text3D comp");
1148 let Ok(mut eng) = Engine::new_headless() else {
1149 return;
1150 };
1151 let r3d = comp.find_node("R3D").unwrap();
1152 let txt = comp.find_node("Txt").unwrap();
1153
1154 let (_, s0) = eng.evaluate(&comp, r3d, 0.0);
1155 assert_eq!(s0.cache_misses, 1);
1156 assert_eq!(eng.scene3d.gpu_mesh_count(), 1);
1157
1158 // Identical second evaluation hits Renderer3D output cache and skips CPU/GPU rebuilds.
1159 let (_, s0_repeat) = eng.evaluate(&comp, r3d, 0.0);
1160 assert_eq!(s0_repeat.cache_hits, 1);
1161 assert_eq!(s0_repeat.cache_misses, 0);
1162
1163 // Moving the camera invalidates Renderer3D output, yet reuses the exact same Text3D mesh key,
1164 // cached Arc, and GPU mesh LRU entry.
1165 let (_, s1) = eng.evaluate(&comp, r3d, 1.0);
1166 assert_eq!(s1.cache_misses, 1);
1167 assert_eq!(eng.scene3d.gpu_mesh_count(), 1);
1168
1169 let ti0 = super::resolve_text_inputs(&comp, comp.node(txt), 0.0, true, &eng.expr);
1170 let ti1 = super::resolve_text_inputs(&comp, comp.node(txt), 1.0, true, &eng.expr);
1171 let mk0 = ti0.geometry_hash(0.2, 0.0, 0.0);
1172 let mk1 = ti1.geometry_hash(0.2, 0.0, 0.0);
1173 assert_eq!(mk0, mk1);
1174 let a0 = eng.scene3d.get_or_build_text3d_mesh(mk0, || panic!("mesh must be cached"));
1175 let a1 = eng.scene3d.get_or_build_text3d_mesh(mk1, || panic!("mesh must be cached"));
1176 assert!(std::sync::Arc::ptr_eq(&a0, &a1));
1177 }
1178
1179 #[test]
1180 fn border_fill_applies_opacity2_once() {
1181 let src = r#"
1182Composition {
1183 CurrentTime = 0,
1184 RenderRange = { 0, 1 },
1185 GlobalRange = { 0, 1 },
1186 Tools = ordered() {
1187 T1 = TextPlus {
1188 Inputs = {
1189 Width = Input { Value = 128, },
1190 Height = Input { Value = 128, },
1191 StyledText = Input { Value = "I", },
1192 Size = Input { Value = 0.25, },
1193 Red1 = Input { Value = 1.0, },
1194 Green1 = Input { Value = 1.0, },
1195 Blue1 = Input { Value = 1.0, },
1196 Alpha1 = Input { Value = 1.0, },
1197 Enabled2 = Input { Value = 1, },
1198 ElementShape2 = Input { Value = 2, },
1199 Red2 = Input { Value = 1.0, },
1200 Green2 = Input { Value = 0.0, },
1201 Blue2 = Input { Value = 0.0, },
1202 Alpha2 = Input { Value = 1.0, },
1203 Opacity2 = Input { Value = 0.5, },
1204 ExtendHorizontal2 = Input { Value = 1.0, },
1205 ExtendVertical2 = Input { Value = 1.0, },
1206 },
1207 },
1208 },
1209}
1210"#;
1211 let comp = Comp::from_fusion_str(src).expect("parse BorderFill comp");
1212 let Ok(mut eng) = Engine::new_headless() else {
1213 return;
1214 };
1215 let t1 = comp.find_node("T1").unwrap();
1216 let (tex, _) = eng.evaluate(&comp, t1, 0.0);
1217 let rgba = eng.readback_rgba(&tex).unwrap();
1218 // Pure red BorderFill margin pixels (outside white glyph 'I') have g=0, b=0, and alpha ~128
1219 // for Opacity2=0.5 (buggy elem2_opacity^2 gave ~64).
1220 let box_alpha = rgba
1221 .chunks_exact(4)
1222 .filter(|px| px[1] == 0 && px[2] == 0 && px[3] > 0)
1223 .map(|px| px[3])
1224 .max()
1225 .unwrap_or(0);
1226 assert!(
1227 (118..=138).contains(&box_alpha),
1228 "BorderFill Opacity2=0.5 should yield ~128 alpha, got {box_alpha}"
1229 );
1230 }
10931231}
crates/engine/src/scene3d/mod.rs+125-7
......@@ -36,6 +36,8 @@ pub struct Scene3DRenderer {
3636 pipelines: [[wgpu::RenderPipeline; 2]; 2],
3737 sampler: wgpu::Sampler,
3838 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,
39 /// Memoized CPU `Text3D` extruded meshes keyed by deterministic geometry content hash.
40 text3d_mesh_cache: Mutex<Lru<u64, Arc<Vec<Vertex3D>>>>,
3941 shadow_pipeline: wgpu::RenderPipeline,
4042 /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass.
4143 shadow_caster_bgl: wgpu::BindGroupLayout,
......@@ -71,8 +73,6 @@ struct GpuMesh {
7173 vbuf: wgpu::Buffer,
7274 ibuf: wgpu::Buffer,
7375 idx_count: u32,
74 /// Keeps a `CustomMesh` allocation alive: `ShapeKind::hash_into` hashes its address.
75 _shape: ShapeKind,
7676}
7777
7878/// Bounded map evicting the least recently used entry.
......@@ -87,6 +87,16 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
8787 Self { cap, tick: 0, entries: HashMap::new() }
8888 }
8989
90 fn get(&mut self, key: K) -> Option<V> {
91 self.tick += 1;
92 if let Some((used, v)) = self.entries.get_mut(&key) {
93 *used = self.tick;
94 Some(v.clone())
95 } else {
96 None
97 }
98 }
99
90100 fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V {
91101 self.tick += 1;
92102 if let Some((used, v)) = self.entries.get_mut(&key) {
......@@ -102,6 +112,11 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
102112 self.entries.insert(key, (self.tick, v.clone()));
103113 v
104114 }
115
116 fn clear(&mut self) {
117 self.entries.clear();
118 self.tick = 0;
119 }
105120}
106121
107122#[derive(Clone)]
......@@ -283,7 +298,6 @@ impl ShapeKind {
283298 ShapeKind::CustomMesh(verts) => {
284299 6u8.hash(h);
285300 verts.len().hash(h);
286 (verts.as_ptr() as usize).hash(h);
287301 let step = (verts.len() / 64).max(1);
288302 for v in verts.iter().step_by(step) {
289303 bytemuck::bytes_of(v).hash(h);
......@@ -377,6 +391,8 @@ pub struct SceneLights {
377391pub struct DrawMesh {
378392 pub world: Mat4,
379393 pub shape: ShapeKind,
394 /// Optional deterministic content key for `ShapeKind::CustomMesh` so GPU mesh LRU avoids pointer hashing.
395 pub custom_mesh_key: Option<u64>,
380396 pub tex: Option<CachedTexture>,
381397 pub diffuse_col: [f32; 4],
382398 pub specular_col: [f32; 3],
......@@ -389,9 +405,16 @@ pub struct DrawMesh {
389405 pub displace: Option<DisplaceHeightmap>,
390406}
391407
392fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {
393 use std::hash::{DefaultHasher, Hasher};
408fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option<u64>, aspect: f32, wireframe: bool) -> MeshKey {
409 use std::hash::{DefaultHasher, Hash, Hasher};
394410 let mut h = DefaultHasher::new();
411 if matches!(base_shape, ShapeKind::CustomMesh(_)) {
412 if let Some(ck) = custom_mesh_key {
413 6u8.hash(&mut h);
414 ck.hash(&mut h);
415 return (h.finish(), 0, wireframe);
416 }
417 }
395418 base_shape.hash_into(&mut h);
396419 let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 };
397420 (h.finish(), aspect_bits, wireframe)
......@@ -627,6 +650,7 @@ impl Scene3DRenderer {
627650 pipelines,
628651 sampler,
629652 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),
653 text3d_mesh_cache: Mutex::new(Lru::new(MESH_CACHE_CAP)),
630654 shadow_pipeline,
631655 shadow_caster_bgl,
632656 shadow_face_bgl,
......@@ -635,6 +659,41 @@ impl Scene3DRenderer {
635659 }
636660 }
637661
662 /// Returns a memoized `Text3D` vertex buffer for `key`, building it on miss.
663 pub fn get_or_build_text3d_mesh(
664 &self,
665 key: u64,
666 build: impl FnOnce() -> Vec<Vertex3D>,
667 ) -> Arc<Vec<Vertex3D>> {
668 if let Some(hit) = self.text3d_mesh_cache.lock().unwrap().get(key) {
669 return hit;
670 }
671 let built = Arc::new(build());
672 self.text3d_mesh_cache
673 .lock()
674 .unwrap()
675 .get_or_insert_with(key, || Arc::clone(&built))
676 }
677
678 /// Drops the cached shadow cube-map pool and memoized `Text3D` CPU meshes.
679 pub fn clear_shadow_targets(&self) {
680 *self.shadow_targets.lock().unwrap() = None;
681 self.text3d_mesh_cache.lock().unwrap().clear();
682 }
683
684 /// Total GPU VRAM in bytes currently occupied by `shadow_targets` (R32Float layers + Depth32Float).
685 pub fn shadow_vram_bytes(&self) -> u64 {
686 self.shadow_targets.lock().unwrap().as_ref().map_or(0, |t| {
687 let layer_bytes = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4;
688 layer_bytes * (u64::from(t.layers) + 1)
689 })
690 }
691
692 #[cfg(test)]
693 pub(crate) fn gpu_mesh_count(&self) -> usize {
694 self.meshes.lock().unwrap().entries.len()
695 }
696
638697 #[allow(clippy::too_many_arguments)]
639698 pub fn render_meshes(
640699 &self,
......@@ -818,13 +877,13 @@ impl Scene3DRenderer {
818877 mapped_at_creation: false,
819878 });
820879 queue.write_buffer(&ibuf, 0, ibytes);
821 Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, _shape: base_shape.clone() })
880 Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32 })
822881 };
823882 // Heightmap contents are not part of the key, so displaced meshes are never cached.
824883 let gpu_mesh = if m.displace.is_some() {
825884 upload()
826885 } else {
827 let key = mesh_key(base_shape, aspect, fx.wireframe);
886 let key = mesh_key(base_shape, m.custom_mesh_key, aspect, fx.wireframe);
828887 self.meshes.lock().unwrap().get_or_insert_with(key, upload)
829888 };
830889 let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else {
......@@ -1192,6 +1251,7 @@ mod tests {
11921251 inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }),
11931252 fx: MaterialFx { wireframe, ..Default::default() },
11941253 },
1254 custom_mesh_key: None,
11951255 tex: None,
11961256 diffuse_col: [1.0; 4],
11971257 specular_col: [1.0; 3],
......@@ -1365,4 +1425,62 @@ mod tests {
13651425 assert_eq!(uncast, unreceived, "either flag alone removes the shadow entirely");
13661426 assert_eq!(uncast, unreceived_by_material, "a material shader owns the receiver flag");
13671427 }
1428
1429 #[test]
1430 fn shadow_vram_bytes_tracks_pool_and_clear_resets_both_caches() {
1431 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
1432 let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return };
1433 let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return };
1434 let renderer = Scene3DRenderer::new(&device);
1435 assert_eq!(renderer.shadow_vram_bytes(), 0);
1436
1437 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] }]);
1438 assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 1);
1439
1440 let tex = device.create_texture(&wgpu::TextureDescriptor {
1441 label: None,
1442 size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 },
1443 mip_level_count: 1,
1444 sample_count: 1,
1445 dimension: wgpu::TextureDimension::D2,
1446 format: wgpu::TextureFormat::Rgba8Unorm,
1447 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
1448 view_formats: &[],
1449 });
1450 let dst = CachedTexture::from_texture(tex, [8, 8], 0);
1451 let dummy = dst.clone();
1452 let mut lights = SceneLights::default();
1453 lights.points.push(PointLight {
1454 pos: [0.0, 0.0, 2.0],
1455 color: [1.0, 1.0, 1.0],
1456 decay_type: 0.0,
1457 decay_rate: 0.0,
1458 shadow_density: Some(1.0),
1459 });
1460 let mut enc = device.create_command_encoder(&Default::default());
1461 renderer.render_meshes(
1462 &device,
1463 &queue,
1464 &mut enc,
1465 &dst,
1466 &dummy,
1467 mat4_identity(),
1468 mat4_identity(),
1469 [0.0, 0.0, 5.0],
1470 100.0,
1471 lights,
1472 true,
1473 true,
1474 &[],
1475 );
1476 queue.submit(Some(enc.finish()));
1477
1478 // 1 shadow light = 6 R32Float layers + 1 Depth32Float texture = 7 * 1024 * 1024 * 4 bytes.
1479 let expected = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4 * 7;
1480 assert_eq!(renderer.shadow_vram_bytes(), expected);
1481
1482 renderer.clear_shadow_targets();
1483 assert_eq!(renderer.shadow_vram_bytes(), 0);
1484 assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 0);
1485 }
13681486}
crates/engine/src/text_engine.rs+449-69
......@@ -4,8 +4,8 @@
44
55use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag};
66use rustybuzz::{Face, Feature, UnicodeBuffer, Variation};
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex, OnceLock};
7use std::collections::{HashMap, HashSet};
8use std::sync::{Arc, Mutex, OnceLock, RwLock};
99use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};
1010
1111/// Tried in order when the requested family is not installed.
......@@ -25,13 +25,17 @@ pub struct Font {
2525
2626impl Font {
2727 /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the
28 /// system fonts, falling back through [`FALLBACK_FAMILIES`] and finally any installed face.
28 /// system fonts and any fonts registered via [`register_font_bytes`], falling back through
29 /// [`FALLBACK_FAMILIES`] and finally any installed face.
2930 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
30 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();
31 let mut cache = CACHE.get_or_init(Default::default).lock().unwrap();
31 let mut cache = font_cache().lock().unwrap();
3232 cache
3333 .entry((family.to_owned(), style.to_owned()))
34 .or_insert_with(|| resolve(database(), family, style).map(Arc::new))
34 .or_insert_with(|| {
35 let db = database().read().unwrap();
36 let aliases = font_aliases().read().unwrap();
37 resolve(&db, &aliases, family, style).map(Arc::new)
38 })
3539 .clone()
3640 }
3741
......@@ -44,15 +48,58 @@ impl Font {
4448 }
4549}
4650
47fn database() -> &'static fontdb::Database {
48 static DB: OnceLock<fontdb::Database> = OnceLock::new();
51fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {
52 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();
53 CACHE.get_or_init(Default::default)
54}
55
56fn font_aliases() -> &'static RwLock<HashMap<String, Vec<fontdb::ID>>> {
57 static ALIASES: OnceLock<RwLock<HashMap<String, Vec<fontdb::ID>>>> = OnceLock::new();
58 ALIASES.get_or_init(Default::default)
59}
60
61fn database() -> &'static RwLock<fontdb::Database> {
62 static DB: OnceLock<RwLock<fontdb::Database>> = OnceLock::new();
4963 DB.get_or_init(|| {
5064 let mut db = fontdb::Database::new();
65 #[cfg(not(target_arch = "wasm32"))]
5166 db.load_system_fonts();
52 db
67 RwLock::new(db)
5368 })
5469}
5570
71/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime
72/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.
73pub fn register_font_bytes(bytes: Vec<u8>) {
74 {
75 let mut db = database().write().unwrap();
76 db.load_font_data(bytes);
77 }
78 font_cache().lock().unwrap().clear();
79}
80
81/// Registers font bytes under an explicit family alias in addition to its embedded family names,
82/// and clears the resolution cache.
83pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
84 {
85 let mut db = database().write().unwrap();
86 let before: HashSet<fontdb::ID> = db.faces().map(|f| f.id).collect();
87 db.load_font_data(bytes);
88 if !family.is_empty() {
89 let added: Vec<fontdb::ID> = db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect();
90 if !added.is_empty() {
91 font_aliases()
92 .write()
93 .unwrap()
94 .entry(family.to_ascii_lowercase())
95 .or_default()
96 .extend(added);
97 }
98 }
99 }
100 font_cache().lock().unwrap().clear();
101}
102
56103/// CSS-style weight and italic flag for a Fusion style name.
57104pub fn parse_style(style: &str) -> (u16, bool) {
58105 let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
......@@ -94,13 +141,18 @@ fn metric_alias(family: &str) -> Option<&'static str> {
94141 }
95142}
96143
97fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {
144fn resolve(
145 db: &fontdb::Database,
146 aliases: &HashMap<String, Vec<fontdb::ID>>,
147 family: &str,
148 style: &str,
149) -> Option<Font> {
98150 let (weight, italic) = parse_style(style);
99151 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
100152 let id = std::iter::once(family)
101153 .chain(metric_alias(family))
102154 .chain(FALLBACK_FAMILIES)
103 .find_map(|name| pick(db, name, &wanted, weight, italic))
155 .find_map(|name| pick(db, aliases, name, &wanted, weight, italic))
104156 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
105157 .or_else(|| db.faces().map(|f| f.id).next())?;
106158 let info = db.face(id)?;
......@@ -112,13 +164,24 @@ fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {
112164
113165/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest
114166/// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere.
115fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, italic: bool) -> Option<fontdb::ID> {
167fn pick(
168 db: &fontdb::Database,
169 aliases: &HashMap<String, Vec<fontdb::ID>>,
170 family: &str,
171 wanted_style: &str,
172 weight: u16,
173 italic: bool,
174) -> Option<fontdb::ID> {
116175 if family.is_empty() {
117176 return None;
118177 }
178 let alias_ids = aliases.get(&family.to_ascii_lowercase());
119179 let mut candidates: Vec<&fontdb::FaceInfo> = db
120180 .faces()
121 .filter(|f| f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family)))
181 .filter(|f| {
182 f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family))
183 || alias_ids.is_some_and(|ids| ids.contains(&f.id))
184 })
122185 .collect();
123186 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));
124187 let first = candidates.first()?;
......@@ -137,13 +200,23 @@ fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, it
137200 if let Some(face) = exact {
138201 return Some(face.id);
139202 }
140 let name = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family))?.0.as_str();
141 db.query(&fontdb::Query {
142 families: &[fontdb::Family::Name(name)],
143 weight: fontdb::Weight(weight),
144 style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
145 ..Default::default()
146 })
203 if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) {
204 return db.query(&fontdb::Query {
205 families: &[fontdb::Family::Name(name)],
206 weight: fontdb::Weight(weight),
207 style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
208 ..Default::default()
209 });
210 }
211 let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal };
212 candidates
213 .into_iter()
214 .min_by_key(|f| {
215 let style_pen = if f.style == want_style { 0i32 } else { 1000 };
216 let weight_diff = (f.weight.0 as i32 - weight as i32).abs();
217 (style_pen + weight_diff, &f.post_script_name, f.index)
218 })
219 .map(|f| f.id)
147220}
148221
149222/// Ascent and descent (both positive) in em units, from `hhea`.
......@@ -415,7 +488,9 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
415488
416489 let mut lines = Vec::new();
417490 let mut char_cursor = 0usize;
418 for line_str in params.text.split('\n') {
491 for raw_line in params.text.split('\n') {
492 let raw_char_len = raw_line.chars().count();
493 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
419494 let line_chars: Vec<char> = line_str.chars().collect();
420495 let mut shaped_runs: Vec<(usize, usize, Arc<Font>, f32, ShapedLine)> = Vec::new();
421496 let mut line_max_size = 0.0_f32;
......@@ -493,7 +568,7 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
493568 descent: max_desc,
494569 top_anchor: max_top_anchor,
495570 });
496 char_cursor += line_chars.len() + 1;
571 char_cursor += raw_char_len + 1;
497572 }
498573
499574 let cx = params.center[0] * wf;
......@@ -558,8 +633,11 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
558633}
559634
560635fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {
561 let r = (sigma * 3.0).ceil().min(64.0) as isize;
562 if r <= 0 || sigma < 0.05 {
636 if !sigma.is_finite() || sigma < 0.05 {
637 return (0, vec![1.0]);
638 }
639 let r = (sigma * 3.0).ceil().clamp(0.0, 64.0) as isize;
640 if r <= 0 {
563641 return (0, vec![1.0]);
564642 }
565643 let inv2s2 = 1.0 / (2.0 * sigma * sigma);
......@@ -652,12 +730,13 @@ pub fn rasterize_text_plus_rich(
652730
653731 // Calibrated on Fusion 21.1 (`text_diag` & `text_diag2`): sigma = SoftnessX * (W / 1280).
654732 let soft_scale = w as f32 / 1280.0;
655 let sx1 = (params.soft_fill[0].max(0.0)) * soft_scale;
656 let sy1 = (params.soft_fill[1].max(0.0)) * soft_scale;
657 let sx2 = (params.soft_outline[0].max(0.0)) * soft_scale;
658 let sy2 = (params.soft_outline[1].max(0.0)) * soft_scale;
659 let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil() as i32;
660 let eff_pad = dod_pad.max(blur_pad);
733 let clamp_sigma = |v: f32| if v.is_finite() { (v.max(0.0) * soft_scale).min(64.0 / 3.0) } else { 0.0 };
734 let sx1 = clamp_sigma(params.soft_fill[0]);
735 let sy1 = clamp_sigma(params.soft_fill[1]);
736 let sx2 = clamp_sigma(params.soft_outline[0]);
737 let sy2 = clamp_sigma(params.soft_outline[1]);
738 let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil().clamp(0.0, 64.0) as i32;
739 let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad);
661740
662741 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);
663742 let mut grow = |c: &Coverage, pad: i32| {
......@@ -736,6 +815,48 @@ pub fn rasterize_text_plus_rich(
736815 ([tw as u32, th as u32], [origin_x, origin_y], out)
737816}
738817
818const MAX_RING_VERTS: usize = 2048;
819const MAX_POLY_VERTS: usize = 4096;
820const MAX_TEXT3D_VERTS: usize = 500_000;
821
822fn same_pt_2d(a: [f32; 2], b: [f32; 2]) -> bool {
823 (a[0] - b[0]).abs() <= 1e-6 && (a[1] - b[1]).abs() <= 1e-6
824}
825
826fn is_forward_collinear(a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
827 let ab = [b[0] - a[0], b[1] - a[1]];
828 let bc = [c[0] - b[0], c[1] - b[1]];
829 let ac = [c[0] - a[0], c[1] - a[1]];
830 let ac_len = ac[0].hypot(ac[1]);
831 if ac_len <= 1e-6 {
832 return false;
833 }
834 let perp = (ab[0] * ac[1] - ab[1] * ac[0]).abs() / ac_len;
835 let dot = ab[0] * bc[0] + ab[1] * bc[1];
836 perp <= 1e-6 && dot >= 0.0
837}
838
839fn strip_forward_collinear(mut ring: Vec<[f32; 2]>) -> Vec<[f32; 2]> {
840 let mut changed = true;
841 while changed && ring.len() >= 3 {
842 changed = false;
843 let n = ring.len();
844 let mut next = Vec::with_capacity(n);
845 for i in 0..n {
846 let a = if next.is_empty() { ring[(i + n - 1) % n] } else { *next.last().unwrap() };
847 let b = ring[i];
848 let c = ring[(i + 1) % n];
849 if is_forward_collinear(a, b, c) && next.len() + (n - 1 - i) >= 3 {
850 changed = true;
851 continue;
852 }
853 next.push(b);
854 }
855 ring = next;
856 }
857 ring
858}
859
739860fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {
740861 let to_world = |p: Vector| -> [f32; 2] { [(p.x - 1024.0) / 512.0, -(p.y - 512.0) / 512.0] };
741862 let mut rings = Vec::new();
......@@ -803,6 +924,13 @@ fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {
803924 if clean.len() >= 2 && (clean[0][0] - clean.last().unwrap()[0]).hypot(clean[0][1] - clean.last().unwrap()[1]) <= 1e-5 {
804925 clean.pop();
805926 }
927 let mut clean = strip_forward_collinear(clean);
928 if clean.len() > MAX_RING_VERTS {
929 let len = clean.len();
930 clean = (0..MAX_RING_VERTS)
931 .map(|i| clean[(i * len) / MAX_RING_VERTS])
932 .collect();
933 }
806934 (clean.len() >= 3 && ring_signed_area(&clean).abs() > 1e-9).then_some(clean)
807935 }).collect()
808936}
......@@ -842,51 +970,95 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {
842970 let Some((m_idx, &m)) = hole
843971 .iter()
844972 .enumerate()
845 .max_by(|a, b| a.1[0].total_cmp(&b.1[0]))
973 .max_by(|a, b| a.1[0].total_cmp(&b.1[0]).then_with(|| a.1[1].total_cmp(&b.1[1])))
846974 else {
847975 return;
848976 };
977 let n_outer = outer.len();
978 if n_outer < 3 || hole.len() < 3 {
979 return;
980 }
849981 let mut best_x = f32::INFINITY;
850 let mut best_edge = None;
851 for i in 0..outer.len() {
852 let a = outer[i];
853 let b = outer[(i + 1) % outer.len()];
854 if (a[1] <= m[1] && b[1] > m[1]) || (b[1] <= m[1] && a[1] > m[1]) {
855 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
856 if x_int >= m[0] - 1e-6 && x_int < best_x {
857 best_x = x_int;
858 let p_idx = if a[0] >= b[0] { i } else { (i + 1) % outer.len() };
859 best_edge = Some((x_int, p_idx));
860 }
982 let mut best_hit: Option<(usize, bool)> = None;
983 let consider_hit = |best_x: &mut f32,
984 best_hit: &mut Option<(usize, bool)>,
985 x_int: f32,
986 p_idx: usize,
987 is_vertex_hit: bool| {
988 if x_int < m[0] - 1e-6 {
989 return;
990 }
991 let better = x_int < *best_x - 1e-6
992 || ((x_int - *best_x).abs() <= 1e-6 && is_vertex_hit && !best_hit.is_some_and(|(_, vh)| vh));
993 if better {
994 *best_x = x_int;
995 *best_hit = Some((p_idx, is_vertex_hit));
861996 }
862 }
863 let Some((x_int, mut p_idx)) = best_edge else {
864 return;
865997 };
866 let inter = [x_int, m[1]];
867 let mut p_pt = outer[p_idx];
868 let mut best_ang = f32::INFINITY;
869 for (vi, &v) in outer.iter().enumerate() {
870 if vi == p_idx || (v[0] - p_pt[0]).abs() + (v[1] - p_pt[1]).abs() < 1e-6 {
998 for i in 0..n_outer {
999 let j = (i + 1) % n_outer;
1000 let (a, b) = (outer[i], outer[j]);
1001 if (a[1] - m[1]).abs() <= 1e-6 && (b[1] - m[1]).abs() <= 1e-6 {
1002 consider_hit(&mut best_x, &mut best_hit, a[0], i, true);
1003 consider_hit(&mut best_x, &mut best_hit, b[0], j, true);
8711004 continue;
8721005 }
873 let cross = (p_pt[0] - m[0]) * (v[1] - m[1]) - (p_pt[1] - m[1]) * (v[0] - m[0]);
874 let tri_inside = if (p_pt[1] - m[1]).abs() > 1e-7 {
875 let orient = p_pt[1] > m[1];
876 if orient {
877 point_in_tri(v, m, inter, p_pt)
1006 // For CCW outer contours, a rightward ray exits across upward edges (`b.y > a.y`).
1007 // Checking `b.y > a.y` also avoids picking the wrong side of an existing bridge.
1008 if a[1] <= m[1] + 1e-6 && b[1] >= m[1] - 1e-6 && b[1] > a[1] + 1e-7 {
1009 if (a[1] - m[1]).abs() <= 1e-6 {
1010 consider_hit(&mut best_x, &mut best_hit, a[0], i, true);
1011 } else if (b[1] - m[1]).abs() <= 1e-6 {
1012 consider_hit(&mut best_x, &mut best_hit, b[0], j, true);
8781013 } else {
879 point_in_tri(v, m, p_pt, inter)
1014 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
1015 let p_idx = if a[0] >= b[0] { i } else { j };
1016 consider_hit(&mut best_x, &mut best_hit, x_int, p_idx, false);
8801017 }
881 } else {
882 false
883 };
884 if tri_inside && cross.abs() > 1e-7 {
885 let ang = ((v[1] - m[1]).atan2((v[0] - m[0]).max(1e-7))).abs();
886 if ang < best_ang {
887 best_ang = ang;
888 p_idx = vi;
889 p_pt = v;
1018 }
1019 }
1020 if best_hit.is_none() {
1021 for i in 0..n_outer {
1022 let j = (i + 1) % n_outer;
1023 let (a, b) = (outer[i], outer[j]);
1024 if (a[1] < m[1] && b[1] > m[1]) || (b[1] < m[1] && a[1] > m[1]) {
1025 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
1026 let p_idx = if a[0] >= b[0] { i } else { j };
1027 consider_hit(&mut best_x, &mut best_hit, x_int, p_idx, false);
1028 }
1029 }
1030 }
1031 let Some((p_initial_idx, is_vertex_hit)) = best_hit else {
1032 return;
1033 };
1034 let mut p_idx = p_initial_idx;
1035 if !is_vertex_hit {
1036 let inter = [best_x, m[1]];
1037 let p_initial = outer[p_initial_idx];
1038 let mut best_ang = (p_initial[1] - m[1]).abs().atan2((p_initial[0] - m[0]).max(0.0));
1039 let mut best_dist2 = (p_initial[0] - m[0]).powi(2) + (p_initial[1] - m[1]).powi(2);
1040 let orient = p_initial[1] > m[1];
1041 for (vi, &v) in outer.iter().enumerate() {
1042 if vi == p_initial_idx || same_pt_2d(v, p_initial) || same_pt_2d(v, m) {
1043 continue;
1044 }
1045 let tri_inside = if (p_initial[1] - m[1]).abs() > 1e-7 {
1046 if orient {
1047 point_in_tri(v, m, inter, p_initial)
1048 } else {
1049 point_in_tri(v, m, p_initial, inter)
1050 }
1051 } else {
1052 false
1053 };
1054 if tri_inside {
1055 let ang = (v[1] - m[1]).abs().atan2((v[0] - m[0]).max(0.0));
1056 let dist2 = (v[0] - m[0]).powi(2) + (v[1] - m[1]).powi(2);
1057 if ang < best_ang - 1e-6 || ((ang - best_ang).abs() <= 1e-6 && dist2 < best_dist2) {
1058 best_ang = ang;
1059 best_dist2 = dist2;
1060 p_idx = vi;
1061 }
8901062 }
8911063 }
8921064 }
......@@ -901,9 +1073,27 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {
9011073}
9021074
9031075fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
1076 if poly.len() < 3 || poly.len() > MAX_POLY_VERTS {
1077 return Vec::new();
1078 }
9041079 let mut idx: Vec<usize> = (0..poly.len()).collect();
905 let mut tris = Vec::with_capacity(poly.len().saturating_sub(2));
906 let mut guard = poly.len() * poly.len() + 16;
1080 let mut stripped = true;
1081 while stripped && idx.len() >= 3 {
1082 stripped = false;
1083 let mut i = 0;
1084 while i < idx.len() && idx.len() >= 4 {
1085 let n = idx.len();
1086 let (a, b, c) = (poly[idx[(i + n - 1) % n]], poly[idx[i]], poly[idx[(i + 1) % n]]);
1087 if is_forward_collinear(a, b, c) {
1088 idx.remove(i);
1089 stripped = true;
1090 } else {
1091 i += 1;
1092 }
1093 }
1094 }
1095 let mut tris = Vec::with_capacity(idx.len().saturating_sub(2));
1096 let mut guard = idx.len() * idx.len() + 16;
9071097 while idx.len() >= 3 && guard > 0 {
9081098 guard -= 1;
9091099 let n = idx.len();
......@@ -916,7 +1106,14 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
9161106 continue;
9171107 }
9181108 let has_inside = idx.iter().enumerate().any(|(j, &iv)| {
919 j != (i + n - 1) % n && j != i && j != (i + 1) % n && point_in_tri(poly[iv], a, b, c)
1109 if j == (i + n - 1) % n || j == i || j == (i + 1) % n {
1110 return false;
1111 }
1112 let p = poly[iv];
1113 if same_pt_2d(p, a) || same_pt_2d(p, b) || same_pt_2d(p, c) {
1114 return false;
1115 }
1116 point_in_tri(p, a, b, c)
9201117 });
9211118 if !has_inside {
9221119 tris.push([a, b, c]);
......@@ -925,6 +1122,30 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
9251122 break;
9261123 }
9271124 }
1125 if !clipped {
1126 for i in 0..n {
1127 let (ia, ib, ic) = (idx[(i + n - 1) % n], idx[i], idx[(i + 1) % n]);
1128 let (a, b, c) = (poly[ia], poly[ib], poly[ic]);
1129 let area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
1130 let degenerate = same_pt_2d(a, b) || same_pt_2d(b, c) || same_pt_2d(a, c);
1131 let collinear_empty = area2.abs() <= 1e-7
1132 && !idx.iter().enumerate().any(|(j, &iv)| {
1133 if j == (i + n - 1) % n || j == i || j == (i + 1) % n {
1134 return false;
1135 }
1136 let p = poly[iv];
1137 !same_pt_2d(p, a)
1138 && !same_pt_2d(p, b)
1139 && !same_pt_2d(p, c)
1140 && point_in_tri(p, a, b, c)
1141 });
1142 if degenerate || collinear_empty {
1143 idx.remove(i);
1144 clipped = true;
1145 break;
1146 }
1147 }
1148 }
9281149 if !clipped {
9291150 break;
9301151 }
......@@ -947,6 +1168,9 @@ pub fn build_text3d_mesh(
9471168 let z_front = depth;
9481169 let z_back = 0.0;
9491170 for g in &glyphs {
1171 if verts.len() >= MAX_TEXT3D_VERTS {
1172 break;
1173 }
9501174 let mut rings = flatten_glyph_rings(&g.commands);
9511175 if rings.is_empty() {
9521176 continue;
......@@ -1003,6 +1227,9 @@ pub fn build_text3d_mesh(
10031227 }
10041228 }
10051229 for oi in outers {
1230 if verts.len() >= MAX_TEXT3D_VERTS {
1231 break;
1232 }
10061233 let mut poly = rings[oi].clone();
10071234 if let Some(mut his) = hole_groups.remove(&oi) {
10081235 his.sort_by(|&a, &b| {
......@@ -1014,6 +1241,9 @@ pub fn build_text3d_mesh(
10141241 }
10151242 }
10161243 for [a, b, c] in ear_clip(&poly) {
1244 if verts.len() + 6 > MAX_TEXT3D_VERTS {
1245 break;
1246 }
10171247 let nf = [0.0, 0.0, 1.0];
10181248 verts.push(Vertex3D { pos: [a[0], a[1], z_front], normal: nf, uv: [0.0, 0.0] });
10191249 verts.push(Vertex3D { pos: [b[0], b[1], z_front], normal: nf, uv: [0.0, 0.0] });
......@@ -1182,7 +1412,7 @@ mod tests {
11821412 #[test]
11831413 fn cls_offsets_move_only_the_styled_characters() {
11841414 let base = render_bounds(&params("HH")).unwrap();
1185 let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05 }];
1415 let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05, text: String::new() }];
11861416 let mut p = params("HH");
11871417 p.cls = &cls;
11881418 let raised = render_bounds(&p).unwrap();
......@@ -1319,4 +1549,154 @@ mod tests {
13191549 assert!((max_z - 0.15).abs() < 1e-4 && min_z.abs() < 1e-4, "{min_z}..{max_z}");
13201550 assert!(verts.iter().any(|v| v.normal[2] == 0.0), "expected extruded side normals");
13211551 }
1552
1553 #[test]
1554 fn ear_clip_and_bridge_hole_triangulate_square_with_hole_exact_area() {
1555 let mut outer = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
1556 let hole = vec![[0.25, 0.25], [0.25, 0.75], [0.75, 0.75], [0.75, 0.25]];
1557 bridge_hole(&mut outer, &hole);
1558 let tris = ear_clip(&outer);
1559 assert!(!tris.is_empty());
1560 let area: f32 = tris
1561 .iter()
1562 .map(|[a, b, c]| 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])))
1563 .sum();
1564 assert!((area - 0.75).abs() < 1e-5, "expected exact 0.75 area, got {area}");
1565 }
1566
1567 #[test]
1568 fn text3d_holed_glyphs_o_and_b_preserve_exact_cap_area() {
1569 for (ch, expected_holes) in [('o', 1usize), ('B', 2usize)] {
1570 let txt = ch.to_string();
1571 let p = RichTextPlusParams {
1572 text: &txt,
1573 font_family: "Liberation Sans",
1574 font_style: "Regular",
1575 size_norm: 0.25,
1576 tracking: 1.0,
1577 line_spacing: 1.0,
1578 center: [0.5, 0.5],
1579 h_lcr: 0.0,
1580 v_tcb: 0.0,
1581 fill_rgba: [1.0; 4],
1582 write_on_start: 0.0,
1583 write_on_end: 1.0,
1584 shear_x: 0.0,
1585 cls: &[],
1586 outline_rgba: [0.0; 4],
1587 outline_thickness_norm: 0.0,
1588 outline_enabled: false,
1589 soft_fill: [0.0; 3],
1590 soft_outline: [0.0; 3],
1591 baseline_at_center: true,
1592 };
1593 let (glyphs, _) = layout_glyphs([2048, 1024], &p).unwrap();
1594 assert_eq!(glyphs.len(), 1);
1595 let mut rings = flatten_glyph_rings(&glyphs[0].commands);
1596 let mut depths = vec![0usize; rings.len()];
1597 for i in 0..rings.len() {
1598 let pt = rings[i][0];
1599 for j in 0..rings.len() {
1600 if i != j && point_in_ring(pt, &rings[j]) {
1601 depths[i] += 1;
1602 }
1603 }
1604 }
1605 assert_eq!(depths.iter().filter(|&&d| d % 2 == 1).count(), expected_holes, "hole count for {ch}");
1606 for (i, ring) in rings.iter_mut().enumerate() {
1607 if (depths[i] % 2 == 0) != (ring_signed_area(ring) > 0.0) {
1608 ring.reverse();
1609 }
1610 }
1611 let expected_area: f32 = rings.iter().map(|r| ring_signed_area(r)).sum();
1612
1613 let verts = build_text3d_mesh(&p, 0.0);
1614 assert_eq!(verts.len() % 3, 0);
1615 let cap_area: f32 = verts
1616 .chunks_exact(3)
1617 .map(|t| {
1618 let (a, b, c) = (t[0].pos, t[1].pos, t[2].pos);
1619 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
1620 })
1621 .sum();
1622 assert!(
1623 (cap_area - expected_area).abs() < 1e-4,
1624 "glyph '{ch}' cap area {cap_area} != ring signed area {expected_area}"
1625 );
1626 }
1627 }
1628
1629 #[test]
1630 fn crlf_strips_cr_and_keeps_cls_indices_aligned() {
1631 let cls = [StyledClsRule {
1632 prop_id: 102,
1633 start: 4,
1634 end: 5,
1635 value: 0.24,
1636 text: String::new(),
1637 }];
1638 let make = |text: &'static str| RichTextPlusParams {
1639 text,
1640 font_family: "Liberation Sans",
1641 font_style: "Regular",
1642 size_norm: 0.08,
1643 tracking: 1.0,
1644 line_spacing: 1.0,
1645 center: [0.5, 0.5],
1646 h_lcr: 0.0,
1647 v_tcb: 0.0,
1648 fill_rgba: [1.0; 4],
1649 write_on_start: 0.0,
1650 write_on_end: 1.0,
1651 shear_x: 0.0,
1652 cls: &cls,
1653 outline_rgba: [0.0; 4],
1654 outline_thickness_norm: 0.0,
1655 outline_enabled: false,
1656 soft_fill: [0.0; 3],
1657 soft_outline: [0.0; 3],
1658 baseline_at_center: false,
1659 };
1660 let lf = rasterize_text_plus_rich([320, 180], &make("HH\nHH"), 0);
1661 let crlf = rasterize_text_plus_rich([320, 180], &make("HH\r\nHH"), 0);
1662 assert_eq!(lf, crlf, "CRLF must render identically to LF without .notdef boxes or CLS drift");
1663 }
1664
1665 #[test]
1666 fn non_finite_and_huge_softness_values_do_not_overflow() {
1667 let p = RichTextPlusParams {
1668 text: "A",
1669 font_family: "Liberation Sans",
1670 font_style: "Regular",
1671 size_norm: 0.12,
1672 tracking: 1.0,
1673 line_spacing: 1.0,
1674 center: [0.5, 0.5],
1675 h_lcr: 0.0,
1676 v_tcb: 0.0,
1677 fill_rgba: [1.0; 4],
1678 write_on_start: 0.0,
1679 write_on_end: 1.0,
1680 shear_x: 0.0,
1681 cls: &[],
1682 outline_rgba: [1.0, 0.0, 0.0, 1.0],
1683 outline_thickness_norm: 0.05,
1684 outline_enabled: true,
1685 soft_fill: [f32::NAN, f32::INFINITY, 0.0],
1686 soft_outline: [1e30, -5.0, 0.0],
1687 baseline_at_center: false,
1688 };
1689 let (sz, _, rgba) = rasterize_text_plus_rich([160, 90], &p, 0);
1690 assert!(sz[0] <= 480 && sz[1] <= 270 && !rgba.is_empty());
1691 }
1692
1693 #[test]
1694 fn runtime_font_registration_resolves_custom_family_alias() {
1695 let base = Font::find("Helvetica", "Regular").expect("system fallback font");
1696 let bytes = base.data.clone();
1697 register_font_bytes(bytes.clone());
1698 register_font_bytes_with_name("FissionRuntimeAliasFont", bytes);
1699 let resolved = Font::find("FissionRuntimeAliasFont", "Regular").expect("registered alias font");
1700 assert!(resolved.face().glyph_index('A').is_some());
1701 }
13221702}
crates/model/src/comp.rs+3-1
......@@ -380,13 +380,15 @@ impl Node {
380380}
381381
382382/// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`).
383/// Common Fusion property IDs: `1350` = Character X offset, `1351` = Character Y offset.
383/// Common Fusion property IDs: `100` = Font family, `102` = Size, `109` = Font style,
384/// `1330` = Character shear X, `1350` = Character X offset, `1351` = Character Y offset.
384385#[derive(Clone, Debug, PartialEq)]
385386pub struct ClsEntry {
386387 pub prop_id: u32,
387388 pub start: usize,
388389 pub end: usize,
389390 pub value: f32,
391 pub text: String,
390392}
391393
392394/// Fusion `Shake` procedural modifier (`Source = "X"` / `"Y"` / `"Value"` / `"Position"`).
crates/model/src/comp/load.rs+158-33
......@@ -84,6 +84,7 @@ impl Comp {
8484 let mut tracker_aliases: Vec<(String, String)> = Vec::new();
8585 let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new();
8686 let mut instanced_from: Vec<(NodeId, String)> = Vec::new();
87 let mut macro_owner: HashMap<NodeId, NodeId> = HashMap::new();
8788
8889 if let Some(tools) = root.get_table("Tools") {
8990 parse_tools_table(
......@@ -103,6 +104,7 @@ impl Comp {
103104 &mut tracker_aliases,
104105 &mut macro_defaults,
105106 &mut instanced_from,
107 &mut macro_owner,
106108 );
107109 }
108110
......@@ -113,7 +115,7 @@ impl Comp {
113115 }
114116 }
115117
116 let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &node_by_name);
118 let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &macro_owner);
117119
118120 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
119121 for (target_op, target_param, val) in macro_defaults {
......@@ -298,16 +300,10 @@ impl Comp {
298300/// enclosing macros, its nested macros) or at top level; a name that only exists inside an
299301/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was
300302/// cleared here so saving keeps the original text.
301fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap<String, NodeId>) -> HashSet<(String, String)> {
302 let mut owner: HashMap<NodeId, NodeId> = HashMap::new();
303 for m in nodes.iter().filter(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) {
304 let Some(inner) = m.raw.get_table("Tools") else { continue };
305 for (key, _) in &inner.entries {
306 let LuaKey::Str(child) = key else { continue };
307 if let Some(&cid) = node_by_name.get(child).filter(|&&c| nodes[c.0].internal) {
308 owner.insert(cid, m.id);
309 }
310 }
303fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>) -> HashSet<(String, String)> {
304 let mut by_name: HashMap<&str, Vec<NodeId>> = HashMap::new();
305 for n in nodes.iter() {
306 by_name.entry(n.name.as_str()).or_default().push(n.id);
311307 }
312308 let encloses = |outer: NodeId, mut inner: NodeId| {
313309 loop {
......@@ -320,15 +316,23 @@ fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap<String, No
320316 }
321317 }
322318 };
319 let in_scope = |n_scope: NodeId, t: NodeId| -> bool {
320 if !nodes[t.0].internal {
321 return true;
322 }
323 owner
324 .get(&t)
325 .is_some_and(|&t_scope| encloses(t_scope, n_scope) || encloses(n_scope, t_scope))
326 };
323327 let mut cleared = Vec::new();
324328 for n in nodes.iter().filter(|n| n.internal) {
325329 let Some(&n_scope) = owner.get(&n.id) else { continue };
326330 for (port, b) in &n.inputs {
327 let Some(&t) = b.source_op.as_ref().and_then(|s| node_by_name.get(s)) else { continue };
328 if let Some(&t_scope) = owner.get(&t) {
329 if !encloses(t_scope, n_scope) && !encloses(n_scope, t_scope) {
330 cleared.push((n.id, port.clone()));
331 }
331 let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else {
332 continue;
333 };
334 if !candidates.iter().any(|&t| in_scope(n_scope, t)) {
335 cleared.push((n.id, port.clone()));
332336 }
333337 }
334338 }
......@@ -514,6 +518,7 @@ fn parse_tools_table(
514518 tracker_aliases: &mut Vec<(String, String)>,
515519 macro_defaults: &mut Vec<(String, String, ParamValue)>,
516520 instanced_from: &mut Vec<(NodeId, String)>,
521 macro_owner: &mut HashMap<NodeId, NodeId>,
517522) {
518523 for (key, val) in &tools.entries {
519524 let LuaKey::Str(name) = key else { continue };
......@@ -572,31 +577,46 @@ fn parse_tools_table(
572577 }
573578 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {
574579 if let Some(in_tbl) = tbl.get_table("Inputs") {
575 if let Some(txt) = in_tbl
576 .get_table("Text")
577 .or_else(|| in_tbl.get_table("StyledText"))
578 .and_then(|s| s.get_str("Value"))
579 {
580 text_modifiers.insert(name.clone(), txt.to_owned());
580 if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) {
581 if let Some(txt) = txt_in
582 .get_table("Value")
583 .and_then(|v| v.get_str("Value"))
584 .or_else(|| txt_in.get_str("Value"))
585 {
586 text_modifiers.insert(name.clone(), txt.to_owned());
587 }
581588 }
582589 if let Some(arr) = in_tbl
583 .get_table("CharacterLevelStyling")
590 .get_table("RightClickHereToAnimateCharacterLevelStyling")
591 .or_else(|| in_tbl.get_table("CharacterLevelStyling"))
584592 .and_then(|c| c.get_table("Value"))
585593 .and_then(|v| v.get_table("Array"))
586594 {
587595 let mut entries = Vec::new();
588596 for (_, ev) in &arr.entries {
589597 let Some(et) = ev.as_table() else { continue };
590 let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue };
591 let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue };
592 let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue };
593 let Some(val) = et.get_f64("Value") else { continue };
594 entries.push(ClsEntry {
595 prop_id: pid.round().max(0.0) as u32,
596 start: s.round().max(0.0) as usize,
597 end: e.round().max(0.0) as usize,
598 value: val as f32,
599 });
598 if let Some(param) = et.get_f64("Parameter") {
599 entries.push(ClsEntry {
600 prop_id: param.round().max(0.0) as u32,
601 start: et.get_f64("First").unwrap_or(0.0).round().max(0.0) as usize,
602 end: et.get_f64("Last").unwrap_or(0.0).round().max(0.0) as usize,
603 value: et.get_f64("Value").unwrap_or(0.0) as f32,
604 text: et.get_str("String").unwrap_or("").to_owned(),
605 });
606 } else if let (Some(pid), Some(s), Some(e), Some(val)) = (
607 et.get_index(1).and_then(LuaValue::as_f64),
608 et.get_index(2).and_then(LuaValue::as_f64),
609 et.get_index(3).and_then(LuaValue::as_f64),
610 et.get_f64("Value"),
611 ) {
612 entries.push(ClsEntry {
613 prop_id: pid.round().max(0.0) as u32,
614 start: s.round().max(0.0) as usize,
615 end: e.round().max(0.0) as usize,
616 value: val as f32,
617 text: et.get_str("String").unwrap_or("").to_owned(),
618 });
619 }
600620 }
601621 if !entries.is_empty() {
602622 text_cls.insert(name.clone(), entries);
......@@ -787,11 +807,13 @@ fn parse_tools_table(
787807 tracker_aliases,
788808 macro_defaults,
789809 instanced_from,
810 macro_owner,
790811 );
791812 }
792813 }
793814
794815 let mut macro_output = None;
816 let mut macro_inner_start = None;
795817 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
796818 let mut out_name: Option<String> = None;
797819 if let Some(outs) = tbl.get_table("Outputs") {
......@@ -805,6 +827,7 @@ fn parse_tools_table(
805827 }
806828 }
807829 let inner_start = nodes.len();
830 macro_inner_start = Some(inner_start);
808831 if let Some(inner_tools) = tbl.get_table("Tools") {
809832 parse_tools_table(
810833 inner_tools,
......@@ -823,6 +846,7 @@ fn parse_tools_table(
823846 tracker_aliases,
824847 macro_defaults,
825848 instanced_from,
849 macro_owner,
826850 );
827851 }
828852 if let Some(oname) = out_name {
......@@ -835,6 +859,11 @@ fn parse_tools_table(
835859 }
836860
837861 let id = NodeId(nodes.len());
862 if let Some(inner_start) = macro_inner_start {
863 for nid_raw in inner_start..id.0 {
864 macro_owner.entry(NodeId(nid_raw)).or_insert(id);
865 }
866 }
838867 // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name.
839868 if !is_internal || !node_by_name.contains_key(name) {
840869 node_by_name.insert(name.clone(), id);
......@@ -856,3 +885,99 @@ fn parse_tools_table(
856885 });
857886 }
858887}
888
889#[cfg(test)]
890mod tests {
891 use super::*;
892
893 #[test]
894 fn styled_text_cls_right_click_rules_parse_inside_macro_operator() {
895 let src = r#"
896Composition {
897 Tools = ordered() {
898 MyMacro = MacroOperator {
899 Outputs = ordered() {
900 Output1 = InstanceOutput { SourceOp = "Txt1", Source = "Output", },
901 },
902 Tools = ordered() {
903 Txt1 = TextPlus {
904 Inputs = {
905 StyledText = Input { SourceOp = "CLS1", Source = "Value", },
906 },
907 },
908 CLS1 = StyledTextCLS {
909 Inputs = {
910 Text = Input { Value = StyledText { Value = "Hello" }, },
911 RightClickHereToAnimateCharacterLevelStyling = Input {
912 Value = StyledTextCLS_Data {
913 Array = {
914 { Parameter = 100, First = 0, Last = 1, String = "Arial", },
915 { Parameter = 102, First = 2, Last = 4, Value = 0.25, },
916 },
917 },
918 },
919 },
920 },
921 },
922 },
923 },
924}
925"#;
926 let comp = Comp::from_fusion_str(src).expect("parse macro StyledTextCLS");
927 let txt = comp.nodes.iter().find(|n| n.name == "Txt1").expect("Txt1");
928 assert_eq!(comp.text_modifiers.get("CLS1").map(String::as_str), Some("Hello"));
929 let entries = comp.text_cls_entries(txt, "StyledText");
930 assert_eq!(entries.len(), 2);
931 assert_eq!(entries[0].prop_id, 100);
932 assert_eq!(entries[0].text, "Arial");
933 assert_eq!(entries[1].prop_id, 102);
934 assert!((entries[1].value - 0.25).abs() < 1e-6);
935 }
936
937 #[test]
938 fn clear_cross_macro_wires_handles_duplicate_internal_names_across_sibling_macros() {
939 let src = r#"
940Composition {
941 Tools = ordered() {
942 MacroA = MacroOperator {
943 Outputs = ordered() {
944 Output1 = InstanceOutput { SourceOp = "OutA", Source = "Output", },
945 },
946 Tools = ordered() {
947 Background1 = Background { },
948 OnlyInA = Background { },
949 OutA = Merge {
950 Inputs = {
951 Background = Input { SourceOp = "Background1", Source = "Output", },
952 Foreground = Input { SourceOp = "OnlyInB", Source = "Output", },
953 },
954 },
955 },
956 },
957 MacroB = MacroOperator {
958 Outputs = ordered() {
959 Output1 = InstanceOutput { SourceOp = "OutB", Source = "Output", },
960 },
961 Tools = ordered() {
962 Background1 = Background { },
963 OnlyInB = Background { },
964 OutB = Merge {
965 Inputs = {
966 Background = Input { SourceOp = "Background1", Source = "Output", },
967 Foreground = Input { SourceOp = "OnlyInA", Source = "Output", },
968 },
969 },
970 },
971 },
972 },
973}
974"#;
975 let comp = Comp::from_fusion_str(src).expect("parse sibling macros with duplicate inner names");
976 let out_a = comp.nodes.iter().find(|n| n.name == "OutA").expect("OutA");
977 let out_b = comp.nodes.iter().find(|n| n.name == "OutB").expect("OutB");
978 assert_eq!(out_a.connected_node("Background"), Some("Background1"));
979 assert_eq!(out_b.connected_node("Background"), Some("Background1"));
980 assert_eq!(out_a.connected_node("Foreground"), None, "OutA -> OnlyInB must be cleared");
981 assert_eq!(out_b.connected_node("Foreground"), None, "OutB -> OnlyInA must be cleared");
982 }
983}