@babylonjs/lite-gl 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +31 -0
  2. package/index.d.ts +13 -0
  3. package/index.js +7 -0
  4. package/index.js.map +1 -1
  5. package/package.json +6 -3
  6. package/text/_gpu/text-effect.d.ts +1 -0
  7. package/text/_gpu/text-effect.js +70 -0
  8. package/text/_gpu/text-effect.js.map +1 -0
  9. package/text/_gpu/text-instances.d.ts +1 -0
  10. package/text/_gpu/text-instances.js +57 -0
  11. package/text/_gpu/text-instances.js.map +1 -0
  12. package/text/_gpu/text-textures.d.ts +1 -0
  13. package/text/_gpu/text-textures.js +82 -0
  14. package/text/_gpu/text-textures.js.map +1 -0
  15. package/text/_gpu/text-vao.d.ts +1 -0
  16. package/text/_gpu/text-vao.js +49 -0
  17. package/text/_gpu/text-vao.js.map +1 -0
  18. package/text/default-text-data.d.ts +28 -0
  19. package/text/default-text-data.js +103 -0
  20. package/text/default-text-data.js.map +1 -0
  21. package/text/font.d.ts +16 -0
  22. package/text/font.js +24 -0
  23. package/text/font.js.map +1 -0
  24. package/text/glyph-extraction.d.ts +19 -0
  25. package/text/glyph-extraction.js +115 -0
  26. package/text/glyph-extraction.js.map +1 -0
  27. package/text/glyph-storage.d.ts +68 -0
  28. package/text/glyph-storage.js +298 -0
  29. package/text/glyph-storage.js.map +1 -0
  30. package/text/layout.d.ts +18 -0
  31. package/text/layout.js +219 -0
  32. package/text/layout.js.map +1 -0
  33. package/text/set-font-weight-offset.d.ts +5 -0
  34. package/text/set-font-weight-offset.js +67 -0
  35. package/text/set-font-weight-offset.js.map +1 -0
  36. package/text/shaders/slug-shader.d.ts +1 -0
  37. package/text/shaders/slug-shader.js +181 -0
  38. package/text/shaders/slug-shader.js.map +1 -0
  39. package/text/shaders/text-shader-fragment.d.ts +1 -0
  40. package/text/shaders/text-shader-fragment.js +2 -0
  41. package/text/shaders/text-shader-fragment.js.map +1 -0
  42. package/text/shaders/weight-shader-fragment.d.ts +1 -0
  43. package/text/shaders/weight-shader-fragment.js +75 -0
  44. package/text/shaders/weight-shader-fragment.js.map +1 -0
  45. package/text/text-data.d.ts +109 -0
  46. package/text/text-data.js +723 -0
  47. package/text/text-data.js.map +1 -0
  48. package/text/text-renderer.d.ts +68 -0
  49. package/text/text-renderer.js +238 -0
  50. package/text/text-renderer.js.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-text-data.js","sourceRoot":"","sources":["../../src/text/default-text-data.ts"],"names":[],"mappings":"AAAA,iGAAiG;AAGjG,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAEjG,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AA6B5C;;;;;;;;;;;;;;;qCAeqC;AACrC,SAAS,gBAAgB,CAAC,IAAgB,EAAE,MAAgC;IACxE,IAAI,KAAK,GAAuB,IAAI,CAAC;IACrC,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACrB,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC;QACrB,IAAI,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;YACjB,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;YACb,CAAC,KAAK,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;2DAC2D;AAC3D,SAAS,gBAAgB,CAAC,IAAY;IAClC,OAAO,CAAC,IAAI,CA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AC;AAED,+FAA+F;AAC/F,MAAM,UAAU,sBAAsB,CAAC,IAAuB;IAC1D,eAAe,CAAC,IAAI,CAAC,CAAC;IACtB,mBAAmB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC","sourcesContent":["/** Default convenience GLTextData: shapes text + extracts curves into a fresh GLGlyphStorage. */\n\nimport type { GLFont } from \"./font.js\";\nimport { extractGlyphCurves } from \"./glyph-extraction.js\";\nimport type { GLCurveSetId, GLGlyphCurves, GLGlyphStorage } from \"./glyph-storage.js\";\nimport { createGlyphStorage, disposeGlyphStorage, updateGlyphStorage } from \"./glyph-storage.js\";\nimport type { GLGlyphRun, GLPlacedGlyph, GLTextData } from \"./text-data.js\";\nimport { createTextData, disposeTextData, updateTextData } from \"./text-data.js\";\nimport type { GLTextLayoutOptions } from \"./layout.js\";\nimport { layoutText } from \"./layout.js\";\nimport { getFontFamily } from \"text-shaper\";\n\ndeclare const defaultTextDataBrand: unique symbol;\n\n/** Convenience text-data variant that owns its `GLGlyphStorage` and exposes the laid-out\n * pixel-space `width` / `height` of the text block. Produced by `createDefaultTextData`. */\nexport interface GLDefaultTextData extends GLTextData {\n readonly [defaultTextDataBrand]: true;\n /** Pixel-space width of the laid-out run (max line width). */\n readonly width: number;\n /** Pixel-space height of the laid-out run (lines × line-height). */\n readonly height: number;\n /** @internal GLFont used to shape this data. */\n readonly _font: GLFont;\n /** @internal GLFont size in pixels used to shape this data. */\n readonly _fontSizePx: number;\n /** @internal Layout options captured at create-time. */\n readonly _options: GLTextLayoutOptions | undefined;\n /** @internal Curve-set id derived from the font's family name. */\n readonly _curveSetId: GLCurveSetId;\n /** @internal GLGlyphStorage owned by this GLDefaultTextData. Disposed by `disposeDefaultTextData`. */\n readonly _storage: GLGlyphStorage;\n /** @internal Glyph ids already offered to `_storage`, indexed by glyph id. Sized to the\n * font's glyph count, and necessarily per-instance because `_storage` is per-instance —\n * so this costs `numGlyphs` bytes per `GLDefaultTextData` (~3 KB for a Latin font, ~65 KB\n * for a full CJK one). */\n readonly _seenGlyphs: Uint8Array;\n}\n\n/** Mark every glyph in `glyphs` as seen, returning only the ids not seen before, or `null`\n * when there are none.\n *\n * Re-shaped text almost always reuses the repertoire it already had — an 840-cell grid of\n * changing numbers is ~37 distinct glyphs across 5,466 placements — so the common answer is\n * \"nothing new\". Answering that with a typed-array probe per glyph keeps the steady state\n * allocation free and lets the caller skip extraction and storage update entirely. That\n * matters more than it looks: `extractGlyphCurves` only early-outs on ids already in the\n * target map, so passing it a fresh map every call made it re-walk the whole repertoire, and\n * glyphs with no outline (space) were re-extracted forever because an absent outline is\n * never cached.\n *\n * A glyph id at or beyond `seen.length` reads `undefined`, which is not `=== 0`, so it is\n * treated as already seen and never reaches extraction. That matches the old behaviour\n * observably: `extractGlyphCurves` asks `extractOne` for such an id, gets `null`, and skips\n * it without recording anything. */\nfunction collectNewGlyphs(seen: Uint8Array, glyphs: readonly GLPlacedGlyph[]): Set<number> | null {\n let added: Set<number> | null = null;\n for (const g of glyphs) {\n const id = g.glyphId;\n if (seen[id] === 0) {\n seen[id] = 1;\n (added ??= new Set()).add(id);\n }\n }\n return added;\n}\n\n/** Derive the curve-set id from the font's family name (e.g. \"Inter\", \"Roboto\"). Falls back\n * to `\"font\"` for fonts that lack a usable name table. */\nfunction familyCurveSetId(font: GLFont): GLCurveSetId {\n return (font._font.name && getFontFamily(font._font.name)) || \"font\";\n}\n\n/** Shape `text` with the default layout, extract glyph curves, and bundle into a\n * `GLDefaultTextData`. `textColor` is applied as the run's defaultColor (per-glyph color\n * overrides remain available via direct `updateTextData(replaceRun)` calls).\n *\n * The returned `GLDefaultTextData` owns its underlying `GLGlyphStorage` — release both with\n * `disposeDefaultTextData(data)`. */\nexport function createDefaultTextData(\n font: GLFont,\n fontSizePx: number,\n text: string,\n textColor?: readonly [number, number, number, number],\n options?: GLTextLayoutOptions\n): GLDefaultTextData {\n const laid = layoutText(font, text, fontSizePx, options);\n const innerCurves = new Map<number, GLGlyphCurves>();\n const seenGlyphs = new Uint8Array(font._font.numGlyphs);\n const ids = collectNewGlyphs(seenGlyphs, laid._glyphs);\n if (ids) {\n extractGlyphCurves(font, ids, innerCurves);\n }\n const curveSetId = familyCurveSetId(font);\n const storage = createGlyphStorage(new Map([[curveSetId, innerCurves]]));\n const run: GLGlyphRun = {\n curveSet: curveSetId,\n glyphs: laid._glyphs,\n pixelsPerFontUnit: laid._pixelsPerFontUnit,\n defaultColor: textColor,\n };\n return Object.assign(createTextData(storage, [run]), {\n width: laid._width,\n height: laid._height,\n _font: font,\n _fontSizePx: fontSizePx,\n _options: options,\n _curveSetId: curveSetId,\n _storage: storage,\n _seenGlyphs: seenGlyphs,\n }) as GLDefaultTextData;\n}\n\n/** Re-shape `text` and apply the new run via `updateTextData(replaceRun)`. New glyphs are\n * added to the storage in place. When `textColor` is omitted, the live run's existing\n * `defaultColor` is preserved (so any caller-driven color override survives a text re-shape). */\nexport function updateDefaultTextData(data: GLDefaultTextData, text: string, textColor?: readonly [number, number, number, number]): void {\n const laid = layoutText(data._font, text, data._fontSizePx, data._options);\n // Extract any glyph outlines this data has not offered to the storage before. Text that\n // reuses its existing repertoire — the overwhelmingly common case — does no work here.\n const ids = collectNewGlyphs(data._seenGlyphs, laid._glyphs);\n if (ids) {\n const innerCurves = new Map<number, GLGlyphCurves>();\n extractGlyphCurves(data._font, ids, innerCurves);\n updateGlyphStorage(data._storage, data._curveSetId, innerCurves);\n }\n // Always use the current `data.runs[0]` as the previous reference; a GLDefaultTextData\n // owns exactly one run and the caller may have swapped it out via their own ops.\n const previousRun = data.runs[0]!;\n const newRun: GLGlyphRun = {\n curveSet: data._curveSetId,\n glyphs: laid._glyphs,\n pixelsPerFontUnit: laid._pixelsPerFontUnit,\n defaultColor: textColor ?? previousRun.defaultColor,\n };\n updateTextData(data, { update: \"replaceRun\", previous: previousRun, run: newRun });\n // Refresh the cached width/height on the branded object.\n Object.assign(data, { width: laid._width, height: laid._height });\n}\n\n/** Release the per-block GPU resources AND the underlying `GLGlyphStorage` owned by `data`. */\nexport function disposeDefaultTextData(data: GLDefaultTextData): void {\n disposeTextData(data);\n disposeGlyphStorage(data._storage);\n}\n"]}
