LayMeshDocs
中文

experiments/opentype-math/README.md

experiments/opentype-math/README.md
# OpenType mathematical fonts Branch: `codex/opentype-math-fonts`. This branch is not a published release. `formula(..., math_font="XITS Math")` selects an installed OpenType math font.A font file path works on native hosts and with fonts supplied through thein-memory/WASM host. Paths are relative to the defining `.lay` module (or`.lcss` stylesheet). `math_font` also inherits from the canvas, text, span,plot, and plot style. Use raw DSL strings for LaTeX, especially when mhchemcontains embedded `$...$` expressions. ```laypage=canvas(size=(160mm,60mm),math_font="XITS Math")page.add(formula(r"\ce{A <=>[{forward}][{reverse}] B}",font_size=16pt))``` The default `ratex-katex` backend is retained. The OpenType backend reuses theRaTeX parser and LayMesh exporters, but obtains glyphs, advances, mathconstants, italic corrections, accent attachments, script kerns, stretchvariants, and connector assemblies from the selected font. It neversubstitutes a KaTeX face for an explicitly selected math font. Covered constructions include fractions/binomials, continued fractions,scripts, indexed roots, operators and limits, `left/right/middle`, matrices,arrays with solid/dashed rules, aligned equations and tags, commutativediagrams, labelled arrows, braces/brackets, accents, enclosures/cancellation,phantoms, overlap/raise commands, line breaks, math alphabets, and inline math.RaTeX's mhchem (`ce`/`pu`) and bussproofs (`prooftree`) use the same font-awareconstructions. Proof trees support unary through quinary inference, labels,solid/dashed/no rules, nested branches, and changing root direction. A font may lack a horizontal arrow assembly, and some installed STIX Two2.02 arrow recipes contain invalid terminal connectors. For horizontalarrows and equality only, the backend then extends the shaft region of thatfont's native outline while preserving its end shapes and stroke thickness.Other finite stretch constructions use their largest native variant whenno assembly exists. Missing glyphs use the same measured vector box in everybackend and emit `W_FONT` with Unicode codepoints. Missing MATH tables, embeddingrestrictions, unavailable math fonts and invalid constructions still fail explicitly. `mathcal` and `mathscr` currently select the same Unicode script alphabet;font-specific GSUB stylistic-set selection is not implemented. Math alphabetcommands follow the inner-command override used by[KaTeX](https://github.com/KaTeX/KaTeX/blob/v0.16.22/src/Options.js):`\mathbf{\mathcal A}` is script A, not bold script A, while`\mathcal{\mathbf A}` is bold roman A. Use `\mathbf{A1}` for bold romanletters/digits and `\bm{\alpha x}` for bold italic symbols. Native styledUnicode letters also retain their selected-font glyphs. XITS Math Boldis a supplementary face with incomplete stretch coverage: algebra works,and missing radical constructions report an error. Regular XITS Math supports`mathbf`, `boldsymbol`, and `bm` without selecting the standalone bold face. ## Fixed upstream corpus Fixtures come from [RaTeX v0.1.14](https://github.com/erweixin/RaTeX/tree/ae391d727ac615437c63c308f4538d971a84bede),the version used by LayMesh. The original source files, SHA-256 hashes, andMIT license are retained under `tests/math/ratex-0.1.14`: - Golden formulas: 1075 entries; parser comparison: 791; layout comparison: 29.- Chemistry: 91; physics: 22; proof trees: 38.- Additional editable domain cases: 32, under `domain-cases.json`. After deduplicating the overlapping primary math suites, the audit runs 1931case entries (1921 distinct formulas), four fonts, and inline/display styles:**15,448 layout checks**. Expected parser/policy errors and real font-coveragelimits are recorded separately. Placeholder exports are not counted as correctglyph rendering. `expected-errors.json` pins parser/policy rejections and`expected-placeholders.json` pins missing-codepoint sequences. | Backend | Exportable checks | Parser/policy rejection | Exports containing placeholders || --- | ---: | ---: | ---: || KaTeX default | 3742 | 120 | 100 || Latin Modern Math | 3742 | 120 | 96 || STIX Two Math | 3742 | 120 | 34 || XITS Math | 3742 | 120 | 34 | All 91 chemistry, 22 physics, 38 proof-tree cases and 32 additional domaincases render in every font and style. No unimplemented OpenType node remainsin the accepted corpus. Every successful OpenType render checks finitegeometry and exported outline bounds. The missing-glyph cases include CJK,other scripts, emoji, and some symbols absent from Latin Modern Math; choosinga math font does not give it glyphs that the file does not contain. The focused regressions also verify MATH-constant fault injection, assemblyparts, alphabet codepoints, text/chemistry roman forms, relative paths, inlinebaselines, plot labels, accent/operator placement, proof rules/root direction,alignment/tag placement, 30-level delimiter nesting, zero-width spacing,cache invalidation, embedding restrictions, and explicit errors. OpenType partial bonds (`~`, `~-`, `~--`, `~=`, `-~-`) are native compoundconstructions. A per-parser adapter retains the bond semantics from RaTeX0.1.14's mhchem token productions before their KaTeX lap/raise/tiny-hyphenrecipes expand. It delegates to the original `ce` handler, preserving theshared recursion limit. No formula text or font name selects a special case.The native minus outline supplies the ink endpoints, advance, axis andthickness; the dashed row uses three horizontally shortened copies of thatoutline. Every layer inherits the current math style, size and color.This adapter is tied to the pinned upstream productions, covered by tests;ordinary overlays and the default RaTeX backend keep their existing behavior. The bond tests measure actual outline endpoints and thickness in **1,280cases**: four font files (including XITS Bold), four sizes (6–48 pt), bothformula styles, four mixed-bond spellings, and ten contexts includingsuperscripts, two levels of subscripts, fractions and explicit script styles.Another 48 chain cases include the bare dashed bond, nested chemistry andcolor; they verify the native axis, consistent atom/bond scale, layer spacingand clearance from adjacent atoms. Separate parser tests preserve ordinaryASTs and upstream recursion errors. Rendering checks cover these paths inSVG, PDF, PNG and PPTX. Math minus and text hyphen remain distinct. Nested math alphabets are tested in both command orders, independently ofthe real bold-letter cases. `regressions.lay` provides an enlarged, editablecomparison; `chemical-bonds.lay` adds compound bonds in different math styles.The existing default RaTeX backend does not select its sans italic face for`\mathsfit`; the OpenType backend selects the correct Unicode alphabet. ## Reproduce ```shmkdir -p target/opentype-math-validationLAYMESH_MATH_AUDIT="$PWD/target/opentype-math-validation/corpus.json" \  cargo test -p laymesh-core --test opentype_math --test opentype_math_corpuspython3 experiments/opentype-math/summarize-corpus.py \  target/opentype-math-validation/corpus.jsoncargo test -p laymesh-render --test opentype_mathcargo build -p laymesh-clipython3 experiments/opentype-math/verify.py.venv/bin/python experiments/opentype-math/build-atlas.pytarget/debug/laymesh render experiments/opentype-math/regressions.lay \  -o target/opentype-math-validation/regressions.png --dpi 160target/debug/laymesh render experiments/opentype-math/chemical-bonds.lay \  -o target/opentype-math-validation/chemical-bonds.png --dpi 180``` Outputs go to `target/opentype-math-validation`: the original comparison,a four-page vector `domain-atlas.pdf`, editable `.lay` pages, SVG/PNG/PPTXexports, PDF-derived previews, and machine-readable audit results. The atlasbuilder needs PyMuPDF and Poppler. A release binary can be selected with`--binary target/release/laymesh` for both render scripts. The deterministic font fixtures are unmodified Latin Modern Math 1.959,STIX Two Math 2.02 b142, and XITS Math 1.302 regular/bold, with license notices.They are test assets and are not bundled into distribution packages. ## Browser corpus gallery The gallery retains every nonempty, noncomment entry in all eleven formulacorpus files from the pinned RaTeX v0.1.14 checkout, including duplicates:the six primary suites above, lexer comparison (791), website mathematics(1048), website proof trees (38), the original chemistry text fixture (103),and the Unicode smoke-test script (18). With the 32 domain examples and 24text fallback cases this is **4100 entries, 1961 distinct formulas, and65,600 font/style/text-policy results**.This scope covers the original formula corpus files; it does not claim todisplay every assertion from RaTeX's Rust, platform or application unit tests. Previews use the shared DisplayList and Vello CPU WASM Canvas renderer, with KaTeX,Latin Modern Math, STIX Two Math and XITS Math in inline and display styles.With body text fallback disabled, the 15,368 distinct combinations alreadypresent in the fixed audit must match its exact parser/policy/font-coverageoutcomes. The remaining 16,008 combinations cover supplementary formulas andthe full corpus with text fallback enabled, and check OpenType geometry withoutassigning new results a pre-existing expected-error baseline.Every original fixture and font asset is verified against its SHA-256.The page exposes source-file positions, errors, text fallback, missing-glyphplaceholders and invalid dimensions. A successful export alone is not avisual-quality assertion. SVG is retained only as a downloadable file export. Native RGBA references at16 px are compared to every successful distinct WASM rendering.Baseline guides, DPR-aware Canvas zoom, source search,category/status/font filters, pagination and detail views support manual review. ```sh# First generate corpus.json using the audit command above.cargo build -p laymesh-render --example math_gallery --releasecargo build --release --locked --target wasm32-unknown-unknown -p laymesh-wasm --no-default-featureswasm-bindgen --target web --out-dir extensions/vscode/dist/wasm target/wasm32-unknown-unknown/release/laymesh_wasm.wasmpython3 experiments/opentype-math/build-gallery.py --output target/rust-renderer-math-gallerypython3 experiments/opentype-math/serve-gallery.py --directory target/rust-renderer-math-gallery --port 8768python3 experiments/opentype-math/verify-gallery.py --url http://100.64.0.6:8768/``` The server binds to the machine's Tailscale IPv4 address by default and servesonly the selected generated directory. It does not publish through Funnel.On this development host the URL is `http://100.64.0.6:8768/`;`?suite=chemistry` opens chemistry and `?suite=domain&q=bond&size=48`opens the enlarged compound-bond example. `/health` reports the loaded count.After frontend-only edits, `build-gallery.py --reuse` refreshes the page whilechecking the renderer fingerprint, all prior outcomes and SVG hashes.  ## Formula text fallback `math_text_fallback=true` is inherited by default. Formula `font_family`selects literal text, independently of `math_font`. An explicit font list isordered and does not silently add unlisted families. A single family or filerequest retains the existing ordinary-text selection and warning behavior. Both engines shape adjacent text runs before mathematical placement, usingactual advances, outline extents, Unicode bidi ordering and Rustybuzz shaping.Text in scripts, fractions, chemical annotations, matrices and proof cellsuses the same flow. Exports use outlines rather than a browser-dependent textfont. Real bold/italic faces are selected by text commands; missing styles warn.Mathematical alphabet commands continue to use the selected math font. ```laypage=canvas(size=(140mm,50mm),math_font="XITS Math",    font_family=["Noto Serif","Noto Serif CJK SC"])page.add(formula(r"\text{你好,世界!}\quad E=mc^2",font_size=16pt))``` The gallery defaults to enabled text fallback with eight pinned, renamed Notosubsets, and has a switch to disable it. This isolates test results from hostfont installation. Details disclose actual family, face, weight and glyphcount. `/sources/text-fonts-manifest.json` retains input and output hashes;[font fixtures](../../tests/fonts/text/README.md) document rebuilding and licenses.The four math font files remain unchanged. Color bitmap emoji are unsupportedby this outline-only text flow. Missing text or math glyphs use vector boxeswith warnings, including when text fallback is disabled or its font list isexhausted; adjacent supported glyphs and mathematical structure remain visible. The default KaTeX route uses the optional measured-text hook in the[muxkin/RaTeX fork](https://github.com/muxkin/RaTeX/blob/9e03b1c0f365a15f51e68649311365c0d62842e1/docs/HOST_TEXT_LAYOUT.md),pinned to commit `9e03b1c0f365a15f51e68649311365c0d62842e1`. When the hook isabsent, the upstream layout is retained. The hook covers literal text groups,including proof text passing through explicit font wrappers; it does not matchsource strings or font names to fix individual formulas. The root Cargo patch pins all six RaTeX dependencies to that same Git revisionso workspace path dependencies share the parser/AST/font types. `Cargo.lock`records the source; builds do not follow the fork's moving `main` branch.The original corpus fixtures remain pinned to upstream v0.1.14, independentlyof the implementation source. The fork keeps that version number, adds itsown API/depth regressions, and needs no RaTeX or LayMesh release for this work.Future crate publication must retain the host-text API in the published RaTeXdependency; publishing LayMesh core against unpatched registry 0.1.14 wouldlose this integration. Validation includes 576 multilingual/domain combinations (24 cases × fourmath fonts × inline/display × three sizes), actual font-advance/space metrics,script-scale and shared-baseline checks, real bold/italic selection, ligatures,combining marks, Arabic joining, explicit-list missing glyphs, disabled fallback,LCSS-relative paths and ordinary-text font embedding. SVG/PDF/PNG/PPTX checkscover Chinese, scripts, chemical annotations, proof labels, Arabic and Indic. ```shcargo test -p laymesh-core --test formula_textcargo test -p laymesh-render --test opentype_math# Browse enabled text cases; append &text=0 to compare strict coverage.# http://100.64.0.6:8768/?suite=text&baselines=1```