From cd6baba53ff3c5e6a140c3e5eec2665a60d669e9 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 20 Oct 2026 12:52:33 +0800 Subject: [PATCH] Add a math atom box model --- crates/texrra-tex-core/src/lib.rs | 17 ++++ crates/texrra-tex-core/src/math.rs | 146 +++++++++++++++++++++++++++++ docs/TEX_CORE.md | 5 +- 3 files changed, 167 insertions(+), 1 deletion(-) create mode 100755 crates/texrra-tex-core/src/math.rs diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index e1e8a03..46a9de6 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1,4 +1,5 @@ pub mod cmr10; +pub mod math; pub mod paragraph; pub use cmr10::Cmr10Metrics; @@ -232,6 +233,22 @@ impl Unit { } } + /// Build a unit from a math atom using CMR10 metrics. + pub fn math( + id: UnitId, + atom: crate::math::MathAtom, + font: &crate::cmr10::Cmr10Metrics, + ) -> Self { + let math_box = math::layout_math(&atom, font); + Self::vertical( + id, + vec![VerticalItem::Box(VerticalBox { + width: math_box.width, + height: math_box.height + math_box.depth, + })], + ) + } + /// Build a unit from arbitrary vertical material. pub fn vertical(id: UnitId, items: Vec) -> Self { Self { diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs new file mode 100755 index 0000000..14f4473 --- /dev/null +++ b/crates/texrra-tex-core/src/math.rs @@ -0,0 +1,146 @@ +//! M4 math list model: symbols, scripts and fractions expressed as boxes. +//! +//! This is deliberately independent of v1's math renderer. It provides the +//! geometry the route-D page builder needs; token-to-atom conversion and the +//! final painter arrive in later M4 slices. + +use crate::cmr10::Cmr10Metrics; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum MathAtom { + Symbol(char), + Script { + base: Box, + sub: Option>, + sup: Option>, + }, + Fraction { + numerator: Box, + denominator: Box, + }, +} + +impl MathAtom { + pub fn symbol(character: char) -> Self { + Self::Symbol(character) + } + + pub fn script(base: MathAtom, sub: Option, sup: Option) -> Self { + Self::Script { + base: Box::new(base), + sub: sub.map(Box::new), + sup: sup.map(Box::new), + } + } + + pub fn fraction(numerator: MathAtom, denominator: MathAtom) -> Self { + Self::Fraction { + numerator: Box::new(numerator), + denominator: Box::new(denominator), + } + } +} + +/// Geometry of a math atom in scaled points, measured from its baseline. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct MathBox { + pub width: i64, + pub height: i64, + pub depth: i64, +} + +fn scaled(value: i64, factor: f64) -> i64 { + (value as f64 * factor).round() as i64 +} + +/// Lay out a math atom at the current style size. +pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { + match atom { + MathAtom::Symbol(character) => MathBox { + width: font.width(*character), + height: 7 * 65_536, + depth: 2 * 65_536, + }, + MathAtom::Script { base, sub, sup } => { + let base_box = layout_math(base, font); + let sub_box = sub.as_deref().map(|atom| layout_math(atom, font)); + let sup_box = sup.as_deref().map(|atom| layout_math(atom, font)); + let script_width = sub_box + .as_ref() + .map(|boxed| boxed.width) + .unwrap_or(0) + .max(sup_box.as_ref().map(|boxed| boxed.width).unwrap_or(0)); + let sup_height = sup_box.as_ref().map_or(0, |boxed| boxed.height); + let sub_depth = sub_box.as_ref().map_or(0, |boxed| boxed.depth); + MathBox { + width: base_box.width + scaled(script_width, 0.7), + height: base_box + .height + .max(scaled(base_box.height, 0.6) + scaled(sup_height, 0.7)), + depth: base_box + .depth + .max(scaled(base_box.depth, 0.5) + scaled(sub_depth, 0.7)), + } + } + MathAtom::Fraction { + numerator, + denominator, + } => { + let numerator_box = layout_math(numerator, font); + let denominator_box = layout_math(denominator, font); + let width = numerator_box + .width + .max(denominator_box.width) + .saturating_add(2 * 65_536); + MathBox { + width, + height: scaled(numerator_box.height + numerator_box.depth, 0.7) + 2 * 65_536, + depth: scaled(denominator_box.height + denominator_box.depth, 0.7) + 2 * 65_536, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn math_symbol_uses_font_width() { + let font = Cmr10Metrics::default(); + let boxed = layout_math(&MathAtom::symbol('x'), &font); + assert_eq!(boxed.width, font.width('x')); + assert!(boxed.height > 0); + assert!(boxed.depth > 0); + } + + #[test] + fn script_stacks_above_and_below_the_base() { + let font = Cmr10Metrics::default(); + let plain = layout_math(&MathAtom::symbol('x'), &font); + let scripted = layout_math( + &MathAtom::script( + MathAtom::symbol('x'), + Some(MathAtom::symbol('i')), + Some(MathAtom::symbol('2')), + ), + &font, + ); + assert!(scripted.width > plain.width); + assert!(scripted.height > plain.height); + assert!(scripted.depth >= plain.depth); + } + + #[test] + fn fraction_is_wider_than_its_parts() { + let font = Cmr10Metrics::default(); + let numerator = layout_math(&MathAtom::symbol('a'), &font); + let fraction = layout_math( + &MathAtom::fraction(MathAtom::symbol('a'), MathAtom::symbol('b')), + &font, + ); + assert!(fraction.width > numerator.width); + assert!(fraction.height > numerator.height); + assert!(fraction.depth > 0); + } +} diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index d5a8a39..37f5b6e 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -76,7 +76,7 @@ next paragraph milestones. | M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, pdfTeX fixture and minimum line fill; hyphenation next | | M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; interpreted `\output`, float pages next | | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: `Halign` model with natural column widths, spans and rule rows; no `\omit`/`\span` token parsing or PDF painting yet | -| M4 | math lists, scripts, fractions, radicals, accents, delimiters | arXiv formulas render without overlap | +| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: `MathAtom` symbol/script/fraction boxes with CMR10 widths; no token conversion, radicals, accents or painter | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | | M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | @@ -104,6 +104,9 @@ overfull ratio 4.11, badness 6942. TeX rejects the underfull candidate under its tolerance but still emits the moderately overfull 5-word line. Reproducing this needs a two-pass tolerance algorithm with an emergency overfull pass, not a single cost function. +- `MathAtom::{Symbol, Script, Fraction}` and `layout_math` produce + `MathBox { width, height, depth }`; `Unit::math` turns an atom into a + vertical box. Parsing TeX math tokens and painting remain future M4 work. - M1 now inserts TeX en-US hyphenation points as `HorizontalItem:: Discretionary`: a break adds the hyphen width, a non-break keeps zero width. The line breaker scores these breakpoints with the same glue