diff --git a/CHANGELOG.md b/CHANGELOG.md index b187e572..f2a5556c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ - MCP 的 RSI 完整验证报告区分首次导出就与检查单匹配和后来才匹配,并显示导出文件总数和多次发布的任务数。 -- 正文和公式中的 Ω、μ 改用所选字体笔宽与倾斜手绘,不再借用手写字体里的印刷体希腊字母。本次更新前保存的精调稿保留原字形和字位,不会因此漂移。 +- 正文、公式和电路标签优先使用主字体的希腊字形。常用单位、变量及 θ/ϑ、φ/ϕ、ε/ϵ、ρ/ϱ 等变体缺字时,按主字体笔迹补绘;随包李国夫手写体中的这组选定字形也使用笔绘。已有精调键的旧稿继续沿用保存时的字形和位置。 - MCP 的 TeX 包目录可按中英文学科词(可多个词)、ID 或命令搜索用途和写法,AI 客户端可在建稿前查看默认包和用户选用的自定义命令。 diff --git a/crates/handwriting-core/examples/math_strokes_gallery.rs b/crates/handwriting-core/examples/math_strokes_gallery.rs index f2de41d1..c304ec1d 100644 --- a/crates/handwriting-core/examples/math_strokes_gallery.rs +++ b/crates/handwriting-core/examples/math_strokes_gallery.rs @@ -6,12 +6,17 @@ fn main() -> Result<(), Box> { let output = PathBuf::from(env::args_os().nth(1).ok_or("output directory required")?); fs::create_dir_all(&output)?; let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/font_assets"); - let text = "离散数学:推理与证明\n1. 拒取式:(A→B)∧¬B ⇒ ¬A\n2. 析取三段论:(A∨B)∧¬A ⇒ B\n3. 等价关系:A↔B,A⇔B;反向推导:B←A,B⇐A。\n4. 序关系:aa,x≤y,y≥x,x≠y,x≈y。\n数值分析:误差估计与根式\n5. |Rₙ|≤(M)/(n+1)! × |x-a|ⁿ⁺¹\n6. 标准差:σ=√((Σᵢ₌₁ⁿ(xᵢ-μ)²)/(n))\n7. 嵌套分式:R=(1)/(1+(x+1)/(x+2))\n8. 根式:√(x²+y²),∛(1+x),√((a+b)/(c+d))\n结论:符号笔画随所选字体,数学含义与连接关系保持。"; + let text = "离散数学:推理与证明\n1. 拒取式:(A→B)∧¬B ⇒ ¬A\n2. 析取三段论:(A∨B)∧¬A ⇒ B\n3. 等价关系:A↔B,A⇔B;反向推导:B←A,B⇐A。\n4. 序关系:aa,x≤y,y≥x,x≠y,x≈y。\n数值分析:误差估计与根式\n5. |Rₙ|≤(M)/(n+1)! × |x-a|ⁿ⁺¹\n6. 标准差:σ=√((Σᵢ₌₁ⁿ(xᵢ-μ)²)/(n))\n7. 嵌套分式:R=(1)/(1+(x+1)/(x+2))\n8. 根式:√(x²+y²),∛(1+x),√((a+b)/(c+d))\n电阻 R=10 kΩ,C=100 μF;热量 ΔH,参数 α β π。\n相位 θ ϑ,磁通 φ ϕ;波长 λ,介电常数 ε ϵ,电阻率 ρ ϱ。\n信号 ω τ ζ,波函数 ψ,磁通 Φ。\n结论:符号笔画随所选字体,数学含义与连接关系保持。"; for (name, file) in [ ("yunyan", "云烟体"), ("huayang", "华阳手写体"), ("liguofu", "李国夫手写体"), ("wenkai", "霞鹜文楷"), + ("zhimang", "志莽行书"), + ("qingye", "青叶手写体"), + ("youzai", "悠哉手写体"), + ("shenyun", "神韵英子楷书"), + ("manhei", "霞鹜漫黑"), ] { let primary = FontBook::load(&fs::read(dir.join(format!("{file}.ttf")))?)?; let fonts = FontBook::with_text_fallbacks(primary, text, |name| { diff --git a/crates/handwriting-core/src/fine_edit.rs b/crates/handwriting-core/src/fine_edit.rs index e590f779..31966881 100644 --- a/crates/handwriting-core/src/fine_edit.rs +++ b/crates/handwriting-core/src/fine_edit.rs @@ -153,22 +153,26 @@ impl Adjustments { } // Crop extents set the pivot and gradient domain; keep them when reopening saved edits. -// Fine4 switched small glyphs to coverage masks; Fine5 hand-draws Ω and μ. +// Fine4 introduced coverage masks; Fine5 drew all Ω/μ. Fine6 selects Greek forms per primary font. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum LayoutVersion { Fine2, Fine3, Fine4, Fine5, + Fine6, } impl LayoutVersion { + pub(crate) const CURRENT: Self = Self::Fine6; + fn prefix(self) -> &'static [u8] { match self { Self::Fine2 => b"panache-fine-2\0", Self::Fine3 => b"panache-fine-3\0", Self::Fine4 => b"panache-fine-4\0", Self::Fine5 => b"panache-fine-5\0", + Self::Fine6 => b"panache-fine-6\0", } } @@ -176,22 +180,18 @@ impl LayoutVersion { if p.fine_edit && let Some(edits) = &p.fine_edits { - for version in [Self::Fine4, Self::Fine3, Self::Fine2] { + for version in [Self::Fine5, Self::Fine4, Self::Fine3, Self::Fine2] { if edits.key == layout_key(text, p, version.prefix()) { return version; } } } - Self::Fine5 + Self::CURRENT } pub(crate) fn legacy_mask(self) -> bool { self < Self::Fine4 } - - pub(crate) fn hand_drawn_greek(self) -> bool { - self >= Self::Fine5 - } } pub(crate) fn document_key(text: &str, p: &Parameters) -> String { @@ -259,7 +259,7 @@ mod layout_version_tests { params.fine_edits.as_mut().unwrap().key = fine4.clone(); let saved = LayoutVersion::for_document(text, ¶ms); assert!(saved == LayoutVersion::Fine4); - assert!(!saved.legacy_mask() && !saved.hand_drawn_greek()); + assert!(!saved.legacy_mask()); assert_eq!( draft_keys(text, ¶ms), ( @@ -267,7 +267,7 @@ mod layout_version_tests { Some(layout_key(text, ¶ms, LayoutVersion::Fine3.prefix())) ) ); - assert!(LayoutVersion::for_document("新内容", ¶ms).hand_drawn_greek()); + assert!(LayoutVersion::for_document("新内容", ¶ms) == LayoutVersion::Fine6); } } diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index 4b07dc62..2b519d00 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -463,8 +463,7 @@ fn render_planes( let mut composer = composition::UnitComposer::new(p, &r.text, source.as_deref(), (w, h)); let mut glyphs = Glyphs::with_parameters(&r.fonts, p)?; let fine_layout = fine_edit::LayoutVersion::for_document(&r.text, &r.params); - glyphs.use_legacy_masks(fine_layout.legacy_mask()); - glyphs.use_hand_drawn_greek(fine_layout.hand_drawn_greek()); + glyphs.set_layout_version(fine_layout); let mut pages = Pages { canvas: if transparent { std::mem::take(&mut background) @@ -763,7 +762,7 @@ mod ruled_tests { x: 10., y: 10. + spacing, previous_bottom: 10., - fine_layout: fine_edit::LayoutVersion::Fine5, + fine_layout: fine_edit::LayoutVersion::CURRENT, table_edge: Vec::new(), written_lines: 0, line: vec![], diff --git a/crates/handwriting-core/src/render/glyph.rs b/crates/handwriting-core/src/render/glyph.rs index df4efea7..e39d43f5 100644 --- a/crates/handwriting-core/src/render/glyph.rs +++ b/crates/handwriting-core/src/render/glyph.rs @@ -108,6 +108,7 @@ pub(super) struct Glyphs<'a> { cache: HashMap<(char, u32), Glyph>, cache_bytes: usize, pen: pen::MathPen, + layout_version: crate::fine_edit::LayoutVersion, drawing_stream: u64, } type Path = (Vec<(i32, i32)>, i32); @@ -122,17 +123,16 @@ impl<'a> Glyphs<'a> { cache: HashMap::new(), cache_bytes: 0, pen: pen::MathPen::sample(book.primary()), + layout_version: crate::fine_edit::LayoutVersion::CURRENT, drawing_stream: 0, } } pub(super) fn legacy_mask(&self) -> bool { self.pen.legacy_mask } - pub(super) fn use_legacy_masks(&mut self, legacy: bool) { - self.pen.legacy_mask = legacy; - } - pub(super) fn use_hand_drawn_greek(&mut self, enabled: bool) { - self.pen.hand_drawn_greek = enabled; + pub(super) fn set_layout_version(&mut self, version: crate::fine_edit::LayoutVersion) { + self.layout_version = version; + self.pen.legacy_mask = version.legacy_mask(); } pub fn with_parameters(book: &'a FontBook, p: &Parameters) -> Result { let mut glyphs = Self::new(book); @@ -163,13 +163,35 @@ impl<'a> Glyphs<'a> { if let Some(g) = self.cache.get(&key) { return Ok(g.clone()); } + use pen::greek::GlyphSource; + let glyph = match pen::greek::source(self.book.primary(), c, self.layout_version) { + GlyphSource::Pen(letter) => self.pen.draw_greek(letter, size)?, + GlyphSource::Font(c) => { + if let Some(glyph) = self.circled(c, size)? { + glyph + } else if let Some(glyph) = self.pen.symbol(c, size)? { + glyph + } else { + self.font_glyph(c, size, uses_latin)? + } + } + }; + if self.cache.len() >= 1024 || self.cache_bytes + glyph.mask.len() > 8 * 1024 * 1024 { + self.cache.clear(); + self.cache_bytes = 0; + } + self.cache_bytes += glyph.mask.len(); + self.cache.insert(key, glyph.clone()); + Ok(glyph) + } + fn font_glyph(&self, c: char, size: f32, uses_latin: bool) -> Result { let selected = match self.latin_font { Some(font) if uses_latin && crate::fonts::visible_glyph(font, c) => font, _ => self.book.for_char(c), }; let (m, data) = selected.rasterize(c, size); let advance = m.advance_width.max((m.xmin + m.width as i32) as f32); - let mut glyph = if m.width == 0 || m.height == 0 { + let glyph = if m.width == 0 || m.height == 0 { Glyph::empty(advance) } else { Self::check_size(m.width as u32, m.height as u32)?; @@ -182,22 +204,9 @@ impl<'a> Glyphs<'a> { } }; // 2026-10-15:裁去栅格化器的空白外缘,避免间距由透明 padding 决定。 - if glyph.ink { - glyph = Self::trim(glyph); - } - if let Some(symbol) = self.circled(c, size)? { - glyph = symbol; - } else if let Some(symbol) = self.pen.symbol(c, size)? { - glyph = symbol; - } - if self.cache.len() >= 1024 || self.cache_bytes + glyph.mask.len() > 8 * 1024 * 1024 { - self.cache.clear(); - self.cache_bytes = 0; - } - self.cache_bytes += glyph.mask.len(); - self.cache.insert(key, glyph.clone()); - Ok(glyph) + Ok(if glyph.ink { Self::trim(glyph) } else { glyph }) } + fn trim(mut g: Glyph) -> Glyph { let mut bounds = (g.mask.width(), g.mask.height(), 0, 0); for (x, y, p) in g.mask.enumerate_pixels() { diff --git a/crates/handwriting-core/src/render/glyph/pen.rs b/crates/handwriting-core/src/render/glyph/pen.rs index ad24a26c..d490745d 100644 --- a/crates/handwriting-core/src/render/glyph/pen.rs +++ b/crates/handwriting-core/src/render/glyph/pen.rs @@ -4,6 +4,7 @@ use crate::Result; use crate::text::ArrowKind; use image::GrayImage; +pub(super) mod greek; mod sample; pub(super) struct MathPen { @@ -18,7 +19,6 @@ pub(super) struct MathPen { pub naturalness: f32, pub seed: u64, pub(super) legacy_mask: bool, - pub(super) hand_drawn_greek: bool, } impl MathPen { @@ -72,59 +72,7 @@ impl MathPen { )?)) } - // 2026-12-02:多数中文手写字体的希腊字母借自印刷体,Ω 与 μ 改用字体采样的笔迹手绘; - // Fine5 之前保存的精调稿保留字体字形,避免已保存字位漂移。 - fn greek(&self, c: char, size: f32) -> Result> { - if !self.hand_drawn_greek { - return Ok(None); - } - let mut paths: Vec> = Vec::new(); - let width; - match c { - '\u{3a9}' | '\u{2126}' => { - let cap = self.cap * size; - width = cap * 0.92; - let (cx, cy) = (width * 0.5, -cap * 0.56); - let (rx, ry) = (width * 0.4, cap * 0.44); - let mut stroke = vec![(0., -cap * 0.015), (width * 0.27, 0.)]; - for i in 0..=24 { - let t = (235. - 290. * i as f32 / 24.).to_radians(); - // 右半弧略收窄,避免镜面对称的印刷轮廓。 - let r = if t.cos() > 0. { rx * 0.94 } else { rx }; - stroke.push((cx + r * t.cos(), cy - ry * t.sin())); - } - stroke.extend([(width * 0.71, -cap * 0.01), (width * 0.95, -cap * 0.04)]); - paths.push(stroke); - } - '\u{3bc}' | '\u{b5}' => { - let x = self.lower * size; - width = x * 0.95; - paths.push(vec![(width * 0.07, -x), (0., x * 0.5)]); - paths.push(vec![ - (width * 0.04, -x * 0.45), - (width * 0.16, -x * 0.08), - (width * 0.4, 0.), - (width * 0.63, -x * 0.14), - (width * 0.8, -x * 0.58), - (width * 0.84, -x), - ]); - paths.push(vec![ - (width * 0.84, -x), - (width * 0.83, -x * 0.14), - (width * 0.9, 0.), - (width, -x * 0.07), - ]); - } - _ => return Ok(None), - } - self.slant_paths(self.axis * size, &mut paths); - Ok(Some(self.draw(size, width + size * 0.08, &paths)?)) - } - pub fn symbol(&self, c: char, size: f32) -> Result> { - if let Some(glyph) = self.greek(c, size)? { - return Ok(Some(glyph)); - } if !"¬→←↔⇒⇐⇔≤≥≠".contains(c) { return Ok(None); } @@ -440,7 +388,7 @@ mod tests { ); } #[test] - fn greek_units_are_single_pen_strokes_except_in_legacy_layouts() { + fn greek_units_have_connected_ink_and_distinct_vertical_metrics() { for name in ["云烟体", "李国夫手写体", "霞鹜文楷"] { let font = FontBook::load( &std::fs::read( @@ -453,19 +401,17 @@ mod tests { let mut pen = MathPen::sample(&font); pen.naturalness = 1.; for size in [18., 36., 72.] { - for c in ['\u{3a9}', '\u{2126}', '\u{3bc}', '\u{b5}'] { - let g = pen.symbol(c, size).unwrap().unwrap(); - assert_eq!(components(&g), 1, "{name} {c} {size}"); + for c in [greek::Letter::Omega, greek::Letter::Mu] { + let g = pen.draw_greek(c, size).unwrap(); + assert_eq!(components(&g), 1, "{name} {c:?} {size}"); assert!(g.advance >= g.right() as f32); assert!((g.mask.height() as f32) < size); } - let omega = pen.symbol('\u{3a9}', size).unwrap().unwrap(); - let mu = pen.symbol('\u{3bc}', size).unwrap().unwrap(); + let omega = pen.draw_greek(greek::Letter::Omega, size).unwrap(); + let mu = pen.draw_greek(greek::Letter::Mu, size).unwrap(); assert!(omega.top < mu.top, "{name}: Ω reaches cap height"); assert!(mu.bottom() > omega.bottom(), "{name}: μ descends"); } - pen.hand_drawn_greek = false; - assert!(pen.symbol('\u{3a9}', 36.).unwrap().is_none()); } } #[test] diff --git a/crates/handwriting-core/src/render/glyph/pen/greek.rs b/crates/handwriting-core/src/render/glyph/pen/greek.rs new file mode 100644 index 00000000..fa48d408 --- /dev/null +++ b/crates/handwriting-core/src/render/glyph/pen/greek.rs @@ -0,0 +1,382 @@ +//! Choose a primary-font glyph or a sampled pen stroke before applying the font fallback chain. +use super::{Glyph, MathPen}; +use crate::{Result, fine_edit::LayoutVersion, fonts::visible_glyph}; +use fontdue::Font; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::render::glyph) enum Letter { + Omega, + Mu, + Delta, + Alpha, + Beta, + Pi, + Theta, + ScriptTheta, + Phi, + StraightPhi, + Lambda, + Epsilon, + LunateEpsilon, + Rho, + ScriptRho, + Sigma, + CapitalSigma, + SmallOmega, + Tau, + Zeta, + Psi, + CapitalPhi, +} + +#[derive(Debug, PartialEq, Eq)] +pub(in crate::render::glyph) enum GlyphSource { + Font(char), + Pen(Letter), +} + +pub(in crate::render::glyph) fn source( + font: &Font, + c: char, + version: LayoutVersion, +) -> GlyphSource { + use GlyphSource::{Font, Pen}; + let letter = match c { + 'Ω' | 'Ω' => Letter::Omega, + 'μ' | 'µ' => Letter::Mu, + 'Δ' => Letter::Delta, + 'α' => Letter::Alpha, + 'β' => Letter::Beta, + 'π' => Letter::Pi, + 'θ' => Letter::Theta, + 'ϑ' => Letter::ScriptTheta, + 'φ' => Letter::Phi, + 'ϕ' => Letter::StraightPhi, + 'λ' => Letter::Lambda, + 'ε' => Letter::Epsilon, + 'ϵ' => Letter::LunateEpsilon, + 'ρ' => Letter::Rho, + 'ϱ' => Letter::ScriptRho, + 'σ' => Letter::Sigma, + 'Σ' => Letter::CapitalSigma, + 'ω' => Letter::SmallOmega, + 'τ' => Letter::Tau, + 'ζ' => Letter::Zeta, + 'ψ' => Letter::Psi, + 'Φ' => Letter::CapitalPhi, + _ => return Font(c), + }; + if version < LayoutVersion::Fine6 { + return if version == LayoutVersion::Fine5 && matches!(letter, Letter::Omega | Letter::Mu) { + Pen(letter) + } else { + Font(c) + }; + } + + // fontdue caches this fingerprint when it opens the font. Only the reviewed Li Guofu + // asset gets an override; renaming it works, and a different font with its name keeps its ink. + #[cfg(target_pointer_width = "64")] + const LI_GUOFU: usize = 0xbd51_9b80_bc0b_2e1f; + #[cfg(target_pointer_width = "32")] + const LI_GUOFU: usize = 0x1e2c_70eb; + if font.file_hash() == LI_GUOFU { + return Pen(letter); + } + if visible_glyph(font, c) { + return Font(c); + } + // Reuse the primary face's equivalent unit sign before synthesizing it. + let alias = match c { + 'Ω' => 'Ω', + 'Ω' => 'Ω', + 'μ' => 'µ', + 'µ' => 'μ', + _ => return Pen(letter), + }; + if visible_glyph(font, alias) { + Font(alias) + } else { + Pen(letter) + } +} + +impl MathPen { + pub(in crate::render::glyph) fn draw_greek(&self, letter: Letter, size: f32) -> Result { + let mut paths: Vec> = Vec::new(); + let width; + match letter { + Letter::Omega => { + let cap = self.cap * size; + width = cap * 0.92; + let (cx, cy) = (width * 0.5, -cap * 0.56); + let (rx, ry) = (width * 0.4, cap * 0.44); + let mut stroke = vec![(0., -cap * 0.015), (width * 0.27, 0.)]; + for i in 0..=24 { + let t = (235. - 290. * i as f32 / 24.).to_radians(); + // 右半弧略收窄,避免镜面对称的印刷轮廓。 + let r = if t.cos() > 0. { rx * 0.94 } else { rx }; + stroke.push((cx + r * t.cos(), cy - ry * t.sin())); + } + stroke.extend([(width * 0.71, -cap * 0.01), (width * 0.95, -cap * 0.04)]); + paths.push(stroke); + } + Letter::Mu => { + let x = self.lower * size; + width = x * 0.95; + paths.push(vec![(width * 0.07, -x), (0., x * 0.5)]); + paths.push(vec![ + (width * 0.04, -x * 0.45), + (width * 0.16, -x * 0.08), + (width * 0.4, 0.), + (width * 0.63, -x * 0.14), + (width * 0.8, -x * 0.58), + (width * 0.84, -x), + ]); + paths.push(vec![ + (width * 0.84, -x), + (width * 0.83, -x * 0.14), + (width * 0.9, 0.), + (width, -x * 0.07), + ]); + } + _ => { + let height = if matches!( + letter, + Letter::Delta + | Letter::Beta + | Letter::Theta + | Letter::ScriptTheta + | Letter::Lambda + | Letter::CapitalSigma + | Letter::CapitalPhi + | Letter::Zeta + ) { + self.cap * size + } else { + self.lower * size + }; + let (advance, strokes) = letter.strokes(); + width = advance * height; + paths = strokes + .iter() + .map(|stroke| quadratic_stroke(stroke, height)) + .collect(); + } + } + self.slant_paths(self.axis * size, &mut paths); + self.draw(size, width + size * 0.08, &paths) + } +} + +// Each stroke starts with its pen-down point, followed by quadratic control/end pairs. +// Coordinates are hundredths of the sampled cap or lowercase height; y=0 is the baseline. +type Stroke = &'static [(i16, i16)]; + +impl Letter { + #[rustfmt::skip] + fn strokes(self) -> (f32, &'static [Stroke]) { + match self { + Self::Delta => (0.94, &[ + &[(3, -2), (20, -46), (43, -98), (66, -59), (91, -4), (49, -1), (3, -2)], + ]), + Self::Alpha => (1.07, &[ + &[(79, -80), (61, -110), (33, -92), (4, -74), (5, -39), + (5, 7), (36, -4), (72, -15), (92, -98)], + &[(79, -80), (72, -43), (82, -13), (89, 6), (105, -6)], + ]), + Self::Beta => (0.72, &[ + &[(5, 31), (9, -38), (17, -77), (22, -106), (44, -101), + (73, -97), (62, -71), (54, -49), (27, -50), + (63, -60), (68, -30), (75, 2), (44, 0), (22, -1), (15, -17)], + ]), + Self::Pi => (1.14, &[ + &[(0, -77), (11, -93), (30, -93), (77, -90), (112, -99)], + &[(30, -92), (32, -37), (15, 0)], + &[(83, -93), (73, -59), (76, -15), (77, 6), (101, -4)], + ]), + Self::Theta => (0.66, &[ + &[(36, -99), (10, -106), (7, -62), (1, -8), (25, 0), + (56, 8), (62, -46), (67, -96), (36, -99)], + &[(8, -45), (33, -53), (61, -50)], + ]), + Self::ScriptTheta => (0.92, &[ + &[(2, -43), (10, 0), (36, -2), (67, 0), (71, -42), + (72, -67), (49, -92), (28, -112), (18, -91), + (9, -61), (47, -54), (69, -49), (90, -56)], + ]), + Self::Phi => (1.00, &[ + &[(21, -85), (1, -64), (8, -34), (15, -3), (48, -4), + (83, -1), (92, -39), (102, -83), (80, -96), + (55, -103), (51, -60), (46, -11), (42, 42)], + ]), + Self::StraightPhi => (0.99, &[ + &[(51, -81), (15, -87), (9, -48), (5, -7), (46, -5), + (84, 0), (92, -40), (96, -78), (51, -81)], + &[(56, -120), (51, -45), (46, 40)], + ]), + Self::Lambda => (0.78, &[ + &[(4, -98), (21, -108), (31, -72), (42, -36), (59, -7), (66, 4), (77, -1)], + &[(36, -57), (22, -24), (4, -1)], + ]), + Self::Epsilon => (0.80, &[ + &[(78, -87), (55, -108), (29, -92), (1, -70), (29, -54), + (45, -47), (57, -51), (31, -57), (13, -39), (-3, -18), (20, -5), + (42, 7), (78, -14)], + ]), + Self::LunateEpsilon => (0.81, &[ + &[(78, -92), (49, -103), (29, -86), (2, -64), (7, -32), + (13, 11), (72, -6)], + &[(9, -49), (38, -51), (66, -51)], + ]), + Self::Rho | Self::ScriptRho => { + const BOWL: Stroke = &[(12, -29), (10, -73), (35, -89), (63, -106), (79, -82), + (98, -53), (76, -20), (50, 13), (16, -12)]; + if self == Self::Rho { + (0.90, &[BOWL, &[(12, -29), (10, 6), (6, 48)]]) + } else { + (0.96, &[BOWL, &[(12, -29), (3, 14), (24, 31), (50, 55), (94, 27)]]) + } + } + Self::Sigma => (1.03, &[ + &[(97, -96), (70, -91), (41, -92), (12, -88), (8, -53), + (0, -18), (26, -5), (58, 10), (74, -23), (93, -62), (48, -90)], + ]), + Self::CapitalSigma => (0.84, &[ + &[(80, -96), (50, -99), (9, -96), (26, -72), (48, -49), + (32, -26), (6, -1), (40, -3), (81, -4)], + ]), + Self::SmallOmega => (1.24, &[ + &[(23, -92), (1, -58), (8, -22), (16, 10), (40, -4), + (61, -17), (60, -62), (55, -25), (72, -7), (90, 11), (108, -11), + (127, -45), (108, -94)], + ]), + Self::Tau => (0.97, &[ + &[(2, -77), (15, -95), (44, -91), (70, -87), (95, -98)], + &[(51, -91), (38, -51), (39, -20), (40, 6), (66, -5)], + ]), + Self::Zeta => (0.68, &[ + &[(14, -101), (36, -92), (64, -97), (25, -68), (12, -40), + (-2, -10), (28, -6), (63, -6), (51, 17), (47, 29), (32, 32)], + ]), + Self::Psi => (1.13, &[ + &[(1, -86), (14, -99), (17, -67), (17, -14), (49, -11), + (87, -7), (94, -55), (99, -82), (111, -96)], + &[(63, -118), (55, -44), (48, 42)], + ]), + Self::CapitalPhi => (0.95, &[ + &[(47, -82), (13, -82), (6, -55), (0, -23), (43, -21), + (83, -18), (88, -47), (94, -77), (47, -82)], + &[(49, -102), (46, -50), (44, 0)], + ]), + Self::Omega | Self::Mu => unreachable!("unit strokes retain their Fine5 geometry"), + } + } +} + +fn quadratic_stroke(stroke: Stroke, height: f32) -> Vec<(f32, f32)> { + let scale = |(x, y): (i16, i16)| (f32::from(x) * height / 100., f32::from(y) * height / 100.); + let mut start = scale(stroke[0]); + let mut path = vec![start]; + for pair in stroke[1..].chunks_exact(2) { + let control = scale(pair[0]); + let end = scale(pair[1]); + for i in 1..=8 { + let t = i as f32 / 8.; + let u = 1. - t; + path.push(( + u * u * start.0 + 2. * u * t * control.0 + t * t * end.0, + u * u * start.1 + 2. * u * t * control.1 + t * t * end.1, + )); + } + start = end; + } + path +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{FontBook, render::glyph::Glyphs}; + use std::{fs, path::PathBuf}; + + #[test] + fn a_different_font_with_the_same_internal_name_keeps_its_own_glyphs() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets/font_assets/李国夫手写体.ttf"); + let mut bytes = fs::read(path).unwrap(); + // Trailing padding leaves names, cmap entries, metrics and outlines intact. + bytes.extend_from_slice(&[0; 4]); + let font = FontBook::load(&bytes).unwrap(); + assert_eq!( + source(&font, 'α', LayoutVersion::Fine6), + GlyphSource::Font('α') + ); + } + + #[test] + fn greek_sources_and_drawn_forms_across_bundled_fonts() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/font_assets"); + let cases = [ + ("云烟体", "", ""), + ("志莽行书", "", ""), + ("青叶手写体", "", ""), + ("李国夫手写体", "", ""), + ("华阳手写体", "ΩΩμαβΔπθφλερσΣωτζψΦ", "µ"), + ("悠哉手写体", "ΩΩμµαβΔπθφλερσΣωτζψΦ", ""), + ("神韵英子楷书", "ΩμµαβΔπθφλερσΣωτζψΦ", "Ω"), + ("霞鹜文楷", "ΩΩμµαβΔπθϑφϕλεϵρϱσΣωτζψΦ", ""), + ("霞鹜漫黑", "ΩΩμµαβΔπθϑφϕλερσΣωτζψΦ", ""), + ]; + for (name, native, aliases) in cases { + let bytes = fs::read(root.join(format!("{name}.ttf"))).unwrap(); + let book = FontBook::new(&bytes, &[]).unwrap(); + let mut glyphs = Glyphs::new(&book); + for c in "ΩΩμµΔαβπθϑφϕλεϵρϱσΣωτζψΦ".chars() { + let choice = source(book.primary(), c, LayoutVersion::Fine6); + let expected_font = if native.contains(c) { + Some(c) + } else if aliases.contains(c) { + Some(if c == 'µ' { 'μ' } else { 'Ω' }) + } else { + None + }; + for size in [18., 36., 72.] { + let g = glyphs.glyph(c, size).unwrap(); + assert!( + g.ink && g.mask.iter().any(|a| *a >= 128), + "{name} {size} {c}" + ); + if let Some(actual_char) = expected_font { + assert_eq!(choice, GlyphSource::Font(actual_char), "{name} {c}"); + let raw = glyphs.font_glyph(actual_char, size, false).unwrap(); + assert_eq!( + (g.mask, g.advance, g.top, g.left), + (raw.mask, raw.advance, raw.top, raw.left) + ); + } else { + assert!(matches!(choice, GlyphSource::Pen(_)), "{name} {c}"); + } + } + for version in [LayoutVersion::Fine4, LayoutVersion::Fine5] { + let drawn = + matches!(c, 'Ω' | 'Ω' | 'μ' | 'µ') && version == LayoutVersion::Fine5; + assert_eq!( + matches!(source(book.primary(), c, version), GlyphSource::Pen(_)), + drawn + ); + } + } + for size in [18., 36., 72.] { + for (ordinary, variant) in [('θ', 'ϑ'), ('φ', 'ϕ'), ('ε', 'ϵ'), ('ρ', 'ϱ')] + { + assert_ne!( + glyphs.glyph(ordinary, size).unwrap().mask, + glyphs.glyph(variant, size).unwrap().mask, + "{name} {size} {ordinary}/{variant}" + ); + } + } + } + } +} diff --git a/crates/handwriting-core/src/render/glyph/pen/sample.rs b/crates/handwriting-core/src/render/glyph/pen/sample.rs index 1a216402..96520167 100644 --- a/crates/handwriting-core/src/render/glyph/pen/sample.rs +++ b/crates/handwriting-core/src/render/glyph/pen/sample.rs @@ -44,7 +44,6 @@ impl MathPen { naturalness: 0., seed: 0, legacy_mask: false, - hand_drawn_greek: true, } } } diff --git a/crates/handwriting-core/tests/generation_pipeline.rs b/crates/handwriting-core/tests/generation_pipeline.rs index 12620892..e735106c 100644 --- a/crates/handwriting-core/tests/generation_pipeline.rs +++ b/crates/handwriting-core/tests/generation_pipeline.rs @@ -808,6 +808,62 @@ fn table_clearance_keeps_its_pagination_at_every_pen_opacity() { } } +#[test] +fn fine5_replays_the_unit_strokes_and_page_pixels_from_pr_95() { + use sha2::{Digest, Sha256}; + let mut req = request("kΩμF"); + req.params.seed = 2; + req.params.fine_edit = true; + let mut key = Sha256::new(); + key.update(b"panache-fine-5\0"); + key.update(req.text.as_bytes()); + key.update([0; 3]); + let key = format!("{:x}", key.finalize()); + req.params.fine_edits = Some(fine_edit::Adjustments { + key: key.clone(), + glyphs: vec![fine_edit::Adjustment { + id: 2, + dx: 5, + dy: -3, + scale: 110, + angle: 7, + opacity: 80, + opacity_ramp: None, + color: None, + thickness: 0, + softness: 0, + warp: None, + }], + }); + let cancel = Cancellation::default(); + let (actual_key, glyphs) = fine_edit::inspect_page(&req, 1, &cancel).unwrap(); + assert_eq!(actual_key, key); + assert_eq!( + glyphs + .iter() + .map(|g| (g.id, g.bounds, g.baseline)) + .collect::>(), + [ + (0, [6, 25, 19, 26], 46), + (1, [19, 23, 26, 28], 46), + (2, [39, 29, 22, 29], 46), + (3, [55, 24, 21, 27], 46), + ] + ); + // Raw RGBA from the same request on 1881df06, independent of PNG compression. + assert_eq!( + render(&req, &cancel, |_, page| { + assert_eq!( + format!("{:x}", Sha256::digest(page.as_raw())), + "dd5f1eb5cb18cd02d3d3d69b5276ef0875d909337cbfa38d0689e87a6b70e93c" + ); + Ok(()) + }) + .unwrap(), + 1 + ); +} + #[test] fn fine4_drafts_keep_font_greek_geometry() { use fine_edit::Adjustments; @@ -823,7 +879,7 @@ fn fine4_drafts_keep_font_greek_geometry() { .collect(); (key, items) }; - let (current_key, hand_drawn) = geometry(&req); + let (current_key, current) = geometry(&req); let mut hash = Sha256::new(); hash.update(b"panache-fine-4\0"); hash.update(req.text.as_bytes()); @@ -846,7 +902,8 @@ fn fine4_drafts_keep_font_greek_geometry() { (3, [52, 24, 21, 27], 46), ] ); - assert_ne!(saved, hand_drawn); + // Fine6 preserves WenKai’s native Greek glyphs, as Fine4 did. + assert_eq!(saved, current); } #[test]