1use super::*;
2
3/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`].
4pub struct TextPlusParams<'a> {
5 pub text: &'a str,
6 pub font_family: &'a str,
7 pub font_style: &'a str,
8 pub size_norm: f32, // Fusion Size (fraction of canvas width, ~0.08 default)
9 pub tracking: f32, // Fusion CharacterSpacing (1.0 = normal)
10 pub line_spacing: f32, // Fusion LineSpacing (1.0 = normal)
11 pub center: [f32; 2], // Fusion normalized Y-up (0.5, 0.5)
12 pub h_lcr: f32, // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center, +1=Right
13 pub v_tcb: f32, // Fusion VerticalTopCenterBottom: -1=Top, 0=Center, +1=Bottom
14 pub fill_rgba: [f32; 4],
15 pub write_on_start: f32,
16 pub write_on_end: f32,
17 pub shear_x: f32, // Fusion CharacterShearX
18 pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides
19 pub outline_rgba: [f32; 4], // Fusion Element 2 color, already scaled by Opacity2
20 pub outline_width_px: f32, // Fusion Thickness2 as a full stroke width; 0 disables the outline
21}
22
23/// Rasterizes a `TextPlus` layer (outline under fill) into premultiplied RGBA8 with automatic
24/// Domain-of-Definition (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a
25/// downstream `Transform`) are never clipped; `dod_pad` adds margin for decoration drawn from
26/// the result. Returns `(tex_size, dod_origin_px, rgba)`.
27pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) {
28 let [w, h] = dims;
29 let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
30 if params.text.is_empty() || !params.size_norm.is_finite() || params.size_norm <= 1e-4 {
31 return empty();
32 }
33
34 // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on!
35 let total_chars = params.text.chars().count();
36 let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize;
37 let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize;
38 if c_start >= c_end || c_start >= total_chars {
39 return empty();
40 }
41 let Some(font) = text_engine::Font::find(params.font_family, params.font_style) else {
42 return empty();
43 };
44 let face = font.face();
45
46 // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units).
47 let mut cls_dx = vec![0.0_f32; total_chars];
48 let mut cls_dy = vec![0.0_f32; total_chars];
49 for e in params.cls {
50 let s = e.start.min(total_chars);
51 let end = e.end.saturating_add(1).min(total_chars);
52 for i in s..end {
53 if e.prop_id == 1350 {
54 cls_dx[i] = e.value;
55 } else if e.prop_id == 1351 {
56 cls_dy[i] = e.value;
57 }
58 }
59 }
60
61 // Fusion Text+ `Size` defines the line box (ascent + descent) as `0.8 * Size * W`
62 // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text
63 // on 16:9, square, and vertical frames).
64 let line_box_px = params.size_norm * w as f32 * 0.8;
65 let (ascent_em, descent_em) = text_engine::vertical_metrics(&face);
66 let font_px = (line_box_px / (ascent_em + descent_em).max(0.5)).clamp(6.0, 1024.0);
67 let descent = descent_em * font_px;
68
69 // Fusion `CharacterSpacing = 1.0` adds nothing; each +1.0 adds `Size * W` between characters,
70 // independent of the font (probed on Fusion 21.1 with Liberation Sans, 8 gaps, 1.3 and 2.0).
71 let extra_track = (params.tracking - 1.0) * params.size_norm * w as f32;
72
73 let lines: Vec<&str> = params.text.split('\n').collect();
74 let line_height = (line_box_px * params.line_spacing.max(0.05)).max(1.0);
75
76 // Fusion Center is Y-up; convert to top-down pixel coordinates.
77 let cx = params.center[0] * w as f32;
78 let cy = (1.0 - params.center[1]) * h as f32;
79
80 // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy).
81 let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5;
82 let top_anchor = (font_px - descent).max(0.0);
83 let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor;
84 let baseline_0 = cy + top_anchor - v_frac * block_h;
85 let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5;
86
87 let outlined = params.outline_width_px > 1e-3 && params.outline_rgba[3] > 0.0;
88
89 // Pass 1: vector-rasterize every visible glyph and collect exact bounds to expand the DoD.
90 let mut placed = Vec::new();
91 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);
92 let mut grow = |c: &text_engine::Coverage, pad: i32| {
93 min_x = min_x.min(c.left.saturating_sub(pad));
94 min_y = min_y.min(c.top.saturating_sub(pad));
95 max_x = max_x.max(c.left.saturating_add(c.width as i32).saturating_add(pad));
96 max_y = max_y.max(c.top.saturating_add(c.height as i32).saturating_add(pad));
97 };
98
99 let mut char_cursor = 0usize;
100 for (li, line_str) in lines.iter().enumerate() {
101 let shaped = text_engine::shape_line(&face, line_str, font_px, extra_track);
102 let start_x = cx - shaped.width * h_frac;
103 let baseline_y = baseline_0 + (li as f32) * line_height;
104 for g in &shaped.glyphs {
105 let idx = char_cursor + g.char_index;
106 if idx < c_start || idx >= c_end {
107 continue;
108 }
109 let origin = [
110 start_x + g.x + cls_dx[idx] * w as f32,
111 baseline_y - g.y - cls_dy[idx] * w as f32,
112 ];
113 let path = text_engine::glyph_path(&font, &face, g.id, font_px, origin, -params.shear_x);
114 let fill = text_engine::fill(&path);
115 let line = if outlined { text_engine::stroke(&path, params.outline_width_px) } else { None };
116 if let Some(c) = &fill {
117 grow(c, dod_pad);
118 }
119 if let Some(c) = &line {
120 grow(c, dod_pad);
121 }
122 placed.push((fill, line));
123 }
124 char_cursor += line_str.chars().count() + 1; // + '\n' separator
125 }
126
127 // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded.
128 let origin_x = min_x.max(-(w as i32));
129 let origin_y = min_y.max(-(h as i32));
130 let end_x = max_x.min((w as i32) * 2);
131 let end_y = max_y.min((h as i32) * 2);
132 let tw = (end_x - origin_x).max(1) as usize;
133 let th = (end_y - origin_y).max(1) as usize;
134
135 let mut fill_plane = vec![0u8; tw * th];
136 let mut line_plane = vec![0.0_f32; if outlined { tw * th } else { 0 }];
137 for (fill, line) in &placed {
138 if let Some(c) = fill {
139 blit_max(c, [origin_x, origin_y], [tw, th], |i, a| fill_plane[i] = fill_plane[i].max(a));
140 }
141 if let Some(c) = line {
142 blit_max(c, [origin_x, origin_y], [tw, th], |i, a| line_plane[i] = line_plane[i].max(a as f32 / 255.0));
143 }
144 }
145
146 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
147 let mut out = vec![0u8; tw * th * 4];
148 for (i, px) in out.chunks_exact_mut(4).enumerate() {
149 let fa = fill_plane[i] as f32 / 255.0 * fc[3];
150 let oa = if outlined { line_plane[i] * oc[3] } else { 0.0 };
151 if fa <= 0.0 && oa <= 0.0 {
152 continue;
153 }
154 let under = 1.0 - fa;
155 for k in 0..3 {
156 let v = fc[k] * fa + oc[k] * oa * under;
157 px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
158 }
159 px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
160 }
161
162 ([tw as u32, th as u32], [origin_x, origin_y], out)
163}
164
165/// Calls `f(plane_index, coverage)` for every non-zero coverage pixel that lands inside the plane.
166fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut f: impl FnMut(usize, u8)) {
167 for y in 0..c.height as i32 {
168 let py = c.top + y - origin[1];
169 if py < 0 || py >= plane[1] as i32 {
170 continue;
171 }
172 for x in 0..c.width as i32 {
173 let px = c.left + x - origin[0];
174 let a = c.data[(y as u32 * c.width + x as u32) as usize];
175 if a > 0 && px >= 0 && px < plane[0] as i32 {
176 f(py as usize * plane[0] + px as usize, a);
177 }
178 }
179 }
180}
181
182/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. Points and handles
183/// are offsets from `center`, rotated counter-clockwise by `angle_deg` in isotropic frame-width units.
184pub fn rasterize_polyline_mask(
185 dims: [u32; 2],
186 points: &[PolyPoint],
187 center: [f32; 2],
188 angle_deg: f32,
189 invert: bool,
190 level: f32,
191) -> Vec<u8> {
192 let [w, h] = dims;
193 let mut out = vec![0u8; (w as usize) * (h as usize) * 4];
194 if points.len() < 2 {
195 return out;
196 }
197 let aspect = w as f32 / (h as f32).max(1.0);
198 let (s, c) = angle_deg.to_radians().sin_cos();
199 let to_px = |x: f64, y: f64| -> [f32; 2] {
200 let (x, y) = (x as f32, y as f32 / aspect);
201 let (rx, ry) = (x * c - y * s, (x * s + y * c) * aspect);
202 [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32]
203 };
204 let mut cmds = Vec::new();
205 let p0 = to_px(points[0].x, points[0].y);
206 cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1])));
207 for i in 0..points.len() {
208 let a = &points[i];
209 let b = &points[(i + 1) % points.len()];
210 let c1 = to_px(a.x + a.rx, a.y + a.ry);
211 let c2 = to_px(b.x + b.lx, b.y + b.ly);
212 let p = to_px(b.x, b.y);
213 if a.linear && b.linear {
214 cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1])));
215 } else {
216 cmds.push(zeno::Command::CurveTo(
217 zeno::Vector::new(c1[0], c1[1]),
218 zeno::Vector::new(c2[0], c2[1]),
219 zeno::Vector::new(p[0], p[1]),
220 ));
221 }
222 }
223 cmds.push(zeno::Command::Close);
224
225 let mut mask = vec![0u8; (w as usize) * (h as usize)];
226 let mut scratch = zeno::Scratch::new();
227 let placement = zeno::Mask::with_scratch(&cmds, &mut scratch)
228 .size(w, h)
229 .origin(zeno::Origin::TopLeft)
230 .render_into(&mut mask, None);
231 let _ = placement;
232 for (i, &cov) in mask.iter().enumerate() {
233 let mut a = cov as f32 / 255.0;
234 if invert { a = 1.0 - a; }
235 let b = (a * level * 255.0).clamp(0.0, 255.0) as u8;
236 out[i * 4] = b;
237 out[i * 4 + 1] = b;
238 out[i * 4 + 2] = b;
239 out[i * 4 + 3] = b;
240 }
241 out
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 fn corner(x: f64, y: f64) -> PolyPoint {
249 PolyPoint { x, y, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }
250 }
251
252 #[test]
253 fn polyline_mask_angle_rotates_ccw_around_center_in_isotropic_units() {
254 // 2:1 canvas; rect is 0.4 frame-widths wide and 0.1 frame-heights tall around Center.
255 let rect = [corner(-0.2, -0.05), corner(0.2, -0.05), corner(0.2, 0.05), corner(-0.2, 0.05)];
256 let on = |px: &[u8], x: usize, y: usize| px[(y * 200 + x) * 4 + 3] > 200;
257
258 let flat = rasterize_polyline_mask([200, 100], &rect, [0.5, 0.5], 0.0, false, 1.0);
259 assert!(on(&flat, 130, 50) && on(&flat, 100, 50));
260 assert!(!on(&flat, 100, 20) && !on(&flat, 100, 80));
261
262 // 90 degrees: 0.2 width = 0.4 height, so the bar spans y 10..90 and is 0.05 width thick.
263 let tall = rasterize_polyline_mask([200, 100], &rect, [0.5, 0.5], 90.0, false, 1.0);
264 assert!(on(&tall, 100, 50) && on(&tall, 100, 20) && on(&tall, 100, 80));
265 assert!(!on(&tall, 130, 50) && !on(&tall, 70, 50) && !on(&tall, 110, 50));
266 }
267}