| author | |
| committer | |
| log | 138aa6b97bbbf1feaf785a127ca34a5e1a487476 |
| tree | 9815f1cafe8b91ed8a46f56c7a4407045fecb714 |
| parent | 5c885076bb1b170ed84529096c0fa94fce3c4cef |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
TextPlus (and Text3D plates, which render through it) now use fontdb
discovery, rustybuzz shaping, ttf-parser outlines and analytic zeno fill
and stroke. The outline is a round-join zeno stroke composed under the
fill on the CPU; CharacterSpacing adds (t-1)*Size*W per gap, calibrated
against Fusion 21.1. Text3D plates render at 2048x1024.
Assisted-by: claude-sonnet-5.57 files changed, 628 insertions(+), 164 deletions(-)
Cargo.lock+65-3| ... | @@ -731,6 +731,15 @@ version = "1.0.0" | ... | @@ -731,6 +731,15 @@ version = "1.0.0" |
| 731 | source = "registry+https://github.com/rust-lang/crates.io-index" | 731 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 732 | checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" | 732 | checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" |
| 733 | 733 | ||
| 734 | [[package]] | ||
| 735 | name = "core_maths" | ||
| 736 | version = "0.1.1" | ||
| 737 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 738 | checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" | ||
| 739 | dependencies = [ | ||
| 740 | "libm", | ||
| 741 | ] | ||
| 742 | |||
| 734 | [[package]] | 743 | [[package]] |
| 735 | name = "coreaudio-rs" | 744 | name = "coreaudio-rs" |
| 736 | version = "0.11.3" | 745 | version = "0.11.3" |
| ... | @@ -1003,12 +1012,13 @@ dependencies = [ | ... | @@ -1003,12 +1012,13 @@ dependencies = [ |
| 1003 | "cc", | 1012 | "cc", |
| 1004 | "cpal", | 1013 | "cpal", |
| 1005 | "exr", | 1014 | "exr", |
| 1015 | "fontdb 0.23.0", | ||
| 1006 | "image", | 1016 | "image", |
| 1007 | "model", | 1017 | "model", |
| 1008 | "png", | 1018 | "png", |
| 1009 | "pollster", | 1019 | "pollster", |
| 1020 | "rustybuzz", | ||
| 1010 | "symphonia", | 1021 | "symphonia", |
| 1011 | "text", | ||
| 1012 | "theme", | 1022 | "theme", |
| 1013 | "wgpu", | 1023 | "wgpu", |
| 1014 | "zeno", | 1024 | "zeno", |
| ... | @@ -1217,6 +1227,19 @@ dependencies = [ | ... | @@ -1217,6 +1227,19 @@ dependencies = [ |
| 1217 | "roxmltree 0.20.0", | 1227 | "roxmltree 0.20.0", |
| 1218 | ] | 1228 | ] |
| 1219 | 1229 | ||
| 1230 | [[package]] | ||
| 1231 | name = "fontdb" | ||
| 1232 | version = "0.23.0" | ||
| 1233 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1234 | checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" | ||
| 1235 | dependencies = [ | ||
| 1236 | "log", | ||
| 1237 | "memmap2", | ||
| 1238 | "slotmap", | ||
| 1239 | "tinyvec", | ||
| 1240 | "ttf-parser", | ||
| 1241 | ] | ||
| 1242 | |||
| 1220 | [[package]] | 1243 | [[package]] |
| 1221 | name = "fontdb" | 1244 | name = "fontdb" |
| 1222 | version = "0.24.0" | 1245 | version = "0.24.0" |
| ... | @@ -2956,6 +2979,24 @@ version = "1.0.23" | ... | @@ -2956,6 +2979,24 @@ version = "1.0.23" |
| 2956 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2979 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2957 | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" | 2980 | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" |
| 2958 | 2981 | ||
| 2982 | [[package]] | ||
| 2983 | name = "rustybuzz" | ||
| 2984 | version = "0.20.1" | ||
| 2985 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2986 | checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" | ||
| 2987 | dependencies = [ | ||
| 2988 | "bitflags 2.13.2", | ||
| 2989 | "bytemuck", | ||
| 2990 | "core_maths", | ||
| 2991 | "log", | ||
| 2992 | "smallvec", | ||
| 2993 | "ttf-parser", | ||
| 2994 | "unicode-bidi-mirroring", | ||
| 2995 | "unicode-ccc", | ||
| 2996 | "unicode-properties", | ||
| 2997 | "unicode-script", | ||
| 2998 | ] | ||
| 2999 | |||
| 2959 | [[package]] | 3000 | [[package]] |
| 2960 | name = "same-file" | 3001 | name = "same-file" |
| 2961 | version = "1.0.6" | 3002 | version = "1.0.6" |
| ... | @@ -3954,6 +3995,9 @@ name = "ttf-parser" | ... | @@ -3954,6 +3995,9 @@ name = "ttf-parser" |
| 3954 | version = "0.25.1" | 3995 | version = "0.25.1" |
| 3955 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3996 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3956 | checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" | 3997 | checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" |
| 3998 | dependencies = [ | ||
| 3999 | "core_maths", | ||
| 4000 | ] | ||
| 3957 | 4001 | ||
| 3958 | [[package]] | 4002 | [[package]] |
| 3959 | name = "typenum" | 4003 | name = "typenum" |
| ... | @@ -3983,7 +4027,7 @@ dependencies = [ | ... | @@ -3983,7 +4027,7 @@ dependencies = [ |
| 3983 | "block2 0.6.2", | 4027 | "block2 0.6.2", |
| 3984 | "draw", | 4028 | "draw", |
| 3985 | "edit", | 4029 | "edit", |
| 3986 | "fontdb", | 4030 | "fontdb 0.24.0", |
| 3987 | "knife-window-host", | 4031 | "knife-window-host", |
| 3988 | "libc", | 4032 | "libc", |
| 3989 | "nucleo-matcher", | 4033 | "nucleo-matcher", |
| ... | @@ -4013,6 +4057,18 @@ version = "0.3.18" | ... | @@ -4013,6 +4057,18 @@ version = "0.3.18" |
| 4013 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4057 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4014 | checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" | 4058 | checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" |
| 4015 | 4059 | ||
| 4060 | [[package]] | ||
| 4061 | name = "unicode-bidi-mirroring" | ||
| 4062 | version = "0.4.0" | ||
| 4063 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4064 | checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" | ||
| 4065 | |||
| 4066 | [[package]] | ||
| 4067 | name = "unicode-ccc" | ||
| 4068 | version = "0.4.0" | ||
| 4069 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4070 | checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" | ||
| 4071 | |||
| 4016 | [[package]] | 4072 | [[package]] |
| 4017 | name = "unicode-general-category" | 4073 | name = "unicode-general-category" |
| 4018 | version = "1.1.0" | 4074 | version = "1.1.0" |
| ... | @@ -4040,6 +4096,12 @@ dependencies = [ | ... | @@ -4040,6 +4096,12 @@ dependencies = [ |
| 4040 | "tinyvec", | 4096 | "tinyvec", |
| 4041 | ] | 4097 | ] |
| 4042 | 4098 | ||
| 4099 | [[package]] | ||
| 4100 | name = "unicode-properties" | ||
| 4101 | version = "0.1.5" | ||
| 4102 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4103 | checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" | ||
| 4104 | |||
| 4043 | [[package]] | 4105 | [[package]] |
| 4044 | name = "unicode-script" | 4106 | name = "unicode-script" |
| 4045 | version = "0.5.9" | 4107 | version = "0.5.9" |
| ... | @@ -4072,7 +4134,7 @@ checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" | ... | @@ -4072,7 +4134,7 @@ checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" |
| 4072 | dependencies = [ | 4134 | dependencies = [ |
| 4073 | "base64", | 4135 | "base64", |
| 4074 | "data-url", | 4136 | "data-url", |
| 4075 | "fontdb", | 4137 | "fontdb 0.24.0", |
| 4076 | "harfrust 0.12.0", | 4138 | "harfrust 0.12.0", |
| 4077 | "imagesize", | 4139 | "imagesize", |
| 4078 | "kurbo", | 4140 | "kurbo", |
Cargo.toml+2| ... | @@ -34,10 +34,12 @@ theme = { path = "../the-knife/knife/theme" } | ... | @@ -34,10 +34,12 @@ theme = { path = "../the-knife/knife/theme" } |
| 34 | accesskit = "0.25.1" | 34 | accesskit = "0.25.1" |
| 35 | accesskit_winit = { version = "0.34", default-features = false, features = ["rwh_06"] } | 35 | accesskit_winit = { version = "0.34", default-features = false, features = ["rwh_06"] } |
| 36 | bytemuck = { version = "1.25", features = ["derive"] } | 36 | bytemuck = { version = "1.25", features = ["derive"] } |
| 37 | fontdb = { version = "0.23", default-features = false, features = ["std", "fs", "memmap"] } | ||
| 37 | image = { version = "0.25", default-features = false, features = ["jpeg", "png", "exr", "tiff", "webp"] } | 38 | image = { version = "0.25", default-features = false, features = ["jpeg", "png", "exr", "tiff", "webp"] } |
| 38 | mlua = { version = "0.10", features = ["lua54", "vendored"] } | 39 | mlua = { version = "0.10", features = ["lua54", "vendored"] } |
| 39 | png = "0.18" | 40 | png = "0.18" |
| 40 | pollster = "0.4" | 41 | pollster = "0.4" |
| 42 | rustybuzz = "0.20" | ||
| 41 | wgpu = "30.0.1" | 43 | wgpu = "30.0.1" |
| 42 | winit = "0.30.13" | 44 | winit = "0.30.13" |
| 43 | zeno = "0.3.3" | 45 | zeno = "0.3.3" |
crates/engine/Cargo.toml+2-1| ... | @@ -12,12 +12,13 @@ path = "src/bin/render_check.rs" | ... | @@ -12,12 +12,13 @@ path = "src/bin/render_check.rs" |
| 12 | bytemuck.workspace = true | 12 | bytemuck.workspace = true |
| 13 | cpal = "0.15" | 13 | cpal = "0.15" |
| 14 | exr = "1.74" | 14 | exr = "1.74" |
| 15 | fontdb.workspace = true | ||
| 15 | image.workspace = true | 16 | image.workspace = true |
| 16 | model.workspace = true | 17 | model.workspace = true |
| 17 | png.workspace = true | 18 | png.workspace = true |
| 18 | pollster.workspace = true | 19 | pollster.workspace = true |
| 20 | rustybuzz.workspace = true | ||
| 19 | symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } | 21 | symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } |
| 20 | text.workspace = true | ||
| 21 | theme.workspace = true | 22 | theme.workspace = true |
| 22 | wgpu.workspace = true | 23 | wgpu.workspace = true |
| 23 | zeno.workspace = true | 24 | zeno.workspace = true |
crates/engine/src/eval/text_3d.rs+9-31| ... | @@ -111,7 +111,7 @@ impl Engine { | ... | @@ -111,7 +111,7 @@ impl Engine { |
| 111 | time: f64, | 111 | time: f64, |
| 112 | frame_i: i64, | 112 | frame_i: i64, |
| 113 | comp_dims: [u32; 2], | 113 | comp_dims: [u32; 2], |
| 114 | enc: &mut wgpu::CommandEncoder, | 114 | _enc: &mut wgpu::CommandEncoder, |
| 115 | stats: &mut EvalStats, | 115 | stats: &mut EvalStats, |
| 116 | ) -> CachedTexture { | 116 | ) -> CachedTexture { |
| 117 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; | 117 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; |
| ... | @@ -190,8 +190,8 @@ impl Engine { | ... | @@ -190,8 +190,8 @@ impl Engine { |
| 190 | stats.nodes_evaluated += 1; | 190 | stats.nodes_evaluated += 1; |
| 191 | 191 | ||
| 192 | let size_px = size_norm * size[0] as f32; | 192 | let size_px = size_norm * size[0] as f32; |
| 193 | let outline_radius = if is_text_outline && outline_thickness > 1e-4 { | 193 | let outline_width_px = if is_text_outline && outline_thickness > 1e-4 { |
| 194 | (outline_thickness * size_px * 0.50).clamp(1.0, 28.0) | 194 | (outline_thickness * size_px).clamp(2.0, 56.0) |
| 195 | } else { | 195 | } else { |
| 196 | 0.0 | 196 | 0.0 |
| 197 | }; | 197 | }; |
| ... | @@ -203,7 +203,6 @@ impl Engine { | ... | @@ -203,7 +203,6 @@ impl Engine { |
| 203 | } else { | 203 | } else { |
| 204 | 0 | 204 | 0 |
| 205 | }; | 205 | }; |
| 206 | let dod_pad = (outline_radius.ceil() as i32 + 2).max(border_pad_px); | ||
| 207 | let (tex_size, origin, mut pixels) = rasterize_text_plus( | 206 | let (tex_size, origin, mut pixels) = rasterize_text_plus( |
| 208 | size, | 207 | size, |
| 209 | &TextPlusParams { | 208 | &TextPlusParams { |
| ... | @@ -221,8 +220,10 @@ impl Engine { | ... | @@ -221,8 +220,10 @@ impl Engine { |
| 221 | write_on_end: write_end, | 220 | write_on_end: write_end, |
| 222 | shear_x, | 221 | shear_x, |
| 223 | cls: cls_entries, | 222 | cls: cls_entries, |
| 223 | outline_rgba: outline_rgba.map(|c| c * elem2_opacity), | ||
| 224 | outline_width_px, | ||
| 224 | }, | 225 | }, |
| 225 | dod_pad, | 226 | border_pad_px, |
| 226 | ); | 227 | ); |
| 227 | 228 | ||
| 228 | // Fusion TextPlus ElementShape = 2 (BorderFill): draw filled (optionally rounded) box(es) | 229 | // Fusion TextPlus ElementShape = 2 (BorderFill): draw filled (optionally rounded) box(es) |
| ... | @@ -433,37 +434,14 @@ impl Engine { | ... | @@ -433,37 +434,14 @@ impl Engine { |
| 433 | } | 434 | } |
| 434 | } | 435 | } |
| 435 | 436 | ||
| 436 | let fill_tex = create_texture_dod( | 437 | let final_tex = create_texture_dod(&self.device, tex_size, origin, size, key); |
| 437 | &self.device, | ||
| 438 | tex_size, | ||
| 439 | origin, | ||
| 440 | size, | ||
| 441 | if outline_radius > 0.0 { 0 } else { key }, | ||
| 442 | ); | ||
| 443 | self.queue.write_texture( | 438 | self.queue.write_texture( |
| 444 | fill_tex.texture.as_image_copy(), | 439 | final_tex.texture.as_image_copy(), |
| 445 | &pixels, | 440 | &pixels, |
| 446 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) }, | 441 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) }, |
| 447 | wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 }, | 442 | wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 }, |
| 448 | ); | 443 | ); |
| 449 | 444 | ||
| 450 | let final_tex = if outline_radius > 0.0 { | ||
| 451 | // Single-pass circular Euclidean L2 outline + fill-over-outline composite across DoD! | ||
| 452 | let dst = create_texture_dod(&self.device, tex_size, origin, size, key); | ||
| 453 | let mut u = UniformParams::default(); | ||
| 454 | u.p[0] = [ | ||
| 455 | outline_rgba[0] * elem2_opacity, | ||
| 456 | outline_rgba[1] * elem2_opacity, | ||
| 457 | outline_rgba[2] * elem2_opacity, | ||
| 458 | outline_rgba[3] * elem2_opacity, | ||
| 459 | ]; | ||
| 460 | u.p[1] = [outline_radius, 0.0, 0.0, 0.0]; | ||
| 461 | self.dispatch_op(enc, ShaderOp::TextOutline, &fill_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u); | ||
| 462 | dst | ||
| 463 | } else { | ||
| 464 | fill_tex | ||
| 465 | }; | ||
| 466 | |||
| 467 | self.cache.insert(key, final_tex.clone(), node.id, frame_i); | 445 | self.cache.insert(key, final_tex.clone(), node.id, frame_i); |
| 468 | final_tex | 446 | final_tex |
| 469 | } | 447 | } |
| ... | @@ -545,7 +523,7 @@ impl Engine { | ... | @@ -545,7 +523,7 @@ impl Engine { |
| 545 | for ms in &mesh_specs { | 523 | for ms in &mesh_specs { |
| 546 | let tex = if let Some(t3d) = &ms.text3d { | 524 | let tex = if let Some(t3d) = &ms.text3d { |
| 547 | let tnode = comp.node(t3d.node_id); | 525 | let tnode = comp.node(t3d.node_id); |
| 548 | Some(self.eval_text_plus(comp, tnode, time, frame_i, [1024, 512], enc, stats)) | 526 | Some(self.eval_text_plus(comp, tnode, time, frame_i, [2048, 1024], enc, stats)) |
| 549 | } else { | 527 | } else { |
| 550 | ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)) | 528 | ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)) |
| 551 | }; | 529 | }; |
crates/engine/src/lib.rs+1| ... | @@ -10,6 +10,7 @@ pub mod particles; | ... | @@ -10,6 +10,7 @@ pub mod particles; |
| 10 | pub mod profile; | 10 | pub mod profile; |
| 11 | pub mod ram_cache; | 11 | pub mod ram_cache; |
| 12 | pub mod scene3d; | 12 | pub mod scene3d; |
| 13 | pub mod text_engine; | ||
| 13 | 14 | ||
| 14 | pub use audio::{AudioPlayer, AudioTrack}; | 15 | pub use audio::{AudioPlayer, AudioTrack}; |
| 15 | pub use cache::{ | 16 | pub use cache::{ |
crates/engine/src/media.rs+101-129| ... | @@ -1,6 +1,7 @@ | ... | @@ -1,6 +1,7 @@ |
| 1 | //! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and | 1 | //! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and |
| 2 | //! CPU rasterizers (`TextPlus` via `knife/text` CoreText, `PolylineMask` via `zeno`). | 2 | //! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`). |
| 3 | 3 | ||
| 4 | use crate::text_engine; | ||
| 4 | use model::{ClipSpec, ClsEntry, PolyPoint}; | 5 | use model::{ClipSpec, ClsEntry, PolyPoint}; |
| 5 | use std::collections::HashMap; | 6 | use std::collections::HashMap; |
| 6 | use std::path::{Path, PathBuf}; | 7 | use std::path::{Path, PathBuf}; |
| ... | @@ -663,7 +664,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> { | ... | @@ -663,7 +664,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> { |
| 663 | } | 664 | } |
| 664 | } | 665 | } |
| 665 | 666 | ||
| 666 | /// Parameters for rasterizing a Fusion `TextPlus` node using `knife/text` (CoreText). | 667 | /// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`]. |
| 667 | pub struct TextPlusParams<'a> { | 668 | pub struct TextPlusParams<'a> { |
| 668 | pub text: &'a str, | 669 | pub text: &'a str, |
| 669 | pub font_family: &'a str, | 670 | pub font_family: &'a str, |
| ... | @@ -679,15 +680,19 @@ pub struct TextPlusParams<'a> { | ... | @@ -679,15 +680,19 @@ pub struct TextPlusParams<'a> { |
| 679 | pub write_on_end: f32, | 680 | pub write_on_end: f32, |
| 680 | pub shear_x: f32, // Fusion CharacterShearX | 681 | pub shear_x: f32, // Fusion CharacterShearX |
| 681 | pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides | 682 | pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides |
| 683 | pub outline_rgba: [f32; 4], // Fusion Element 2 color, already scaled by Opacity2 | ||
| 684 | pub outline_width_px: f32, // Fusion Thickness2 as a full stroke width; 0 disables the outline | ||
| 682 | } | 685 | } |
| 683 | 686 | ||
| 684 | /// Rasterizes a `TextPlus` fill layer into premultiplied RGBA8 with automatic Domain-of-Definition | 687 | /// Rasterizes a `TextPlus` layer (outline under fill) into premultiplied RGBA8 with automatic |
| 685 | /// (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a downstream `Transform`) | 688 | /// Domain-of-Definition (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a |
| 686 | /// are never clipped. Returns `(tex_size, dod_origin_px, rgba)`. | 689 | /// downstream `Transform`) are never clipped; `dod_pad` adds margin for decoration drawn from |
| 687 | pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) { | 690 | /// the result. Returns `(tex_size, dod_origin_px, rgba)`. |
| 691 | pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) { | ||
| 688 | let [w, h] = dims; | 692 | let [w, h] = dims; |
| 693 | let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); | ||
| 689 | if params.text.is_empty() || params.size_norm <= 1e-4 { | 694 | if params.text.is_empty() || params.size_norm <= 1e-4 { |
| 690 | return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); | 695 | return empty(); |
| 691 | } | 696 | } |
| 692 | 697 | ||
| 693 | // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on! | 698 | // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on! |
| ... | @@ -695,8 +700,12 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ | ... | @@ -695,8 +700,12 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ |
| 695 | let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize; | 700 | let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize; |
| 696 | let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize; | 701 | let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize; |
| 697 | if c_start >= c_end || c_start >= total_chars { | 702 | if c_start >= c_end || c_start >= total_chars { |
| 698 | return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); | 703 | return empty(); |
| 699 | } | 704 | } |
| 705 | let Some(font) = text_engine::Font::find(params.font_family, params.font_style) else { | ||
| 706 | return empty(); | ||
| 707 | }; | ||
| 708 | let face = font.face(); | ||
| 700 | 709 | ||
| 701 | // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units). | 710 | // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units). |
| 702 | let mut cls_dx = vec![0.0_f32; total_chars]; | 711 | let mut cls_dx = vec![0.0_f32; total_chars]; |
| ... | @@ -717,38 +726,13 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ | ... | @@ -717,38 +726,13 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ |
| 717 | // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text | 726 | // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text |
| 718 | // on 16:9, square, and vertical frames). | 727 | // on 16:9, square, and vertical frames). |
| 719 | let line_box_px = params.size_norm * w as f32 * 0.8; | 728 | let line_box_px = params.size_norm * w as f32 * 0.8; |
| 720 | let weight = style_to_weight(params.font_style); | 729 | let (ascent_em, descent_em) = text_engine::vertical_metrics(&face); |
| 721 | let italic = params.font_style.to_ascii_lowercase().contains("italic") | 730 | let font_px = (line_box_px / (ascent_em + descent_em).max(0.5)).clamp(6.0, 1024.0); |
| 722 | || params.font_style.to_ascii_lowercase().contains("oblique"); | 731 | let descent = descent_em * font_px; |
| 723 | |||
| 724 | let families: Arc<[text::Family]> = if params.font_family.is_empty() { | ||
| 725 | Arc::from([text::Family::Sans]) | ||
| 726 | } else { | ||
| 727 | Arc::from([ | ||
| 728 | text::Family::Named(Arc::from(params.font_family)), | ||
| 729 | text::Family::Sans, | ||
| 730 | ]) | ||
| 731 | }; | ||
| 732 | let probe_font = text::Font { | ||
| 733 | families: families.clone(), | ||
| 734 | size: 100.0, | ||
| 735 | weight, | ||
| 736 | italic, | ||
| 737 | }; | ||
| 738 | let probe_metrics = text::FontHandle::new(&probe_font).metrics(); | ||
| 739 | let design_span = ((probe_metrics.ascent + probe_metrics.descent) / 100.0).max(0.5); | ||
| 740 | let font_px = (line_box_px / design_span).clamp(6.0, 1024.0); | ||
| 741 | let font = text::Font { | ||
| 742 | families, | ||
| 743 | size: font_px, | ||
| 744 | weight, | ||
| 745 | italic, | ||
| 746 | }; | ||
| 747 | let handle = text::FontHandle::new(&font); | ||
| 748 | let metrics = handle.metrics(); | ||
| 749 | 732 | ||
| 750 | // Extra tracking per glyph: Fusion `CharacterSpacing = 1.0` means 0 extra; >1.0 expands cleanly. | 733 | // Fusion `CharacterSpacing = 1.0` adds nothing; each +1.0 adds `Size * W` between characters, |
| 751 | let extra_track = (params.tracking - 1.0) * font_px * 1.15; | 734 | // independent of the font (probed on Fusion 21.1 with Liberation Sans, 8 gaps, 1.3 and 2.0). |
| 735 | let extra_track = (params.tracking - 1.0) * params.size_norm * w as f32; | ||
| 752 | 736 | ||
| 753 | let lines: Vec<&str> = params.text.split('\n').collect(); | 737 | let lines: Vec<&str> = params.text.split('\n').collect(); |
| 754 | let line_height = (line_box_px * params.line_spacing.max(0.05)).max(1.0); | 738 | let line_height = (line_box_px * params.line_spacing.max(0.05)).max(1.0); |
| ... | @@ -759,66 +743,49 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ | ... | @@ -759,66 +743,49 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ |
| 759 | 743 | ||
| 760 | // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy). | 744 | // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy). |
| 761 | let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; | 745 | let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; |
| 762 | let top_anchor = (font_px - metrics.descent).max(0.0); | 746 | let top_anchor = (font_px - descent).max(0.0); |
| 763 | let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor; | 747 | let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor; |
| 764 | let baseline_0 = cy + top_anchor - v_frac * block_h; | 748 | let baseline_0 = cy + top_anchor - v_frac * block_h; |
| 765 | let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; | 749 | let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; |
| 766 | let fc = params.fill_rgba; | 750 | |
| 767 | let shear_x = params.shear_x; | 751 | let outlined = params.outline_width_px > 1e-3 && params.outline_rgba[3] > 0.0; |
| 768 | 752 | ||
| 769 | // Pass 1: rasterize all visible glyphs & collect exact bounds to expand DoD if anything overflows canvas! | 753 | // Pass 1: vector-rasterize every visible glyph and collect exact bounds to expand the DoD. |
| 770 | struct PlacedGlyph { | ||
| 771 | ox: i32, | ||
| 772 | oy: i32, | ||
| 773 | baseline_y: f32, | ||
| 774 | w: i32, | ||
| 775 | h: i32, | ||
| 776 | data: Vec<u8>, | ||
| 777 | } | ||
| 778 | let mut placed = Vec::new(); | 754 | let mut placed = Vec::new(); |
| 779 | let mut min_x = 0i32; | 755 | let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); |
| 780 | let mut min_y = 0i32; | 756 | let mut grow = |c: &text_engine::Coverage, pad: i32| { |
| 781 | let mut max_x = w as i32; | 757 | min_x = min_x.min(c.left - pad); |
| 782 | let mut max_y = h as i32; | 758 | min_y = min_y.min(c.top - pad); |
| 759 | max_x = max_x.max(c.left + c.width as i32 + pad); | ||
| 760 | max_y = max_y.max(c.top + c.height as i32 + pad); | ||
| 761 | }; | ||
| 783 | 762 | ||
| 784 | let mut char_cursor = 0usize; | 763 | let mut char_cursor = 0usize; |
| 785 | for (li, line_str) in lines.iter().enumerate() { | 764 | for (li, line_str) in lines.iter().enumerate() { |
| 786 | let mut glyphs = Vec::new(); | 765 | let shaped = text_engine::shape_line(&face, line_str, font_px, extra_track); |
| 787 | let mut pen_x = 0.0_f32; | 766 | let start_x = cx - shaped.width * h_frac; |
| 788 | for ch in line_str.chars() { | ||
| 789 | let idx = char_cursor; | ||
| 790 | char_cursor += 1; | ||
| 791 | let adv = handle.advance(ch); | ||
| 792 | if idx >= c_start && idx < c_end { | ||
| 793 | if let Some(gid) = handle.glyph(ch) { | ||
| 794 | glyphs.push((gid, pen_x, idx)); | ||
| 795 | } | ||
| 796 | } | ||
| 797 | pen_x += adv + extra_track; | ||
| 798 | } | ||
| 799 | char_cursor += 1; // account for '\n' separator | ||
| 800 | let line_w = (pen_x - extra_track).max(0.0); | ||
| 801 | let start_x = cx - line_w * h_frac; | ||
| 802 | let baseline_y = baseline_0 + (li as f32) * line_height; | 767 | let baseline_y = baseline_0 + (li as f32) * line_height; |
| 803 | 768 | for g in &shaped.glyphs { | |
| 804 | for (gid, gx, idx) in glyphs { | 769 | let idx = char_cursor + g.char_index; |
| 805 | let Some(mask) = handle.rasterize(gid, 1.0, [0, 0]) else { continue }; | 770 | if idx < c_start || idx >= c_end { |
| 806 | let cdx = cls_dx[idx] * w as f32; | 771 | continue; |
| 807 | let cdy = -cls_dy[idx] * w as f32; | ||
| 808 | let ox = (start_x + gx + cdx).round() as i32 + mask.left; | ||
| 809 | let g_base_y = baseline_y + cdy; | ||
| 810 | let oy = g_base_y.round() as i32 - mask.top; | ||
| 811 | let mw = mask.width as i32; | ||
| 812 | let mh = mask.height as i32; | ||
| 813 | let shear_pad = (shear_x.abs() * mh as f32).ceil() as i32; | ||
| 814 | if mw > 0 && mh > 0 { | ||
| 815 | min_x = min_x.min(ox - outline_pad - shear_pad); | ||
| 816 | min_y = min_y.min(oy - outline_pad); | ||
| 817 | max_x = max_x.max(ox + mw + outline_pad + shear_pad); | ||
| 818 | max_y = max_y.max(oy + mh + outline_pad); | ||
| 819 | placed.push(PlacedGlyph { ox, oy, baseline_y: g_base_y, w: mw, h: mh, data: mask.data }); | ||
| 820 | } | 772 | } |
| 773 | let origin = [ | ||
| 774 | start_x + g.x + cls_dx[idx] * w as f32, | ||
| 775 | baseline_y - g.y - cls_dy[idx] * w as f32, | ||
| 776 | ]; | ||
| 777 | let path = text_engine::glyph_path(&font, &face, g.id, font_px, origin, -params.shear_x); | ||
| 778 | let fill = text_engine::fill(&path); | ||
| 779 | let line = if outlined { text_engine::stroke(&path, params.outline_width_px) } else { None }; | ||
| 780 | if let Some(c) = &fill { | ||
| 781 | grow(c, dod_pad); | ||
| 782 | } | ||
| 783 | if let Some(c) = &line { | ||
| 784 | grow(c, dod_pad); | ||
| 785 | } | ||
| 786 | placed.push((fill, line)); | ||
| 821 | } | 787 | } |
| 788 | char_cursor += line_str.chars().count() + 1; // + '\n' separator | ||
| 822 | } | 789 | } |
| 823 | 790 | ||
| 824 | // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded. | 791 | // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded. |
| ... | @@ -826,51 +793,54 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ | ... | @@ -826,51 +793,54 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ |
| 826 | let origin_y = min_y.max(-(h as i32)); | 793 | let origin_y = min_y.max(-(h as i32)); |
| 827 | let end_x = max_x.min((w as i32) * 2); | 794 | let end_x = max_x.min((w as i32) * 2); |
| 828 | let end_y = max_y.min((h as i32) * 2); | 795 | let end_y = max_y.min((h as i32) * 2); |
| 829 | let tw = (end_x - origin_x).max(1) as u32; | 796 | let tw = (end_x - origin_x).max(1) as usize; |
| 830 | let th = (end_y - origin_y).max(1) as u32; | 797 | let th = (end_y - origin_y).max(1) as usize; |
| 831 | let mut out = vec![0u8; (tw as usize) * (th as usize) * 4]; | 798 | |
| 832 | 799 | let mut fill_plane = vec![0u8; tw * th]; | |
| 833 | for g in placed { | 800 | let mut line_plane = vec![0.0_f32; if outlined { tw * th } else { 0 }]; |
| 834 | for my in 0..g.h { | 801 | for (fill, line) in &placed { |
| 835 | let py = g.oy + my; | 802 | if let Some(c) = fill { |
| 836 | let dy = py - origin_y; | 803 | blit_max(c, [origin_x, origin_y], [tw, th], |i, a| fill_plane[i] = fill_plane[i].max(a)); |
| 837 | if dy < 0 || dy >= th as i32 { continue; } | 804 | } |
| 838 | let row_shear = if shear_x.abs() > 1e-4 { | 805 | if let Some(c) = line { |
| 839 | (-((g.baseline_y - py as f32) * shear_x)).round() as i32 | 806 | blit_max(c, [origin_x, origin_y], [tw, th], |i, a| line_plane[i] = line_plane[i].max(a as f32 / 255.0)); |
| 840 | } else { | ||
| 841 | 0 | ||
| 842 | }; | ||
| 843 | for mx in 0..g.w { | ||
| 844 | let dx = g.ox + mx + row_shear - origin_x; | ||
| 845 | if dx < 0 || dx >= tw as i32 { continue; } | ||
| 846 | let cov = g.data[(my * g.w + mx) as usize]; | ||
| 847 | if cov > 0 { | ||
| 848 | let i = ((dy as usize) * (tw as usize) + (dx as usize)) * 4; | ||
| 849 | let a = (cov as f32 / 255.0) * fc[3]; | ||
| 850 | let prev_a = out[i + 3] as f32 / 255.0; | ||
| 851 | let na = a.max(prev_a); | ||
| 852 | out[i] = (fc[0] * na * 255.0).clamp(0.0, 255.0) as u8; | ||
| 853 | out[i + 1] = (fc[1] * na * 255.0).clamp(0.0, 255.0) as u8; | ||
| 854 | out[i + 2] = (fc[2] * na * 255.0).clamp(0.0, 255.0) as u8; | ||
| 855 | out[i + 3] = (na * 255.0).clamp(0.0, 255.0) as u8; | ||
| 856 | } | ||
| 857 | } | ||
| 858 | } | 807 | } |
| 859 | } | 808 | } |
| 860 | 809 | ||
| 861 | ([tw, th], [origin_x, origin_y], out) | 810 | let (fc, oc) = (params.fill_rgba, params.outline_rgba); |
| 811 | let mut out = vec![0u8; tw * th * 4]; | ||
| 812 | for (i, px) in out.chunks_exact_mut(4).enumerate() { | ||
| 813 | let fa = fill_plane[i] as f32 / 255.0 * fc[3]; | ||
| 814 | let oa = if outlined { line_plane[i] * oc[3] } else { 0.0 }; | ||
| 815 | if fa <= 0.0 && oa <= 0.0 { | ||
| 816 | continue; | ||
| 817 | } | ||
| 818 | let under = 1.0 - fa; | ||
| 819 | for k in 0..3 { | ||
| 820 | let v = fc[k] * fa + oc[k] * oa * under; | ||
| 821 | px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8; | ||
| 822 | } | ||
| 823 | px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; | ||
| 824 | } | ||
| 825 | |||
| 826 | ([tw as u32, th as u32], [origin_x, origin_y], out) | ||
| 862 | } | 827 | } |
| 863 | 828 | ||
| 864 | fn style_to_weight(style: &str) -> u16 { | 829 | /// Calls `f(plane_index, coverage)` for every non-zero coverage pixel that lands inside the plane. |
| 865 | let s = style.to_ascii_lowercase(); | 830 | fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut f: impl FnMut(usize, u8)) { |
| 866 | if s.contains("black") || s.contains("heavy") { 900 } | 831 | for y in 0..c.height as i32 { |
| 867 | else if s.contains("extrabold") || s.contains("ultrabold") { 800 } | 832 | let py = c.top + y - origin[1]; |
| 868 | else if s.contains("bold") { 700 } | 833 | if py < 0 || py >= plane[1] as i32 { |
| 869 | else if s.contains("semibold") || s.contains("demi") { 600 } | 834 | continue; |
| 870 | else if s.contains("medium") { 500 } | 835 | } |
| 871 | else if s.contains("light") { 300 } | 836 | for x in 0..c.width as i32 { |
| 872 | else if s.contains("thin") || s.contains("hairline") { 100 } | 837 | let px = c.left + x - origin[0]; |
| 873 | else { 400 } | 838 | let a = c.data[(y as u32 * c.width + x as u32) as usize]; |
| 839 | if a > 0 && px >= 0 && px < plane[0] as i32 { | ||
| 840 | f(py as usize * plane[0] + px as usize, a); | ||
| 841 | } | ||
| 842 | } | ||
| 843 | } | ||
| 874 | } | 844 | } |
| 875 | 845 | ||
| 876 | /// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. | 846 | /// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. |
| ... | @@ -1093,6 +1063,8 @@ mod tests { | ... | @@ -1093,6 +1063,8 @@ mod tests { |
| 1093 | write_on_end: 1.0, | 1063 | write_on_end: 1.0, |
| 1094 | shear_x: 0.0, | 1064 | shear_x: 0.0, |
| 1095 | cls: &[], | 1065 | cls: &[], |
| 1066 | outline_rgba: [0.0; 4], | ||
| 1067 | outline_width_px: 0.0, | ||
| 1096 | }, | 1068 | }, |
| 1097 | 0, | 1069 | 0, |
| 1098 | ) | 1070 | ) |
crates/engine/src/text_engine.rs created+448| ... | @@ -0,0 +1,448 @@ | ||
| 1 | //! Deterministic vector text for `TextPlus` / `Text3D`: system font discovery (`fontdb`), | ||
| 2 | //! HarfBuzz-compatible shaping (`rustybuzz`), OpenType outlines and analytic `zeno` fill and | ||
| 3 | //! stroke. No platform text stack is involved, so glyph coverage depends only on the font file. | ||
| 4 | |||
| 5 | use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag}; | ||
| 6 | use rustybuzz::{Face, Feature, UnicodeBuffer, Variation}; | ||
| 7 | use std::collections::HashMap; | ||
| 8 | use std::sync::{Arc, Mutex, OnceLock}; | ||
| 9 | use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector}; | ||
| 10 | |||
| 11 | /// Tried in order when the requested family is not installed. | ||
| 12 | const FALLBACK_FAMILIES: [&str; 6] = | ||
| 13 | ["Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "Open Sans", "DejaVu Sans"]; | ||
| 14 | |||
| 15 | /// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face. | ||
| 16 | const SYNTHETIC_ITALIC: f32 = 0.2126; | ||
| 17 | |||
| 18 | /// A resolved font file; `face()` parses it on demand. | ||
| 19 | pub struct Font { | ||
| 20 | data: Vec<u8>, | ||
| 21 | index: u32, | ||
| 22 | weight: u16, | ||
| 23 | lean: f32, | ||
| 24 | } | ||
| 25 | |||
| 26 | impl Font { | ||
| 27 | /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the | ||
| 28 | /// system fonts, falling back through [`FALLBACK_FAMILIES`] and finally any installed face. | ||
| 29 | pub fn find(family: &str, style: &str) -> Option<Arc<Font>> { | ||
| 30 | static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new(); | ||
| 31 | let mut cache = CACHE.get_or_init(Default::default).lock().unwrap(); | ||
| 32 | cache | ||
| 33 | .entry((family.to_owned(), style.to_owned())) | ||
| 34 | .or_insert_with(|| resolve(database(), family, style).map(Arc::new)) | ||
| 35 | .clone() | ||
| 36 | } | ||
| 37 | |||
| 38 | pub fn face(&self) -> Face<'_> { | ||
| 39 | let mut face = Face::from_slice(&self.data, self.index).expect("font validated on load"); | ||
| 40 | if face.is_variable() { | ||
| 41 | face.set_variations(&[Variation { tag: Tag::from_bytes(b"wght"), value: self.weight as f32 }]); | ||
| 42 | } | ||
| 43 | face | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | fn database() -> &'static fontdb::Database { | ||
| 48 | static DB: OnceLock<fontdb::Database> = OnceLock::new(); | ||
| 49 | DB.get_or_init(|| { | ||
| 50 | let mut db = fontdb::Database::new(); | ||
| 51 | db.load_system_fonts(); | ||
| 52 | db | ||
| 53 | }) | ||
| 54 | } | ||
| 55 | |||
| 56 | /// CSS-style weight and italic flag for a Fusion style name. | ||
| 57 | pub fn parse_style(style: &str) -> (u16, bool) { | ||
| 58 | let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase(); | ||
| 59 | let weight = if s.contains("black") || s.contains("heavy") { | ||
| 60 | 900 | ||
| 61 | } else if s.contains("extrabold") || s.contains("ultrabold") { | ||
| 62 | 800 | ||
| 63 | } else if s.contains("semibold") || s.contains("demibold") || s.contains("demi") { | ||
| 64 | 600 | ||
| 65 | } else if s.contains("bold") { | ||
| 66 | 700 | ||
| 67 | } else if s.contains("medium") { | ||
| 68 | 500 | ||
| 69 | } else if s.contains("extralight") || s.contains("ultralight") || s.contains("thin") || s.contains("hairline") { | ||
| 70 | 200 | ||
| 71 | } else if s.contains("light") { | ||
| 72 | 300 | ||
| 73 | } else { | ||
| 74 | 400 | ||
| 75 | }; | ||
| 76 | (weight, s.contains("italic") || s.contains("oblique")) | ||
| 77 | } | ||
| 78 | |||
| 79 | fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> { | ||
| 80 | let (weight, italic) = parse_style(style); | ||
| 81 | let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase(); | ||
| 82 | let id = std::iter::once(family) | ||
| 83 | .chain(FALLBACK_FAMILIES) | ||
| 84 | .find_map(|name| pick(db, name, &wanted, weight, italic)) | ||
| 85 | .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) | ||
| 86 | .or_else(|| db.faces().map(|f| f.id).next())?; | ||
| 87 | let info = db.face(id)?; | ||
| 88 | let data = db.with_face_data(id, |data, _| data.to_vec())?; | ||
| 89 | let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 }; | ||
| 90 | Face::from_slice(&data, info.index)?; | ||
| 91 | Some(Font { data, index: info.index, weight, lean }) | ||
| 92 | } | ||
| 93 | |||
| 94 | /// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest | ||
| 95 | /// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere. | ||
| 96 | fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, italic: bool) -> Option<fontdb::ID> { | ||
| 97 | if family.is_empty() { | ||
| 98 | return None; | ||
| 99 | } | ||
| 100 | let mut candidates: Vec<&fontdb::FaceInfo> = db | ||
| 101 | .faces() | ||
| 102 | .filter(|f| f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family))) | ||
| 103 | .collect(); | ||
| 104 | candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index))); | ||
| 105 | let first = candidates.first()?; | ||
| 106 | let exact = candidates.iter().find(|f| { | ||
| 107 | db.with_face_data(f.id, |data, index| { | ||
| 108 | let face = ttf_parser::Face::parse(data, index).ok()?; | ||
| 109 | let names = face.names(); | ||
| 110 | let name = [17, 2].into_iter().find_map(|id| { | ||
| 111 | names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string()) | ||
| 112 | })?; | ||
| 113 | Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style)) | ||
| 114 | }) | ||
| 115 | .flatten() | ||
| 116 | .unwrap_or(false) | ||
| 117 | }); | ||
| 118 | if let Some(face) = exact { | ||
| 119 | return Some(face.id); | ||
| 120 | } | ||
| 121 | let name = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family))?.0.as_str(); | ||
| 122 | db.query(&fontdb::Query { | ||
| 123 | families: &[fontdb::Family::Name(name)], | ||
| 124 | weight: fontdb::Weight(weight), | ||
| 125 | style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, | ||
| 126 | ..Default::default() | ||
| 127 | }) | ||
| 128 | } | ||
| 129 | |||
| 130 | /// Ascent and descent (both positive) in em units, from `hhea`. | ||
| 131 | pub fn vertical_metrics(face: &Face<'_>) -> (f32, f32) { | ||
| 132 | let upem = face.units_per_em() as f32; | ||
| 133 | (face.ascender() as f32 / upem, -(face.descender() as f32) / upem) | ||
| 134 | } | ||
| 135 | |||
| 136 | pub struct ShapedGlyph { | ||
| 137 | pub id: GlyphId, | ||
| 138 | /// Pen offset from the line origin in pixels. | ||
| 139 | pub x: f32, | ||
| 140 | pub y: f32, | ||
| 141 | /// Index (in `char`s) of the first source character of the glyph's cluster. | ||
| 142 | pub char_index: usize, | ||
| 143 | } | ||
| 144 | |||
| 145 | pub struct ShapedLine { | ||
| 146 | pub glyphs: Vec<ShapedGlyph>, | ||
| 147 | /// Advance width in pixels, excluding trailing tracking. | ||
| 148 | pub width: f32, | ||
| 149 | } | ||
| 150 | |||
| 151 | /// Shapes one line at `px` pixels per em. `tracking_px` is added after every cluster and turns | ||
| 152 | /// ligatures off, as ligated glyphs cannot be spaced per character. | ||
| 153 | pub fn shape_line(face: &Face<'_>, text: &str, px: f32, tracking_px: f32) -> ShapedLine { | ||
| 154 | let scale = px / face.units_per_em() as f32; | ||
| 155 | let mut buffer = UnicodeBuffer::new(); | ||
| 156 | buffer.push_str(text); | ||
| 157 | buffer.guess_segment_properties(); | ||
| 158 | let features: &[Feature] = if tracking_px != 0.0 { | ||
| 159 | &[Feature::new(Tag::from_bytes(b"liga"), 0, ..), Feature::new(Tag::from_bytes(b"clig"), 0, ..)] | ||
| 160 | } else { | ||
| 161 | &[] | ||
| 162 | }; | ||
| 163 | let shaped = rustybuzz::shape(face, features, buffer); | ||
| 164 | |||
| 165 | let char_starts: Vec<usize> = text.char_indices().map(|(i, _)| i).collect(); | ||
| 166 | let mut glyphs = Vec::with_capacity(shaped.len()); | ||
| 167 | let (mut pen, mut last_cluster) = (0.0_f32, None); | ||
| 168 | for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) { | ||
| 169 | if last_cluster.is_some_and(|c| c != info.cluster) { | ||
| 170 | pen += tracking_px; | ||
| 171 | } | ||
| 172 | last_cluster = Some(info.cluster); | ||
| 173 | glyphs.push(ShapedGlyph { | ||
| 174 | id: GlyphId(info.glyph_id as u16), | ||
| 175 | x: pen + pos.x_offset as f32 * scale, | ||
| 176 | y: pos.y_offset as f32 * scale, | ||
| 177 | char_index: char_starts.partition_point(|&s| s < info.cluster as usize), | ||
| 178 | }); | ||
| 179 | pen += pos.x_advance as f32 * scale; | ||
| 180 | } | ||
| 181 | ShapedLine { glyphs, width: pen } | ||
| 182 | } | ||
| 183 | |||
| 184 | struct PathBuilder { | ||
| 185 | commands: Vec<Command>, | ||
| 186 | scale: f32, | ||
| 187 | origin: [f32; 2], | ||
| 188 | /// Horizontal shift per pixel above the baseline. | ||
| 189 | lean: f32, | ||
| 190 | } | ||
| 191 | |||
| 192 | impl PathBuilder { | ||
| 193 | fn point(&self, x: f32, y: f32) -> Vector { | ||
| 194 | let (px, py) = (x * self.scale, y * self.scale); | ||
| 195 | Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] - py) | ||
| 196 | } | ||
| 197 | } | ||
| 198 | |||
| 199 | impl OutlineBuilder for PathBuilder { | ||
| 200 | fn move_to(&mut self, x: f32, y: f32) { | ||
| 201 | let p = self.point(x, y); | ||
| 202 | self.commands.push(Command::MoveTo(p)); | ||
| 203 | } | ||
| 204 | fn line_to(&mut self, x: f32, y: f32) { | ||
| 205 | let p = self.point(x, y); | ||
| 206 | self.commands.push(Command::LineTo(p)); | ||
| 207 | } | ||
| 208 | fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { | ||
| 209 | let (c, p) = (self.point(x1, y1), self.point(x, y)); | ||
| 210 | self.commands.push(Command::QuadTo(c, p)); | ||
| 211 | } | ||
| 212 | fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { | ||
| 213 | let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y)); | ||
| 214 | self.commands.push(Command::CurveTo(c1, c2, p)); | ||
| 215 | } | ||
| 216 | fn close(&mut self) { | ||
| 217 | self.commands.push(Command::Close); | ||
| 218 | } | ||
| 219 | } | ||
| 220 | |||
| 221 | /// The glyph's Bézier contours in pixel space (y down) with the baseline pen at `origin`. | ||
| 222 | /// `shear` leans the glyph right per pixel of height; the font's own synthetic italic is added. | ||
| 223 | pub fn glyph_path(font: &Font, face: &Face<'_>, glyph: GlyphId, px: f32, origin: [f32; 2], shear: f32) -> Vec<Command> { | ||
| 224 | let mut builder = PathBuilder { | ||
| 225 | commands: Vec::new(), | ||
| 226 | scale: px / face.units_per_em() as f32, | ||
| 227 | origin, | ||
| 228 | lean: font.lean + shear, | ||
| 229 | }; | ||
| 230 | face.outline_glyph(glyph, &mut builder); | ||
| 231 | builder.commands | ||
| 232 | } | ||
| 233 | |||
| 234 | /// 8-bit coverage over a tight pixel rectangle. | ||
| 235 | pub struct Coverage { | ||
| 236 | pub left: i32, | ||
| 237 | pub top: i32, | ||
| 238 | pub width: u32, | ||
| 239 | pub height: u32, | ||
| 240 | pub data: Vec<u8>, | ||
| 241 | } | ||
| 242 | |||
| 243 | fn render(mask: &mut Mask<'_, '_, &[Command]>) -> Option<Coverage> { | ||
| 244 | let (data, placement) = mask.render(); | ||
| 245 | (placement.width > 0 && placement.height > 0).then_some(Coverage { | ||
| 246 | left: placement.left, | ||
| 247 | top: placement.top, | ||
| 248 | width: placement.width, | ||
| 249 | height: placement.height, | ||
| 250 | data, | ||
| 251 | }) | ||
| 252 | } | ||
| 253 | |||
| 254 | /// Analytic non-zero fill of `path`. | ||
| 255 | pub fn fill(path: &[Command]) -> Option<Coverage> { | ||
| 256 | render(Mask::new(path).style(Fill::NonZero)) | ||
| 257 | } | ||
| 258 | |||
| 259 | /// Analytic stroke of `path`, centered on the contour, with round joins and caps. | ||
| 260 | pub fn stroke(path: &[Command], width: f32) -> Option<Coverage> { | ||
| 261 | render(Mask::new(path).style(Stroke::new(width).join(Join::Round).cap(Cap::Round))) | ||
| 262 | } | ||
| 263 | |||
| 264 | #[cfg(test)] | ||
| 265 | mod tests { | ||
| 266 | use super::*; | ||
| 267 | use crate::media::{TextPlusParams, rasterize_text_plus}; | ||
| 268 | use model::ClsEntry; | ||
| 269 | |||
| 270 | fn params<'a>(text: &'a str) -> TextPlusParams<'a> { | ||
| 271 | TextPlusParams { | ||
| 272 | text, | ||
| 273 | font_family: "Helvetica", | ||
| 274 | font_style: "Regular", | ||
| 275 | size_norm: 0.08, | ||
| 276 | tracking: 1.0, | ||
| 277 | line_spacing: 1.0, | ||
| 278 | center: [0.5, 0.5], | ||
| 279 | h_lcr: 0.0, | ||
| 280 | v_tcb: 0.0, | ||
| 281 | fill_rgba: [1.0, 1.0, 1.0, 1.0], | ||
| 282 | write_on_start: 0.0, | ||
| 283 | write_on_end: 1.0, | ||
| 284 | shear_x: 0.0, | ||
| 285 | cls: &[], | ||
| 286 | outline_rgba: [0.0; 4], | ||
| 287 | outline_width_px: 0.0, | ||
| 288 | } | ||
| 289 | } | ||
| 290 | |||
| 291 | const DIMS: [u32; 2] = [960, 540]; | ||
| 292 | |||
| 293 | fn alpha_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> Option<[i32; 4]> { | ||
| 294 | let mut b: Option<[i32; 4]> = None; | ||
| 295 | for (i, px) in rgba.chunks_exact(4).enumerate() { | ||
| 296 | if px[3] == 0 { | ||
| 297 | continue; | ||
| 298 | } | ||
| 299 | let (x, y) = ((i as u32 % size[0]) as i32 + origin[0], (i as u32 / size[0]) as i32 + origin[1]); | ||
| 300 | let b = b.get_or_insert([x, y, x, y]); | ||
| 301 | *b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)]; | ||
| 302 | } | ||
| 303 | b | ||
| 304 | } | ||
| 305 | |||
| 306 | fn render_bounds(p: &TextPlusParams<'_>) -> Option<[i32; 4]> { | ||
| 307 | let (size, origin, rgba) = rasterize_text_plus(DIMS, p, 0); | ||
| 308 | alpha_bounds(size, origin, &rgba) | ||
| 309 | } | ||
| 310 | |||
| 311 | #[test] | ||
| 312 | fn system_fonts_resolve_with_fallback() { | ||
| 313 | let font = Font::find("Definitely Not Installed 123", "Regular").expect("fallback font"); | ||
| 314 | let face = font.face(); | ||
| 315 | assert!(face.glyph_index('A').is_some()); | ||
| 316 | let (asc, desc) = vertical_metrics(&face); | ||
| 317 | assert!(asc > 0.5 && desc > 0.0 && asc + desc < 2.0, "{asc} {desc}"); | ||
| 318 | } | ||
| 319 | |||
| 320 | #[test] | ||
| 321 | fn style_names_map_to_weight_and_slant() { | ||
| 322 | assert_eq!(parse_style("Regular"), (400, false)); | ||
| 323 | assert_eq!(parse_style("Extra Bold"), (800, false)); | ||
| 324 | assert_eq!(parse_style("Semi Bold Italic"), (600, true)); | ||
| 325 | assert_eq!(parse_style("Light Oblique"), (300, true)); | ||
| 326 | assert_eq!(parse_style("Extra Light"), (200, false)); | ||
| 327 | } | ||
| 328 | |||
| 329 | #[test] | ||
| 330 | fn bold_face_is_heavier_than_regular() { | ||
| 331 | let ink = |style: &str| { | ||
| 332 | let mut p = params("HHHH"); | ||
| 333 | p.font_style = style; | ||
| 334 | let (_, _, rgba) = rasterize_text_plus(DIMS, &p, 0); | ||
| 335 | rgba.chunks_exact(4).map(|px| px[3] as u64).sum::<u64>() | ||
| 336 | }; | ||
| 337 | assert!(ink("Bold") > ink("Regular")); | ||
| 338 | } | ||
| 339 | |||
| 340 | #[test] | ||
| 341 | fn rendering_is_deterministic() { | ||
| 342 | let mut p = params("Fission 2 \u{2014} fi AV"); | ||
| 343 | p.outline_rgba = [1.0, 0.0, 0.0, 1.0]; | ||
| 344 | p.outline_width_px = 6.0; | ||
| 345 | assert_eq!(rasterize_text_plus(DIMS, &p, 0), rasterize_text_plus(DIMS, &p, 0)); | ||
| 346 | } | ||
| 347 | |||
| 348 | #[test] | ||
| 349 | fn kerning_tightens_av_pair() { | ||
| 350 | let font = Font::find("Helvetica", "Regular").unwrap(); | ||
| 351 | let face = font.face(); | ||
| 352 | let solo = |s: &str| shape_line(&face, s, 100.0, 0.0).width; | ||
| 353 | assert!(solo("AV") < solo("A") + solo("V") - 1.0, "{} vs {}", solo("AV"), solo("A") + solo("V")); | ||
| 354 | } | ||
| 355 | |||
| 356 | #[test] | ||
| 357 | fn tracking_adds_space_between_clusters_only() { | ||
| 358 | let font = Font::find("Helvetica", "Regular").unwrap(); | ||
| 359 | let face = font.face(); | ||
| 360 | let plain = shape_line(&face, "HHH", 100.0, 0.0); | ||
| 361 | let spaced = shape_line(&face, "HHH", 100.0, 10.0); | ||
| 362 | assert!((spaced.width - plain.width - 20.0).abs() < 1e-3); | ||
| 363 | assert_eq!(spaced.glyphs.iter().map(|g| g.char_index).collect::<Vec<_>>(), [0, 1, 2]); | ||
| 364 | } | ||
| 365 | |||
| 366 | #[test] | ||
| 367 | fn outlines_are_true_curves() { | ||
| 368 | let font = Font::find("Helvetica", "Regular").unwrap(); | ||
| 369 | let face = font.face(); | ||
| 370 | let gid = face.glyph_index('O').unwrap(); | ||
| 371 | let path = glyph_path(&font, &face, gid, 100.0, [0.0, 0.0], 0.0); | ||
| 372 | assert!(path.iter().any(|c| matches!(c, Command::QuadTo(..) | Command::CurveTo(..)))); | ||
| 373 | let cov = fill(&path).unwrap(); | ||
| 374 | assert!((60..=90).contains(&cov.height), "O cap height {}", cov.height); | ||
| 375 | let ring = stroke(&path, 10.0).unwrap(); | ||
| 376 | assert!(ring.width >= cov.width + 8, "stroke must extend past the fill"); | ||
| 377 | assert!(cov.data.iter().any(|&a| a > 0 && a < 255), "edges are antialiased"); | ||
| 378 | } | ||
| 379 | |||
| 380 | #[test] | ||
| 381 | fn outline_stroke_grows_the_domain_and_sits_under_the_fill() { | ||
| 382 | let plain = render_bounds(&params("HI")).unwrap(); | ||
| 383 | let mut p = params("HI"); | ||
| 384 | p.outline_rgba = [1.0, 0.0, 0.0, 1.0]; | ||
| 385 | p.outline_width_px = 12.0; | ||
| 386 | let outlined = render_bounds(&p).unwrap(); | ||
| 387 | assert!(outlined[0] <= plain[0] - 5 && outlined[2] >= plain[2] + 5, "{outlined:?} vs {plain:?}"); | ||
| 388 | let (size, origin, rgba) = rasterize_text_plus(DIMS, &p, 0); | ||
| 389 | let at = |x: i32, y: i32| { | ||
| 390 | let i = (((y - origin[1]) as u32 * size[0] + (x - origin[0]) as u32) * 4) as usize; | ||
| 391 | [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] | ||
| 392 | }; | ||
| 393 | let ring = at(plain[0] - 3, (plain[1] + plain[3]) / 2); | ||
| 394 | assert!(ring[0] > 200 && ring[1] < 10 && ring[3] > 200, "outline pixel {ring:?}"); | ||
| 395 | } | ||
| 396 | |||
| 397 | #[test] | ||
| 398 | fn write_on_reveals_by_character_without_moving_layout() { | ||
| 399 | let full = render_bounds(&params("HHHH")).unwrap(); | ||
| 400 | let mut p = params("HHHH"); | ||
| 401 | p.write_on_end = 0.5; | ||
| 402 | let half = render_bounds(&p).unwrap(); | ||
| 403 | assert_eq!(half[0], full[0], "the first glyph stays put"); | ||
| 404 | assert!(half[2] < (full[0] + full[2]) / 2 + 3, "{half:?} vs {full:?}"); | ||
| 405 | p.write_on_start = 0.5; | ||
| 406 | p.write_on_end = 1.0; | ||
| 407 | let tail = render_bounds(&p).unwrap(); | ||
| 408 | assert_eq!(tail[2], full[2], "the last glyph stays put"); | ||
| 409 | p.write_on_start = 1.0; | ||
| 410 | assert!(render_bounds(&p).is_none()); | ||
| 411 | } | ||
| 412 | |||
| 413 | #[test] | ||
| 414 | fn cls_offsets_move_only_the_styled_characters() { | ||
| 415 | let base = render_bounds(&params("HH")).unwrap(); | ||
| 416 | let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05 }]; | ||
| 417 | let mut p = params("HH"); | ||
| 418 | p.cls = &cls; | ||
| 419 | let raised = render_bounds(&p).unwrap(); | ||
| 420 | assert_eq!(raised[0], base[0]); | ||
| 421 | assert_eq!(raised[2], base[2]); | ||
| 422 | assert!(raised[1] < base[1] - 30, "{raised:?} vs {base:?}"); | ||
| 423 | } | ||
| 424 | |||
| 425 | #[test] | ||
| 426 | fn character_spacing_widens_lines() { | ||
| 427 | let width = |t: f32| { | ||
| 428 | let mut p = params("HHHH"); | ||
| 429 | p.tracking = t; | ||
| 430 | let b = render_bounds(&p).unwrap(); | ||
| 431 | b[2] - b[0] | ||
| 432 | }; | ||
| 433 | assert!(width(1.5) > width(1.0) + 20); | ||
| 434 | } | ||
| 435 | |||
| 436 | #[test] | ||
| 437 | fn justification_anchors_lines() { | ||
| 438 | let at = |h: f32| { | ||
| 439 | let mut p = params("HHHH"); | ||
| 440 | p.h_lcr = h; | ||
| 441 | render_bounds(&p).unwrap() | ||
| 442 | }; | ||
| 443 | let (left, centre, right) = (at(-1.0), at(0.0), at(1.0)); | ||
| 444 | assert!((left[0] - 480).abs() <= 6, "{left:?}"); | ||
| 445 | assert!((right[2] - 480).abs() <= 6, "{right:?}"); | ||
| 446 | assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}"); | ||
| 447 | } | ||
| 448 | } | ||