authoravatarclover caruso<git@paperclover.net>2026-12-01 14:46:24-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:56:10-08:00
logde5c6ae72b3c41dc1fa498b17a13ad09d826fd45
treef602fe60e2e1a0600f13606c54b837915dc415d6
parent77ddd505408d3e7449f36f8c597a005212f5c4cd
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): optimize TextPlus font/glyph caching and core WGSL compute shaders


4 files changed, 1009 insertions(+), 328 deletions(-)

crates/engine/src/shaders/composite.wgsl+118-60
...@@ -8,50 +8,58 @@...@@ -8,50 +8,58 @@
8fn bg_op(@builtin(global_invocation_id) gid: vec3<u32>) {8fn bg_op(@builtin(global_invocation_id) gid: vec3<u32>) {
9 let dims = textureDimensions(dst_tex);9 let dims = textureDimensions(dst_tex);
10 if (gid.x >= dims.x || gid.y >= dims.y) { return; }10 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
11 let fu = pix_to_fu(gid.xy, dims);
12 let kind = i32(u.p[4].x + 0.5);11 let kind = i32(u.p[4].x + 0.5);
13 let has_lut = u.p[4].y > 0.5;12 let has_mask = u.p[5].z;
13 if (kind == 0 && has_mask < 0.5) {
14 store_dst(vec2<i32>(gid.xy), u.p[0]);
15 return;
16 }
14 var col = u.p[0];17 var col = u.p[0];
15 if (kind == 1) {18 if (kind != 0) {
16 col = mix(u.p[0], u.p[1], fu.x);19 let fu = pix_to_fu(gid.xy, dims);
17 } else if (kind == 2) {20 let has_lut = u.p[4].y > 0.5;
18 col = mix(u.p[2], u.p[0], fu.y);21 if (kind == 1) {
19 } else if (kind == 3) {22 col = mix(u.p[0], u.p[1], fu.x);
20 let top = mix(u.p[0], u.p[1], fu.x);23 } else if (kind == 2) {
21 let bot = mix(u.p[2], u.p[3], fu.x);24 col = mix(u.p[2], u.p[0], fu.y);
22 col = mix(bot, top, fu.y);25 } else if (kind == 3) {
23 } else if (kind >= 4) {26 let top = mix(u.p[0], u.p[1], fu.x);
24 let fdims = vec2<f32>(dims);27 let bot = mix(u.p[2], u.p[3], fu.x);
25 let p_px = fu * fdims;28 col = mix(bot, top, fu.y);
26 let s_px = u.p[4].zw * fdims;
27 let e_px = u.p[5].xy * fdims;
28 let d_px = e_px - s_px;
29 var t = 0.0;
30 if (kind == 5) {
31 let r = max(length(d_px), 1e-5);
32 t = clamp(length(p_px - s_px) / r, 0.0, 1.0);
33 } else if (kind == 6) {
34 let rel = p_px - s_px;
35 let a_p = select(0.0, atan2(rel.y, rel.x), dot(rel, rel) > 1e-12);
36 let a_d = select(0.0, atan2(d_px.y, d_px.x), dot(d_px, d_px) > 1e-12);
37 t = fract((a_p - a_d) / 6.28318530718);
38 } else if (kind == 7) {
39 let len2 = max(dot(d_px, d_px), 1e-6);
40 t = clamp(abs(dot(p_px - s_px, d_px) / len2), 0.0, 1.0);
41 } else {
42 let len2 = max(dot(d_px, d_px), 1e-6);
43 t = clamp(dot(p_px - s_px, d_px) / len2, 0.0, 1.0);
44 }
45 if (has_lut) {
46 let lut_w = max(f32(textureDimensions(src_b).x), 1.0);
47 let lut_u = (0.5 + t * (lut_w - 1.0)) / lut_w;
48 col = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u, 0.5), 0.0);
49 } else {29 } else {
50 col = mix(u.p[0], u.p[1], t);30 let fdims = vec2<f32>(dims);
31 let p_px = fu * fdims;
32 let s_px = u.p[4].zw * fdims;
33 let e_px = u.p[5].xy * fdims;
34 let d_px = e_px - s_px;
35 var t = 0.0;
36 if (kind == 5) {
37 let r = max(length(d_px), 1e-5);
38 t = clamp(length(p_px - s_px) / r, 0.0, 1.0);
39 } else if (kind == 6) {
40 let rel = p_px - s_px;
41 let a_p = select(0.0, atan2(rel.y, rel.x), dot(rel, rel) > 1e-12);
42 let a_d = select(0.0, atan2(d_px.y, d_px.x), dot(d_px, d_px) > 1e-12);
43 t = fract((a_p - a_d) / 6.28318530718);
44 } else if (kind == 7) {
45 let len2 = max(dot(d_px, d_px), 1e-6);
46 t = clamp(abs(dot(p_px - s_px, d_px) / len2), 0.0, 1.0);
47 } else {
48 let len2 = max(dot(d_px, d_px), 1e-6);
49 t = clamp(dot(p_px - s_px, d_px) / len2, 0.0, 1.0);
50 }
51 if (has_lut) {
52 let lut_w = max(f32(textureDimensions(src_b).x), 1.0);
53 let lut_u = (0.5 + t * (lut_w - 1.0)) / lut_w;
54 col = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u, 0.5), 0.0);
55 } else {
56 col = mix(u.p[0], u.p[1], t);
57 }
51 }58 }
52 }59 }
53 let m = read_mask(gid.xy, dims, u.p[5].z, u.p[5].w);60 if (has_mask >= 0.5) {
54 col = col * m;61 col = col * read_mask(gid.xy, dims, has_mask, u.p[5].w);
62 }
55 store_dst(vec2<i32>(gid.xy), col);63 store_dst(vec2<i32>(gid.xy), col);
56}64}
5765
...@@ -257,23 +265,53 @@ fn merge_sample_fg(tex: texture_2d<f32>, fu: vec2<f32>, edges: i32, dod: vec4<f3...@@ -257,23 +265,53 @@ fn merge_sample_fg(tex: texture_2d<f32>, fu: vec2<f32>, edges: i32, dod: vec4<f3
257 uv = fu_to_uv(fu);265 uv = fu_to_uv(fu);
258 }266 }
259 let inv_s = clamp(1.0 / max(size, 0.1), 1.0, 4.0);267 let inv_s = clamp(1.0 / max(size, 0.1), 1.0, 4.0);
268 let inv_scale = 1.0 / inv_s;
260 let sx_c = uv.x * tdims.x - 0.5;269 let sx_c = uv.x * tdims.x - 0.5;
261 let sy_c = uv.y * tdims.y - 0.5;270 let sy_c = uv.y * tdims.y - 0.5;
262 let ixc = i32(floor(sx_c));271 let ixc = i32(floor(sx_c));
263 let iyc = i32(floor(sy_c));272 let iyc = i32(floor(sy_c));
264 let rad = i32(ceil(2.0 * inv_s));273 let rad = i32(ceil(2.0 * inv_s));
274 let x0 = ixc - rad;
275 let x1 = ixc + rad + 1;
276 let y0 = iyc - rad;
277 let y1 = iyc + rad + 1;
278 if (edges == 0 && (x1 < 0 || x0 >= itdims.x || y1 < 0 || y0 >= itdims.y)) {
279 return vec4<f32>(0.0);
280 }
281 // Precompute separable 1D horizontal weights once (`rad <= 8`, so at most 18 taps).
282 var wx_arr: array<f32, 18>;
283 let x_count = x1 - x0 + 1;
284 for (var k = 0; k < x_count; k = k + 1) {
285 wx_arr[k] = merge_bspline_w((f32(x0 + k) - sx_c) * inv_scale);
286 }
287 let interior = x0 >= 0 && x1 < itdims.x && y0 >= 0 && y1 < itdims.y;
265 var acc = vec4<f32>(0.0);288 var acc = vec4<f32>(0.0);
266 var wsum = 0.0;289 var wsum = 0.0;
267 for (var iy = iyc - rad; iy <= iyc + rad + 1; iy = iy + 1) {290 if (interior) {
268 let wy = merge_bspline_w((f32(iy) - sy_c) / inv_s);291 for (var iy = y0; iy <= y1; iy = iy + 1) {
269 if (wy <= 0.0) { continue; }292 let wy = merge_bspline_w((f32(iy) - sy_c) * inv_scale);
270 for (var ix = ixc - rad; ix <= ixc + rad + 1; ix = ix + 1) {293 if (wy <= 0.0) { continue; }
271 let wx = merge_bspline_w((f32(ix) - sx_c) / inv_s);294 for (var k = 0; k < x_count; k = k + 1) {
272 let w = wx * wy;295 let wx = wx_arr[k];
273 if (w <= 0.0) { continue; }296 let w = wx * wy;
274 let s = merge_fetch_edges(tex, ix, iy, itdims, edges);297 if (w <= 0.0) { continue; }
275 wsum = wsum + w;298 let s = textureLoad(tex, vec2<i32>(x0 + k, iy), 0);
276 acc = acc + s * w;299 wsum = wsum + w;
300 acc = acc + s * w;
301 }
302 }
303 } else {
304 for (var iy = y0; iy <= y1; iy = iy + 1) {
305 let wy = merge_bspline_w((f32(iy) - sy_c) * inv_scale);
306 if (wy <= 0.0) { continue; }
307 for (var k = 0; k < x_count; k = k + 1) {
308 let wx = wx_arr[k];
309 let w = wx * wy;
310 if (w <= 0.0) { continue; }
311 let s = merge_fetch_edges(tex, x0 + k, iy, itdims, edges);
312 wsum = wsum + w;
313 acc = acc + s * w;
314 }
277 }315 }
278 }316 }
279 if (wsum > 1e-6) {317 if (wsum > 1e-6) {
...@@ -298,6 +336,14 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -298,6 +336,14 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
298 if (bg_coord.x >= 0 && bg_coord.y >= 0 && bg_coord.x < bg_tex_dims.x && bg_coord.y < bg_tex_dims.y) {336 if (bg_coord.x >= 0 && bg_coord.y >= 0 && bg_coord.x < bg_tex_dims.x && bg_coord.y < bg_tex_dims.y) {
299 bg = textureLoad(src_a, bg_coord, 0);337 bg = textureLoad(src_a, bg_coord, 0);
300 }338 }
339
340 let blend = u.p[1].x;
341 let mbm = u.p[7].x > 0.5;
342 if (blend <= 0.0 && !mbm) {
343 store_dst(vec2<i32>(gid.xy), bg);
344 return;
345 }
346
301 // If BG has expanded DoD, map output texel into logical BG canvas Fusion UV!347 // If BG has expanded DoD, map output texel into logical BG canvas Fusion UV!
302 let canvas_px = select(348 let canvas_px = select(
303 vec2<f32>(gid.xy) + vec2<f32>(0.5),349 vec2<f32>(gid.xy) + vec2<f32>(0.5),
...@@ -309,30 +355,42 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -309,30 +355,42 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
309 let center = u.p[0].xy;355 let center = u.p[0].xy;
310 let size = max(u.p[0].z, 1e-5);356 let size = max(u.p[0].z, 1e-5);
311 let angle = u.p[0].w;357 let angle = u.p[0].w;
312 let blend = u.p[1].x;
313 let gain = clamp(u.p[1].y, 0.0, 1.0);358 let gain = clamp(u.p[1].y, 0.0, 1.0);
314 let mode = i32(u.p[1].z + 0.5);359 let mode = i32(u.p[1].z + 0.5);
315 let edges = i32(u.p[1].w + 0.5);360 let edges = i32(u.p[1].w + 0.5);
316 let nearest = u.p[2].z > 0.5;361 let nearest = u.p[2].z > 0.5;
362 let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr
363 let has_mask = u.p[3].x;
364 let burn_in = u.p[6].x;
365 let sub_add = u.p[6].y;
317366
318 // Map output pixel in Fusion pixel space relative to Center into FG pixel space.367 // Map output pixel in Fusion pixel space relative to Center into FG pixel space.
319 let delta_px = (fu - center) * bg_dims;368 let delta_px = (fu - center) * bg_dims;
320 let c = cos(angle);369 var rot_px: vec2<f32>;
321 let s = sin(angle);370 if (abs(angle) < 1e-6) {
322 // Fusion Angle rotates CCW in Y-up, so inverse rotates CW:371 rot_px = delta_px / size;
323 let rot_px = vec2<f32>(delta_px.x * c + delta_px.y * s, -delta_px.x * s + delta_px.y * c) / size;372 } else {
373 let c = cos(angle);
374 let s = sin(angle);
375 // Fusion Angle rotates CCW in Y-up, so inverse rotates CW:
376 rot_px = vec2<f32>(delta_px.x * c + delta_px.y * s, -delta_px.x * s + delta_px.y * c) / size;
377 }
324 var fg_fu = rot_px / fg_dims + vec2<f32>(0.5);378 var fg_fu = rot_px / fg_dims + vec2<f32>(0.5);
325 if (u.p[2].x > 0.5) { fg_fu.x = 1.0 - fg_fu.x; }379 if (u.p[2].x > 0.5) { fg_fu.x = 1.0 - fg_fu.x; }
326 if (u.p[2].y > 0.5) { fg_fu.y = 1.0 - fg_fu.y; }380 if (u.p[2].y > 0.5) { fg_fu.y = 1.0 - fg_fu.y; }
327381
328 let fg = merge_sample_fg(src_b, fg_fu, edges, u.p[4], nearest, size);382 let fg = merge_sample_fg(src_b, fg_fu, edges, u.p[4], nearest, size);
329 let mask = read_mask_uv(canvas_px / bg_dims, u.p[3].x, u.p[3].y);
330 let mbm = u.p[7].x > 0.5;
331 let eff_blend = select(clamp(blend * mask, 0.0, 1.0), clamp(blend, 0.0, 1.0), mbm);
332 let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr
333383
334 let burn_in = u.p[6].x;384 // Fast path for the common Normal + Over + Gain=1.0 + no mask + Blend=1.0 case.
335 let sub_add = u.p[6].y;385 if (mode == 0 && op == 0 && gain >= 0.9999 && has_mask < 0.5 && blend >= 0.9999 && !mbm && burn_in == 0.0) {
386 let fg_rgb = select(fg.rgb * mix(fg.a, 1.0, sub_add), fg.rgb, sub_add >= 0.9999);
387 let out_col = vec4<f32>(fg_rgb + bg.rgb * (1.0 - fg.a), fg.a + bg.a * (1.0 - fg.a));
388 store_dst(vec2<i32>(gid.xy), out_col);
389 return;
390 }
391
392 let mask = read_mask_uv(canvas_px / bg_dims, has_mask, u.p[3].y);
393 let eff_blend = select(clamp(blend * mask, 0.0, 1.0), clamp(blend, 0.0, 1.0), mbm);
336394
337 var out_col: vec4<f32>;395 var out_col: vec4<f32>;
338 if (mode == 0) {396 if (mode == 0) {
crates/engine/src/shaders/keyers_gen.wgsl+37-24
...@@ -70,7 +70,7 @@ fn luma_key_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -70,7 +70,7 @@ fn luma_key_op(@builtin(global_invocation_id) gid: vec3<u32>) {
70// p[3] = color1 RGBA, p[4] = color2 RGBA (used directly in Two Color mode without clamping `val`)70// p[3] = color1 RGBA, p[4] = color2 RGBA (used directly in Two Color mode without clamping `val`)
71// src_b = 256x1 straight-alpha color LUT indexed by the noise value in Gradient mode71// src_b = 256x1 straight-alpha color LUT indexed by the noise value in Gradient mode
72// ============================================================================72// ============================================================================
73var<private> PERM: array<u32, 256> = array<u32, 256>(73const PERM: array<u32, 256> = array<u32, 256>(
74 151u, 160u, 137u, 91u, 90u, 15u, 131u, 13u, 201u, 95u, 96u, 53u, 194u, 233u, 7u, 225u,74 151u, 160u, 137u, 91u, 90u, 15u, 131u, 13u, 201u, 95u, 96u, 53u, 194u, 233u, 7u, 225u,
75 140u, 36u, 103u, 30u, 69u, 142u, 8u, 99u, 37u, 240u, 21u, 10u, 23u, 190u, 6u, 148u,75 140u, 36u, 103u, 30u, 69u, 142u, 8u, 99u, 37u, 240u, 21u, 10u, 23u, 190u, 6u, 148u,
76 247u, 120u, 234u, 75u, 0u, 26u, 197u, 62u, 94u, 252u, 219u, 203u, 117u, 35u, 11u, 32u,76 247u, 120u, 234u, 75u, 0u, 26u, 197u, 62u, 94u, 252u, 219u, 203u, 117u, 35u, 11u, 32u,
...@@ -99,8 +99,8 @@ const GRAD16: array<vec3<f32>, 16> = array<vec3<f32>, 16>(...@@ -99,8 +99,8 @@ const GRAD16: array<vec3<f32>, 16> = array<vec3<f32>, 16>(
99fn simplex_corner(ijk: vec3<i32>, d: vec3<f32>) -> f32 {99fn simplex_corner(ijk: vec3<i32>, d: vec3<f32>) -> f32 {
100 let t = SIMPLEX_RADIUS2 - dot(d, d);100 let t = SIMPLEX_RADIUS2 - dot(d, d);
101 if (t <= 0.0) { return 0.0; }101 if (t <= 0.0) { return 0.0; }
102 let c = ijk & vec3<i32>(255);102 let c = vec3<u32>(ijk & vec3<i32>(255));
103 let h = PERM[(u32(c.z) + PERM[(u32(c.y) + PERM[u32(c.x)]) & 255u]) & 255u] & 15u;103 let h = PERM[(c.z + PERM[(c.y + PERM[c.x]) & 255u]) & 255u] & 15u;
104 let t2 = t * t;104 let t2 = t * t;
105 return t2 * t2 * dot(GRAD16[h], d);105 return t2 * t2 * dot(GRAD16[h], d);
106}106}
...@@ -108,9 +108,9 @@ fn simplex_corner(ijk: vec3<i32>, d: vec3<f32>) -> f32 {...@@ -108,9 +108,9 @@ fn simplex_corner(ijk: vec3<i32>, d: vec3<f32>) -> f32 {
108// Fusion's lattice: Gustavson-style 3D simplex noise with kernel (0.5196 - r^2)^4 and a 16-entry108// Fusion's lattice: Gustavson-style 3D simplex noise with kernel (0.5196 - r^2)^4 and a 16-entry
109// gradient table, recovered from Float32 probes (residual 2e-7).109// gradient table, recovered from Float32 probes (residual 2e-7).
110fn simplex3d(p: vec3<f32>) -> f32 {110fn simplex3d(p: vec3<f32>) -> f32 {
111 let cell = floor(p + (p.x + p.y + p.z) / 3.0);111 let cell = floor(p + (p.x + p.y + p.z) * (1.0 / 3.0));
112 let ijk = vec3<i32>(cell);112 let ijk = vec3<i32>(cell);
113 let d0 = p - (cell - (cell.x + cell.y + cell.z) / 6.0);113 let d0 = p - (cell - (cell.x + cell.y + cell.z) * (1.0 / 6.0));
114 var a = vec3<i32>(0);114 var a = vec3<i32>(0);
115 var b = vec3<i32>(0);115 var b = vec3<i32>(0);
116 if (d0.x >= d0.y) {116 if (d0.x >= d0.y) {
...@@ -127,7 +127,7 @@ fn simplex3d(p: vec3<f32>) -> f32 {...@@ -127,7 +127,7 @@ fn simplex3d(p: vec3<f32>) -> f32 {
127 simplex_corner(ijk, d0)127 simplex_corner(ijk, d0)
128 + simplex_corner(ijk + a, d0 - vec3<f32>(a) + g)128 + simplex_corner(ijk + a, d0 - vec3<f32>(a) + g)
129 + simplex_corner(ijk + b, d0 - vec3<f32>(b) + 2.0 * g)129 + simplex_corner(ijk + b, d0 - vec3<f32>(b) + 2.0 * g)
130 + simplex_corner(ijk + vec3<i32>(1), d0 - 1.0 + 3.0 * g)130 + simplex_corner(ijk + vec3<i32>(1), d0 - 0.5)
131 );131 );
132}132}
133133
...@@ -153,25 +153,38 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -153,25 +153,38 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {
153 let angle = u.p[2].y;153 let angle = u.p[2].y;
154 let gradient = u.p[2].w > 1.5;154 let gradient = u.p[2].w > 1.5;
155155
156 // Frame-width units, y up, measured from the pixel corner.
157 let w = f32(dims.x);
158 let h = f32(dims.y);
159 let rel = vec2<f32>(f32(gid.x) / w, (h - 1.0 - f32(gid.y)) / w) - center * vec2<f32>(1.0, h / w);
160 let ca = cos(angle);
161 let sa = sin(angle);
162 let p = vec2<f32>(rel.x * ca + rel.y * sa, rel.y * ca - rel.x * sa) * scale;
163
164 let octaves = i32(ceil(detail));
165 var sum = 0.0;156 var sum = 0.0;
166 var amp = 1.0;157 if (abs(contrast) > 1e-6 && detail > 0.0) {
167 var freq = 1.0;158 // Frame-width units, y up, measured from the pixel corner.
168 for (var i = 0; i < octaves; i = i + 1) {159 let w = f32(dims.x);
169 let weight = amp * clamp(detail - f32(i), 0.0, 1.0);160 let h = f32(dims.y);
170 let off = OCTAVE_OFFSET * f32(i);161 let inv_w = 1.0 / w;
171 let n = simplex3d(vec3<f32>(p * freq + off, seethe * freq + off));162 let rel = vec2<f32>(f32(gid.x) * inv_w, (h - 1.0 - f32(gid.y)) * inv_w) - center * vec2<f32>(1.0, h * inv_w);
172 sum = sum + weight * select(n, 2.0 * abs(n), disc);163 var p: vec2<f32>;
173 freq = freq * 2.0;164 if (abs(angle) < 1e-6) {
174 amp = amp * 0.5;165 p = rel * scale;
166 } else {
167 let ca = cos(angle);
168 let sa = sin(angle);
169 p = vec2<f32>(rel.x * ca + rel.y * sa, rel.y * ca - rel.x * sa) * scale;
170 }
171
172 let full_octaves = i32(floor(detail));
173 let frac_w = detail - f32(full_octaves);
174 var amp = select(1.0, 2.0, disc);
175 var cur = vec3<f32>(p, seethe);
176 var off = 0.0;
177 for (var i = 0; i < full_octaves; i = i + 1) {
178 let n = simplex3d(cur + vec3<f32>(off));
179 sum = sum + amp * select(n, abs(n), disc);
180 cur = cur * 2.0;
181 off = off + OCTAVE_OFFSET;
182 amp = amp * 0.5;
183 }
184 if (frac_w > 0.0) {
185 let n = simplex3d(cur + vec3<f32>(off));
186 sum = sum + (amp * frac_w) * select(n, abs(n), disc);
187 }
175 }188 }
176189
177 var val = select(0.5 + sum, sum, disc);190 var val = select(0.5 + sum, sum, disc);
crates/engine/src/shaders/transform.wgsl+97-46
...@@ -21,6 +21,15 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -21,6 +21,15 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
21 has_dst_dod,21 has_dst_dod,
22 );22 );
2323
24 let nearest = u.p[3].y > 0.5;
25 let blend = u.p[2].z;
26 let has_mask = u.p[2].w;
27 let mbm = u.p[3].z > 0.5;
28 if (blend <= 0.0 && !mbm) {
29 store_dst(vec2<i32>(gid.xy), sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest));
30 return;
31 }
32
24 let center = u.p[0].xy;33 let center = u.p[0].xy;
25 let pivot = u.p[0].zw;34 let pivot = u.p[0].zw;
26 let sx = max(u.p[1].x, 1e-5);35 let sx = max(u.p[1].x, 1e-5);
...@@ -30,8 +39,6 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -30,8 +39,6 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
3039
31 // Forward in Fusion: p' = R(angle) * S(sx, sy) * (p - pivot) + pivot + (center - 0.5)40 // Forward in Fusion: p' = R(angle) * S(sx, sy) * (p - pivot) + pivot + (center - 0.5)
32 let shift = center - vec2<f32>(0.5);41 let shift = center - vec2<f32>(0.5);
33 let c = cos(angle);
34 let s = sin(angle);
35 var src_fu: vec2<f32>;42 var src_fu: vec2<f32>;
36 if (u.p[3].w > 0.5) {43 if (u.p[3].w > 0.5) {
37 // InvertTransform samples through the forward map instead of its inverse (flips apply first).44 // InvertTransform samples through the forward map instead of its inverse (flips apply first).
...@@ -39,31 +46,48 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -39,31 +46,48 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
39 if (u.p[2].x > 0.5) { p.x = 1.0 - p.x; }46 if (u.p[2].x > 0.5) { p.x = 1.0 - p.x; }
40 if (u.p[2].y > 0.5) { p.y = 1.0 - p.y; }47 if (u.p[2].y > 0.5) { p.y = 1.0 - p.y; }
41 let scaled = (p - pivot) * fdims * vec2<f32>(sx, sy);48 let scaled = (p - pivot) * fdims * vec2<f32>(sx, sy);
42 let rot = vec2<f32>(scaled.x * c - scaled.y * s, scaled.x * s + scaled.y * c);49 if (abs(angle) < 1e-6) {
43 src_fu = rot / fdims + pivot + shift;50 src_fu = scaled / fdims + pivot + shift;
51 } else {
52 let c = cos(angle);
53 let s = sin(angle);
54 let rot = vec2<f32>(scaled.x * c - scaled.y * s, scaled.x * s + scaled.y * c);
55 src_fu = rot / fdims + pivot + shift;
56 }
44 } else {57 } else {
45 let rel_px = (fu - pivot - shift) * fdims;58 let rel = fu - pivot - shift;
46 let unrot = vec2<f32>(rel_px.x * c + rel_px.y * s, -rel_px.x * s + rel_px.y * c);59 if (abs(angle) < 1e-6) {
47 src_fu = vec2<f32>(unrot.x / sx, unrot.y / sy) / fdims + pivot;60 src_fu = rel / vec2<f32>(sx, sy) + pivot;
61 } else {
62 let c = cos(angle);
63 let s = sin(angle);
64 let rel_px = rel * fdims;
65 let unrot = vec2<f32>(rel_px.x * c + rel_px.y * s, -rel_px.x * s + rel_px.y * c);
66 src_fu = vec2<f32>(unrot.x / sx, unrot.y / sy) / fdims + pivot;
67 }
48 if (u.p[2].x > 0.5) { src_fu.x = 1.0 - src_fu.x; }68 if (u.p[2].x > 0.5) { src_fu.x = 1.0 - src_fu.x; }
49 if (u.p[2].y > 0.5) { src_fu.y = 1.0 - src_fu.y; }69 if (u.p[2].y > 0.5) { src_fu.y = 1.0 - src_fu.y; }
50 }70 }
5171
52 let nearest = u.p[3].y > 0.5;
53 let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest);
54 let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest);72 let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest);
55 let raw_mask = select(73 let skip_mask = u.p[6] > vec4<f32>(0.5);
56 read_mask(gid.xy, dims, u.p[2].w, u.p[3].x),74 if (blend >= 1.0 && has_mask < 0.5 && !mbm && !any(skip_mask)) {
57 read_mask_uv(fu_to_uv(fu), u.p[2].w, u.p[3].x),75 store_dst(vec2<i32>(gid.xy), moved);
58 has_dst_dod,76 return;
59 );77 }
60 let mbm = u.p[3].z > 0.5;78
61 let m = select(raw_mask, 1.0, mbm) * u.p[2].z;79 let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest);
80 var raw_mask = 1.0;
81 if (has_mask >= 0.5) {
82 let mask_uv = select((vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims), fu_to_uv(fu), has_dst_dod);
83 raw_mask = read_mask_uv(mask_uv, has_mask, u.p[3].x);
84 }
85 let m = select(raw_mask, 1.0, mbm) * blend;
62 var out_col = mix(orig, moved, clamp(m, 0.0, 1.0));86 var out_col = mix(orig, moved, clamp(m, 0.0, 1.0));
63 if (mbm) {87 if (mbm) {
64 out_col = out_col * raw_mask;88 out_col = out_col * raw_mask;
65 }89 }
66 store_dst(vec2<i32>(gid.xy), select(out_col, orig, u.p[6] > vec4<f32>(0.5)));90 store_dst(vec2<i32>(gid.xy), select(out_col, orig, skip_mask));
67}91}
68// MultiplyByMask scales the warped result by mask * blend instead of mixing against the source.92// MultiplyByMask scales the warped result by mask * blend instead of mixing against the source.
69fn mask_mix(orig: vec4<f32>, warped: vec4<f32>, raw_mask: f32, blend: f32, mbm: bool) -> vec4<f32> {93fn mask_mix(orig: vec4<f32>, warped: vec4<f32>, raw_mask: f32, blend: f32, mbm: bool) -> vec4<f32> {
...@@ -112,8 +136,14 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -112,8 +136,14 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
112 store_dst(vec2<i32>(gid.xy), textureLoad(src_a, vec2<i32>(gid.xy), 0) + d * (u.p[2].z * m));136 store_dst(vec2<i32>(gid.xy), textureLoad(src_a, vec2<i32>(gid.xy), 0) + d * (u.p[2].z * m));
113 return;137 return;
114 }138 }
139 let blend = u.p[1].z;
140 let has_mask = u.p[1].w;
141 let mbm = u.p[4].z > 0.5;
142 if (blend <= 0.0 && !mbm) {
143 store_dst(vec2<i32>(gid.xy), textureLoad(src_a, vec2<i32>(gid.xy), 0));
144 return;
145 }
115 let kind = i32(u.p[0].x + 0.5);146 let kind = i32(u.p[0].x + 0.5);
116 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
117147
118 var warped: vec4<f32>;148 var warped: vec4<f32>;
119 if (kind == 1) {149 if (kind == 1) {
...@@ -123,11 +153,11 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -123,11 +153,11 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
123 let ych = i32(u.p[3].w + 0.5);153 let ych = i32(u.p[3].w + 0.5);
124 let vx = pick_channel(fg, xch);154 let vx = pick_channel(fg, xch);
125 let vy = pick_channel(fg, ych);155 let vy = pick_channel(fg, ych);
126 let disp = vec2<f32>(156 let disp_uv = vec2<f32>(
127 (vx + u.p[0].w) * u.p[0].y,157 (vx + u.p[0].w) * u.p[0].y,
128 (vy + u.p[1].x) * u.p[0].z,158 -((vy + u.p[1].x) * u.p[0].z),
129 );159 );
130 warped = sample_edges(src_a, fu + disp, 2);160 warped = textureSampleLevel(src_a, samp_lin, clamp(uv + disp_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
131 } else {161 } else {
132 // Radial displace: Fusion shifts radially from Center by -(fu - center) * (luma + offset) * strength * 0.51.162 // Radial displace: Fusion shifts radially from Center by -(fu - center) * (luma + offset) * strength * 0.51.
133 let fg_c = textureSampleLevel(src_b, samp_lin, uv, 0.0);163 let fg_c = textureSampleLevel(src_b, samp_lin, uv, 0.0);
...@@ -136,21 +166,26 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -136,21 +166,26 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
136 let strength = u.p[1].y;166 let strength = u.p[1].y;
137 let spread = u.p[2].y;167 let spread = u.p[2].y;
138 let center = u.p[3].xy;168 let center = u.p[3].xy;
139 let dir_c = fu - center;169 let base_disp = -(fu - center) * ((l_c + offset) * (strength * 0.51));
140 let base_disp = -dir_c * (l_c + offset) * strength * 0.51;170 let base_uv = vec2<f32>(base_disp.x, -base_disp.y);
141171
142 if (abs(spread) > 1e-4) {172 if (abs(spread) > 1e-4) {
143 let sp = spread * 0.02;173 let sp = spread * 0.02;
144 let sr = sample_edges(src_a, fu + base_disp * (1.0 - sp), 2);174 let sr = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv * (1.0 - sp), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
145 let sg = sample_edges(src_a, fu + base_disp, 2);175 let sg = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
146 let sb = sample_edges(src_a, fu + base_disp * (1.0 + sp), 2);176 let sb = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv * (1.0 + sp), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
147 warped = vec4<f32>(sr.r, sg.g, sb.b, max(sr.a, max(sg.a, sb.a)));177 warped = vec4<f32>(sr.r, sg.g, sb.b, max(sr.a, max(sg.a, sb.a)));
148 } else {178 } else {
149 warped = sample_edges(src_a, fu + base_disp, 2);179 warped = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
150 }180 }
151 }181 }
152182
153 store_dst(vec2<i32>(gid.xy), mask_mix(orig, warped, read_mask(gid.xy, dims, u.p[1].w, u.p[2].x), u.p[1].z, u.p[4].z > 0.5));183 if (blend >= 1.0 && has_mask < 0.5 && !mbm) {
184 store_dst(vec2<i32>(gid.xy), warped);
185 return;
186 }
187 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
188 store_dst(vec2<i32>(gid.xy), mask_mix(orig, warped, read_mask(gid.xy, dims, has_mask, u.p[2].x), blend, mbm));
154}189}
155// ============================================================================190// ============================================================================
156// 14. Crop / Scale / Copy191// 14. Crop / Scale / Copy
...@@ -193,12 +228,20 @@ fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -193,12 +228,20 @@ fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {
193fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {228fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
194 let dims = textureDimensions(dst_tex);229 let dims = textureDimensions(dst_tex);
195 if (gid.x >= dims.x || gid.y >= dims.y) { return; }230 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
231 let blend = u.p[3].x;
196 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);232 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
233 if (blend <= 0.0) {
234 store_dst(vec2<i32>(gid.xy), orig);
235 return;
236 }
197 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);237 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);
238 let aspect_v = vec2<f32>(aspect, 1.0);
239 let inv_aspect_v = vec2<f32>(1.0 / aspect, 1.0);
198 let fu = pix_to_fu(gid.xy, dims);240 let fu = pix_to_fu(gid.xy, dims);
199241
200 let center = u.p[0].xy;242 let center = u.p[0].xy;
201 let pivot = u.p[0].zw;243 let pivot = u.p[0].zw;
244 let piv_off = pivot - vec2<f32>(0.5, 0.5);
202 let xsize = u.p[1].x;245 let xsize = u.p[1].x;
203 let ysize = u.p[1].y;246 let ysize = u.p[1].y;
204 let angle = u.p[1].z;247 let angle = u.p[1].z;
...@@ -207,16 +250,18 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -207,16 +250,18 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
207 let normalize = u.p[2].y > 0.5;250 let normalize = u.p[2].y > 0.5;
208 let gain = u.p[2].z;251 let gain = u.p[2].z;
209 let gamma = max(u.p[2].w, 0.05);252 let gamma = max(u.p[2].w, 0.05);
210 let blend = u.p[3].x;253 let do_gamma = abs(gamma - 1.0) > 1e-3;
211254
212 var acc = vec4<f32>(0.0);255 var acc = vec4<f32>(0.0);
213 var grad_sum = vec4<f32>(0.0);256 var grad_sum = vec4<f32>(0.0);
214 let inv_steps = 1.0 / f32(steps);257 let inv_steps = 1.0 / f32(steps);
215258
216 let grad_n = f32(textureDimensions(src_b).x);259 let grad_n = f32(textureDimensions(src_b).x);
260 let grad_scale = (grad_n - 1.0) / grad_n;
261 let grad_bias = 0.5 / grad_n;
217 for (var i = 0; i <= steps; i = i + 1) {262 for (var i = 0; i <= steps; i = i + 1) {
218 let n = f32(i) * inv_steps;263 let n = f32(i) * inv_steps;
219 let grad_u = (0.5 + clamp(n, 0.0, 1.0) * (grad_n - 1.0)) / grad_n;264 let grad_u = grad_bias + clamp(n, 0.0, 1.0) * grad_scale;
220 let grad = textureSampleLevel(src_b, samp_lin, vec2<f32>(grad_u, 0.5), 0.0);265 let grad = textureSampleLevel(src_b, samp_lin, vec2<f32>(grad_u, 0.5), 0.0);
221266
222 let cur_c = mix(vec2<f32>(0.5, 0.5), center, n);267 let cur_c = mix(vec2<f32>(0.5, 0.5), center, n);
...@@ -225,15 +270,20 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -225,15 +270,20 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
225 let cur_a = angle * n;270 let cur_a = angle * n;
226271
227 // Inverse transform matching Fusion Transform/XfChroma around pivot272 // Inverse transform matching Fusion Transform/XfChroma around pivot
228 let rel = (fu - cur_c + (pivot - vec2<f32>(0.5, 0.5))) * vec2<f32>(aspect, 1.0);273 let rel = (fu - cur_c + piv_off) * aspect_v;
229 let ca = cos(cur_a);274 var rot: vec2<f32>;
230 let sa = sin(cur_a);275 if (abs(cur_a) < 1e-6) {
231 let rot = vec2<f32>(rel.x * ca + rel.y * sa, -rel.x * sa + rel.y * ca);276 rot = rel;
277 } else {
278 let ca = cos(cur_a);
279 let sa = sin(cur_a);
280 rot = vec2<f32>(rel.x * ca + rel.y * sa, -rel.x * sa + rel.y * ca);
281 }
232 let scaled = rot / vec2<f32>(cur_sx, cur_sy);282 let scaled = rot / vec2<f32>(cur_sx, cur_sy);
233 let src_fu = pivot + scaled / vec2<f32>(aspect, 1.0);283 let src_fu = pivot + scaled * inv_aspect_v;
234284
235 var s = sample_dod_edges_mode(src_a, src_fu, 0, u.p[4], false);285 var s = sample_dod_edges_mode(src_a, src_fu, 0, u.p[4], false);
236 if (abs(gamma - 1.0) > 1e-3) {286 if (do_gamma) {
237 s = vec4<f32>(pow(max(s.rgb, vec3<f32>(0.0)), vec3<f32>(gamma)), s.a);287 s = vec4<f32>(pow(max(s.rgb, vec3<f32>(0.0)), vec3<f32>(gamma)), s.a);
238 }288 }
239 let tinted = s * grad;289 let tinted = s * grad;
...@@ -328,11 +378,12 @@ fn homography_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -328,11 +378,12 @@ fn homography_op(@builtin(global_invocation_id) gid: vec3<u32>) {
328 ),378 ),
329 has_dod,379 has_dod,
330 );380 );
331 let orig = select(381 var orig = vec4<f32>(0.0);
332 textureLoad(src_a, vec2<i32>(gid.xy), 0),382 if (has_dod) {
333 sample_edges(src_a, fu, 0),383 orig = sample_edges(src_a, fu, 0);
334 has_dod,384 } else {
335 );385 orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
386 }
336387
337 var s_fu = vec2<f32>(0.0);388 var s_fu = vec2<f32>(0.0);
338 var valid = false;389 var valid = false;
...@@ -355,11 +406,11 @@ fn homography_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -355,11 +406,11 @@ fn homography_op(@builtin(global_invocation_id) gid: vec3<u32>) {
355 warped.a = 1.0;406 warped.a = 1.0;
356 }407 }
357 }408 }
358 let raw_mask = select(409 var raw_mask = 1.0;
359 read_mask(gid.xy, dims, u.p[2].z, u.p[2].w),410 if (u.p[2].z >= 0.5) {
360 read_mask_uv(fu_to_uv(fu), u.p[2].z, u.p[2].w),411 let mask_uv = select((vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims), fu_to_uv(fu), has_dod);
361 has_dod,412 raw_mask = read_mask_uv(mask_uv, u.p[2].z, u.p[2].w);
362 );413 }
363 let res = mask_mix(orig, warped, raw_mask, u.p[2].y, u.p[3].y > 0.5);414 let res = mask_mix(orig, warped, raw_mask, u.p[2].y, u.p[3].y > 0.5);
364 let unproc = select(orig, vec4<f32>(0.0), u.p[3].y > 0.5);415 let unproc = select(orig, vec4<f32>(0.0), u.p[3].y > 0.5);
365 store_dst(vec2<i32>(gid.xy), select(res, unproc, u.p[5] > vec4<f32>(0.5)));416 store_dst(vec2<i32>(gid.xy), select(res, unproc, u.p[5] > vec4<f32>(0.5)));
crates/engine/src/text_engine.rs+757-198
...@@ -4,7 +4,10 @@...@@ -4,7 +4,10 @@
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, HashSet};7use std::collections::{HashMap, HashSet, VecDeque};
8#[cfg(not(target_arch = "wasm32"))]
9use std::path::PathBuf;
10use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, Mutex, OnceLock, RwLock};11use std::sync::{Arc, Mutex, OnceLock, RwLock};
9use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};12use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};
1013
...@@ -15,8 +18,11 @@ const FALLBACK_FAMILIES: [&str; 6] =...@@ -15,8 +18,11 @@ const FALLBACK_FAMILIES: [&str; 6] =
15/// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face.18/// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face.
16const SYNTHETIC_ITALIC: f32 = 0.2126;19const SYNTHETIC_ITALIC: f32 = 0.2126;
1720
21static NEXT_FONT_ID: AtomicU64 = AtomicU64::new(1);
22
18/// A resolved font file; `face()` parses it on demand.23/// A resolved font file; `face()` parses it on demand.
19pub struct Font {24pub struct Font {
25 id: u64,
20 data: Vec<u8>,26 data: Vec<u8>,
21 index: u32,27 index: u32,
22 weight: u16,28 weight: u16,
...@@ -28,15 +34,21 @@ impl Font {...@@ -28,15 +34,21 @@ impl Font {
28 /// system fonts and any fonts registered via [`register_font_bytes`], falling back through34 /// system fonts and any fonts registered via [`register_font_bytes`], falling back through
29 /// [`FALLBACK_FAMILIES`] and finally any installed face.35 /// [`FALLBACK_FAMILIES`] and finally any installed face.
30 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {36 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
37 {
38 let cache = font_cache().lock().unwrap();
39 if let Some(hit) = cache.get(&(family.to_owned(), style.to_owned())) {
40 return hit.clone();
41 }
42 }
43 let resolved = {
44 let mut reg = registry().write().unwrap();
45 resolve_lazy(&mut reg, family, style).map(Arc::new)
46 };
31 let mut cache = font_cache().lock().unwrap();47 let mut cache = font_cache().lock().unwrap();
32 cache48 let entry = cache
33 .entry((family.to_owned(), style.to_owned()))49 .entry((family.to_owned(), style.to_owned()))
34 .or_insert_with(|| {50 .or_insert_with(|| resolved.clone());
35 let db = database().read().unwrap();51 entry.clone()
36 let aliases = font_aliases().read().unwrap();
37 resolve(&db, &aliases, family, style).map(Arc::new)
38 })
39 .clone()
40 }52 }
4153
42 pub fn face(&self) -> Face<'_> {54 pub fn face(&self) -> Face<'_> {
...@@ -48,33 +60,198 @@ impl Font {...@@ -48,33 +60,198 @@ impl Font {
48 }60 }
49}61}
5062
63struct FontRegistry {
64 db: fontdb::Database,
65 aliases: HashMap<String, Vec<fontdb::ID>>,
66 #[cfg(not(target_arch = "wasm32"))]
67 system_fonts_loaded: bool,
68 #[cfg(not(target_arch = "wasm32"))]
69 loaded_paths: HashSet<PathBuf>,
70 #[cfg(not(target_arch = "wasm32"))]
71 loaded_families: HashSet<String>,
72 #[cfg(not(target_arch = "wasm32"))]
73 loaded_style_keys: HashSet<(String, String)>,
74}
75
76impl FontRegistry {
77 fn new() -> Self {
78 Self {
79 db: fontdb::Database::new(),
80 aliases: HashMap::new(),
81 #[cfg(not(target_arch = "wasm32"))]
82 system_fonts_loaded: false,
83 #[cfg(not(target_arch = "wasm32"))]
84 loaded_paths: HashSet::new(),
85 #[cfg(not(target_arch = "wasm32"))]
86 loaded_families: HashSet::new(),
87 #[cfg(not(target_arch = "wasm32"))]
88 loaded_style_keys: HashSet::new(),
89 }
90 }
91
92 #[cfg(not(target_arch = "wasm32"))]
93 fn ensure_system_fonts_loaded(&mut self) {
94 if !self.system_fonts_loaded {
95 self.db.load_system_fonts();
96 self.system_fonts_loaded = true;
97 }
98 }
99}
100
51fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {101fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {
52 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();102 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();
53 CACHE.get_or_init(Default::default)103 CACHE.get_or_init(Default::default)
54}104}
55105
56fn font_aliases() -> &'static RwLock<HashMap<String, Vec<fontdb::ID>>> {106fn registry() -> &'static RwLock<FontRegistry> {
57 static ALIASES: OnceLock<RwLock<HashMap<String, Vec<fontdb::ID>>>> = OnceLock::new();107 static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new();
58 ALIASES.get_or_init(Default::default)108 REG.get_or_init(|| RwLock::new(FontRegistry::new()))
109}
110
111#[cfg(not(target_arch = "wasm32"))]
112struct FontFileEntry {
113 path: PathBuf,
114 stem_norm: String,
115}
116
117#[cfg(not(target_arch = "wasm32"))]
118fn norm_alnum(s: &str) -> String {
119 s.chars()
120 .filter(|c| c.is_ascii_alphanumeric())
121 .map(|c| c.to_ascii_lowercase())
122 .collect()
123}
124
125#[cfg(not(target_arch = "wasm32"))]
126fn is_font_extension(path: &std::path::Path) -> bool {
127 path.extension()
128 .and_then(|e| e.to_str())
129 .is_some_and(|ext| {
130 ext.eq_ignore_ascii_case("ttf")
131 || ext.eq_ignore_ascii_case("otf")
132 || ext.eq_ignore_ascii_case("ttc")
133 || ext.eq_ignore_ascii_case("otc")
134 })
59}135}
60136
61fn database() -> &'static RwLock<fontdb::Database> {137#[cfg(not(target_arch = "wasm32"))]
62 static DB: OnceLock<RwLock<fontdb::Database>> = OnceLock::new();138fn collect_font_dir(dir: &std::path::Path, depth: u8, out: &mut Vec<FontFileEntry>) {
63 DB.get_or_init(|| {139 let Ok(entries) = std::fs::read_dir(dir) else {
64 #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]140 return;
65 let mut db = fontdb::Database::new();141 };
66 #[cfg(not(target_arch = "wasm32"))]142 for entry in entries.flatten() {
67 db.load_system_fonts();143 let path = entry.path();
68 RwLock::new(db)144 if path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) {
145 continue;
146 }
147 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
148 || (entry.file_type().map(|ft| ft.is_symlink()).unwrap_or(false) && path.is_dir());
149 if is_dir {
150 if depth > 0 {
151 collect_font_dir(&path, depth - 1, out);
152 }
153 } else if is_font_extension(&path) {
154 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
155 let stem_norm = norm_alnum(stem);
156 if !stem_norm.is_empty() {
157 out.push(FontFileEntry { path, stem_norm });
158 }
159 }
160 }
161 }
162}
163
164#[cfg(not(target_arch = "wasm32"))]
165fn system_font_index() -> &'static [FontFileEntry] {
166 static INDEX: OnceLock<Vec<FontFileEntry>> = OnceLock::new();
167 INDEX.get_or_init(|| {
168 let mut out = Vec::with_capacity(768);
169 let mut dirs: Vec<PathBuf> = Vec::new();
170 #[cfg(target_os = "macos")]
171 {
172 dirs.push(PathBuf::from("/System/Library/Fonts"));
173 dirs.push(PathBuf::from("/Library/Fonts"));
174 if let Some(home) = std::env::var_os("HOME") {
175 dirs.push(PathBuf::from(home).join("Library/Fonts"));
176 }
177 }
178 #[cfg(all(unix, not(target_os = "macos")))]
179 {
180 dirs.push(PathBuf::from("/usr/share/fonts"));
181 dirs.push(PathBuf::from("/usr/local/share/fonts"));
182 if let Some(home) = std::env::var_os("HOME") {
183 let h = PathBuf::from(home);
184 dirs.push(h.join(".local/share/fonts"));
185 dirs.push(h.join(".fonts"));
186 }
187 }
188 #[cfg(target_os = "windows")]
189 {
190 if let Some(win) = std::env::var_os("WINDIR") {
191 dirs.push(PathBuf::from(win).join("Fonts"));
192 }
193 if let Some(local) = std::env::var_os("LOCALAPPDATA") {
194 dirs.push(PathBuf::from(local).join("Microsoft/Windows/Fonts"));
195 }
196 }
197 for d in &dirs {
198 collect_font_dir(d, 4, &mut out);
199 }
200 out
69 })201 })
70}202}
71203
204#[cfg(not(target_arch = "wasm32"))]
205fn is_style_suffix(rest: &str) -> bool {
206 const PREFIXES: &[&str] = &[
207 "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy",
208 "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow",
209 "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps",
210 ];
211 rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p))
212}
213
214#[cfg(not(target_arch = "wasm32"))]
215fn load_style_candidates(reg: &mut FontRegistry, fam_norm: &str, style_key: &str) {
216 if fam_norm.is_empty() || reg.system_fonts_loaded || reg.loaded_families.contains(fam_norm) {
217 return;
218 }
219 let key = (fam_norm.to_owned(), style_key.to_owned());
220 if !reg.loaded_style_keys.insert(key) {
221 return;
222 }
223 let combined_len = fam_norm.len() + style_key.len();
224 for entry in system_font_index() {
225 let exact_match = entry.stem_norm == fam_norm
226 || (entry.stem_norm.len() == combined_len
227 && entry.stem_norm.starts_with(fam_norm)
228 && entry.stem_norm.ends_with(style_key));
229 if exact_match && reg.loaded_paths.insert(entry.path.clone()) {
230 let _ = reg.db.load_font_file(&entry.path);
231 }
232 }
233}
234
235#[cfg(not(target_arch = "wasm32"))]
236fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) {
237 if fam_norm.is_empty() || reg.system_fonts_loaded || !reg.loaded_families.insert(fam_norm.to_owned()) {
238 return;
239 }
240 for entry in system_font_index() {
241 if let Some(rest) = entry.stem_norm.strip_prefix(fam_norm) {
242 if is_style_suffix(rest) && reg.loaded_paths.insert(entry.path.clone()) {
243 let _ = reg.db.load_font_file(&entry.path);
244 }
245 }
246 }
247}
248
72/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime249/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime
73/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.250/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.
74pub fn register_font_bytes(bytes: Vec<u8>) {251pub fn register_font_bytes(bytes: Vec<u8>) {
75 {252 {
76 let mut db = database().write().unwrap();253 let mut reg = registry().write().unwrap();
77 db.load_font_data(bytes);254 reg.db.load_font_data(bytes);
78 }255 }
79 font_cache().lock().unwrap().clear();256 font_cache().lock().unwrap().clear();
80}257}
...@@ -83,15 +260,13 @@ pub fn register_font_bytes(bytes: Vec<u8>) {...@@ -83,15 +260,13 @@ pub fn register_font_bytes(bytes: Vec<u8>) {
83/// and clears the resolution cache.260/// and clears the resolution cache.
84pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {261pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
85 {262 {
86 let mut db = database().write().unwrap();263 let mut reg = registry().write().unwrap();
87 let before: HashSet<fontdb::ID> = db.faces().map(|f| f.id).collect();264 let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect();
88 db.load_font_data(bytes);265 reg.db.load_font_data(bytes);
89 if !family.is_empty() {266 if !family.is_empty() {
90 let added: Vec<fontdb::ID> = db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect();267 let added: Vec<fontdb::ID> = reg.db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect();
91 if !added.is_empty() {268 if !added.is_empty() {
92 font_aliases()269 reg.aliases
93 .write()
94 .unwrap()
95 .entry(family.to_ascii_lowercase())270 .entry(family.to_ascii_lowercase())
96 .or_default()271 .or_default()
97 .extend(added);272 .extend(added);
...@@ -142,25 +317,102 @@ fn metric_alias(family: &str) -> Option<&'static str> {...@@ -142,25 +317,102 @@ fn metric_alias(family: &str) -> Option<&'static str> {
142 }317 }
143}318}
144319
145fn resolve(320#[cfg(not(target_arch = "wasm32"))]
321fn is_exact_face_match(
146 db: &fontdb::Database,322 db: &fontdb::Database,
147 aliases: &HashMap<String, Vec<fontdb::ID>>,323 id: fontdb::ID,
324 wanted_style: &str,
325 weight: u16,
326 italic: bool,
327) -> bool {
328 if !wanted_style.is_empty() {
329 let matched_name = db
330 .with_face_data(id, |data, index| {
331 let face = ttf_parser::Face::parse(data, index).ok()?;
332 let names = face.names();
333 let name = [17, 2].into_iter().find_map(|nid| {
334 names.into_iter().find(|n| n.name_id == nid && n.is_unicode()).and_then(|n| n.to_string())
335 })?;
336 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
337 })
338 .flatten()
339 .unwrap_or(false);
340 if matched_name {
341 return true;
342 }
343 }
344 let Some(info) = db.face(id) else {
345 return false;
346 };
347 let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal };
348 info.weight.0 == weight && info.style == want_style
349}
350
351fn try_pick_family_lazy(
352 reg: &mut FontRegistry,
148 family: &str,353 family: &str,
149 style: &str,354 wanted_style: &str,
150) -> Option<Font> {355 weight: u16,
356 italic: bool,
357) -> Option<fontdb::ID> {
358 if family.is_empty() {
359 return None;
360 }
361 #[cfg(not(target_arch = "wasm32"))]
362 {
363 let fam_norm = norm_alnum(family);
364 let style_key = if wanted_style.is_empty() { "regular" } else { wanted_style };
365 if !reg.system_fonts_loaded
366 && !reg.loaded_families.contains(&fam_norm)
367 && !reg.aliases.contains_key(&family.to_ascii_lowercase())
368 {
369 load_style_candidates(reg, &fam_norm, style_key);
370 if let Some(id) = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic) {
371 if is_exact_face_match(&reg.db, id, wanted_style, weight, italic) {
372 return Some(id);
373 }
374 }
375 load_family_candidates(reg, &fam_norm);
376 }
377 }
378 pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic)
379}
380
381fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> {
151 let (weight, italic) = parse_style(style);382 let (weight, italic) = parse_style(style);
152 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();383 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
153 let id = std::iter::once(family)384
154 .chain(metric_alias(family))385 let mut id = try_pick_family_lazy(reg, family, &wanted, weight, italic)
155 .chain(FALLBACK_FAMILIES)386 .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic)));
156 .find_map(|name| pick(db, aliases, name, &wanted, weight, italic))387
157 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))388 #[cfg(not(target_arch = "wasm32"))]
158 .or_else(|| db.faces().map(|f| f.id).next())?;389 if id.is_none() && !family.is_empty() && !reg.system_fonts_loaded {
159 let info = db.face(id)?;390 reg.ensure_system_fonts_loaded();
160 let data = db.with_face_data(id, |data, _| data.to_vec())?;391 id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic)
392 .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic)));
393 }
394
395 if id.is_none() {
396 id = FALLBACK_FAMILIES
397 .iter()
398 .find_map(|fb| try_pick_family_lazy(reg, fb, &wanted, weight, italic));
399 }
400
401 #[cfg(not(target_arch = "wasm32"))]
402 if id.is_none() && !reg.system_fonts_loaded {
403 reg.ensure_system_fonts_loaded();
404 }
405
406 let id = id
407 .or_else(|| reg.db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
408 .or_else(|| reg.db.faces().map(|f| f.id).next())?;
409
410 let info = reg.db.face(id)?;
411 let data = reg.db.with_face_data(id, |data, _| data.to_vec())?;
161 let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 };412 let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 };
162 Face::from_slice(&data, info.index)?;413 Face::from_slice(&data, info.index)?;
163 Some(Font { data, index: info.index, weight, lean })414 let font_id = NEXT_FONT_ID.fetch_add(1, Ordering::Relaxed);
415 Some(Font { id: font_id, data, index: info.index, weight, lean })
164}416}
165417
166/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest418/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest
...@@ -186,20 +438,22 @@ fn pick(...@@ -186,20 +438,22 @@ fn pick(
186 .collect();438 .collect();
187 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));439 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));
188 let first = candidates.first()?;440 let first = candidates.first()?;
189 let exact = candidates.iter().find(|f| {441 if !wanted_style.is_empty() {
190 db.with_face_data(f.id, |data, index| {442 let exact = candidates.iter().find(|f| {
191 let face = ttf_parser::Face::parse(data, index).ok()?;443 db.with_face_data(f.id, |data, index| {
192 let names = face.names();444 let face = ttf_parser::Face::parse(data, index).ok()?;
193 let name = [17, 2].into_iter().find_map(|id| {445 let names = face.names();
194 names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string())446 let name = [17, 2].into_iter().find_map(|id| {
195 })?;447 names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string())
196 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))448 })?;
197 })449 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
198 .flatten()450 })
199 .unwrap_or(false)451 .flatten()
200 });452 .unwrap_or(false)
201 if let Some(face) = exact {453 });
202 return Some(face.id);454 if let Some(face) = exact {
455 return Some(face.id);
456 }
203 }457 }
204 if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) {458 if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) {
205 return db.query(&fontdb::Query {459 return db.query(&fontdb::Query {
...@@ -451,12 +705,20 @@ fn resolve_char_styles(params: &RichTextPlusParams<'_>) -> Vec<CharStyle> {...@@ -451,12 +705,20 @@ fn resolve_char_styles(params: &RichTextPlusParams<'_>) -> Vec<CharStyle> {
451705
452struct PlacedGlyph {706struct PlacedGlyph {
453 commands: Vec<Command>,707 commands: Vec<Command>,
454 char_idx: usize,708}
709
710struct GlyphSpec {
711 font: Arc<Font>,
712 glyph_id: GlyphId,
713 font_px: f32,
714 shear: f32,
455 outline_w: f32,715 outline_w: f32,
716 abs_x: f32,
717 abs_y: f32,
456}718}
457719
458struct LayoutLine {720struct LayoutSpecLine {
459 glyphs: Vec<PlacedGlyph>,721 glyphs: Vec<GlyphSpec>,
460 width: f32,722 width: f32,
461 ascent: f32,723 ascent: f32,
462 descent: f32,724 descent: f32,
...@@ -470,7 +732,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3...@@ -470,7 +732,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3
470 (font_px, asc_em * font_px, desc_em * font_px)732 (font_px, asc_em * font_px, desc_em * font_px)
471}733}
472734
473fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> {735fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<GlyphSpec>, usize)> {
474 let [w, h] = dims;736 let [w, h] = dims;
475 let total_chars = params.text.chars().count();737 let total_chars = params.text.chars().count();
476 if total_chars == 0 || params.size_norm <= 1e-4 {738 if total_chars == 0 || params.size_norm <= 1e-4 {
...@@ -481,7 +743,6 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec...@@ -481,7 +743,6 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
481 if c_start >= c_end || c_start >= total_chars {743 if c_start >= c_end || c_start >= total_chars {
482 return None;744 return None;
483 }745 }
484 let styles = resolve_char_styles(params);
485 let wf = w as f32;746 let wf = w as f32;
486 let hf = h as f32;747 let hf = h as f32;
487 let base_font = Font::find(params.font_family, params.font_style)?;748 let base_font = Font::find(params.font_family, params.font_style)?;
...@@ -489,87 +750,141 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec...@@ -489,87 +750,141 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
489750
490 let mut lines = Vec::new();751 let mut lines = Vec::new();
491 let mut char_cursor = 0usize;752 let mut char_cursor = 0usize;
492 for raw_line in params.text.split('\n') {753
493 let raw_char_len = raw_line.chars().count();754 if params.cls.is_empty() {
494 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);755 let (font_px, asc, desc) = size_metrics(&base_face, params.size_norm, wf);
495 let line_chars: Vec<char> = line_str.chars().collect();756 let top_anchor = (font_px - desc).max(0.0);
496 let mut shaped_runs: Vec<(usize, usize, Arc<Font>, f32, ShapedLine)> = Vec::new();757 let extra_track = (params.tracking - 1.0) * params.size_norm * wf;
497 let mut line_max_size = 0.0_f32;758 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
498 let mut max_asc = 0.0_f32;759 (params.outline_thickness_norm * params.size_norm * wf).clamp(1.0, 128.0)
499 let mut max_desc = 0.0_f32;
500 let mut max_top_anchor = 0.0_f32;
501
502 if line_chars.is_empty() {
503 let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm);
504 let (font_px, asc, desc) = size_metrics(&base_face, st, wf);
505 max_asc = asc;
506 max_desc = desc;
507 max_top_anchor = (font_px - desc).max(0.0);
508 } else {760 } else {
509 let mut r0 = 0usize;761 0.0
510 while r0 < line_chars.len() {762 };
511 let st0 = &styles[char_cursor + r0];763 for raw_line in params.text.split('\n') {
512 let mut r1 = r0 + 1;764 let raw_char_len = raw_line.chars().count();
513 while r1 < line_chars.len() {765 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
514 let st1 = &styles[char_cursor + r1];766 let mut line_glyphs = Vec::new();
515 if st1.family != st0.family767 let width = if line_str.is_empty() {
516 || st1.style != st0.style768 0.0
517 || (st1.size_norm - st0.size_norm).abs() > 1e-5769 } else {
518 {770 let shaped = shape_line(&base_face, line_str, font_px, extra_track);
519 break;771 line_glyphs.reserve(shaped.glyphs.len());
772 for g in &shaped.glyphs {
773 let idx = char_cursor + g.char_index;
774 if idx < c_start || idx >= c_end {
775 continue;
520 }776 }
521 r1 += 1;777 line_glyphs.push(GlyphSpec {
778 font: Arc::clone(&base_font),
779 glyph_id: g.id,
780 font_px,
781 shear: -params.shear_x,
782 outline_w,
783 abs_x: g.x,
784 abs_y: -g.y,
785 });
522 }786 }
523 let run_str: String = line_chars[r0..r1].iter().collect();787 shaped.width
524 let font = Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font));788 };
525 let face = font.face();789 lines.push(LayoutSpecLine {
526 let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf);790 glyphs: line_glyphs,
527 max_asc = max_asc.max(asc);791 width,
528 max_desc = max_desc.max(desc);792 ascent: asc,
529 max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0));793 descent: desc,
530 line_max_size = line_max_size.max(st0.size_norm);794 top_anchor,
531 let extra_track = (params.tracking - 1.0) * st0.size_norm * wf;795 });
532 let shaped = shape_line(&face, &run_str, font_px, extra_track);796 char_cursor += raw_char_len + 1;
533 shaped_runs.push((r0, r1, font, font_px, shaped));
534 r0 = r1;
535 }
536 }797 }
537798 } else {
538 let mut total_w = 0.0_f32;799 let styles = resolve_char_styles(params);
539 let mut line_glyphs = Vec::new();800 for raw_line in params.text.split('\n') {
540 for (ri, &(r0, _, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() {801 let raw_char_len = raw_line.chars().count();
541 if ri > 0 {802 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
542 let st_prev = &styles[char_cursor + r0 - 1];803 let line_chars: Vec<char> = line_str.chars().collect();
543 total_w += (params.tracking - 1.0) * st_prev.size_norm * wf;804 let mut shaped_runs: Vec<(usize, Arc<Font>, f32, ShapedLine)> = Vec::new();
544 }805 let mut max_asc = 0.0_f32;
545 let face = font.face();806 let mut max_desc = 0.0_f32;
546 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {807 let mut max_top_anchor = 0.0_f32;
547 let size_px = styles[char_cursor + r0].size_norm * wf;808
548 (params.outline_thickness_norm * size_px).clamp(1.0, 128.0)809 if line_chars.is_empty() {
810 let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm);
811 let (font_px, asc, desc) = size_metrics(&base_face, st, wf);
812 max_asc = asc;
813 max_desc = desc;
814 max_top_anchor = (font_px - desc).max(0.0);
549 } else {815 } else {
550 0.0816 let mut r0 = 0usize;
551 };817 while r0 < line_chars.len() {
552 for g in &shaped.glyphs {818 let st0 = &styles[char_cursor + r0];
553 let idx = char_cursor + r0 + g.char_index;819 let mut r1 = r0 + 1;
554 if idx < c_start || idx >= c_end {820 while r1 < line_chars.len() {
555 continue;821 let st1 = &styles[char_cursor + r1];
822 if st1.family != st0.family
823 || st1.style != st0.style
824 || (st1.size_norm - st0.size_norm).abs() > 1e-5
825 {
826 break;
827 }
828 r1 += 1;
829 }
830 let run_str: String = line_chars[r0..r1].iter().collect();
831 let font = if st0.family == params.font_family && st0.style == params.font_style {
832 Arc::clone(&base_font)
833 } else {
834 Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font))
835 };
836 let face = font.face();
837 let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf);
838 max_asc = max_asc.max(asc);
839 max_desc = max_desc.max(desc);
840 max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0));
841 let extra_track = (params.tracking - 1.0) * st0.size_norm * wf;
842 let shaped = shape_line(&face, &run_str, font_px, extra_track);
843 shaped_runs.push((r0, font, font_px, shaped));
844 r0 = r1;
556 }845 }
557 let st = &styles[idx];
558 let local_origin = [total_w + g.x + st.dx * wf, -g.y - st.dy * wf];
559 let cmds = glyph_path(font, &face, g.id, font_px, local_origin, -st.shear_x);
560 line_glyphs.push(PlacedGlyph { commands: cmds, char_idx: idx, outline_w });
561 }846 }
562 total_w += shaped.width;847
563 }848 let mut total_w = 0.0_f32;
564 let _ = line_max_size;849 let mut line_glyphs = Vec::new();
565 lines.push(LayoutLine {850 for (ri, &(r0, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() {
566 glyphs: line_glyphs,851 if ri > 0 {
567 width: total_w,852 let st_prev = &styles[char_cursor + r0 - 1];
568 ascent: max_asc,853 total_w += (params.tracking - 1.0) * st_prev.size_norm * wf;
569 descent: max_desc,854 }
570 top_anchor: max_top_anchor,855 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
571 });856 let size_px = styles[char_cursor + r0].size_norm * wf;
572 char_cursor += raw_char_len + 1;857 (params.outline_thickness_norm * size_px).clamp(1.0, 128.0)
858 } else {
859 0.0
860 };
861 for g in &shaped.glyphs {
862 let idx = char_cursor + r0 + g.char_index;
863 if idx < c_start || idx >= c_end {
864 continue;
865 }
866 let st = &styles[idx];
867 line_glyphs.push(GlyphSpec {
868 font: Arc::clone(font),
869 glyph_id: g.id,
870 font_px,
871 shear: -st.shear_x,
872 outline_w,
873 abs_x: total_w + g.x + st.dx * wf,
874 abs_y: -g.y - st.dy * wf,
875 });
876 }
877 total_w += shaped.width;
878 }
879 lines.push(LayoutSpecLine {
880 glyphs: line_glyphs,
881 width: total_w,
882 ascent: max_asc,
883 descent: max_desc,
884 top_anchor: max_top_anchor,
885 });
886 char_cursor += raw_char_len + 1;
887 }
573 }888 }
574889
575 let cx = params.center[0] * wf;890 let cx = params.center[0] * wf;
...@@ -602,37 +917,146 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec...@@ -602,37 +917,146 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
602 for (li, line) in lines.into_iter().enumerate() {917 for (li, line) in lines.into_iter().enumerate() {
603 let start_x = cx - line.width * h_frac;918 let start_x = cx - line.width * h_frac;
604 let base_y = baseline_0 + baselines[li];919 let base_y = baseline_0 + baselines[li];
605 for mut pg in line.glyphs {920 for mut spec in line.glyphs {
606 for cmd in &mut pg.commands {921 spec.abs_x += start_x;
607 match cmd {922 spec.abs_y += base_y;
608 Command::MoveTo(p) | Command::LineTo(p) => {923 out.push(spec);
609 p.x += start_x;
610 p.y += base_y;
611 }
612 Command::QuadTo(c, p) => {
613 c.x += start_x;
614 c.y += base_y;
615 p.x += start_x;
616 p.y += base_y;
617 }
618 Command::CurveTo(c1, c2, p) => {
619 c1.x += start_x;
620 c1.y += base_y;
621 c2.x += start_x;
622 c2.y += base_y;
623 p.x += start_x;
624 p.y += base_y;
625 }
626 Command::Close => {}
627 }
628 }
629 let _ = pg.char_idx;
630 out.push(pg);
631 }924 }
632 }925 }
633 Some((out, total_chars))926 Some((out, total_chars))
634}927}
635928
929fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> {
930 let (specs, total_chars) = layout_glyph_specs(dims, params)?;
931 let mut out = Vec::with_capacity(specs.len());
932 for spec in &specs {
933 let face = spec.font.face();
934 let commands = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, [spec.abs_x, spec.abs_y], spec.shear);
935 out.push(PlacedGlyph { commands });
936 }
937 Some((out, total_chars))
938}
939
940const GLYPH_BASELINE_ANCHOR: f32 = 256.0;
941const GLYPH_BASELINE_ANCHOR_I32: i32 = 256;
942const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;
943const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024;
944
945#[derive(Clone, Copy, PartialEq, Eq, Hash)]
946struct GlyphCacheKey {
947 font_id: u64,
948 glyph_id: u16,
949 size_bits: u32,
950 lean_bits: u32,
951 stroke_bits: u32,
952 sub_x_bits: u32,
953 sub_y_bits: u32,
954}
955
956struct CachedGlyphCoverage {
957 fill: Option<Coverage>,
958 stroke: Option<Coverage>,
959 bytes: usize,
960}
961
962struct GlyphCache {
963 map: HashMap<GlyphCacheKey, Arc<CachedGlyphCoverage>>,
964 order: VecDeque<GlyphCacheKey>,
965 total_bytes: usize,
966}
967
968impl GlyphCache {
969 fn new() -> Self {
970 Self {
971 map: HashMap::new(),
972 order: VecDeque::new(),
973 total_bytes: 0,
974 }
975 }
976
977 fn get(&self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {
978 self.map.get(key).cloned()
979 }
980
981 fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) {
982 if val.bytes > MAX_GLYPH_CACHE_BYTES || self.map.contains_key(&key) {
983 return;
984 }
985 while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES {
986 let Some(old_key) = self.order.pop_front() else {
987 break;
988 };
989 if let Some(removed) = self.map.remove(&old_key) {
990 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);
991 }
992 }
993 self.total_bytes += val.bytes;
994 self.order.push_back(key);
995 self.map.insert(key, val);
996 }
997}
998
999fn glyph_cache() -> &'static Mutex<GlyphCache> {
1000 static CACHE: OnceLock<Mutex<GlyphCache>> = OnceLock::new();
1001 CACHE.get_or_init(|| Mutex::new(GlyphCache::new()))
1002}
1003
1004fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) {
1005 let ix = spec.abs_x.floor() as i32;
1006 let iy = spec.abs_y.floor() as i32;
1007 let fx = spec.abs_x - ix as f32;
1008 let fy = spec.abs_y - iy as f32;
1009
1010 let total_lean = spec.font.lean + spec.shear;
1011 let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean };
1012 let stroke_bits = if want_outline {
1013 spec.outline_w.to_bits()
1014 } else {
1015 0
1016 };
1017 let key = GlyphCacheKey {
1018 font_id: spec.font.id,
1019 glyph_id: spec.glyph_id.0,
1020 size_bits: spec.font_px.to_bits(),
1021 lean_bits: lean_norm.to_bits(),
1022 stroke_bits,
1023 sub_x_bits: if fx == 0.0 { 0 } else { fx.to_bits() },
1024 sub_y_bits: if fy == 0.0 { 0 } else { fy.to_bits() },
1025 };
1026
1027 if let Some(hit) = glyph_cache().lock().unwrap().get(&key) {
1028 return (ix, iy, hit);
1029 }
1030
1031 // Anchor outlines near 256px so zeno's flattening precision matches full-canvas rasterization.
1032 let sub_origin = [GLYPH_BASELINE_ANCHOR + fx, GLYPH_BASELINE_ANCHOR + fy];
1033 let face = spec.font.face();
1034 let path = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, sub_origin, spec.shear);
1035 let fill_cov = fill(&path).map(|mut c| {
1036 c.left -= GLYPH_BASELINE_ANCHOR_I32;
1037 c.top -= GLYPH_BASELINE_ANCHOR_I32;
1038 c
1039 });
1040 let stroke_cov = if want_outline {
1041 stroke(&path, spec.outline_w).map(|mut c| {
1042 c.left -= GLYPH_BASELINE_ANCHOR_I32;
1043 c.top -= GLYPH_BASELINE_ANCHOR_I32;
1044 c
1045 })
1046 } else {
1047 None
1048 };
1049 let bytes = fill_cov.as_ref().map_or(0, |c| c.data.len())
1050 + stroke_cov.as_ref().map_or(0, |c| c.data.len());
1051 let entry = Arc::new(CachedGlyphCoverage {
1052 fill: fill_cov,
1053 stroke: stroke_cov,
1054 bytes,
1055 });
1056 glyph_cache().lock().unwrap().insert(key, Arc::clone(&entry));
1057 (ix, iy, entry)
1058}
1059
636fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {1060fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {
637 if !sigma.is_finite() || sigma < 0.05 {1061 if !sigma.is_finite() || sigma < 0.05 {
638 return (0, vec![1.0]);1062 return (0, vec![1.0]);
...@@ -730,20 +1154,22 @@ fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32,...@@ -730,20 +1154,22 @@ fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32,
730 }1154 }
731}1155}
7321156
733fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) {1157fn blit_plane_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) {
1158 let c_left = c.left + offset[0];
1159 let c_top = c.top + offset[1];
734 let cw = c.width as i32;1160 let cw = c.width as i32;
735 let ch = c.height as i32;1161 let ch = c.height as i32;
736 let x0 = (origin[0] - c.left).max(0);1162 let x0 = (origin[0] - c_left).max(0);
737 let y0 = (origin[1] - c.top).max(0);1163 let y0 = (origin[1] - c_top).max(0);
738 let x1 = (origin[0] + tw as i32 - c.left).min(cw);1164 let x1 = (origin[0] + tw as i32 - c_left).min(cw);
739 let y1 = (origin[1] + th as i32 - c.top).min(ch);1165 let y1 = (origin[1] + th as i32 - c_top).min(ch);
740 if x0 >= x1 || y0 >= y1 {1166 if x0 >= x1 || y0 >= y1 {
741 return;1167 return;
742 }1168 }
743 let span = (x1 - x0) as usize;1169 let span = (x1 - x0) as usize;
744 let dst_x0 = (c.left + x0 - origin[0]) as usize;1170 let dst_x0 = (c_left + x0 - origin[0]) as usize;
745 for y in y0..y1 {1171 for y in y0..y1 {
746 let py = (c.top + y - origin[1]) as usize;1172 let py = (c_top + y - origin[1]) as usize;
747 let src_start = y as usize * c.width as usize + x0 as usize;1173 let src_start = y as usize * c.width as usize + x0 as usize;
748 let src_row = &c.data[src_start..src_start + span];1174 let src_row = &c.data[src_start..src_start + span];
749 let dst_start = py * tw + dst_x0;1175 let dst_start = py * tw + dst_x0;
...@@ -756,6 +1182,32 @@ fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &...@@ -756,6 +1182,32 @@ fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &
756 }1182 }
757}1183}
7581184
1185fn blit_plane_u8_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [u8]) {
1186 let c_left = c.left + offset[0];
1187 let c_top = c.top + offset[1];
1188 let cw = c.width as i32;
1189 let ch = c.height as i32;
1190 let x0 = (origin[0] - c_left).max(0);
1191 let y0 = (origin[1] - c_top).max(0);
1192 let x1 = (origin[0] + tw as i32 - c_left).min(cw);
1193 let y1 = (origin[1] + th as i32 - c_top).min(ch);
1194 if x0 >= x1 || y0 >= y1 {
1195 return;
1196 }
1197 let span = (x1 - x0) as usize;
1198 let dst_x0 = (c_left + x0 - origin[0]) as usize;
1199 for y in y0..y1 {
1200 let py = (c_top + y - origin[1]) as usize;
1201 let src_start = y as usize * c.width as usize + x0 as usize;
1202 let src_row = &c.data[src_start..src_start + span];
1203 let dst_start = py * tw + dst_x0;
1204 let dst_row = &mut plane[dst_start..dst_start + span];
1205 for (d, &a) in dst_row.iter_mut().zip(src_row.iter()) {
1206 *d = (*d).max(a);
1207 }
1208 }
1209}
1210
759/// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and1211/// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and
760/// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer.1212/// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer.
761pub fn rasterize_text_plus_rich(1213pub fn rasterize_text_plus_rich(
...@@ -769,10 +1221,10 @@ pub fn rasterize_text_plus_rich(...@@ -769,10 +1221,10 @@ pub fn rasterize_text_plus_rich(
769 if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 {1221 if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 {
770 return empty();1222 return empty();
771 }1223 }
772 let Some((glyphs, _)) = layout_glyphs(dims, params) else {1224 let Some((specs, _)) = layout_glyph_specs(dims, params) else {
773 return empty();1225 return empty();
774 };1226 };
775 if glyphs.is_empty() {1227 if specs.is_empty() {
776 return empty();1228 return empty();
777 }1229 }
7781230
...@@ -788,31 +1240,31 @@ pub fn rasterize_text_plus_rich(...@@ -788,31 +1240,31 @@ pub fn rasterize_text_plus_rich(
788 let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1);1240 let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1);
7891241
790 let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);1242 let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
791 let mut grow = |c: &Coverage, pad: i32| {1243 let mut grow = |c: &Coverage, ox: i32, oy: i32, pad: i32| {
792 min_x = min_x.min(c.left.saturating_sub(pad));1244 let left = c.left.saturating_add(ox);
793 min_y = min_y.min(c.top.saturating_sub(pad));1245 let top = c.top.saturating_add(oy);
794 max_x = max_x.max((c.left + c.width as i32).saturating_add(pad));1246 min_x = min_x.min(left.saturating_sub(pad));
795 max_y = max_y.max((c.top + c.height as i32).saturating_add(pad));1247 min_y = min_y.min(top.saturating_sub(pad));
1248 max_x = max_x.max((left + c.width as i32).saturating_add(pad));
1249 max_y = max_y.max((top + c.height as i32).saturating_add(pad));
796 };1250 };
7971251
798 let mut placed = Vec::with_capacity(glyphs.len());1252 let mut placed = Vec::with_capacity(specs.len());
799 let mut any_outline = false;1253 let mut any_outline = false;
800 for g in &glyphs {1254 for spec in &specs {
801 let f = fill(&g.commands);1255 if !spec.abs_x.is_finite() || !spec.abs_y.is_finite() {
802 let l = if has_outline && g.outline_w > 1e-3 {1256 continue;
803 let s = stroke(&g.commands, g.outline_w);1257 }
804 any_outline |= s.is_some();1258 let want_outline = has_outline && spec.outline_w > 1e-3;
805 s1259 let (ix, iy, cov) = cached_glyph_coverage(spec, want_outline);
806 } else {1260 if let Some(c) = &cov.fill {
807 None1261 grow(c, ix, iy, eff_pad);
808 };
809 if let Some(c) = &f {
810 grow(c, eff_pad);
811 }1262 }
812 if let Some(c) = &l {1263 if let Some(c) = &cov.stroke {
813 grow(c, eff_pad);1264 any_outline = true;
1265 grow(c, ix, iy, eff_pad);
814 }1266 }
815 placed.push((f, l));1267 placed.push((ix, iy, cov));
816 }1268 }
817 if min_x > max_x || min_y > max_y {1269 if min_x > max_x || min_y > max_y {
818 return empty();1270 return empty();
...@@ -828,14 +1280,47 @@ pub fn rasterize_text_plus_rich(...@@ -828,14 +1280,47 @@ pub fn rasterize_text_plus_rich(
828 let tw = (end_x - origin_x) as usize;1280 let tw = (end_x - origin_x) as usize;
829 let th = (end_y - origin_y) as usize;1281 let th = (end_y - origin_y) as usize;
8301282
1283 let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999));
1284 let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999));
1285 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
1286 let mut out = vec![0u8; tw * th * 4];
1287
1288 if !any_outline && sx1 <= 0.05 && sy1 <= 0.05 {
1289 let mut fill_u8 = vec![0u8; tw * th];
1290 for (ix, iy, cov) in &placed {
1291 if let Some(c) = &cov.fill {
1292 blit_plane_u8_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_u8);
1293 }
1294 }
1295 let f_scale = fc[3] * glow1;
1296 let mut lut = [[0u8; 4]; 256];
1297 for (a_u8, entry) in lut.iter_mut().enumerate().skip(1) {
1298 let fa = ((a_u8 as f32 / 255.0) * f_scale).clamp(0.0, 1.0);
1299 if fa > 0.0 {
1300 *entry = [
1301 (fc[0] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1302 (fc[1] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1303 (fc[2] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1304 (fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1305 ];
1306 }
1307 }
1308 for (px, &a) in out.chunks_exact_mut(4).zip(fill_u8.iter()) {
1309 if a != 0 {
1310 px.copy_from_slice(&lut[a as usize]);
1311 }
1312 }
1313 return ([tw as u32, th as u32], [origin_x, origin_y], out);
1314 }
1315
831 let mut fill_plane = vec![0.0_f32; tw * th];1316 let mut fill_plane = vec![0.0_f32; tw * th];
832 let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }];1317 let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }];
833 for (f, l) in &placed {1318 for (ix, iy, cov) in &placed {
834 if let Some(c) = f {1319 if let Some(c) = &cov.fill {
835 blit_plane_max(c, [origin_x, origin_y], tw, th, &mut fill_plane);1320 blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_plane);
836 }1321 }
837 if let Some(c) = l {1322 if let Some(c) = &cov.stroke {
838 blit_plane_max(c, [origin_x, origin_y], tw, th, &mut line_plane);1323 blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut line_plane);
839 }1324 }
840 }1325 }
8411326
...@@ -846,10 +1331,6 @@ pub fn rasterize_text_plus_rich(...@@ -846,10 +1331,6 @@ pub fn rasterize_text_plus_rich(
846 apply_separable_gaussian(&mut line_plane, tw, th, sx2, sy2);1331 apply_separable_gaussian(&mut line_plane, tw, th, sx2, sy2);
847 }1332 }
8481333
849 let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999));
850 let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999));
851 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
852 let mut out = vec![0u8; tw * th * 4];
853 if any_outline {1334 if any_outline {
854 let f_scale = fc[3] * glow1;1335 let f_scale = fc[3] * glow1;
855 let o_scale = oc[3] * glow2;1336 let o_scale = oc[3] * glow2;
...@@ -1956,4 +2437,82 @@ mod tests {...@@ -1956,4 +2437,82 @@ mod tests {
1956 }2437 }
1957 }2438 }
1958 }2439 }
2440
2441 #[test]
2442 fn glyph_cache_is_deterministic_and_bounded() {
2443 let p = RichTextPlusParams {
2444 text: "Mississippi 1234",
2445 font_family: "Helvetica",
2446 font_style: "Regular",
2447 size_norm: 0.08,
2448 tracking: 1.0,
2449 line_spacing: 1.0,
2450 center: [0.5, 0.5],
2451 h_lcr: 0.0,
2452 v_tcb: 0.0,
2453 fill_rgba: [1.0, 0.85, 0.7, 1.0],
2454 write_on_start: 0.0,
2455 write_on_end: 1.0,
2456 shear_x: 0.0,
2457 cls: &[],
2458 outline_rgba: [0.1, 0.2, 0.3, 0.9],
2459 outline_thickness_norm: 0.03,
2460 outline_enabled: true,
2461 soft_fill: [0.0; 3],
2462 soft_outline: [0.0; 3],
2463 baseline_at_center: false,
2464 };
2465 let first = rasterize_text_plus_rich([960, 540], &p, 0);
2466 let second = rasterize_text_plus_rich([960, 540], &p, 0);
2467 assert_eq!(first, second, "cached glyph rasterization must be bit-identical");
2468
2469 let mut p_plain = p;
2470 p_plain.outline_enabled = false;
2471 let p1 = rasterize_text_plus_rich([960, 540], &p_plain, 0);
2472 let p2 = rasterize_text_plus_rich([960, 540], &p_plain, 0);
2473 assert_eq!(p1, p2, "u8 fast-path glyph rasterization must be bit-identical");
2474
2475 // Verify bounded eviction in GlyphCache.
2476 let mut cache = GlyphCache::new();
2477 for i in 0..(MAX_GLYPH_CACHE_ENTRIES + 64) {
2478 let key = GlyphCacheKey {
2479 font_id: 999,
2480 glyph_id: i as u16,
2481 size_bits: 1000,
2482 lean_bits: 0,
2483 stroke_bits: 0,
2484 sub_x_bits: 0,
2485 sub_y_bits: 0,
2486 };
2487 let entry = Arc::new(CachedGlyphCoverage {
2488 fill: Some(Coverage {
2489 left: 0,
2490 top: 0,
2491 width: 4,
2492 height: 4,
2493 data: vec![255; 16],
2494 }),
2495 stroke: None,
2496 bytes: 16,
2497 });
2498 cache.insert(key, entry);
2499 }
2500 assert!(cache.map.len() <= MAX_GLYPH_CACHE_ENTRIES);
2501 assert!(cache.total_bytes <= MAX_GLYPH_CACHE_BYTES);
2502 }
2503
2504 #[test]
2505 fn lazy_font_lookup_resolves_and_caches() {
2506 let f1 = Font::find("Helvetica Neue", "Regular").expect("Helvetica Neue");
2507 let f2 = Font::find("Helvetica Neue", "Regular").expect("cached Helvetica Neue");
2508 assert_eq!(f1.id, f2.id);
2509 let mut t_sum = std::time::Duration::ZERO;
2510 for _ in 0..20 {
2511 let t0 = std::time::Instant::now();
2512 let f = Font::find("Helvetica Neue", "Regular").unwrap();
2513 t_sum += t0.elapsed();
2514 assert_eq!(f.id, f1.id);
2515 }
2516 assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}");
2517 }
1959}2518}