package/text/font.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /** GLFont loading. Wraps text-shaper behind a branded opaque type.
2
+ *
3
+ * A `GLFont` is the boundary between Babylon Lite and the text-shaper library. It is
4
+ * consumed by the default-layout pipeline (`layoutText` in `layout.ts`) and by the
5
+ * default-curve-extraction pipeline (`extractGlyphCurves` in `glyph-extraction.ts`).
6
+ * Callers driving their own text layout and outline extraction never need a `GLFont`. */
7
+ declare const fontBrand: unique symbol;
8
+ /** Opaque handle for a loaded TrueType/OpenType font used by the default text layout and glyph extraction helpers. */
9
+ export interface GLFont {
10
+ readonly [fontBrand]: true;
11
+ }
12
+ /** Load a TTF or OTF font from a URL. */
13
+ export declare function loadFont(url: string): Promise<GLFont>;
14
+ /** Build a `GLFont` from an in-memory TTF/OTF buffer. */
15
+ export declare function createFontFromBuffer(data: ArrayBuffer): GLFont;
16
+ export {};
package/text/font.js ADDED
@@ -0,0 +1,24 @@
1
+ /** GLFont loading. Wraps text-shaper behind a branded opaque type.
2
+ *
3
+ * A `GLFont` is the boundary between Babylon Lite and the text-shaper library. It is
4
+ * consumed by the default-layout pipeline (`layoutText` in `layout.ts`) and by the
5
+ * default-curve-extraction pipeline (`extractGlyphCurves` in `glyph-extraction.ts`).
6
+ * Callers driving their own text layout and outline extraction never need a `GLFont`. */
7
+ import { Font as TextShaperFont } from "text-shaper";
8
+ /** Load a TTF or OTF font from a URL. */
9
+ export async function loadFont(url) {
10
+ const response = await fetch(url);
11
+ if (!response.ok) {
12
+ throw new Error(`loadFont: failed to fetch ${url} (${response.status})`);
13
+ }
14
+ const data = await response.arrayBuffer();
15
+ return createFontFromBuffer(data);
16
+ }
17
+ /** Build a `GLFont` from an in-memory TTF/OTF buffer. */
18
+ export function createFontFromBuffer(data) {
19
+ return {
20
+ _font: TextShaperFont.load(data),
21
+ _curvesCache: null,
22
+ };
23
+ }
24
+ //# sourceMappingURL=font.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"font.js","sourceRoot":"","sources":["../../src/text/font.ts"],"names":[],"mappings":"AAAA;;;;;0FAK0F;AAE1F,OAAO,EAAE,IAAI,IAAI,cAAc,EAAE,MAAM,aAAa,CAAC;AAcrD,yCAAyC;AACzC,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,GAAW;IACtC,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,6BAA6B,GAAG,KAAK,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAC7E,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;IAC1C,OAAO,oBAAoB,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC;AAED,yDAAyD;AACzD,MAAM,UAAU,oBAAoB,CAAC,IAAiB;IAClD,OAAO;QACH,KAAK,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC;QAChC,YAAY,EAAE,IAAI;KACA,CAAC;AAC3B,CAAC","sourcesContent":["/** GLFont loading. Wraps text-shaper behind a branded opaque type.\n *\n * A `GLFont` is the boundary between Babylon Lite and the text-shaper library. It is\n * consumed by the default-layout pipeline (`layoutText` in `layout.ts`) and by the\n * default-curve-extraction pipeline (`extractGlyphCurves` in `glyph-extraction.ts`).\n * Callers driving their own text layout and outline extraction never need a `GLFont`. */\n\nimport { Font as TextShaperFont } from \"text-shaper\";\nimport type { GLGlyphCurves } from \"./glyph-storage.js\";\n\ndeclare const fontBrand: unique symbol;\n\n/** Opaque handle for a loaded TrueType/OpenType font used by the default text layout and glyph extraction helpers. */\nexport interface GLFont {\n readonly [fontBrand]: true;\n /** @internal Underlying text-shaper font handle. */\n readonly _font: TextShaperFont;\n /** @internal Lazily-allocated per-font glyph-curves cache. */\n _curvesCache: Map<number, GLGlyphCurves> | null;\n}\n\n/** Load a TTF or OTF font from a URL. */\nexport async function loadFont(url: string): Promise<GLFont> {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`loadFont: failed to fetch ${url} (${response.status})`);\n }\n const data = await response.arrayBuffer();\n return createFontFromBuffer(data);\n}\n\n/** Build a `GLFont` from an in-memory TTF/OTF buffer. */\nexport function createFontFromBuffer(data: ArrayBuffer): GLFont {\n return {\n _font: TextShaperFont.load(data),\n _curvesCache: null,\n } as unknown as GLFont;\n}\n"]}
@@ -0,0 +1,19 @@
1
+ /** Glyph outline extraction: the default `text-shaper`-backed pipeline that
2
+ * produces `GLGlyphCurves` values from a `GLFont`'s glyph paths.
3
+ *
4
+ * The outline value types themselves (`GLQuadCurve`, `GLGlyphBounds`, `GLGlyphCurves`)
5
+ * live in `glyph-storage.ts` because storage is what owns and persists them.
6
+ * Callers using their own outline source (DirectWrite, FreeType, hand-rolled)
7
+ * import those types directly from `glyph-storage.js` and never pull this
8
+ * module — so `text-shaper` stays out of their bundle. The only helper they
9
+ * may want is `cubicToQuadratics`, which has no dependency on text-shaper. */
10
+ import type { GLFont } from "./font.js";
11
+ import type { GLGlyphCurves, GLQuadCurve } from "./glyph-storage.js";
12
+ /** Approximate a cubic Bézier with two quadratics using the "3/4 rule" (matches Slug reference).
13
+ * Exposed as a public helper so callers that ingest cubic outlines from their own font sources
14
+ * (e.g. DirectWrite, FreeType) can convert into the quadratic-only format `GLGlyphCurves` expects. */
15
+ export declare function cubicToQuadratics(p0x: number, p0y: number, c1x: number, c1y: number, c2x: number, c2y: number, p1x: number, p1y: number): [GLQuadCurve, GLQuadCurve];
16
+ /** Extract outlines for the requested glyph ids and add them to `target`.
17
+ * Skips ids already present in `target`. Glyphs with no outline are silently skipped.
18
+ * Mutates `target` directly — no allocation when no new glyphs appear. */
19
+ export declare function extractGlyphCurves(font: GLFont, glyphIds: ReadonlySet<number>, target: Map<number, GLGlyphCurves>): void;
@@ -0,0 +1,115 @@
1
+ /** Glyph outline extraction: the default `text-shaper`-backed pipeline that
2
+ * produces `GLGlyphCurves` values from a `GLFont`'s glyph paths.
3
+ *
4
+ * The outline value types themselves (`GLQuadCurve`, `GLGlyphBounds`, `GLGlyphCurves`)
5
+ * live in `glyph-storage.ts` because storage is what owns and persists them.
6
+ * Callers using their own outline source (DirectWrite, FreeType, hand-rolled)
7
+ * import those types directly from `glyph-storage.js` and never pull this
8
+ * module — so `text-shaper` stays out of their bundle. The only helper they
9
+ * may want is `cubicToQuadratics`, which has no dependency on text-shaper. */
10
+ import { getGlyphPath } from "text-shaper";
11
+ /** Approximate a cubic Bézier with two quadratics using the "3/4 rule" (matches Slug reference).
12
+ * Exposed as a public helper so callers that ingest cubic outlines from their own font sources
13
+ * (e.g. DirectWrite, FreeType) can convert into the quadratic-only format `GLGlyphCurves` expects. */
14
+ export function cubicToQuadratics(p0x, p0y, c1x, c1y, c2x, c2y, p1x, p1y) {
15
+ const q0cx = p0x + (c1x - p0x) * 0.75;
16
+ const q0cy = p0y + (c1y - p0y) * 0.75;
17
+ const q1cx = p1x + (c2x - p1x) * 0.75;
18
+ const q1cy = p1y + (c2y - p1y) * 0.75;
19
+ const midx = (q0cx + q1cx) * 0.5;
20
+ const midy = (q0cy + q1cy) * 0.5;
21
+ return [
22
+ { p0x, p0y, p1x: q0cx, p1y: q0cy, p2x: midx, p2y: midy },
23
+ { p0x: midx, p0y: midy, p1x: q1cx, p1y: q1cy, p2x: p1x, p2y: p1y },
24
+ ];
25
+ }
26
+ function extractOne(font, glyphId) {
27
+ const path = getGlyphPath(font._font, glyphId);
28
+ if (!path || !path.bounds) {
29
+ return null;
30
+ }
31
+ const curves = [];
32
+ let curX = 0;
33
+ let curY = 0;
34
+ let startX = 0;
35
+ let startY = 0;
36
+ for (const cmd of path.commands) {
37
+ switch (cmd.type) {
38
+ case "M":
39
+ curX = cmd.x;
40
+ curY = cmd.y;
41
+ startX = cmd.x;
42
+ startY = cmd.y;
43
+ break;
44
+ case "L": {
45
+ const dx = cmd.x - curX;
46
+ const dy = cmd.y - curY;
47
+ if (Math.abs(dx) >= 0.1 || Math.abs(dy) >= 0.1) {
48
+ const mx = (curX + cmd.x) * 0.5;
49
+ const my = (curY + cmd.y) * 0.5;
50
+ curves.push({ p0x: curX, p0y: curY, p1x: mx, p1y: my, p2x: cmd.x, p2y: cmd.y });
51
+ }
52
+ curX = cmd.x;
53
+ curY = cmd.y;
54
+ break;
55
+ }
56
+ case "Q":
57
+ curves.push({ p0x: curX, p0y: curY, p1x: cmd.x1, p1y: cmd.y1, p2x: cmd.x, p2y: cmd.y });
58
+ curX = cmd.x;
59
+ curY = cmd.y;
60
+ break;
61
+ case "C": {
62
+ const [q1, q2] = cubicToQuadratics(curX, curY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
63
+ curves.push(q1, q2);
64
+ curX = cmd.x;
65
+ curY = cmd.y;
66
+ break;
67
+ }
68
+ case "Z": {
69
+ const cdx = startX - curX;
70
+ const cdy = startY - curY;
71
+ if (Math.abs(cdx) > 0.1 || Math.abs(cdy) > 0.1) {
72
+ const mx = (curX + startX) * 0.5;
73
+ const my = (curY + startY) * 0.5;
74
+ curves.push({ p0x: curX, p0y: curY, p1x: mx, p1y: my, p2x: startX, p2y: startY });
75
+ }
76
+ curX = startX;
77
+ curY = startY;
78
+ break;
79
+ }
80
+ }
81
+ }
82
+ if (curves.length === 0) {
83
+ return null;
84
+ }
85
+ const bounds = {
86
+ xMin: path.bounds.xMin,
87
+ yMin: path.bounds.yMin,
88
+ xMax: path.bounds.xMax,
89
+ yMax: path.bounds.yMax,
90
+ };
91
+ return { glyphId, curves, bounds };
92
+ }
93
+ /** Extract outlines for the requested glyph ids and add them to `target`.
94
+ * Skips ids already present in `target`. Glyphs with no outline are silently skipped.
95
+ * Mutates `target` directly — no allocation when no new glyphs appear. */
96
+ export function extractGlyphCurves(font, glyphIds, target) {
97
+ const cache = (font._curvesCache ??= new Map());
98
+ for (const id of glyphIds) {
99
+ if (target.has(id)) {
100
+ continue;
101
+ }
102
+ let entry = cache.get(id);
103
+ if (entry === undefined) {
104
+ const extracted = extractOne(font, id);
105
+ if (extracted == null) {
106
+ // Sentinel: cache the absence by skipping target; future calls re-skip via target.has.
107
+ continue;
108
+ }
109
+ entry = extracted;
110
+ cache.set(id, entry);
111
+ }
112
+ target.set(id, entry);
113
+ }
114
+ }
115
+ //# sourceMappingURL=glyph-extraction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"glyph-extraction.js","sourceRoot":"","sources":["../../src/text/glyph-extraction.ts"],"names":[],"mappings":"AAAA;;;;;;;;+EAQ+E;AAE/E,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAI3C;;uGAEuG;AACvG,MAAM,UAAU,iBAAiB,CAAC,GAAW,EAAE,GAAW,EAAE,GAAW,EAAE,GAAW,EAAE,GAAW,EAAE,GAAW,EAAE,GAAW,EAAE,GAAW;IACpI,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;IACtC,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;IACtC,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;IACtC,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;IACtC,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,GAAG,CAAC;IACjC,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,GAAG,CAAC;IACjC,OAAO;QACH,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,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AM,KAAK,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;IAChD,KAAK,MAAM,EAAE,IAAI,QAAQ,EAAE,CAAC;QACxB,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;YACjB,SAAS;QACb,CAAC;QACD,IAAI,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC1B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACvC,IAAI,SAAS,IAAI,IAAI,EAAE,CAAC;gBACpB,uFAAuF;gBACvF,SAAS;YACb,CAAC;YACD,KAAK,GAAG,SAAS,CAAC;YAClB,KAAK,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QACzB,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC1B,CAAC;AACL,CAAC","sourcesContent":["/** Glyph outline extraction: the default `text-shaper`-backed pipeline that\n * produces `GLGlyphCurves` values from a `GLFont`'s glyph paths.\n *\n * The outline value types themselves (`GLQuadCurve`, `GLGlyphBounds`, `GLGlyphCurves`)\n * live in `glyph-storage.ts` because storage is what owns and persists them.\n * Callers using their own outline source (DirectWrite, FreeType, hand-rolled)\n * import those types directly from `glyph-storage.js` and never pull this\n * module — so `text-shaper` stays out of their bundle. The only helper they\n * may want is `cubicToQuadratics`, which has no dependency on text-shaper. */\n\nimport { getGlyphPath } from \"text-shaper\";\nimport type { GLFont } from \"./font.js\";\nimport type { GLGlyphBounds, GLGlyphCurves, GLQuadCurve } from \"./glyph-storage.js\";\n\n/** Approximate a cubic Bézier with two quadratics using the \"3/4 rule\" (matches Slug reference).\n * Exposed as a public helper so callers that ingest cubic outlines from their own font sources\n * (e.g. DirectWrite, FreeType) can convert into the quadratic-only format `GLGlyphCurves` expects. */\nexport function cubicToQuadratics(p0x: number, p0y: number, c1x: number, c1y: number, c2x: number, c2y: number, p1x: number, p1y: number): [GLQuadCurve, GLQuadCurve] {\n const q0cx = p0x + (c1x - p0x) * 0.75;\n const q0cy = p0y + (c1y - p0y) * 0.75;\n const q1cx = p1x + (c2x - p1x) * 0.75;\n const q1cy = p1y + (c2y - p1y) * 0.75;\n const midx = (q0cx + q1cx) * 0.5;\n const midy = (q0cy + q1cy) * 0.5;\n return [\n { p0x, p0y, p1x: q0cx, p1y: q0cy, p2x: midx, p2y: midy },\n { p0x: midx, p0y: midy, p1x: q1cx, p1y: q1cy, p2x: p1x, p2y: p1y },\n ];\n}\n\nfunction extractOne(font: GLFont, glyphId: number): GLGlyphCurves | null {\n const path = getGlyphPath(font._font, glyphId);\n if (!path || !path.bounds) {\n return null;\n }\n const curves: GLQuadCurve[] = [];\n let curX = 0;\n let curY = 0;\n let startX = 0;\n let startY = 0;\n for (const cmd of path.commands) {\n switch (cmd.type) {\n case \"M\":\n curX = cmd.x;\n curY = cmd.y;\n startX = cmd.x;\n startY = cmd.y;\n break;\n case \"L\": {\n const dx = cmd.x - curX;\n const dy = cmd.y - curY;\n if (Math.abs(dx) >= 0.1 || Math.abs(dy) >= 0.1) {\n const mx = (curX + cmd.x) * 0.5;\n const my = (curY + cmd.y) * 0.5;\n curves.push({ p0x: curX, p0y: curY, p1x: mx, p1y: my, p2x: cmd.x, p2y: cmd.y });\n }\n curX = cmd.x;\n curY = cmd.y;\n break;\n }\n case \"Q\":\n curves.push({ p0x: curX, p0y: curY, p1x: cmd.x1, p1y: cmd.y1, p2x: cmd.x, p2y: cmd.y });\n curX = cmd.x;\n curY = cmd.y;\n break;\n case \"C\": {\n const [q1, q2] = cubicToQuadratics(curX, curY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);\n curves.push(q1, q2);\n curX = cmd.x;\n curY = cmd.y;\n break;\n }\n case \"Z\": {\n const cdx = startX - curX;\n const cdy = startY - curY;\n if (Math.abs(cdx) > 0.1 || Math.abs(cdy) > 0.1) {\n const mx = (curX + startX) * 0.5;\n const my = (curY + startY) * 0.5;\n curves.push({ p0x: curX, p0y: curY, p1x: mx, p1y: my, p2x: startX, p2y: startY });\n }\n curX = startX;\n curY = startY;\n break;\n }\n }\n }\n if (curves.length === 0) {\n return null;\n }\n const bounds: GLGlyphBounds = {\n xMin: path.bounds.xMin,\n yMin: path.bounds.yMin,\n xMax: path.bounds.xMax,\n yMax: path.bounds.yMax,\n };\n return { glyphId, curves, bounds };\n}\n\n/** Extract outlines for the requested glyph ids and add them to `target`.\n * Skips ids already present in `target`. Glyphs with no outline are silently skipped.\n * Mutates `target` directly — no allocation when no new glyphs appear. */\nexport function extractGlyphCurves(font: GLFont, glyphIds: ReadonlySet<number>, target: Map<number, GLGlyphCurves>): void {\n const cache = (font._curvesCache ??= new Map());\n for (const id of glyphIds) {\n if (target.has(id)) {\n continue;\n }\n let entry = cache.get(id);\n if (entry === undefined) {\n const extracted = extractOne(font, id);\n if (extracted == null) {\n // Sentinel: cache the absence by skipping target; future calls re-skip via target.has.\n continue;\n }\n entry = extracted;\n cache.set(id, entry);\n }\n target.set(id, entry);\n }\n}\n"]}
@@ -0,0 +1,68 @@
1
+ /** Glyph storage: per-curve-set CPU outline catalog plus the GPU atlas packed from it.
2
+ *
3
+ * Layered:
4
+ * - `GLGlyphStorage` is the opaque public handle. Holds one or more curve-sets keyed by
5
+ * `GLCurveSetId` (typically a font family name). Each curve-set owns its glyph
6
+ * outlines plus the `SharedAtlas` packed from them.
7
+ * - `SharedAtlas` stages float32 curve control points and uint32 band headers/
8
+ * curve-reference lists in append-only RGBA and RG arrays, respectively.
9
+ * - Atlas packing (`packAppendGlyph`) and spatial-band partitioning (`buildGlyphBands`)
10
+ * live here as internal helpers — they implement the storage's invariants and are
11
+ * not callable from outside the module.
12
+ * - GPU creation/upload (`SharedAtlasGpu`, `ensureSharedAtlasGpu`) lives in
13
+ * `_gpu/text-textures.ts`; the shared types are exported from here. GPU teardown
14
+ * is performed inline in `disposeGlyphStorage` to avoid a circular import edge.
15
+ *
16
+ * Lifetime is caller-owned (matches `Texture2D` semantics):
17
+ * - `createGlyphStorage(initial?)` allocates a fresh storage, optionally seeded.
18
+ * - `updateGlyphStorage(storage, curveSetId, curves)` adds glyphs (creating the
19
+ * curve-set on demand). Glyph ids already present are skipped.
20
+ * - `disposeGlyphStorage(storage)` releases every atlas. The caller must ensure no
21
+ * `GLTextData` is still drawing from it — using a disposed storage is undefined
22
+ * behavior. Idempotent.
23
+ */
24
+ declare const glyphStorageBrand: unique symbol;
25
+ /** Quadratic Bézier curve describing one segment of a glyph outline in font units. */
26
+ export type GLQuadCurve = {
27
+ readonly p0x: number;
28
+ readonly p0y: number;
29
+ readonly p1x: number;
30
+ readonly p1y: number;
31
+ readonly p2x: number;
32
+ readonly p2y: number;
33
+ };
34
+ /** Axis-aligned glyph extents in font units, used to size the rendered quad and spatial curve bands. */
35
+ export type GLGlyphBounds = {
36
+ readonly xMin: number;
37
+ readonly yMin: number;
38
+ readonly xMax: number;
39
+ readonly yMax: number;
40
+ };
41
+ /** Complete outline data for one glyph id, ready to be packed into a `GLGlyphStorage` atlas. */
42
+ export type GLGlyphCurves = {
43
+ readonly glyphId: number;
44
+ readonly curves: readonly GLQuadCurve[];
45
+ readonly bounds: GLGlyphBounds;
46
+ };
47
+ /** Identifier for a curve set (a font's glyph-curves map). Strings let callers use a
48
+ * human-readable key (e.g. the font face name) for easy debugging. */
49
+ export type GLCurveSetId = string;
50
+ /** Opaque bundle of glyph outlines (organized by curve-set) and the GPU atlases packed
51
+ * from them. Holds an arbitrary number of curve-sets — each curve-set gets its own atlas.
52
+ * Shared by reference across any number of `GLTextData`s that need the same glyph catalog. */
53
+ export interface GLGlyphStorage {
54
+ readonly [glyphStorageBrand]: true;
55
+ }
56
+ /** Build a `GLGlyphStorage`. If `initial` is provided, each curve-set is packed into its
57
+ * own atlas synchronously. The passed inner maps are *adopted* by the storage — the
58
+ * caller must not mutate them directly afterward (use `updateGlyphStorage` instead). */
59
+ export declare function createGlyphStorage(initial?: Map<GLCurveSetId, Map<number, GLGlyphCurves>>): GLGlyphStorage;
60
+ /** Add glyphs to the named curve-set, creating it if it doesn't exist yet. Glyph ids
61
+ * already present in the curve-set are skipped (the existing outline + atlas slot wins).
62
+ * Safe to call between frames: the atlas grows in place and the next render uploads the
63
+ * new glyphs. */
64
+ export declare function updateGlyphStorage(storage: GLGlyphStorage, curveSetId: GLCurveSetId, curves: ReadonlyMap<number, GLGlyphCurves>): void;
65
+ /** Release every GPU atlas owned by `storage`. Idempotent. The caller is responsible for
66
+ * ensuring no `GLTextData` is still drawing from this storage. */
67
+ export declare function disposeGlyphStorage(storage: GLGlyphStorage): void;
68
+ export {};
@@ -0,0 +1,298 @@
1
+ /** Glyph storage: per-curve-set CPU outline catalog plus the GPU atlas packed from it.
2
+ *
3
+ * Layered:
4
+ * - `GLGlyphStorage` is the opaque public handle. Holds one or more curve-sets keyed by
5
+ * `GLCurveSetId` (typically a font family name). Each curve-set owns its glyph
6
+ * outlines plus the `SharedAtlas` packed from them.
7
+ * - `SharedAtlas` stages float32 curve control points and uint32 band headers/
8
+ * curve-reference lists in append-only RGBA and RG arrays, respectively.
9
+ * - Atlas packing (`packAppendGlyph`) and spatial-band partitioning (`buildGlyphBands`)
10
+ * live here as internal helpers — they implement the storage's invariants and are
11
+ * not callable from outside the module.
12
+ * - GPU creation/upload (`SharedAtlasGpu`, `ensureSharedAtlasGpu`) lives in
13
+ * `_gpu/text-textures.ts`; the shared types are exported from here. GPU teardown
14
+ * is performed inline in `disposeGlyphStorage` to avoid a circular import edge.
15
+ *
16
+ * Lifetime is caller-owned (matches `Texture2D` semantics):
17
+ * - `createGlyphStorage(initial?)` allocates a fresh storage, optionally seeded.
18
+ * - `updateGlyphStorage(storage, curveSetId, curves)` adds glyphs (creating the
19
+ * curve-set on demand). Glyph ids already present are skipped.
20
+ * - `disposeGlyphStorage(storage)` releases every atlas. The caller must ensure no
21
+ * `GLTextData` is still drawing from it — using a disposed storage is undefined
22
+ * behavior. Idempotent.
23
+ */
24
+ import { disposeTexture } from "../texture.js";
25
+ // ─── Internal supporting types ────────────────────────────────────────────
26
+ // Tagged `@internal` on the type itself so the d.ts trim pass strips them from the
27
+ // published types. Fields still use `_` prefixes so production property mangling can
28
+ // shorten them.
29
+ /** @internal Width of the curve / band textures (texels). */
30
+ export const TEX_WIDTH = 4096;
31
+ /** @internal Floats per glyph in `SharedAtlas._metaData`, laid out as three `vec4<f32>` to match
32
+ * the shader's `GlyphMetadata`: bounds (xMin, yMin, xMax, yMax), atlas (glyphLocX, glyphLocY,
33
+ * bandMaxX, bandMaxY), band (bandScaleX, bandScaleY, bandOffsetX, bandOffsetY).
34
+ *
35
+ * All twelve depend only on the glyph, so they live here — written once when the glyph is
36
+ * appended — instead of being copied into every instance that references the glyph. */
37
+ export const GLYPH_METADATA_FLOATS = 12;
38
+ // ─── Public API ───────────────────────────────────────────────────────────
39
+ /** Build a `GLGlyphStorage`. If `initial` is provided, each curve-set is packed into its
40
+ * own atlas synchronously. The passed inner maps are *adopted* by the storage — the
41
+ * caller must not mutate them directly afterward (use `updateGlyphStorage` instead). */
42
+ export function createGlyphStorage(initial) {
43
+ const _curveSets = new Map();
44
+ if (initial) {
45
+ for (const [curveSetId, curves] of initial) {
46
+ _curveSets.set(curveSetId, makeCurveSet(curves));
47
+ }
48
+ }
49
+ return { _curveSets };
50
+ }
51
+ /** Add glyphs to the named curve-set, creating it if it doesn't exist yet. Glyph ids
52
+ * already present in the curve-set are skipped (the existing outline + atlas slot wins).
53
+ * Safe to call between frames: the atlas grows in place and the next render uploads the
54
+ * new glyphs. */
55
+ export function updateGlyphStorage(storage, curveSetId, curves) {
56
+ let cs = storage._curveSets.get(curveSetId);
57
+ if (!cs) {
58
+ cs = makeCurveSet(new Map());
59
+ storage._curveSets.set(curveSetId, cs);
60
+ }
61
+ for (const [glyphId, glyph] of curves) {
62
+ if (cs._curves.has(glyphId)) {
63
+ continue;
64
+ }
65
+ cs._curves.set(glyphId, glyph);
66
+ cs._atlas._glyphSlots.set(glyphId, packAppendGlyph(cs._atlas, glyph));
67
+ }
68
+ }
69
+ /** Release every GPU atlas owned by `storage`. Idempotent. The caller is responsible for
70
+ * ensuring no `GLTextData` is still drawing from this storage. */
71
+ export function disposeGlyphStorage(storage) {
72
+ for (const cs of storage._curveSets.values()) {
73
+ const gpu = cs._atlas._gpu;
74
+ if (gpu) {
75
+ disposeTexture(gpu._engine, gpu._curveTex);
76
+ disposeTexture(gpu._engine, gpu._bandTex);
77
+ disposeTexture(gpu._engine, gpu._metaTex);
78
+ cs._atlas._gpu = null;
79
+ }
80
+ }
81
+ storage._curveSets.clear();
82
+ }
83
+ // ─── Internal: SharedAtlas construction + glyph packing ───────────────────
84
+ const ROW_COMPONENTS = TEX_WIDTH * 4;
85
+ /** @internal Create an empty `SharedAtlas`. */
86
+ export function createSharedAtlas() {
87
+ return {
88
+ _curveTexData: new Float32Array(ROW_COMPONENTS),
89
+ _curveTexelsUsed: 0,
90
+ _bandTexData: new Uint32Array(TEX_WIDTH * 2),
91
+ _bandTexelsUsed: 0,
92
+ _glyphSlots: new Map(),
93
+ _metaData: new Float32Array(GLYPH_METADATA_FLOATS * 16),
94
+ _slotCount: 0,
95
+ _version: 0,
96
+ _gpu: null,
97
+ };
98
+ }
99
+ function makeCurveSet(curves) {
100
+ const atlas = createSharedAtlas();
101
+ for (const [glyphId, glyph] of curves) {
102
+ atlas._glyphSlots.set(glyphId, packAppendGlyph(atlas, glyph));
103
+ }
104
+ return { _curves: curves, _atlas: atlas };
105
+ }
106
+ /** Grow a texel-staging array to hold at least `neededTexels` texels,
107
+ * rounded up to a whole 4096-texel row. Returns the same array when already large enough. */
108
+ function ensureTexelCapacity(current, neededTexels, ArrayType, componentsPerTexel = 4) {
109
+ const neededComponents = neededTexels * componentsPerTexel;
110
+ const rowComponents = TEX_WIDTH * componentsPerTexel;
111
+ if (current.length >= neededComponents) {
112
+ return current;
113
+ }
114
+ let newLength = Math.max(current.length * 2, rowComponents);
115
+ while (newLength < neededComponents) {
116
+ newLength *= 2;
117
+ }
118
+ // Round up to a whole row to keep texel math aligned.
119
+ newLength = Math.ceil(newLength / rowComponents) * rowComponents;
120
+ const grown = new ArrayType(newLength);
121
+ grown.set(current);
122
+ return grown;
123
+ }
124
+ /** @internal Append `glyph` to `atlas`. Returns the new slot. Caller must guarantee
125
+ * glyph is not already present. */
126
+ export function packAppendGlyph(atlas, glyph) {
127
+ const bands = buildGlyphBands(glyph);
128
+ const curves = glyph.curves;
129
+ // ── Curve texels: 2 texels per curve, must not straddle a row boundary. ──
130
+ let curveTexel = atlas._curveTexelsUsed;
131
+ const curveTexelPositions = new Array(curves.length);
132
+ for (let i = 0; i < curves.length; i++) {
133
+ const row0 = (curveTexel / TEX_WIDTH) | 0;
134
+ const row1 = ((curveTexel + 1) / TEX_WIDTH) | 0;
135
+ if (row0 !== row1) {
136
+ curveTexel = row1 * TEX_WIDTH;
137
+ }
138
+ curveTexelPositions[i] = curveTexel;
139
+ curveTexel += 2;
140
+ }
141
+ const curveTexelsEnd = curveTexel;
142
+ atlas._curveTexData = ensureTexelCapacity(atlas._curveTexData, curveTexelsEnd, Float32Array);
143
+ const curveData = atlas._curveTexData;
144
+ for (let i = 0; i < curves.length; i++) {
145
+ const c = curves[i];
146
+ const tl = curveTexelPositions[i];
147
+ const o0 = tl * 4;
148
+ curveData[o0] = c.p0x;
149
+ curveData[o0 + 1] = c.p0y;
150
+ curveData[o0 + 2] = c.p1x;
151
+ curveData[o0 + 3] = c.p1y;
152
+ const o1 = (tl + 1) * 4;
153
+ curveData[o1] = c.p2x;
154
+ curveData[o1 + 1] = c.p2y;
155
+ // (.zw left zero; padded.)
156
+ }
157
+ atlas._curveTexelsUsed = curveTexelsEnd;
158
+ // ── Band block: headers must not straddle a row; followed by curve-index lists. ──
159
+ const headerCount = bands._hBandCount + bands._vBandCount;
160
+ let bandStart = atlas._bandTexelsUsed;
161
+ const curX = bandStart % TEX_WIDTH;
162
+ if (curX + headerCount > TEX_WIDTH) {
163
+ bandStart = (((bandStart / TEX_WIDTH) | 0) + 1) * TEX_WIDTH;
164
+ }
165
+ const glyphLocX = bandStart % TEX_WIDTH;
166
+ const glyphLocY = (bandStart / TEX_WIDTH) | 0;
167
+ const allBands = [...bands._hBands, ...bands._vBands];
168
+ let curveListOffset = headerCount;
169
+ const bandOffsets = new Array(allBands.length);
170
+ for (let i = 0; i < allBands.length; i++) {
171
+ bandOffsets[i] = curveListOffset;
172
+ curveListOffset += allBands[i]._curveIndices.length;
173
+ }
174
+ const bandTexelsEnd = bandStart + curveListOffset;
175
+ atlas._bandTexData = ensureTexelCapacity(atlas._bandTexData, bandTexelsEnd, Uint32Array, 2);
176
+ const bandData = atlas._bandTexData;
177
+ // Headers.
178
+ for (let i = 0; i < allBands.length; i++) {
179
+ const tl = bandStart + i;
180
+ const di = tl * 2;
181
+ bandData[di] = allBands[i]._curveIndices.length;
182
+ bandData[di + 1] = bandOffsets[i];
183
+ }
184
+ // Curve refs.
185
+ for (let i = 0; i < allBands.length; i++) {
186
+ const band = allBands[i];
187
+ const listStart = bandStart + bandOffsets[i];
188
+ for (let j = 0; j < band._curveIndices.length; j++) {
189
+ const ci = band._curveIndices[j];
190
+ const curveTexelAbs = curveTexelPositions[ci];
191
+ const cTexX = curveTexelAbs % TEX_WIDTH;
192
+ const cTexY = (curveTexelAbs / TEX_WIDTH) | 0;
193
+ const tl = listStart + j;
194
+ const di = tl * 2;
195
+ bandData[di] = cTexX;
196
+ bandData[di + 1] = cTexY;
197
+ }
198
+ }
199
+ atlas._bandTexelsUsed = bandTexelsEnd;
200
+ atlas._version++;
201
+ const { xMin, yMin, xMax, yMax } = glyph.bounds;
202
+ const widthFu = xMax - xMin;
203
+ const heightFu = yMax - yMin;
204
+ const bandScaleX = widthFu > 0 ? bands._vBandCount / widthFu : 0;
205
+ const bandScaleY = heightFu > 0 ? bands._hBandCount / heightFu : 0;
206
+ // ── Glyph metadata: written once here, read by every instance that uses this glyph. ──
207
+ const index = atlas._slotCount++;
208
+ const needMetaFloats = atlas._slotCount * GLYPH_METADATA_FLOATS;
209
+ if (atlas._metaData.length < needMetaFloats) {
210
+ const grown = new Float32Array(Math.max(atlas._metaData.length * 2, needMetaFloats));
211
+ grown.set(atlas._metaData);
212
+ atlas._metaData = grown;
213
+ }
214
+ const m = index * GLYPH_METADATA_FLOATS;
215
+ const meta = atlas._metaData;
216
+ meta[m] = xMin;
217
+ meta[m + 1] = yMin;
218
+ meta[m + 2] = xMax;
219
+ meta[m + 3] = yMax;
220
+ meta[m + 4] = glyphLocX;
221
+ meta[m + 5] = glyphLocY;
222
+ meta[m + 6] = bands._vBandCount - 1;
223
+ meta[m + 7] = bands._hBandCount - 1;
224
+ meta[m + 8] = bandScaleX;
225
+ meta[m + 9] = bandScaleY;
226
+ meta[m + 10] = -xMin * bandScaleX;
227
+ meta[m + 11] = -yMin * bandScaleY;
228
+ return { _index: index };
229
+ }
230
+ // ─── Internal: spatial-band partitioning ──────────────────────────────────
231
+ function curveAt(curves, i) {
232
+ const c = curves[i];
233
+ if (!c) {
234
+ throw new Error("buildGlyphBands: invalid curve index");
235
+ }
236
+ return c;
237
+ }
238
+ function buildBandsInternal(g) {
239
+ const { curves, bounds } = g;
240
+ const numBands = Math.max(1, Math.min(8, Math.floor(curves.length / 2)));
241
+ const { xMin, yMin, xMax, yMax } = bounds;
242
+ const width = xMax - xMin;
243
+ const height = yMax - yMin;
244
+ const bandH = height / numBands;
245
+ const bandW = width / numBands;
246
+ const hBands = [];
247
+ const vBands = [];
248
+ for (let i = 0; i < numBands; i++) {
249
+ hBands.push({ _curveIndices: [] });
250
+ vBands.push({ _curveIndices: [] });
251
+ }
252
+ for (let ci = 0; ci < curves.length; ci++) {
253
+ const c = curveAt(curves, ci);
254
+ const cyMin = Math.min(c.p0y, c.p1y, c.p2y);
255
+ const cyMax = Math.max(c.p0y, c.p1y, c.p2y);
256
+ const cxMin = Math.min(c.p0x, c.p1x, c.p2x);
257
+ const cxMax = Math.max(c.p0x, c.p1x, c.p2x);
258
+ if (height > 0) {
259
+ for (let b = 0; b < numBands; b++) {
260
+ const bMinY = yMin + b * bandH;
261
+ const bMaxY = yMin + (b + 1) * bandH;
262
+ if (cyMax >= bMinY && cyMin <= bMaxY) {
263
+ hBands[b]._curveIndices.push(ci);
264
+ }
265
+ }
266
+ }
267
+ if (width > 0) {
268
+ for (let b = 0; b < numBands; b++) {
269
+ const bMinX = xMin + b * bandW;
270
+ const bMaxX = xMin + (b + 1) * bandW;
271
+ if (cxMax >= bMinX && cxMin <= bMaxX) {
272
+ vBands[b]._curveIndices.push(ci);
273
+ }
274
+ }
275
+ }
276
+ }
277
+ // Sort curves: h-bands by descending max x, v-bands by descending max y (early-exit in shader).
278
+ for (const band of hBands) {
279
+ band._curveIndices.sort((a, b) => {
280
+ const ca = curveAt(curves, a);
281
+ const cb = curveAt(curves, b);
282
+ return Math.max(cb.p0x, cb.p1x, cb.p2x) - Math.max(ca.p0x, ca.p1x, ca.p2x);
283
+ });
284
+ }
285
+ for (const band of vBands) {
286
+ band._curveIndices.sort((a, b) => {
287
+ const ca = curveAt(curves, a);
288
+ const cb = curveAt(curves, b);
289
+ return Math.max(cb.p0y, cb.p1y, cb.p2y) - Math.max(ca.p0y, ca.p1y, ca.p2y);
290
+ });
291
+ }
292
+ return { _hBands: hBands, _vBands: vBands, _hBandCount: numBands, _vBandCount: numBands };
293
+ }
294
+ /** @internal Get (and memoize) the band partitioning for a glyph's curves. */
295
+ export function buildGlyphBands(g) {
296
+ return (g._bands ??= buildBandsInternal(g));
297
+ }
298
+ //# sourceMappingURL=glyph-storage.js.map