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 @@...@@ -1,5 +1,3 @@
1use std::sync::Arc;
2
3use super::*;1use super::*;
4use crate::text_engine::{RichTextPlusParams, StyledClsRule};2use crate::text_engine::{RichTextPlusParams, StyledClsRule};
53
...@@ -33,46 +31,9 @@ struct ResolvedTextInputs {...@@ -33,46 +31,9 @@ struct ResolvedTextInputs {
33 baseline_at_center: bool,31 baseline_at_center: bool,
34}32}
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
73fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, expr: &ExprEngine) -> ResolvedTextInputs {34fn 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);35 let text_str = comp.eval_text(node, "StyledText", time, "", expr);
75 let mut cls_rules: Vec<StyledClsRule> = comp36 let cls_rules: Vec<StyledClsRule> = comp
76 .text_cls_entries(node, "StyledText")37 .text_cls_entries(node, "StyledText")
77 .iter()38 .iter()
78 .map(|e| StyledClsRule {39 .map(|e| StyledClsRule {
...@@ -80,17 +41,9 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp...@@ -80,17 +41,9 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp
80 start: e.start,41 start: e.start,
81 end: e.end,42 end: e.end,
82 value: e.value,43 value: e.value,
83 text: String::new(),44 text: e.text.clone(),
84 })45 })
85 .collect();46 .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
95 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue").to_owned();48 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue").to_owned();
96 let font_style = node.static_str("Style").unwrap_or("Regular").to_owned();49 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...@@ -188,6 +141,41 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp
188}141}
189142
190impl ResolvedTextInputs {143impl 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
191 fn as_rich_params(&self) -> RichTextPlusParams<'_> {179 fn as_rich_params(&self) -> RichTextPlusParams<'_> {
192 let is_text_outline = self.outline_enabled && self.elem2_shape != 2;180 let is_text_outline = self.outline_enabled && self.elem2_shape != 2;
193 let outline_rgba = self.outline_rgba.map(|c| c * self.elem2_opacity);181 let outline_rgba = self.outline_rgba.map(|c| c * self.elem2_opacity);
...@@ -640,10 +628,10 @@ impl Engine {...@@ -640,10 +628,10 @@ impl Engine {
640 }628 }
641 }629 }
642630
643 let br = outline_rgba[0] * elem2_opacity;631 let br = outline_rgba[0];
644 let bg = outline_rgba[1] * elem2_opacity;632 let bg = outline_rgba[1];
645 let bb = outline_rgba[2] * elem2_opacity;633 let bb = outline_rgba[2];
646 let ba = outline_rgba[3] * elem2_opacity;634 let ba = outline_rgba[3];
647 for i in 0..(tw * th) {635 for i in 0..(tw * th) {
648 let cov = box_cov[i];636 let cov = box_cov[i];
649 if cov <= 1e-4 {637 if cov <= 1e-4 {
...@@ -823,6 +811,7 @@ impl Engine {...@@ -823,6 +811,7 @@ impl Engine {
823 let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len());811 let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len());
824 for ms in &mesh_specs {812 for ms in &mesh_specs {
825 let mut mesh_shape = ms.shape.clone();813 let mut mesh_shape = ms.shape.clone();
814 let mut custom_mesh_key = None;
826 let mut diffuse_col = ms.diffuse_col;815 let mut diffuse_col = ms.diffuse_col;
827 let tex = if let Some(t3d) = &ms.text3d {816 let tex = if let Some(t3d) = &ms.text3d {
828 let tnode = comp.node(t3d.node_id);817 let tnode = comp.node(t3d.node_id);
...@@ -835,11 +824,27 @@ impl Engine {...@@ -835,11 +824,27 @@ impl Engine {
835 };824 };
836 if ext_depth.abs() > 1e-4 {825 if ext_depth.abs() > 1e-4 {
837 let ti = resolve_text_inputs(comp, tnode, time, true, &self.expr);826 let ti = resolve_text_inputs(comp, tnode, time, true, &self.expr);
838 ti.text_str.hash(&mut h_scene);827 let bevel_depth = comp.eval_number(
839 ti.size_norm.to_bits().hash(&mut h_scene);828 tnode,
840 ext_depth.to_bits().hash(&mut h_scene);829 "Extrusion.BevelDepth",
841 let verts = crate::text_engine::build_text3d_mesh(&ti.as_rich_params(), ext_depth);830 time,
842 let custom = crate::scene3d::ShapeKind::CustomMesh(Arc::new(verts));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);
843 mesh_shape = match &ms.shape {848 mesh_shape = match &ms.shape {
844 crate::scene3d::ShapeKind::WithMaterialFx { fx, .. } => {849 crate::scene3d::ShapeKind::WithMaterialFx { fx, .. } => {
845 crate::scene3d::ShapeKind::WithMaterialFx { inner: Box::new(custom), fx: *fx }850 crate::scene3d::ShapeKind::WithMaterialFx { inner: Box::new(custom), fx: *fx }
...@@ -880,6 +885,7 @@ impl Engine {...@@ -880,6 +885,7 @@ impl Engine {
880 draw_meshes.push(crate::scene3d::DrawMesh {885 draw_meshes.push(crate::scene3d::DrawMesh {
881 world: ms.world,886 world: ms.world,
882 shape: mesh_shape,887 shape: mesh_shape,
888 custom_mesh_key,
883 tex,889 tex,
884 diffuse_col,890 diffuse_col,
885 specular_col: ms.specular_col,891 specular_col: ms.specular_col,
...@@ -1090,4 +1096,136 @@ Composition {...@@ -1090,4 +1096,136 @@ Composition {
1090 "frame 5 larger Radius must invalidate Renderer3D cache and cover far more pixels (f0={c0}, f5={c5})"1096 "frame 5 larger Radius must invalidate Renderer3D cache and cover far more pixels (f0={c0}, f5={c5})"
1091 );1097 );
1092 }1098 }
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 }
1093}1231}
crates/engine/src/scene3d/mod.rs+125-7
...@@ -36,6 +36,8 @@ pub struct Scene3DRenderer {...@@ -36,6 +36,8 @@ pub struct Scene3DRenderer {
36 pipelines: [[wgpu::RenderPipeline; 2]; 2],36 pipelines: [[wgpu::RenderPipeline; 2]; 2],
37 sampler: wgpu::Sampler,37 sampler: wgpu::Sampler,
38 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,38 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>>>>,
39 shadow_pipeline: wgpu::RenderPipeline,41 shadow_pipeline: wgpu::RenderPipeline,
40 /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass.42 /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass.
41 shadow_caster_bgl: wgpu::BindGroupLayout,43 shadow_caster_bgl: wgpu::BindGroupLayout,
...@@ -71,8 +73,6 @@ struct GpuMesh {...@@ -71,8 +73,6 @@ struct GpuMesh {
71 vbuf: wgpu::Buffer,73 vbuf: wgpu::Buffer,
72 ibuf: wgpu::Buffer,74 ibuf: wgpu::Buffer,
73 idx_count: u32,75 idx_count: u32,
74 /// Keeps a `CustomMesh` allocation alive: `ShapeKind::hash_into` hashes its address.
75 _shape: ShapeKind,
76}76}
7777
78/// Bounded map evicting the least recently used entry.78/// Bounded map evicting the least recently used entry.
...@@ -87,6 +87,16 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {...@@ -87,6 +87,16 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
87 Self { cap, tick: 0, entries: HashMap::new() }87 Self { cap, tick: 0, entries: HashMap::new() }
88 }88 }
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
90 fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V {100 fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V {
91 self.tick += 1;101 self.tick += 1;
92 if let Some((used, v)) = self.entries.get_mut(&key) {102 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> {...@@ -102,6 +112,11 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
102 self.entries.insert(key, (self.tick, v.clone()));112 self.entries.insert(key, (self.tick, v.clone()));
103 v113 v
104 }114 }
115
116 fn clear(&mut self) {
117 self.entries.clear();
118 self.tick = 0;
119 }
105}120}
106121
107#[derive(Clone)]122#[derive(Clone)]
...@@ -283,7 +298,6 @@ impl ShapeKind {...@@ -283,7 +298,6 @@ impl ShapeKind {
283 ShapeKind::CustomMesh(verts) => {298 ShapeKind::CustomMesh(verts) => {
284 6u8.hash(h);299 6u8.hash(h);
285 verts.len().hash(h);300 verts.len().hash(h);
286 (verts.as_ptr() as usize).hash(h);
287 let step = (verts.len() / 64).max(1);301 let step = (verts.len() / 64).max(1);
288 for v in verts.iter().step_by(step) {302 for v in verts.iter().step_by(step) {
289 bytemuck::bytes_of(v).hash(h);303 bytemuck::bytes_of(v).hash(h);
...@@ -377,6 +391,8 @@ pub struct SceneLights {...@@ -377,6 +391,8 @@ pub struct SceneLights {
377pub struct DrawMesh {391pub struct DrawMesh {
378 pub world: Mat4,392 pub world: Mat4,
379 pub shape: ShapeKind,393 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>,
380 pub tex: Option<CachedTexture>,396 pub tex: Option<CachedTexture>,
381 pub diffuse_col: [f32; 4],397 pub diffuse_col: [f32; 4],
382 pub specular_col: [f32; 3],398 pub specular_col: [f32; 3],
...@@ -389,9 +405,16 @@ pub struct DrawMesh {...@@ -389,9 +405,16 @@ pub struct DrawMesh {
389 pub displace: Option<DisplaceHeightmap>,405 pub displace: Option<DisplaceHeightmap>,
390}406}
391407
392fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {408fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option<u64>, aspect: f32, wireframe: bool) -> MeshKey {
393 use std::hash::{DefaultHasher, Hasher};409 use std::hash::{DefaultHasher, Hash, Hasher};
394 let mut h = DefaultHasher::new();410 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 }
395 base_shape.hash_into(&mut h);418 base_shape.hash_into(&mut h);
396 let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 };419 let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 };
397 (h.finish(), aspect_bits, wireframe)420 (h.finish(), aspect_bits, wireframe)
...@@ -627,6 +650,7 @@ impl Scene3DRenderer {...@@ -627,6 +650,7 @@ impl Scene3DRenderer {
627 pipelines,650 pipelines,
628 sampler,651 sampler,
629 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),652 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),
653 text3d_mesh_cache: Mutex::new(Lru::new(MESH_CACHE_CAP)),
630 shadow_pipeline,654 shadow_pipeline,
631 shadow_caster_bgl,655 shadow_caster_bgl,
632 shadow_face_bgl,656 shadow_face_bgl,
...@@ -635,6 +659,41 @@ impl Scene3DRenderer {...@@ -635,6 +659,41 @@ impl Scene3DRenderer {
635 }659 }
636 }660 }
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
638 #[allow(clippy::too_many_arguments)]697 #[allow(clippy::too_many_arguments)]
639 pub fn render_meshes(698 pub fn render_meshes(
640 &self,699 &self,
...@@ -818,13 +877,13 @@ impl Scene3DRenderer {...@@ -818,13 +877,13 @@ impl Scene3DRenderer {
818 mapped_at_creation: false,877 mapped_at_creation: false,
819 });878 });
820 queue.write_buffer(&ibuf, 0, ibytes);879 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 })
822 };881 };
823 // Heightmap contents are not part of the key, so displaced meshes are never cached.882 // Heightmap contents are not part of the key, so displaced meshes are never cached.
824 let gpu_mesh = if m.displace.is_some() {883 let gpu_mesh = if m.displace.is_some() {
825 upload()884 upload()
826 } else {885 } 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);
828 self.meshes.lock().unwrap().get_or_insert_with(key, upload)887 self.meshes.lock().unwrap().get_or_insert_with(key, upload)
829 };888 };
830 let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else {889 let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else {
...@@ -1192,6 +1251,7 @@ mod tests {...@@ -1192,6 +1251,7 @@ mod tests {
1192 inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }),1251 inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }),
1193 fx: MaterialFx { wireframe, ..Default::default() },1252 fx: MaterialFx { wireframe, ..Default::default() },
1194 },1253 },
1254 custom_mesh_key: None,
1195 tex: None,1255 tex: None,
1196 diffuse_col: [1.0; 4],1256 diffuse_col: [1.0; 4],
1197 specular_col: [1.0; 3],1257 specular_col: [1.0; 3],
...@@ -1365,4 +1425,62 @@ mod tests {...@@ -1365,4 +1425,62 @@ mod tests {
1365 assert_eq!(uncast, unreceived, "either flag alone removes the shadow entirely");1425 assert_eq!(uncast, unreceived, "either flag alone removes the shadow entirely");
1366 assert_eq!(uncast, unreceived_by_material, "a material shader owns the receiver flag");1426 assert_eq!(uncast, unreceived_by_material, "a material shader owns the receiver flag");
1367 }1427 }
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 }
1368}1486}
crates/engine/src/text_engine.rs+449-69
...@@ -4,8 +4,8 @@...@@ -4,8 +4,8 @@
44
5use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag};5use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag};
6use rustybuzz::{Face, Feature, UnicodeBuffer, Variation};6use rustybuzz::{Face, Feature, UnicodeBuffer, Variation};
7use std::collections::HashMap;7use std::collections::{HashMap, HashSet};
8use std::sync::{Arc, Mutex, OnceLock};8use std::sync::{Arc, Mutex, OnceLock, RwLock};
9use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};9use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};
1010
11/// Tried in order when the requested family is not installed.11/// Tried in order when the requested family is not installed.
...@@ -25,13 +25,17 @@ pub struct Font {...@@ -25,13 +25,17 @@ pub struct Font {
2525
26impl Font {26impl Font {
27 /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the27 /// 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.
29 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {30 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 = font_cache().lock().unwrap();
31 let mut cache = CACHE.get_or_init(Default::default).lock().unwrap();
32 cache32 cache
33 .entry((family.to_owned(), style.to_owned()))33 .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 })
35 .clone()39 .clone()
36 }40 }
3741
...@@ -44,15 +48,58 @@ impl Font {...@@ -44,15 +48,58 @@ impl Font {
44 }48 }
45}49}
4650
47fn database() -> &'static fontdb::Database {51fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {
48 static DB: OnceLock<fontdb::Database> = OnceLock::new();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();
49 DB.get_or_init(|| {63 DB.get_or_init(|| {
50 let mut db = fontdb::Database::new();64 let mut db = fontdb::Database::new();
65 #[cfg(not(target_arch = "wasm32"))]
51 db.load_system_fonts();66 db.load_system_fonts();
52 db67 RwLock::new(db)
53 })68 })
54}69}
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
56/// CSS-style weight and italic flag for a Fusion style name.103/// CSS-style weight and italic flag for a Fusion style name.
57pub fn parse_style(style: &str) -> (u16, bool) {104pub fn parse_style(style: &str) -> (u16, bool) {
58 let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();105 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> {...@@ -94,13 +141,18 @@ fn metric_alias(family: &str) -> Option<&'static str> {
94 }141 }
95}142}
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> {
98 let (weight, italic) = parse_style(style);150 let (weight, italic) = parse_style(style);
99 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();151 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
100 let id = std::iter::once(family)152 let id = std::iter::once(family)
101 .chain(metric_alias(family))153 .chain(metric_alias(family))
102 .chain(FALLBACK_FAMILIES)154 .chain(FALLBACK_FAMILIES)
103 .find_map(|name| pick(db, name, &wanted, weight, italic))155 .find_map(|name| pick(db, aliases, name, &wanted, weight, italic))
104 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))156 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
105 .or_else(|| db.faces().map(|f| f.id).next())?;157 .or_else(|| db.faces().map(|f| f.id).next())?;
106 let info = db.face(id)?;158 let info = db.face(id)?;
...@@ -112,13 +164,24 @@ fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {...@@ -112,13 +164,24 @@ fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {
112164
113/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest165/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest
114/// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere.166/// 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> {
116 if family.is_empty() {175 if family.is_empty() {
117 return None;176 return None;
118 }177 }
178 let alias_ids = aliases.get(&family.to_ascii_lowercase());
119 let mut candidates: Vec<&fontdb::FaceInfo> = db179 let mut candidates: Vec<&fontdb::FaceInfo> = db
120 .faces()180 .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 })
122 .collect();185 .collect();
123 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));186 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));
124 let first = candidates.first()?;187 let first = candidates.first()?;
...@@ -137,13 +200,23 @@ fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, it...@@ -137,13 +200,23 @@ fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, it
137 if let Some(face) = exact {200 if let Some(face) = exact {
138 return Some(face.id);201 return Some(face.id);
139 }202 }
140 let name = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family))?.0.as_str();203 if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) {
141 db.query(&fontdb::Query {204 return db.query(&fontdb::Query {
142 families: &[fontdb::Family::Name(name)],205 families: &[fontdb::Family::Name(name)],
143 weight: fontdb::Weight(weight),206 weight: fontdb::Weight(weight),
144 style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },207 style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
145 ..Default::default()208 ..Default::default()
146 })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)
147}220}
148221
149/// Ascent and descent (both positive) in em units, from `hhea`.222/// Ascent and descent (both positive) in em units, from `hhea`.
...@@ -415,7 +488,9 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec...@@ -415,7 +488,9 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
415488
416 let mut lines = Vec::new();489 let mut lines = Vec::new();
417 let mut char_cursor = 0usize;490 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);
419 let line_chars: Vec<char> = line_str.chars().collect();494 let line_chars: Vec<char> = line_str.chars().collect();
420 let mut shaped_runs: Vec<(usize, usize, Arc<Font>, f32, ShapedLine)> = Vec::new();495 let mut shaped_runs: Vec<(usize, usize, Arc<Font>, f32, ShapedLine)> = Vec::new();
421 let mut line_max_size = 0.0_f32;496 let mut line_max_size = 0.0_f32;
...@@ -493,7 +568,7 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec...@@ -493,7 +568,7 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
493 descent: max_desc,568 descent: max_desc,
494 top_anchor: max_top_anchor,569 top_anchor: max_top_anchor,
495 });570 });
496 char_cursor += line_chars.len() + 1;571 char_cursor += raw_char_len + 1;
497 }572 }
498573
499 let cx = params.center[0] * wf;574 let cx = params.center[0] * wf;
...@@ -558,8 +633,11 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec...@@ -558,8 +633,11 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
558}633}
559634
560fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {635fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {
561 let r = (sigma * 3.0).ceil().min(64.0) as isize;636 if !sigma.is_finite() || sigma < 0.05 {
562 if r <= 0 || 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 {
563 return (0, vec![1.0]);641 return (0, vec![1.0]);
564 }642 }
565 let inv2s2 = 1.0 / (2.0 * sigma * sigma);643 let inv2s2 = 1.0 / (2.0 * sigma * sigma);
...@@ -652,12 +730,13 @@ pub fn rasterize_text_plus_rich(...@@ -652,12 +730,13 @@ pub fn rasterize_text_plus_rich(
652730
653 // Calibrated on Fusion 21.1 (`text_diag` & `text_diag2`): sigma = SoftnessX * (W / 1280).731 // Calibrated on Fusion 21.1 (`text_diag` & `text_diag2`): sigma = SoftnessX * (W / 1280).
654 let soft_scale = w as f32 / 1280.0;732 let soft_scale = w as f32 / 1280.0;
655 let sx1 = (params.soft_fill[0].max(0.0)) * soft_scale;733 let clamp_sigma = |v: f32| if v.is_finite() { (v.max(0.0) * soft_scale).min(64.0 / 3.0) } else { 0.0 };
656 let sy1 = (params.soft_fill[1].max(0.0)) * soft_scale;734 let sx1 = clamp_sigma(params.soft_fill[0]);
657 let sx2 = (params.soft_outline[0].max(0.0)) * soft_scale;735 let sy1 = clamp_sigma(params.soft_fill[1]);
658 let sy2 = (params.soft_outline[1].max(0.0)) * soft_scale;736 let sx2 = clamp_sigma(params.soft_outline[0]);
659 let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil() as i32;737 let sy2 = clamp_sigma(params.soft_outline[1]);
660 let eff_pad = dod_pad.max(blur_pad);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
662 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);741 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);
663 let mut grow = |c: &Coverage, pad: i32| {742 let mut grow = |c: &Coverage, pad: i32| {
...@@ -736,6 +815,48 @@ pub fn rasterize_text_plus_rich(...@@ -736,6 +815,48 @@ pub fn rasterize_text_plus_rich(
736 ([tw as u32, th as u32], [origin_x, origin_y], out)815 ([tw as u32, th as u32], [origin_x, origin_y], out)
737}816}
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
739fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {860fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {
740 let to_world = |p: Vector| -> [f32; 2] { [(p.x - 1024.0) / 512.0, -(p.y - 512.0) / 512.0] };861 let to_world = |p: Vector| -> [f32; 2] { [(p.x - 1024.0) / 512.0, -(p.y - 512.0) / 512.0] };
741 let mut rings = Vec::new();862 let mut rings = Vec::new();
...@@ -803,6 +924,13 @@ fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {...@@ -803,6 +924,13 @@ fn flatten_glyph_rings(commands: &[Command]) -> Vec<Vec<[f32; 2]>> {
803 if clean.len() >= 2 && (clean[0][0] - clean.last().unwrap()[0]).hypot(clean[0][1] - clean.last().unwrap()[1]) <= 1e-5 {924 if clean.len() >= 2 && (clean[0][0] - clean.last().unwrap()[0]).hypot(clean[0][1] - clean.last().unwrap()[1]) <= 1e-5 {
804 clean.pop();925 clean.pop();
805 }926 }
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 }
806 (clean.len() >= 3 && ring_signed_area(&clean).abs() > 1e-9).then_some(clean)934 (clean.len() >= 3 && ring_signed_area(&clean).abs() > 1e-9).then_some(clean)
807 }).collect()935 }).collect()
808}936}
...@@ -842,51 +970,95 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {...@@ -842,51 +970,95 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {
842 let Some((m_idx, &m)) = hole970 let Some((m_idx, &m)) = hole
843 .iter()971 .iter()
844 .enumerate()972 .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])))
846 else {974 else {
847 return;975 return;
848 };976 };
977 let n_outer = outer.len();
978 if n_outer < 3 || hole.len() < 3 {
979 return;
980 }
849 let mut best_x = f32::INFINITY;981 let mut best_x = f32::INFINITY;
850 let mut best_edge = None;982 let mut best_hit: Option<(usize, bool)> = None;
851 for i in 0..outer.len() {983 let consider_hit = |best_x: &mut f32,
852 let a = outer[i];984 best_hit: &mut Option<(usize, bool)>,
853 let b = outer[(i + 1) % outer.len()];985 x_int: f32,
854 if (a[1] <= m[1] && b[1] > m[1]) || (b[1] <= m[1] && a[1] > m[1]) {986 p_idx: usize,
855 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);987 is_vertex_hit: bool| {
856 if x_int >= m[0] - 1e-6 && x_int < best_x {988 if x_int < m[0] - 1e-6 {
857 best_x = x_int;989 return;
858 let p_idx = if a[0] >= b[0] { i } else { (i + 1) % outer.len() };990 }
859 best_edge = Some((x_int, p_idx));991 let better = x_int < *best_x - 1e-6
860 }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));
861 }996 }
862 }
863 let Some((x_int, mut p_idx)) = best_edge else {
864 return;
865 };997 };
866 let inter = [x_int, m[1]];998 for i in 0..n_outer {
867 let mut p_pt = outer[p_idx];999 let j = (i + 1) % n_outer;
868 let mut best_ang = f32::INFINITY;1000 let (a, b) = (outer[i], outer[j]);
869 for (vi, &v) in outer.iter().enumerate() {1001 if (a[1] - m[1]).abs() <= 1e-6 && (b[1] - m[1]).abs() <= 1e-6 {
870 if vi == p_idx || (v[0] - p_pt[0]).abs() + (v[1] - p_pt[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);
871 continue;1004 continue;
872 }1005 }
873 let cross = (p_pt[0] - m[0]) * (v[1] - m[1]) - (p_pt[1] - m[1]) * (v[0] - m[0]);1006 // For CCW outer contours, a rightward ray exits across upward edges (`b.y > a.y`).
874 let tri_inside = if (p_pt[1] - m[1]).abs() > 1e-7 {1007 // Checking `b.y > a.y` also avoids picking the wrong side of an existing bridge.
875 let orient = p_pt[1] > m[1];1008 if a[1] <= m[1] + 1e-6 && b[1] >= m[1] - 1e-6 && b[1] > a[1] + 1e-7 {
876 if orient {1009 if (a[1] - m[1]).abs() <= 1e-6 {
877 point_in_tri(v, m, inter, p_pt)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);
878 } else {1013 } 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);
880 }1017 }
881 } else {1018 }
882 false1019 }
883 };1020 if best_hit.is_none() {
884 if tri_inside && cross.abs() > 1e-7 {1021 for i in 0..n_outer {
885 let ang = ((v[1] - m[1]).atan2((v[0] - m[0]).max(1e-7))).abs();1022 let j = (i + 1) % n_outer;
886 if ang < best_ang {1023 let (a, b) = (outer[i], outer[j]);
887 best_ang = ang;1024 if (a[1] < m[1] && b[1] > m[1]) || (b[1] < m[1] && a[1] > m[1]) {
888 p_idx = vi;1025 let x_int = a[0] + (m[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
889 p_pt = v;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 }
890 }1062 }
891 }1063 }
892 }1064 }
...@@ -901,9 +1073,27 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {...@@ -901,9 +1073,27 @@ fn bridge_hole(outer: &mut Vec<[f32; 2]>, hole: &[[f32; 2]]) {
901}1073}
9021074
903fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {1075fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
1076 if poly.len() < 3 || poly.len() > MAX_POLY_VERTS {
1077 return Vec::new();
1078 }
904 let mut idx: Vec<usize> = (0..poly.len()).collect();1079 let mut idx: Vec<usize> = (0..poly.len()).collect();
905 let mut tris = Vec::with_capacity(poly.len().saturating_sub(2));1080 let mut stripped = true;
906 let mut guard = poly.len() * poly.len() + 16;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;
907 while idx.len() >= 3 && guard > 0 {1097 while idx.len() >= 3 && guard > 0 {
908 guard -= 1;1098 guard -= 1;
909 let n = idx.len();1099 let n = idx.len();
...@@ -916,7 +1106,14 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {...@@ -916,7 +1106,14 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
916 continue;1106 continue;
917 }1107 }
918 let has_inside = idx.iter().enumerate().any(|(j, &iv)| {1108 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)
920 });1117 });
921 if !has_inside {1118 if !has_inside {
922 tris.push([a, b, c]);1119 tris.push([a, b, c]);
...@@ -925,6 +1122,30 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {...@@ -925,6 +1122,30 @@ fn ear_clip(poly: &[[f32; 2]]) -> Vec<[[f32; 2]; 3]> {
925 break;1122 break;
926 }1123 }
927 }1124 }
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 }
928 if !clipped {1149 if !clipped {
929 break;1150 break;
930 }1151 }
...@@ -947,6 +1168,9 @@ pub fn build_text3d_mesh(...@@ -947,6 +1168,9 @@ pub fn build_text3d_mesh(
947 let z_front = depth;1168 let z_front = depth;
948 let z_back = 0.0;1169 let z_back = 0.0;
949 for g in &glyphs {1170 for g in &glyphs {
1171 if verts.len() >= MAX_TEXT3D_VERTS {
1172 break;
1173 }
950 let mut rings = flatten_glyph_rings(&g.commands);1174 let mut rings = flatten_glyph_rings(&g.commands);
951 if rings.is_empty() {1175 if rings.is_empty() {
952 continue;1176 continue;
...@@ -1003,6 +1227,9 @@ pub fn build_text3d_mesh(...@@ -1003,6 +1227,9 @@ pub fn build_text3d_mesh(
1003 }1227 }
1004 }1228 }
1005 for oi in outers {1229 for oi in outers {
1230 if verts.len() >= MAX_TEXT3D_VERTS {
1231 break;
1232 }
1006 let mut poly = rings[oi].clone();1233 let mut poly = rings[oi].clone();
1007 if let Some(mut his) = hole_groups.remove(&oi) {1234 if let Some(mut his) = hole_groups.remove(&oi) {
1008 his.sort_by(|&a, &b| {1235 his.sort_by(|&a, &b| {
...@@ -1014,6 +1241,9 @@ pub fn build_text3d_mesh(...@@ -1014,6 +1241,9 @@ pub fn build_text3d_mesh(
1014 }1241 }
1015 }1242 }
1016 for [a, b, c] in ear_clip(&poly) {1243 for [a, b, c] in ear_clip(&poly) {
1244 if verts.len() + 6 > MAX_TEXT3D_VERTS {
1245 break;
1246 }
1017 let nf = [0.0, 0.0, 1.0];1247 let nf = [0.0, 0.0, 1.0];
1018 verts.push(Vertex3D { pos: [a[0], a[1], z_front], normal: nf, uv: [0.0, 0.0] });1248 verts.push(Vertex3D { pos: [a[0], a[1], z_front], normal: nf, uv: [0.0, 0.0] });
1019 verts.push(Vertex3D { pos: [b[0], b[1], z_front], normal: nf, uv: [0.0, 0.0] });1249 verts.push(Vertex3D { pos: [b[0], b[1], z_front], normal: nf, uv: [0.0, 0.0] });
...@@ -1182,7 +1412,7 @@ mod tests {...@@ -1182,7 +1412,7 @@ mod tests {
1182 #[test]1412 #[test]
1183 fn cls_offsets_move_only_the_styled_characters() {1413 fn cls_offsets_move_only_the_styled_characters() {
1184 let base = render_bounds(&params("HH")).unwrap();1414 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() }];
1186 let mut p = params("HH");1416 let mut p = params("HH");
1187 p.cls = &cls;1417 p.cls = &cls;
1188 let raised = render_bounds(&p).unwrap();1418 let raised = render_bounds(&p).unwrap();
...@@ -1319,4 +1549,154 @@ mod tests {...@@ -1319,4 +1549,154 @@ mod tests {
1319 assert!((max_z - 0.15).abs() < 1e-4 && min_z.abs() < 1e-4, "{min_z}..{max_z}");1549 assert!((max_z - 0.15).abs() < 1e-4 && min_z.abs() < 1e-4, "{min_z}..{max_z}");
1320 assert!(verts.iter().any(|v| v.normal[2] == 0.0), "expected extruded side normals");1550 assert!(verts.iter().any(|v| v.normal[2] == 0.0), "expected extruded side normals");
1321 }1551 }
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 }
1322}1702}
crates/model/src/comp.rs+3-1
...@@ -380,13 +380,15 @@ impl Node {...@@ -380,13 +380,15 @@ impl Node {
380}380}
381381
382/// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`).382/// 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.
384#[derive(Clone, Debug, PartialEq)]385#[derive(Clone, Debug, PartialEq)]
385pub struct ClsEntry {386pub struct ClsEntry {
386 pub prop_id: u32,387 pub prop_id: u32,
387 pub start: usize,388 pub start: usize,
388 pub end: usize,389 pub end: usize,
389 pub value: f32,390 pub value: f32,
391 pub text: String,
390}392}
391393
392/// Fusion `Shake` procedural modifier (`Source = "X"` / `"Y"` / `"Value"` / `"Position"`).394/// Fusion `Shake` procedural modifier (`Source = "X"` / `"Y"` / `"Value"` / `"Position"`).
crates/model/src/comp/load.rs+158-33
...@@ -84,6 +84,7 @@ impl Comp {...@@ -84,6 +84,7 @@ impl Comp {
84 let mut tracker_aliases: Vec<(String, String)> = Vec::new();84 let mut tracker_aliases: Vec<(String, String)> = Vec::new();
85 let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new();85 let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new();
86 let mut instanced_from: Vec<(NodeId, String)> = Vec::new();86 let mut instanced_from: Vec<(NodeId, String)> = Vec::new();
87 let mut macro_owner: HashMap<NodeId, NodeId> = HashMap::new();
8788
88 if let Some(tools) = root.get_table("Tools") {89 if let Some(tools) = root.get_table("Tools") {
89 parse_tools_table(90 parse_tools_table(
...@@ -103,6 +104,7 @@ impl Comp {...@@ -103,6 +104,7 @@ impl Comp {
103 &mut tracker_aliases,104 &mut tracker_aliases,
104 &mut macro_defaults,105 &mut macro_defaults,
105 &mut instanced_from,106 &mut instanced_from,
107 &mut macro_owner,
106 );108 );
107 }109 }
108110
...@@ -113,7 +115,7 @@ impl Comp {...@@ -113,7 +115,7 @@ impl Comp {
113 }115 }
114 }116 }
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
118 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.120 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
119 for (target_op, target_param, val) in macro_defaults {121 for (target_op, target_param, val) in macro_defaults {
...@@ -298,16 +300,10 @@ impl Comp {...@@ -298,16 +300,10 @@ impl Comp {
298/// enclosing macros, its nested macros) or at top level; a name that only exists inside an300/// enclosing macros, its nested macros) or at top level; a name that only exists inside an
299/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was301/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was
300/// cleared here so saving keeps the original text.302/// 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)> {303fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>) -> HashSet<(String, String)> {
302 let mut owner: HashMap<NodeId, NodeId> = HashMap::new();304 let mut by_name: HashMap<&str, Vec<NodeId>> = HashMap::new();
303 for m in nodes.iter().filter(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) {305 for n in nodes.iter() {
304 let Some(inner) = m.raw.get_table("Tools") else { continue };306 by_name.entry(n.name.as_str()).or_default().push(n.id);
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 }
311 }307 }
312 let encloses = |outer: NodeId, mut inner: NodeId| {308 let encloses = |outer: NodeId, mut inner: NodeId| {
313 loop {309 loop {
...@@ -320,15 +316,23 @@ fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap<String, No...@@ -320,15 +316,23 @@ fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap<String, No
320 }316 }
321 }317 }
322 };318 };
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 };
323 let mut cleared = Vec::new();327 let mut cleared = Vec::new();
324 for n in nodes.iter().filter(|n| n.internal) {328 for n in nodes.iter().filter(|n| n.internal) {
325 let Some(&n_scope) = owner.get(&n.id) else { continue };329 let Some(&n_scope) = owner.get(&n.id) else { continue };
326 for (port, b) in &n.inputs {330 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 };331 let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else {
328 if let Some(&t_scope) = owner.get(&t) {332 continue;
329 if !encloses(t_scope, n_scope) && !encloses(n_scope, t_scope) {333 };
330 cleared.push((n.id, port.clone()));334 if !candidates.iter().any(|&t| in_scope(n_scope, t)) {
331 }335 cleared.push((n.id, port.clone()));
332 }336 }
333 }337 }
334 }338 }
...@@ -514,6 +518,7 @@ fn parse_tools_table(...@@ -514,6 +518,7 @@ fn parse_tools_table(
514 tracker_aliases: &mut Vec<(String, String)>,518 tracker_aliases: &mut Vec<(String, String)>,
515 macro_defaults: &mut Vec<(String, String, ParamValue)>,519 macro_defaults: &mut Vec<(String, String, ParamValue)>,
516 instanced_from: &mut Vec<(NodeId, String)>,520 instanced_from: &mut Vec<(NodeId, String)>,
521 macro_owner: &mut HashMap<NodeId, NodeId>,
517) {522) {
518 for (key, val) in &tools.entries {523 for (key, val) in &tools.entries {
519 let LuaKey::Str(name) = key else { continue };524 let LuaKey::Str(name) = key else { continue };
...@@ -572,31 +577,46 @@ fn parse_tools_table(...@@ -572,31 +577,46 @@ fn parse_tools_table(
572 }577 }
573 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {578 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {
574 if let Some(in_tbl) = tbl.get_table("Inputs") {579 if let Some(in_tbl) = tbl.get_table("Inputs") {
575 if let Some(txt) = in_tbl580 if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) {
576 .get_table("Text")581 if let Some(txt) = txt_in
577 .or_else(|| in_tbl.get_table("StyledText"))582 .get_table("Value")
578 .and_then(|s| s.get_str("Value"))583 .and_then(|v| v.get_str("Value"))
579 {584 .or_else(|| txt_in.get_str("Value"))
580 text_modifiers.insert(name.clone(), txt.to_owned());585 {
586 text_modifiers.insert(name.clone(), txt.to_owned());
587 }
581 }588 }
582 if let Some(arr) = in_tbl589 if let Some(arr) = in_tbl
583 .get_table("CharacterLevelStyling")590 .get_table("RightClickHereToAnimateCharacterLevelStyling")
591 .or_else(|| in_tbl.get_table("CharacterLevelStyling"))
584 .and_then(|c| c.get_table("Value"))592 .and_then(|c| c.get_table("Value"))
585 .and_then(|v| v.get_table("Array"))593 .and_then(|v| v.get_table("Array"))
586 {594 {
587 let mut entries = Vec::new();595 let mut entries = Vec::new();
588 for (_, ev) in &arr.entries {596 for (_, ev) in &arr.entries {
589 let Some(et) = ev.as_table() else { continue };597 let Some(et) = ev.as_table() else { continue };
590 let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue };598 if let Some(param) = et.get_f64("Parameter") {
591 let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue };599 entries.push(ClsEntry {
592 let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue };600 prop_id: param.round().max(0.0) as u32,
593 let Some(val) = et.get_f64("Value") else { continue };601 start: et.get_f64("First").unwrap_or(0.0).round().max(0.0) as usize,
594 entries.push(ClsEntry {602 end: et.get_f64("Last").unwrap_or(0.0).round().max(0.0) as usize,
595 prop_id: pid.round().max(0.0) as u32,603 value: et.get_f64("Value").unwrap_or(0.0) as f32,
596 start: s.round().max(0.0) as usize,604 text: et.get_str("String").unwrap_or("").to_owned(),
597 end: e.round().max(0.0) as usize,605 });
598 value: val as f32,606 } else if let (Some(pid), Some(s), Some(e), Some(val)) = (
599 });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 }
600 }620 }
601 if !entries.is_empty() {621 if !entries.is_empty() {
602 text_cls.insert(name.clone(), entries);622 text_cls.insert(name.clone(), entries);
...@@ -787,11 +807,13 @@ fn parse_tools_table(...@@ -787,11 +807,13 @@ fn parse_tools_table(
787 tracker_aliases,807 tracker_aliases,
788 macro_defaults,808 macro_defaults,
789 instanced_from,809 instanced_from,
810 macro_owner,
790 );811 );
791 }812 }
792 }813 }
793814
794 let mut macro_output = None;815 let mut macro_output = None;
816 let mut macro_inner_start = None;
795 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {817 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
796 let mut out_name: Option<String> = None;818 let mut out_name: Option<String> = None;
797 if let Some(outs) = tbl.get_table("Outputs") {819 if let Some(outs) = tbl.get_table("Outputs") {
...@@ -805,6 +827,7 @@ fn parse_tools_table(...@@ -805,6 +827,7 @@ fn parse_tools_table(
805 }827 }
806 }828 }
807 let inner_start = nodes.len();829 let inner_start = nodes.len();
830 macro_inner_start = Some(inner_start);
808 if let Some(inner_tools) = tbl.get_table("Tools") {831 if let Some(inner_tools) = tbl.get_table("Tools") {
809 parse_tools_table(832 parse_tools_table(
810 inner_tools,833 inner_tools,
...@@ -823,6 +846,7 @@ fn parse_tools_table(...@@ -823,6 +846,7 @@ fn parse_tools_table(
823 tracker_aliases,846 tracker_aliases,
824 macro_defaults,847 macro_defaults,
825 instanced_from,848 instanced_from,
849 macro_owner,
826 );850 );
827 }851 }
828 if let Some(oname) = out_name {852 if let Some(oname) = out_name {
...@@ -835,6 +859,11 @@ fn parse_tools_table(...@@ -835,6 +859,11 @@ fn parse_tools_table(
835 }859 }
836860
837 let id = NodeId(nodes.len());861 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 }
838 // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name.867 // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name.
839 if !is_internal || !node_by_name.contains_key(name) {868 if !is_internal || !node_by_name.contains_key(name) {
840 node_by_name.insert(name.clone(), id);869 node_by_name.insert(name.clone(), id);
...@@ -856,3 +885,99 @@ fn parse_tools_table(...@@ -856,3 +885,99 @@ fn parse_tools_table(
856 });885 });
857 }886 }
858}887}
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}