ultra-text 1.0.1 → 1.0.2

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 (150) hide show
  1. package/README.md +224 -1002
  2. package/dist/assets/{cpuSdf.worker-xS57yQbP.js → cpuSdf.worker--X1Qpmdp.js} +136 -47
  3. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  4. package/dist/atlas/appendAtlas.js +67 -25
  5. package/dist/atlas/appendAtlas.js.map +1 -1
  6. package/dist/atlas/buildAtlas.js +3 -2
  7. package/dist/atlas/buildAtlas.js.map +1 -1
  8. package/dist/atlas/cpuAtlas.d.ts +4 -1
  9. package/dist/atlas/cpuAtlas.js +8 -6
  10. package/dist/atlas/cpuAtlas.js.map +1 -1
  11. package/dist/atlas/cpuSdf.js +152 -40
  12. package/dist/atlas/cpuSdf.js.map +1 -1
  13. package/dist/atlas/cpuWorker.d.ts +5 -3
  14. package/dist/atlas/cpuWorker.js +119 -12
  15. package/dist/atlas/cpuWorker.js.map +1 -1
  16. package/dist/atlas/gpuAtlas.js +100 -276
  17. package/dist/atlas/gpuAtlas.js.map +1 -1
  18. package/dist/atlas/gpuCommon.d.ts +135 -0
  19. package/dist/atlas/gpuCommon.js +223 -0
  20. package/dist/atlas/gpuCommon.js.map +1 -0
  21. package/dist/atlas/jfaWgsl.js +47 -241
  22. package/dist/atlas/jfaWgsl.js.map +1 -1
  23. package/dist/atlas/rasterize.js +103 -58
  24. package/dist/atlas/rasterize.js.map +1 -1
  25. package/dist/atlas/shapeRaster.js +2 -1
  26. package/dist/atlas/shapeRaster.js.map +1 -1
  27. package/dist/atlas/vanillaBounds.d.ts +64 -0
  28. package/dist/atlas/vanillaBounds.js +42 -0
  29. package/dist/atlas/vanillaBounds.js.map +1 -0
  30. package/dist/atlas/vanillaCore.d.ts +100 -0
  31. package/dist/atlas/vanillaCore.js +1012 -0
  32. package/dist/atlas/vanillaCore.js.map +1 -0
  33. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  34. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  35. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  36. package/dist/atlas/vanillaExtras.d.ts +8 -0
  37. package/dist/atlas/vanillaExtras.js +166 -0
  38. package/dist/atlas/vanillaExtras.js.map +1 -0
  39. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  40. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  41. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  42. package/dist/dom/DomSdf.js +224 -284
  43. package/dist/dom/DomSdf.js.map +1 -1
  44. package/dist/dom/DomSlug.js +75 -151
  45. package/dist/dom/DomSlug.js.map +1 -1
  46. package/dist/dom/domAnalytic.d.ts +54 -0
  47. package/dist/dom/domAnalytic.js +282 -0
  48. package/dist/dom/domAnalytic.js.map +1 -0
  49. package/dist/dom/domExtras.d.ts +27 -0
  50. package/dist/dom/domExtras.js +137 -0
  51. package/dist/dom/domExtras.js.map +1 -0
  52. package/dist/dom/fontCanvas.js +27 -9
  53. package/dist/dom/fontCanvas.js.map +1 -1
  54. package/dist/dom/layoutSignature.js +150 -48
  55. package/dist/dom/layoutSignature.js.map +1 -1
  56. package/dist/dom/pretextLayout.js +55 -13
  57. package/dist/dom/pretextLayout.js.map +1 -1
  58. package/dist/dom/snapshot.js +369 -204
  59. package/dist/dom/snapshot.js.map +1 -1
  60. package/dist/dom/svgCapture.d.ts +8 -1
  61. package/dist/dom/svgCapture.js +75 -1
  62. package/dist/dom/svgCapture.js.map +1 -1
  63. package/dist/dom/tone.js +76 -36
  64. package/dist/dom/tone.js.map +1 -1
  65. package/dist/index.js +4 -3
  66. package/dist/slug/SlugMaterial.d.ts +11 -3
  67. package/dist/slug/SlugMaterial.js +54 -10
  68. package/dist/slug/SlugMaterial.js.map +1 -1
  69. package/dist/slug/coverage.d.ts +16 -12
  70. package/dist/slug/coverage.js +194 -221
  71. package/dist/slug/coverage.js.map +1 -1
  72. package/dist/slug/preprocessCore.d.ts +5 -1
  73. package/dist/slug/preprocessCore.js +118 -87
  74. package/dist/slug/preprocessCore.js.map +1 -1
  75. package/dist/slug/runtime.d.ts +1 -0
  76. package/dist/slug/runtime.js +90 -44
  77. package/dist/slug/runtime.js.map +1 -1
  78. package/dist/slug/standaloneRuntime.d.ts +3 -2
  79. package/dist/slug/standaloneRuntime.js +75 -40
  80. package/dist/slug/standaloneRuntime.js.map +1 -1
  81. package/dist/slug/truetype.js +166 -193
  82. package/dist/slug/truetype.js.map +1 -1
  83. package/dist/slug/vanillaCore.d.ts +340 -0
  84. package/dist/slug/vanillaCore.js +1621 -0
  85. package/dist/slug/vanillaCore.js.map +1 -0
  86. package/dist/slug-vanilla.d.ts +13 -364
  87. package/dist/slug-vanilla.js +5 -1453
  88. package/dist/slug.d.ts +1 -1
  89. package/dist/slug.js +6 -6
  90. package/dist/text/GlyphTextMaterial.d.ts +1 -1
  91. package/dist/text/GlyphTextMaterial.js +5 -5
  92. package/dist/text/GlyphTextMaterial.js.map +1 -1
  93. package/dist/text/SdfTextMaterial.js +7 -5
  94. package/dist/text/SdfTextMaterial.js.map +1 -1
  95. package/dist/text/decorations.js +36 -19
  96. package/dist/text/decorations.js.map +1 -1
  97. package/dist/text/geometry.d.ts +3 -22
  98. package/dist/text/geometryUtils.d.ts +11 -1
  99. package/dist/text/geometryUtils.js +22 -1
  100. package/dist/text/geometryUtils.js.map +1 -1
  101. package/dist/text/glyphGeometry.d.ts +9 -0
  102. package/dist/text/glyphGeometry.js +353 -0
  103. package/dist/text/glyphGeometry.js.map +1 -0
  104. package/dist/text/index.d.ts +2 -1
  105. package/dist/text/rectGeometry.d.ts +13 -0
  106. package/dist/text/rectGeometry.js +97 -0
  107. package/dist/text/rectGeometry.js.map +1 -0
  108. package/dist/text/reflow.d.ts +18 -1
  109. package/dist/text/reflow.js +108 -38
  110. package/dist/text/reflow.js.map +1 -1
  111. package/dist/text/snap.d.ts +1 -0
  112. package/dist/text/snap.js +26 -0
  113. package/dist/text/snap.js.map +1 -0
  114. package/dist/vanilla.d.ts +13 -363
  115. package/dist/vanilla.js +6 -1473
  116. package/dist/windfoil/geometry.d.ts +2 -2
  117. package/dist/windfoil/geometry.js +113 -40
  118. package/dist/windfoil/geometry.js.map +1 -1
  119. package/dist/windfoil/mixed.d.ts +1 -0
  120. package/dist/windfoil/mixed.js +44 -25
  121. package/dist/windfoil/mixed.js.map +1 -1
  122. package/dist/windfoil/preprocess.js +2 -2
  123. package/dist/windfoil/preprocessCore.d.ts +1 -0
  124. package/dist/windfoil/preprocessCore.js +9 -4
  125. package/dist/windfoil/preprocessCore.js.map +1 -1
  126. package/dist/windfoil/runtime.d.ts +3 -1
  127. package/dist/windfoil/runtime.js +62 -40
  128. package/dist/windfoil/runtime.js.map +1 -1
  129. package/dist/windfoil/storage.d.ts +60 -2
  130. package/dist/windfoil/storage.js +142 -6
  131. package/dist/windfoil/storage.js.map +1 -1
  132. package/dist/windfoil/trace/contours.d.ts +5 -0
  133. package/dist/windfoil/trace/contours.js +167 -43
  134. package/dist/windfoil/trace/contours.js.map +1 -1
  135. package/dist/windfoil/trace/fit.d.ts +3 -1
  136. package/dist/windfoil/trace/fit.js +471 -175
  137. package/dist/windfoil/trace/fit.js.map +1 -1
  138. package/dist/windfoil/trace/outline.js +55 -30
  139. package/dist/windfoil/trace/outline.js.map +1 -1
  140. package/dist/windfoil/trace/types.d.ts +10 -0
  141. package/dist/windfoil/tracedOutlines.js +59 -34
  142. package/dist/windfoil/tracedOutlines.js.map +1 -1
  143. package/package.json +11 -11
  144. package/skills/ultra-text/references/three-tsl.md +2 -2
  145. package/skills/ultra-text/references/vanilla-webgpu.md +3 -2
  146. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +0 -1
  147. package/dist/slug-vanilla.js.map +0 -1
  148. package/dist/text/geometry.js +0 -348
  149. package/dist/text/geometry.js.map +0 -1
  150. package/dist/vanilla.js.map +0 -1
@@ -17,7 +17,7 @@ function align4(value) {
17
17
  }
18
18
  /** @internal Measures one text glyph's slot; `appendAtlas.ts` shares it with the cold build. */
19
19
  function measureGlyph(context, request, padding, shaping, candidate = false, lastFont = null) {
20
- const nextFont = setFontContext(context, request, shaping, lastFont);
20
+ setFontContext(context, request, shaping, lastFont);
21
21
  const metrics = context.measureText(request.character);
22
22
  const slice = request.shaping?.slice;
23
23
  const from = slice?.[0] ?? 0;
@@ -39,7 +39,7 @@ function measureGlyph(context, request, padding, shaping, candidate = false, las
39
39
  metrics.actualBoundingBoxRight,
40
40
  metrics.actualBoundingBoxAscent
41
41
  ];
42
- return [{
42
+ return {
43
43
  request,
44
44
  width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),
45
45
  height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),
@@ -52,8 +52,9 @@ function measureGlyph(context, request, padding, shaping, candidate = false, las
52
52
  drawOffsetX,
53
53
  ...ink?.every(Number.isFinite) ? { ink } : {},
54
54
  x: 0,
55
- y: 0
56
- }, nextFont];
55
+ y: 0,
56
+ flags: 0
57
+ };
57
58
  }
58
59
  /**
59
60
  * @internal The slot of a glyph drawn at (glyph.x, glyph.y) of a `width`×`height` atlas. The
@@ -67,31 +68,41 @@ function slotOf(glyph, padding, bakeSize, width, height, banded, uncoloured) {
67
68
  const planeY0 = glyph.planeY0 + .5;
68
69
  const planeX1 = glyph.planeX1 - (slice && slice[1] < 1 ? glyph.planeX1 - glyph.advance : .5);
69
70
  const planeY1 = glyph.planeY1 - .5;
70
- const uv = (x0, y0, x1, y1) => ({
71
- u0: (glyph.x + 1 + x0 - glyph.planeX0) / width,
72
- v0: (glyph.y + 1 + glyph.planeY1 - y1) / height,
73
- u1: (glyph.x + 1 + x1 - glyph.planeX0) / width,
74
- v1: (glyph.y + 1 + glyph.planeY1 - y0) / height
75
- });
71
+ const baseU = glyph.x + 1 - glyph.planeX0;
72
+ const baseV = glyph.y + 1 + glyph.planeY1;
73
+ const invW = 1 / width;
74
+ const invH = 1 / height;
76
75
  const ink = banded ? void 0 : glyph.ink;
77
- const reach = padding / 2 + 2 + .006 * bakeSize;
78
- const sx0 = ink ? Math.max(planeX0, Math.floor(ink[0] - reach)) : 0;
79
- const sy0 = ink ? Math.max(planeY0, Math.floor(ink[1] - reach)) : 0;
80
- const sx1 = ink ? Math.min(planeX1, Math.ceil(ink[2] + reach)) : 0;
81
- const sy1 = ink ? Math.min(planeY1, Math.ceil(ink[3] + reach)) : 0;
76
+ let support;
77
+ if (ink) {
78
+ const reach = padding / 2 + 2 + .006 * bakeSize;
79
+ const sx0 = Math.max(planeX0, Math.floor(ink[0] - reach));
80
+ const sy0 = Math.max(planeY0, Math.floor(ink[1] - reach));
81
+ const sx1 = Math.min(planeX1, Math.ceil(ink[2] + reach));
82
+ const sy1 = Math.min(planeY1, Math.ceil(ink[3] + reach));
83
+ if (sx1 > sx0 && sy1 > sy0) support = {
84
+ u0: (baseU + sx0) * invW,
85
+ v0: (baseV - sy1) * invH,
86
+ u1: (baseU + sx1) * invW,
87
+ v1: (baseV - sy0) * invH
88
+ };
89
+ }
82
90
  return {
83
91
  ...uncoloured ? { color: false } : {},
84
92
  key: glyph.request.key,
85
93
  character: glyph.request.character,
86
94
  fontKey: glyph.request.font.key,
87
- ...uv(planeX0, planeY0, planeX1, planeY1),
95
+ u0: (baseU + planeX0) * invW,
96
+ v0: (baseV - planeY1) * invH,
97
+ u1: (baseU + planeX1) * invW,
98
+ v1: (baseV - planeY0) * invH,
88
99
  planeX0,
89
100
  planeY0,
90
101
  planeX1,
91
102
  planeY1,
92
103
  descent: glyph.descent,
93
104
  advance: glyph.advance,
94
- ...ink && sx1 > sx0 && sy1 > sy0 ? { support: uv(sx0, sy0, sx1, sy1) } : {}
105
+ ...support ? { support } : {}
95
106
  };
96
107
  }
97
108
  /**
@@ -183,6 +194,15 @@ function packShelves(glyphs, width, maxSize) {
183
194
  var skylineX = /* @__PURE__ */ new Int32Array(256);
184
195
  var skylineY = /* @__PURE__ */ new Int32Array(256);
185
196
  var skylineW = /* @__PURE__ */ new Int32Array(256);
197
+ function shiftSkyline(to, from, len) {
198
+ skylineX.copyWithin(to, from, len);
199
+ skylineY.copyWithin(to, from, len);
200
+ skylineW.copyWithin(to, from, len);
201
+ }
202
+ function recordSkylineOverflow(width, maxSize, wasteBudget) {
203
+ lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize));
204
+ return null;
205
+ }
186
206
  /** Bottom-left skyline packing fills the vertical gaps that fixed-height shelves leave behind. */
187
207
  function packSkyline(glyphs, width, maxSize) {
188
208
  const needed = glyphs.length + 2;
@@ -200,16 +220,10 @@ function packSkyline(glyphs, width, maxSize) {
200
220
  let skylineLen = 1;
201
221
  let usedWidth = 0;
202
222
  let usedHeight = 0;
203
- const shift = (to, from) => {
204
- sx.copyWithin(to, from, skylineLen);
205
- sy.copyWithin(to, from, skylineLen);
206
- sw.copyWithin(to, from, skylineLen);
207
- };
208
223
  const minH = glyphs[glyphs.length - 1].height;
209
224
  let wasteBudget = width * maxSize;
210
- const over = () => (lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize)), null);
211
225
  for (const g of glyphs) wasteBudget -= g.width * g.height;
212
- if (wasteBudget < 0) return over();
226
+ if (wasteBudget < 0) return recordSkylineOverflow(width, maxSize, wasteBudget);
213
227
  for (const glyph of glyphs) {
214
228
  const gw = glyph.width;
215
229
  const gh = glyph.height;
@@ -257,7 +271,7 @@ function packSkyline(glyphs, width, maxSize) {
257
271
  }
258
272
  }
259
273
  if (maxAllowedY >= 0 && usedWidth + gw < lastOverflowWidth) lastOverflowWidth = usedWidth + gw;
260
- if (bestIndex < 0 || (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) < 0) return bestIndex < 0 ? null : over();
274
+ if (bestIndex < 0 || (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) < 0) return bestIndex < 0 ? null : recordSkylineOverflow(width, maxSize, wasteBudget);
261
275
  const gx = sx[bestIndex];
262
276
  const right = gx + gw;
263
277
  glyph.x = gx;
@@ -282,7 +296,7 @@ function packSkyline(glyphs, width, maxSize) {
282
296
  newCount = 0;
283
297
  }
284
298
  const delta = newCount - (cursor - bestIndex);
285
- if (delta !== 0 && cursor < skylineLen) shift(cursor + delta, cursor);
299
+ if (delta !== 0 && cursor < skylineLen) shiftSkyline(cursor + delta, cursor, skylineLen);
286
300
  skylineLen += delta;
287
301
  if (newCount) {
288
302
  sx[bestIndex] = gx;
@@ -348,28 +362,30 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
348
362
  const shaping = shapingModule?.setShapingContext;
349
363
  throwIfAborted(options.signal);
350
364
  const canvas = createCanvas(document);
365
+ let returned = false;
351
366
  try {
352
367
  const previous = options.previousAtlas?.bakeSize === bakeSize && options.previousAtlas.pxRange === padding ? options.previousAtlas.glyphs : void 0;
353
- const context = canvas.getContext("2d", { willReadFrequently: !options.gpuUpload || requests.some((request) => isColorCandidate(request, options.colorGlyphs) && (request.shape !== void 0 || (options.colorGlyphs === "all" || isEmojiGrapheme(request.character)) && previous?.get(request.key)?.color !== false)) });
368
+ const willReadFrequently = !options.gpuUpload || requests.some((request) => isColorCandidate(request, options.colorGlyphs) && (request.shape !== void 0 || (options.colorGlyphs === "all" || isEmojiGrapheme(request.character)) && previous?.get(request.key)?.color !== false));
369
+ const context = canvas.getContext("2d", { willReadFrequently });
354
370
  if (!context) throw new Error("rasterizeGlyphAtlas: Canvas 2D is unavailable");
355
371
  const packingLimit = maxAtlasSize - maxAtlasSize % 4;
356
372
  let lastFont = null;
357
373
  const measured = requests.map((request) => {
358
374
  if (request.shape) return shapes.measureShape(request, bakeSize, padding);
359
- const [glyph, nextFont] = measureGlyph(context, request, padding, shaping, isColorCandidate(request, options.colorGlyphs), lastFont);
360
- lastFont = nextFont;
375
+ const glyph = measureGlyph(context, request, padding, shaping, isColorCandidate(request, options.colorGlyphs), lastFont);
376
+ lastFont = request.font;
361
377
  return glyph;
362
378
  });
363
379
  measured.sort((a, b) => b.height - a.height || b.width - a.width || (a.request.key < b.request.key ? -1 : a.request.key > b.request.key ? 1 : 0));
364
- const banded = /* @__PURE__ */ new Set();
365
- const uncoloured = /* @__PURE__ */ new Set();
380
+ let bandedCount = 0;
366
381
  const tested = [];
367
382
  for (const glyph of measured) {
368
383
  if (!isColorCandidate(glyph.request, options.colorGlyphs)) continue;
369
384
  const known = glyph.request.shape ? void 0 : previous?.get(glyph.request.key)?.color;
370
- if (known === false) uncoloured.add(glyph);
385
+ if (known === false) glyph.flags = 2;
371
386
  else {
372
- banded.add(glyph);
387
+ glyph.flags = 1;
388
+ bandedCount++;
373
389
  if (!glyph.request.shape && known === void 0) tested.push(glyph);
374
390
  }
375
391
  }
@@ -377,27 +393,39 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
377
393
  shapes.drawShapeSlot(context, glyph, bakeSize);
378
394
  });
379
395
  const drawGlyph = (glyph, fill) => {
380
- painter.draw(glyph, !glyph.request.shape && !banded.has(glyph), fill);
396
+ painter.draw(glyph, !glyph.request.shape && (glyph.flags & 1) === 0, fill);
381
397
  };
382
- const colorGlyphs = banded.size ? await import("./colorGlyphs.js") : void 0;
398
+ const colorGlyphs = bandedCount ? await import("./colorGlyphs.js") : void 0;
383
399
  throwIfAborted(options.signal);
384
400
  const scratch = tested.length ? packShelves(tested, packingLimit, packingLimit) : null;
385
401
  if (scratch) {
386
- canvas.width = scratch.width;
387
- canvas.height = scratch.height;
388
- painter.reset();
389
- const paint = (fill) => {
390
- context.clearRect(0, 0, canvas.width, canvas.height);
391
- for (const glyph of tested) drawGlyph(glyph, fill);
392
- return context.getImageData(0, 0, canvas.width, canvas.height).data;
393
- };
394
- const dark = paint("#000");
395
- const { colored } = colorGlyphs.encodeColorBand(paint("#fff"), dark, canvas.width, canvas.height, 0, tested);
396
- tested.forEach((glyph, index) => {
397
- if (colored[index]) return;
398
- banded.delete(glyph);
399
- uncoloured.add(glyph);
400
- });
402
+ const scratchCanvas = willReadFrequently ? null : createCanvas(document);
403
+ try {
404
+ const targetCanvas = scratchCanvas ?? canvas;
405
+ targetCanvas.width = scratch.width;
406
+ targetCanvas.height = scratch.height;
407
+ const targetContext = scratchCanvas ? scratchCanvas.getContext("2d", { willReadFrequently: true }) : context;
408
+ if (!targetContext) throw new Error("rasterizeGlyphAtlas: Canvas 2D is unavailable");
409
+ const targetPainter = scratchCanvas ? glyphPainter(targetContext, shaping, options.signal) : painter;
410
+ targetPainter.reset();
411
+ const paint = (fill) => {
412
+ targetContext.clearRect(0, 0, scratch.width, scratch.height);
413
+ for (const glyph of tested) targetPainter.draw(glyph, false, fill);
414
+ return targetContext.getImageData(0, 0, scratch.width, scratch.height).data;
415
+ };
416
+ const dark = paint("#000");
417
+ const { colored } = colorGlyphs.encodeColorBand(paint("#fff"), dark, scratch.width, scratch.height, 0, tested);
418
+ tested.forEach((glyph, index) => {
419
+ if (colored[index]) return;
420
+ glyph.flags = 2;
421
+ });
422
+ } finally {
423
+ if (scratchCanvas) {
424
+ scratchCanvas.width = 0;
425
+ scratchCanvas.height = 0;
426
+ scratchCanvas.remove();
427
+ }
428
+ }
401
429
  }
402
430
  const textRows = [];
403
431
  const shapeRows = [];
@@ -409,7 +437,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
409
437
  totalArea += glyph.width * glyph.height;
410
438
  if (glyph.width > widestGlyph) widestGlyph = glyph.width;
411
439
  if (glyph.width > packingLimit || glyph.height > packingLimit) exceedsLimit = true;
412
- if (banded.has(glyph)) band.push(glyph);
440
+ if (glyph.flags & 1) band.push(glyph);
413
441
  else if (glyph.request.shape) shapeRows.push(glyph);
414
442
  else textRows.push(glyph);
415
443
  }
@@ -431,14 +459,14 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
431
459
  if (!impossible && measured.length > 0) {
432
460
  const minRequiredLimit = groups.reduce((sum, g) => sum + align4(g[0].height), 0);
433
461
  const minimumWidth = Math.min(packingLimit, align4(Math.max(widestGlyph, Math.ceil(totalArea / packingLimit))));
434
- const widthStep = align4(Math.max(4, Math.ceil((packingLimit - minimumWidth) / 64)));
462
+ const packerCount = groups.some((g) => g[0].height !== g[g.length - 1].height) ? 2 : 1;
435
463
  const maxHeightFor = (width) => best ? Math.min(packingLimit, Math.floor(best.width * best.height / width)) : packingLimit;
436
464
  const nextW = [minimumWidth, minimumWidth];
437
- for (let width = minimumWidth;; width = Math.min(packingLimit, width + widthStep)) {
465
+ for (let width = minimumWidth; width <= packingLimit; width += 4) {
438
466
  throwIfAborted(options.signal);
439
467
  if (maxHeightFor(width) < minRequiredLimit) break;
440
468
  const minH = align4(Math.max(minRequiredLimit, Math.ceil(totalArea / width)));
441
- for (let i = 0; i < 2; i++) {
469
+ for (let i = 0; i < packerCount; i++) {
442
470
  if (width < nextW[i]) continue;
443
471
  const maxCandidateHeight = maxHeightFor(width);
444
472
  if (minH > maxCandidateHeight) break;
@@ -447,7 +475,6 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
447
475
  nextW[i] = lastOverflowWidth;
448
476
  if (candidate && (!best || isBetterPacking(candidate, best))) best = rememberPacking(measured, candidate, bestPositions);
449
477
  }
450
- if (width === packingLimit) break;
451
478
  }
452
479
  }
453
480
  if (!best) {
@@ -485,7 +512,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
485
512
  canvas.width = best.width;
486
513
  canvas.height = best.height;
487
514
  painter.reset();
488
- if (scratch) context.clearRect(0, 0, canvas.width, canvas.height);
515
+ if (scratch && willReadFrequently) context.clearRect(0, 0, canvas.width, canvas.height);
489
516
  const bandTop = band.length ? topOf(band) : 0;
490
517
  const bandHeight = canvas.height - bandTop;
491
518
  let black;
@@ -495,10 +522,23 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
495
522
  context.clearRect(0, bandTop, canvas.width, bandHeight);
496
523
  }
497
524
  const glyphSlots = /* @__PURE__ */ new Map();
525
+ const byFont = /* @__PURE__ */ new Map();
526
+ const shapeGlyphs = [];
498
527
  for (const glyph of measured) {
499
- drawGlyph(glyph);
500
- glyphSlots.set(glyph.request.key, slotOf(glyph, padding, bakeSize, canvas.width, canvas.height, banded.has(glyph), uncoloured.has(glyph)));
528
+ if (glyph.request.shape) {
529
+ shapeGlyphs.push(glyph);
530
+ continue;
531
+ }
532
+ let group = byFont.get(glyph.request.font.key);
533
+ if (!group) byFont.set(glyph.request.font.key, group = []);
534
+ group.push(glyph);
501
535
  }
536
+ const drawAndRecord = (glyph) => {
537
+ drawGlyph(glyph);
538
+ glyphSlots.set(glyph.request.key, slotOf(glyph, padding, bakeSize, canvas.width, canvas.height, (glyph.flags & 1) !== 0, (glyph.flags & 2) !== 0));
539
+ };
540
+ for (const group of byFont.values()) for (const glyph of group) drawAndRecord(glyph);
541
+ for (const glyph of shapeGlyphs) drawAndRecord(glyph);
502
542
  let colorBand;
503
543
  if (black) {
504
544
  const white = context.getImageData(0, bandTop, canvas.width, bandHeight).data;
@@ -544,6 +584,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
544
584
  rowHeight
545
585
  });
546
586
  }
587
+ returned = true;
547
588
  return {
548
589
  ...colorBand ? { colorBand } : {},
549
590
  ...shapeTop !== void 0 ? { shapeTop } : {},
@@ -555,6 +596,10 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
555
596
  glyphs: glyphSlots
556
597
  };
557
598
  } finally {
599
+ if (!returned) {
600
+ canvas.width = 0;
601
+ canvas.height = 0;
602
+ }
558
603
  canvas.remove();
559
604
  }
560
605
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rasterize.js","names":[],"sources":["../../src/atlas/rasterize.ts"],"sourcesContent":["import type {\n ColorGlyphMode,\n GlyphRequest,\n GlyphSlot,\n RasterAtlas,\n RasterColorBand,\n} from '../types.js'\nimport { isEmojiCandidate, isEmojiGrapheme } from '../dom/clusters.js'\nimport {\n createCanvas,\n isColorCandidate,\n setFontContext,\n waitForFonts,\n type ShapingContext,\n} from '../dom/fontCanvas.js'\n\nexport { createCanvas, isColorCandidate, setFontContext, waitForFonts }\n\n/** @internal Shared measured slot used by the lazy shape rasterizer. */\nexport interface MeasuredGlyph {\n readonly request: GlyphRequest\n readonly width: number\n readonly height: number\n readonly planeX0: number\n readonly planeY0: number\n readonly planeX1: number\n readonly planeY1: number\n readonly descent: number\n readonly advance: number\n readonly drawOffsetX: number\n /**\n * The ink box of a text glyph in plane units (x0, y0, x1, y1, y up from the baseline), from\n * the canvas's own metrics; absent where the slot is drawn whole.\n */\n readonly ink?: readonly [number, number, number, number]\n x: number\n y: number\n}\n\n/**\n * @internal The first atlas row of the monochrome shapes, when the raster holds any. They are\n * packed below the text so that a material can tell them from text by their place in the atlas.\n */\nexport interface ShapeRows {\n readonly shapeTop?: number\n}\n\n/**\n * @internal Where later text glyphs fit in an atlas without moving any slot: a shelf cursor\n * over its text rows, which end at `bottom`, the first row of its shapes or colour band (or its\n * height). Every slot that reaches row `y` or below ends left of `x`; below `y + rowHeight`\n * the text rows are free.\n */\nexport interface AppendCursor {\n readonly width: number\n readonly height: number\n readonly bakeSize: number\n readonly pxRange: number\n readonly colorGlyphs: ColorGlyphMode\n readonly bottom: number\n readonly x: number\n readonly y: number\n readonly rowHeight: number\n}\n\n/**\n * @internal The cursors of the rasters built with `appendable`, keyed by their glyph map, which\n * every `SdfAtlas` built from the raster shares. A few numbers each: no canvas is kept.\n */\nexport const appendCursors = new WeakMap<ReadonlyMap<string, GlyphSlot>, AppendCursor>()\n\ninterface PackedGlyphs {\n width: number\n height: number\n}\n\nexport interface RasterizeOptions {\n /** Colour-glyph detection; defaults to 'emoji'. */\n colorGlyphs?: ColorGlyphMode\n /** Canvas font raster size in pixels; must be at least `16`. Defaults to `96`. */\n bakeSize?: number\n /**\n * Retry overflowing atlases at a smaller bake size, down to 16px.\n * Defaults to `false`; fitting atlases keep their requested resolution.\n */\n adaptiveBakeSize?: boolean\n /**\n * Glyph slot padding in texels; must be at least `2`. Defaults to `12`. The\n * padding doubles as the SDF pixel range (`RasterAtlas.pxRange`).\n */\n padding?: number\n /**\n * Maximum atlas dimension in texels; must be an integer of at least `64`.\n * Defaults to `2048`. Glyphs that cannot pack reject instead of dropping. Text, monochrome\n * shapes and colour glyphs take rows of their own, one kind below the other.\n */\n maxAtlasSize?: number\n /** Aborts the rasterization between font waits and glyph draws. */\n signal?: AbortSignal\n /**\n * An atlas built earlier for the same fonts, with this `bakeSize` and `padding`\n * (`pxRange`): a colour candidate whose slot there already carries `GlyphSlot.color` keeps\n * that classification, instead of being drawn twice on a scratch canvas and read back.\n * Bitmap SVG shapes and glyphs it lacks are classified as usual, and every glyph is still\n * measured, packed and drawn: only the classification is reused. Omit it after a webfont\n * swap. `DomSdf` passes its retained atlas when a capture's new glyphs rebuild it in full.\n */\n previousAtlas?: Pick<RasterAtlas, 'glyphs' | 'bakeSize' | 'pxRange'> | undefined\n /**\n * @internal Set by `DomSdf` for its own SDF atlases. The raster then records its\n * `AppendCursor` in `appendCursors`, so that `appendAtlas.ts` can draw later text glyphs\n * into the live texture. `'headroom'` also leaves free text rows for them, within\n * `maxAtlasSize`: a tallest text slot, or a quarter of the text rows when more, between\n * the text and the shapes and colour band, which therefore keep their rows across appends,\n * in an atlas at least two of its widest text glyphs wide. DomSdf asks for it once an\n * instance has gained glyphs; a capture that never gains any stays tight.\n */\n appendable?: boolean | 'headroom' | undefined\n /**\n * @internal Set by `DomSdf` when only a WebGPU atlas uploads the raster. Without colour\n * candidates, which are read back, the bake canvas is then GPU-backed (no\n * `willReadFrequently`): its first draw on a page skips the software canvas's set-up, 7 to\n * 12 ms on an M3 Max, and the atlas copies it on the GPU. Reading such a canvas back takes\n * hundreds of milliseconds, which only the CPU fallback of a failed GPU build pays.\n */\n gpuUpload?: boolean | undefined\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The atlas build was aborted', 'AbortError')\n }\n}\n\nfunction nextPowerOfTwo(value: number): number {\n return 2 ** Math.ceil(Math.log2(Math.max(1, value)))\n}\n\nfunction align4(value: number): number {\n return Math.max(4, Math.ceil(value / 4) * 4)\n}\n\n/** @internal Measures one text glyph's slot; `appendAtlas.ts` shares it with the cold build. */\nexport function measureGlyph(\n context: CanvasRenderingContext2D,\n request: GlyphRequest,\n padding: number,\n shaping: ShapingContext | undefined,\n candidate = false,\n lastFont: GlyphRequest['font'] | null = null,\n): [MeasuredGlyph, GlyphRequest['font']] {\n const nextFont = setFontContext(context, request, shaping, lastFont)\n const metrics = context.measureText(request.character)\n const slice = request.shaping?.slice\n const from = slice?.[0] ?? 0\n const to = slice?.[1] ?? 1\n const advance = metrics.width * (to - from)\n const left = from === 0 ? Math.max(0, metrics.actualBoundingBoxLeft) : 0\n const right = slice\n ? advance + (to === 1 ? Math.max(0, metrics.actualBoundingBoxRight - metrics.width) : 0)\n : Math.max(metrics.width, metrics.actualBoundingBoxRight)\n const ascent = Math.max(1, metrics.fontBoundingBoxAscent || metrics.actualBoundingBoxAscent)\n const descent = Math.max(1, metrics.fontBoundingBoxDescent || metrics.actualBoundingBoxDescent)\n // A canvas draws text on a whole pixel row and, across, on a quarter pixel at best, whatever\n // origin it is given. The slot's origin is therefore a whole pixel: ink left of the origin\n // or taller than the font box was otherwise baked up to half a texel off, and the tiles of\n // a sliced run a quarter texel off each other.\n const drawOffsetX = metrics.width * from\n const planeX0 = -Math.ceil(left + padding - drawOffsetX) - drawOffsetX\n const planeX1 = right + padding\n const inkBounds =\n request.shaping !== undefined || candidate || isEmojiCandidate(request.character)\n const planeY0 = -Math.max(descent, inkBounds ? metrics.actualBoundingBoxDescent : 0) - padding\n const planeY1 = Math.ceil(\n Math.max(ascent, inkBounds ? metrics.actualBoundingBoxAscent : 0) + padding,\n )\n // Only whole, plain text glyphs trim their quads: a tile of a shaped line is clipped to its\n // slice, and colour candidates are bitmaps whose ink the metrics need not bound.\n const ink: MeasuredGlyph['ink'] =\n inkBounds || slice\n ? undefined\n : [\n -metrics.actualBoundingBoxLeft,\n -metrics.actualBoundingBoxDescent,\n metrics.actualBoundingBoxRight,\n metrics.actualBoundingBoxAscent,\n ]\n\n return [\n {\n request,\n width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),\n height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent,\n advance,\n drawOffsetX,\n ...(ink?.every(Number.isFinite) ? { ink } : {}),\n x: 0,\n y: 0,\n },\n nextFont,\n ]\n}\n\n/**\n * @internal The slot of a glyph drawn at (glyph.x, glyph.y) of a `width`×`height` atlas. The\n * full build and an append patch both take their slots from here, so they cannot drift apart.\n * A `banded` glyph is a colour candidate in the band; an `uncoloured` one a candidate that\n * classified as text.\n */\nexport function slotOf(\n glyph: MeasuredGlyph,\n padding: number,\n bakeSize: number,\n width: number,\n height: number,\n banded: boolean,\n uncoloured: boolean,\n): GlyphSlot {\n // The sampled window must follow the drawn plane box, not the shelf slot:\n // the slot is `ceil(extent) + 2` texels wide and the glyph origin above is\n // offset by one, so the plane spans texels 1 .. 1 + extent. Both bounds move\n // inward by half a texel so bilinear filtering cannot reach a neighbour.\n const slice = glyph.request.shaping?.slice\n const planeX0 = glyph.planeX0 + (slice && slice[0] > 0 ? -glyph.planeX0 : 0.5)\n const planeY0 = glyph.planeY0 + 0.5\n const planeX1 = glyph.planeX1 - (slice && slice[1] < 1 ? glyph.planeX1 - glyph.advance : 0.5)\n const planeY1 = glyph.planeY1 - 0.5\n const uv = (x0: number, y0: number, x1: number, y1: number) => ({\n u0: (glyph.x + 1 + x0 - glyph.planeX0) / width,\n v0: (glyph.y + 1 + glyph.planeY1 - y1) / height,\n u1: (glyph.x + 1 + x1 - glyph.planeX0) / width,\n v1: (glyph.y + 1 + glyph.planeY1 - y0) / height,\n })\n const ink = banded ? undefined : glyph.ink\n const reach = padding / 2 + 2 + 0.006 * bakeSize\n const sx0 = ink ? Math.max(planeX0, Math.floor(ink[0] - reach)) : 0\n const sy0 = ink ? Math.max(planeY0, Math.floor(ink[1] - reach)) : 0\n const sx1 = ink ? Math.min(planeX1, Math.ceil(ink[2] + reach)) : 0\n const sy1 = ink ? Math.min(planeY1, Math.ceil(ink[3] + reach)) : 0\n return {\n ...(uncoloured ? { color: false } : {}),\n key: glyph.request.key,\n character: glyph.request.character,\n fontKey: glyph.request.font.key,\n ...uv(planeX0, planeY0, planeX1, planeY1),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent: glyph.descent,\n advance: glyph.advance,\n ...(ink && sx1 > sx0 && sy1 > sy0 ? { support: uv(sx0, sy0, sx1, sy1) } : {}),\n }\n}\n\n/**\n * @internal Draws glyphs into their slots of one canvas, by the rules of the full build and of\n * an append patch alike. `reset()` forgets the context state cached here: call it whenever\n * the canvas is resized, which resets that state.\n */\nexport function glyphPainter(\n context: CanvasRenderingContext2D,\n shaping: ShapingContext | undefined,\n signal: AbortSignal | undefined,\n drawShape?: (glyph: MeasuredGlyph) => void,\n): { draw(glyph: MeasuredGlyph, text: boolean, fill?: string): void; reset(): void } {\n // A text mask must be the outline itself on every platform. The bake canvas has font\n // smoothing off; where the engine has the property, text also asks for exact geometry,\n // and it takes a mid grey fill, the neutral middle of a rasterizer's contrast table.\n // Colour glyphs keep the default rendering and the fills their classification compares;\n // shapes are paths, which none of this affects.\n const exactText = 'textRendering' in context\n let lastFont: GlyphRequest['font'] | null = null\n let lastFill = ''\n let lastTextRendering = ''\n return {\n reset() {\n lastFont = null\n lastFill = ''\n lastTextRendering = ''\n },\n draw(glyph, text, fill = '#fff') {\n throwIfAborted(signal)\n const targetFill = text ? '#606060' : fill\n if (lastFill !== targetFill) {\n context.fillStyle = targetFill\n lastFill = targetFill\n }\n if (glyph.request.shape) {\n drawShape!(glyph)\n lastFill = ''\n return\n }\n lastFont = setFontContext(context, glyph.request, shaping, lastFont)\n if (exactText) {\n const targetRendering = text ? 'geometricPrecision' : 'auto'\n if (lastTextRendering !== targetRendering) {\n context.textRendering = targetRendering\n lastTextRendering = targetRendering\n }\n }\n const originX = glyph.x - glyph.planeX0 + 1\n const baselineY = glyph.y + glyph.planeY1 + 1\n if (glyph.request.shaping?.slice) {\n context.save()\n context.beginPath()\n context.rect(\n glyph.x + 1,\n glyph.y + 1,\n glyph.planeX1 - glyph.planeX0,\n glyph.planeY1 - glyph.planeY0,\n )\n context.clip()\n context.fillText(glyph.request.character, originX - glyph.drawOffsetX, baselineY)\n context.restore()\n } else context.fillText(glyph.request.character, originX, baselineY)\n },\n }\n}\n\n/** The first row of a non-empty run of packed glyphs. */\nfunction topOf(rows: readonly MeasuredGlyph[]): number {\n return rows.reduce((top, glyph) => (glyph.y < top ? glyph.y : top), rows[0]!.y)\n}\n\nlet lastOverflowWidth = Infinity\n\n/** @internal Row-major shelf packing; also lays out the colour candidates of an append. */\nexport function packShelves(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n let x = 0\n let y = 0\n let rowHeight = 0\n let usedWidth = 0\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gw > width) {\n if (gw < lastOverflowWidth) lastOverflowWidth = gw\n return null\n }\n if (gh > maxSize) return null\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (y + gh > maxSize) return null\n glyph.x = x\n glyph.y = y\n x += gw\n if (gh > rowHeight) rowHeight = gh\n if (x > usedWidth) usedWidth = x\n }\n\n return {\n width: align4(usedWidth),\n height: align4(y + rowHeight),\n }\n}\n\nlet skylineX = new Int32Array(256)\nlet skylineY = new Int32Array(256)\nlet skylineW = new Int32Array(256)\n\n/** Bottom-left skyline packing fills the vertical gaps that fixed-height shelves leave behind. */\nfunction packSkyline(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n const needed = glyphs.length + 2\n if (skylineX.length < needed) {\n skylineX = new Int32Array(needed)\n skylineY = new Int32Array(needed)\n skylineW = new Int32Array(needed)\n }\n const sx = skylineX\n const sy = skylineY\n const sw = skylineW\n sx[0] = 0\n sy[0] = 0\n sw[0] = width\n let skylineLen = 1\n let usedWidth = 0\n let usedHeight = 0\n const shift = (to: number, from: number): void => {\n sx.copyWithin(to, from, skylineLen)\n sy.copyWithin(to, from, skylineLen)\n sw.copyWithin(to, from, skylineLen)\n }\n\n const minH = glyphs[glyphs.length - 1]!.height\n let wasteBudget = width * maxSize\n const over = (): null => (\n (lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize))),\n null\n )\n for (const g of glyphs) wasteBudget -= g.width * g.height\n if (wasteBudget < 0) return over()\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gh > maxSize) return null\n let bestIndex = -1\n let bestBottom = Infinity\n let bestWaste = Infinity\n const tail = skylineLen - 1\n let maxAllowedY = sw[tail]! >= gw && sy[tail]! < maxSize - gh ? sy[tail]! : maxSize - gh\n\n for (let index = 0; index < skylineLen; index++) {\n const firstY = sy[index]!\n if (firstY > maxAllowedY) continue\n const x = sx[index]!\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n break\n }\n\n let remaining = gw - sw[index]!\n let y = firstY\n let waste = 0\n if (remaining > 0) {\n let coveredArea = sw[index]! * firstY\n for (let cursor = index + 1; ; cursor++) {\n const nodeY = sy[cursor]!\n if (nodeY > maxAllowedY) {\n index = cursor\n remaining = 1\n break\n }\n if (nodeY > y) y = nodeY\n const nodeW = sw[cursor]!\n coveredArea += (remaining < nodeW ? remaining : nodeW) * nodeY\n if ((remaining -= nodeW) <= 0) break\n }\n if (remaining > 0) continue\n waste = y * gw - coveredArea\n }\n const bottom = y + gh\n if (bottom < bestBottom || waste < bestWaste) {\n bestIndex = index\n bestBottom = bottom\n bestWaste = waste\n maxAllowedY = waste === 0 ? y - 1 : y\n if (maxAllowedY < 0) break\n }\n }\n if (maxAllowedY >= 0 && usedWidth + gw < lastOverflowWidth) lastOverflowWidth = usedWidth + gw\n\n if (\n bestIndex < 0 ||\n (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) <\n 0\n )\n return bestIndex < 0 ? null : over()\n const gx = sx[bestIndex]!\n const right = gx + gw\n glyph.x = gx\n glyph.y = bestBottom - gh\n let cursor = bestIndex\n while (cursor < skylineLen && sx[cursor]! + sw[cursor]! <= right) cursor++\n if (cursor < skylineLen && sx[cursor]! < right) {\n sw[cursor] = sx[cursor]! + sw[cursor]! - right\n sx[cursor] = right\n }\n let newCount = 1\n if (bestIndex > 0 && sy[bestIndex - 1] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + gw\n newCount = 0\n if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + sw[cursor]!\n cursor++\n }\n } else if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sx[cursor] = gx\n sw[cursor] = sw[cursor]! + gw\n newCount = 0\n }\n const delta = newCount - (cursor - bestIndex)\n if (delta !== 0 && cursor < skylineLen) shift(cursor + delta, cursor)\n skylineLen += delta\n if (newCount) {\n sx[bestIndex] = gx\n sy[bestIndex] = bestBottom\n sw[bestIndex] = gw\n }\n\n if (right > usedWidth) usedWidth = right\n if (bestBottom > usedHeight) usedHeight = bestBottom\n }\n\n return { width: align4(usedWidth), height: align4(usedHeight) }\n}\n\n/** Packs each group into rows of its own, one group below the other. */\nfunction packStacked(\n groups: readonly MeasuredGlyph[][],\n width: number,\n limit: number,\n pack: typeof packShelves,\n): { width: number; height: number } | null {\n let packedWidth = 0\n let height = 0\n for (const group of groups) {\n const packed = pack(group, width, limit - height)\n if (!packed || height + packed.height > limit) return null\n for (const glyph of group) glyph.y += height\n packedWidth = Math.max(packedWidth, packed.width)\n height += packed.height\n }\n return { width: packedWidth, height }\n}\n\nfunction rememberPacking(\n glyphs: readonly MeasuredGlyph[],\n size: { width: number; height: number },\n positions: Int32Array,\n): PackedGlyphs {\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n positions[index * 2] = glyph.x\n positions[index * 2 + 1] = glyph.y\n }\n return { width: size.width, height: size.height }\n}\n\nfunction isBetterPacking(\n candidate: Pick<PackedGlyphs, 'width' | 'height'>,\n current: PackedGlyphs,\n): boolean {\n return (\n (candidate.width * candidate.height - current.width * current.height ||\n Math.max(candidate.width, candidate.height) - Math.max(current.width, current.height) ||\n candidate.width - current.width) < 0\n )\n}\n\n/**\n * Rasterizes every required font-face/character or emoji-sequence pair into one tightly packed\n * alpha atlas. The output is a transient mask; the retained texture is a\n * single-channel distance field produced by the CPU or WebGPU compute backend.\n */\nexport async function rasterizeGlyphAtlas(\n document: Document,\n requests: readonly GlyphRequest[],\n options: RasterizeOptions = {},\n): Promise<RasterAtlas> {\n const bakeSize = options.bakeSize ?? 96\n const padding = options.padding ?? 12\n const maxAtlasSize = options.maxAtlasSize ?? 2048\n if (!Number.isFinite(bakeSize) || bakeSize < 16) {\n throw new RangeError('rasterizeGlyphAtlas: bakeSize must be at least 16')\n }\n if (!Number.isFinite(padding) || padding < 2) {\n throw new RangeError('rasterizeGlyphAtlas: padding must be at least 2')\n }\n if (!Number.isInteger(maxAtlasSize) || maxAtlasSize < 64) {\n throw new RangeError('rasterizeGlyphAtlas: maxAtlasSize must be an integer of at least 64')\n }\n\n throwIfAborted(options.signal)\n const [, shapingModule, shapes] = await Promise.all([\n waitForFonts(document, requests, options.signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n requests.some((request) => request.shape) ? import('./shapeRaster.js') : undefined,\n ])\n const shaping = shapingModule?.setShapingContext\n throwIfAborted(options.signal)\n\n const canvas = createCanvas(document)\n try {\n // A glyph a matching previous atlas has classified keeps its classification. A bitmap\n // shape always keeps its place in the band, as on a cold build: never history-dependent.\n const previous =\n options.previousAtlas?.bakeSize === bakeSize && options.previousAtlas.pxRange === padding\n ? options.previousAtlas.glyphs\n : undefined\n const context = canvas.getContext('2d', {\n willReadFrequently:\n !options.gpuUpload ||\n requests.some(\n (request) =>\n isColorCandidate(request, options.colorGlyphs) &&\n (request.shape !== undefined ||\n ((options.colorGlyphs === 'all' || isEmojiGrapheme(request.character)) &&\n previous?.get(request.key)?.color !== false)),\n ),\n })\n if (!context) throw new Error('rasterizeGlyphAtlas: Canvas 2D is unavailable')\n\n const packingLimit = maxAtlasSize - (maxAtlasSize % 4)\n let lastFont: GlyphRequest['font'] | null = null\n const measured = requests.map((request) => {\n if (request.shape) return shapes!.measureShape(request, bakeSize, padding)\n const [glyph, nextFont] = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, options.colorGlyphs),\n lastFont,\n )\n lastFont = nextFont\n return glyph\n })\n measured.sort(\n (a, b) =>\n b.height - a.height ||\n b.width - a.width ||\n (a.request.key < b.request.key ? -1 : a.request.key > b.request.key ? 1 : 0),\n )\n\n const banded = new Set<MeasuredGlyph>()\n const uncoloured = new Set<MeasuredGlyph>()\n const tested: MeasuredGlyph[] = []\n for (const glyph of measured) {\n if (!isColorCandidate(glyph.request, options.colorGlyphs)) continue\n const known = glyph.request.shape ? undefined : previous?.get(glyph.request.key)?.color\n if (known === false) uncoloured.add(glyph)\n else {\n banded.add(glyph)\n if (!glyph.request.shape && known === undefined) tested.push(glyph)\n }\n }\n const painter = glyphPainter(context, shaping, options.signal, (glyph) => {\n shapes!.drawShapeSlot(context, glyph, bakeSize)\n })\n const drawGlyph = (glyph: MeasuredGlyph, fill?: string): void => {\n painter.draw(glyph, !glyph.request.shape && !banded.has(glyph), fill)\n }\n\n // A candidate the font draws in the fill colour alone is text, whatever Unicode lists it\n // as: a copyright sign, an arrow, the tiles of a shaped line beside the one that holds\n // its emoji. Each font candidate is drawn in black and in white on a pack of their own,\n // and only one with ink that ignores the fill keeps its place in the band; the others are\n // baked, packed and flagged with the text.\n const colorGlyphs = banded.size ? await import('./colorGlyphs.js') : undefined\n throwIfAborted(options.signal)\n const scratch = tested.length ? packShelves(tested, packingLimit, packingLimit) : null\n if (scratch) {\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n context.clearRect(0, 0, canvas.width, canvas.height)\n for (const glyph of tested) drawGlyph(glyph, fill)\n return context.getImageData(0, 0, canvas.width, canvas.height).data\n }\n const dark = paint('#000')\n const { colored } = colorGlyphs!.encodeColorBand(\n paint('#fff'),\n dark,\n canvas.width,\n canvas.height,\n 0,\n tested,\n )\n tested.forEach((glyph, index) => {\n if (colored[index]) return\n banded.delete(glyph)\n uncoloured.add(glyph)\n })\n }\n\n // Three kinds of rows, top to bottom: text, monochrome shapes, colour.\n const textRows: MeasuredGlyph[] = []\n const shapeRows: MeasuredGlyph[] = []\n const band: MeasuredGlyph[] = []\n let totalArea = 0\n let widestGlyph = 4\n let exceedsLimit = false\n for (const glyph of measured) {\n totalArea += glyph.width * glyph.height\n if (glyph.width > widestGlyph) widestGlyph = glyph.width\n if (glyph.width > packingLimit || glyph.height > packingLimit) exceedsLimit = true\n if (banded.has(glyph)) band.push(glyph)\n else if (glyph.request.shape) shapeRows.push(glyph)\n else textRows.push(glyph)\n }\n const groups = [textRows, shapeRows, band].filter((group) => group.length)\n const packGlyphs = (pack: typeof packShelves, width: number, limit: number) =>\n groups.length > 1 ? packStacked(groups, width, limit, pack) : pack(measured, width, limit)\n const impossible = totalArea > packingLimit * packingLimit || exceedsLimit\n const bestPositions = new Int32Array(measured.length * 2)\n let shelfWidth = Math.min(packingLimit, Math.max(64, nextPowerOfTwo(Math.sqrt(totalArea))))\n let packed = impossible ? null : packGlyphs(packShelves, shelfWidth, packingLimit)\n while (!packed && shelfWidth < packingLimit) {\n shelfWidth = Math.min(packingLimit, shelfWidth * 2)\n packed = packGlyphs(packShelves, shelfWidth, packingLimit)\n }\n let best = packed && !impossible ? rememberPacking(measured, packed, bestPositions) : null\n\n if (!impossible && measured.length > 0) {\n const minRequiredLimit = groups.reduce((sum, g) => sum + align4(g[0]!.height), 0)\n const minimumWidth = Math.min(\n packingLimit,\n align4(Math.max(widestGlyph, Math.ceil(totalArea / packingLimit))),\n )\n // Search at most about 64 aligned widths. Trying both the shelf and skyline\n // heuristic keeps the old pack as a no-regression candidate while allowing\n // short glyphs to occupy holes below taller neighbours.\n const widthStep = align4(Math.max(4, Math.ceil((packingLimit - minimumWidth) / 64)))\n const maxHeightFor = (width: number): number =>\n best ? Math.min(packingLimit, Math.floor((best.width * best.height) / width)) : packingLimit\n const nextW = [minimumWidth, minimumWidth]\n for (let width = minimumWidth; ; width = Math.min(packingLimit, width + widthStep)) {\n throwIfAborted(options.signal)\n if (maxHeightFor(width) < minRequiredLimit) break\n const minH = align4(Math.max(minRequiredLimit, Math.ceil(totalArea / width)))\n for (let i = 0; i < 2; i++) {\n if (width < nextW[i]!) continue\n const maxCandidateHeight = maxHeightFor(width)\n if (minH > maxCandidateHeight) break\n lastOverflowWidth = Infinity\n const candidate = packGlyphs(i ? packSkyline : packShelves, width, maxCandidateHeight)\n nextW[i] = lastOverflowWidth\n if (candidate && (!best || isBetterPacking(candidate, best))) {\n best = rememberPacking(measured, candidate, bestPositions)\n }\n }\n if (width === packingLimit) break\n }\n }\n\n if (!best) {\n if (options.adaptiveBakeSize === true && bakeSize > 16) {\n const nextSize = Math.max(16, Math.floor(bakeSize * 0.8))\n const scaled = requests.map((request) => ({\n ...request,\n font: {\n ...request.font,\n canvasFont: request.font.canvasFont.replace(\n /[\\d.]+px/,\n (size) => `${(Number.parseFloat(size) * nextSize) / bakeSize}px`,\n ),\n },\n }))\n return await rasterizeGlyphAtlas(document, scaled, { ...options, bakeSize: nextSize })\n }\n throw new Error(\n `rasterizeGlyphAtlas: ${requests.length} glyphs exceed the ${maxAtlasSize}×${maxAtlasSize} atlas limit`,\n )\n }\n for (let index = 0; index < measured.length; index++) {\n measured[index]!.x = bestPositions[index * 2]!\n measured[index]!.y = bestPositions[index * 2 + 1]!\n }\n\n // The text rows, packed first, end where the shapes or else the colour band begin. Headroom\n // for later appends goes there, so the rows below move down once, now, never on an append.\n let textBottom = !textRows.length ? 0 : groups.length > 1 ? topOf(groups[1]!) : best.height\n if (options.appendable === 'headroom' && textRows.length) {\n // Rows of at least two of the widest text glyphs: a one-column atlas has no row that\n // takes a glyph wider than its own.\n let widestText = 0\n for (const glyph of textRows) if (glyph.width > widestText) widestText = glyph.width\n best.width = Math.min(packingLimit, Math.max(best.width, align4(2 * widestText)))\n const room = Math.min(\n packingLimit - best.height,\n align4(Math.max(textRows[0]!.height, textBottom / 4)),\n )\n if (room > 0) {\n for (const glyph of measured) if (glyph.y >= textBottom) glyph.y += room\n best.height += room\n textBottom += room\n }\n }\n\n canvas.width = best.width\n canvas.height = best.height\n painter.reset()\n if (scratch) context.clearRect(0, 0, canvas.width, canvas.height)\n const bandTop = band.length ? topOf(band) : 0\n const bandHeight = canvas.height - bandTop\n let black: Uint8ClampedArray | undefined\n if (band.length) {\n for (const glyph of band) drawGlyph(glyph, '#000')\n black = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n context.clearRect(0, bandTop, canvas.width, bandHeight)\n }\n const glyphSlots = new Map<string, GlyphSlot>()\n for (const glyph of measured) {\n drawGlyph(glyph)\n glyphSlots.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n canvas.width,\n canvas.height,\n banded.has(glyph),\n uncoloured.has(glyph),\n ),\n )\n }\n\n let colorBand: RasterColorBand | undefined\n if (black) {\n const white = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n const encoded = colorGlyphs!.encodeColorBand(\n white,\n black,\n canvas.width,\n bandHeight,\n padding,\n band.map((glyph) => ({ ...glyph, y: glyph.y - bandTop })),\n )\n for (const [index, glyph] of band.entries()) {\n const slot = glyphSlots.get(glyph.request.key)!\n glyphSlots.set(glyph.request.key, { ...slot, color: encoded.colored[index]! })\n }\n if (encoded.colored.some(Boolean))\n colorBand = { top: bandTop, height: bandHeight, data: encoded.data }\n }\n const shapeTop = shapeRows.length ? topOf(shapeRows) : undefined\n if (options.appendable) {\n // The last text row is the one the lowest-starting slot begins on; whatever reaches\n // that row or below bounds where the cursor starts and how far the row runs down.\n let x = 0\n let y = 0\n let rowHeight = 0\n for (const glyph of textRows)\n if (glyph.y > y && glyph.y + textRows[0]!.height <= textBottom) y = glyph.y\n for (const glyph of textRows) {\n const reach = glyph.y + glyph.height - y\n if (reach > 0) {\n if (glyph.x + glyph.width > x) x = glyph.x + glyph.width\n if (reach > rowHeight) rowHeight = reach\n }\n }\n appendCursors.set(glyphSlots, {\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n colorGlyphs: options.colorGlyphs ?? 'emoji',\n bottom: textBottom,\n x,\n y,\n rowHeight,\n })\n }\n return {\n ...(colorBand ? { colorBand } : {}),\n ...(shapeTop !== undefined ? { shapeTop } : {}),\n canvas,\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n glyphs: glyphSlots,\n }\n } finally {\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;AAqEA,IAAa,gCAAgB,IAAI,QAAsD;AA2DvF,SAAS,eAAe,QAA4B;CAClD,IAAI,QAAQ,SACV,MAAM,OAAO,UAAU,IAAI,aAAa,+BAA+B,YAAY;AAEvF;AAEA,SAAS,eAAe,OAAuB;CAC7C,OAAO,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG,KAAK,CAAC,CAAC;AACrD;AAEA,SAAS,OAAO,OAAuB;CACrC,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,CAAC,IAAI,CAAC;AAC7C;;AAGA,SAAgB,aACd,SACA,SACA,SACA,SACA,YAAY,OACZ,WAAwC,MACD;CACvC,MAAM,WAAW,eAAe,SAAS,SAAS,SAAS,QAAQ;CACnE,MAAM,UAAU,QAAQ,YAAY,QAAQ,SAAS;CACrD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,OAAO,QAAQ,MAAM;CAC3B,MAAM,KAAK,QAAQ,MAAM;CACzB,M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GACF;GACA,cAAc,IAAI,YAAY;IAC5B,OAAO,OAAO;IACd,QAAQ,OAAO;IACf;IACA,SAAS;IACT,aAAa,QAAQ,eAAe;IACpC,QAAQ;IACR;IACA;IACA;GACF,CAAC;EACH;EACA,OAAO;GACL,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;GACjC,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;GAC7C;GACA,OAAO,OAAO;GACd,QAAQ,OAAO;GACf;GACA,SAAS;GACT,QAAQ;EACV;CACF,UAAU;EACR,OAAO,OAAO;CAChB;AACF"}
1
+ {"version":3,"file":"rasterize.js","names":[],"sources":["../../src/atlas/rasterize.ts"],"sourcesContent":["import type {\n ColorGlyphMode,\n GlyphRequest,\n GlyphSlot,\n RasterAtlas,\n RasterColorBand,\n} from '../types.js'\nimport { isEmojiCandidate, isEmojiGrapheme } from '../dom/clusters.js'\nimport {\n createCanvas,\n isColorCandidate,\n setFontContext,\n waitForFonts,\n type ShapingContext,\n} from '../dom/fontCanvas.js'\n\nexport { createCanvas, isColorCandidate, setFontContext, waitForFonts }\n\n/** @internal Shared measured slot used by the lazy shape rasterizer. */\nexport interface MeasuredGlyph {\n readonly request: GlyphRequest\n readonly width: number\n readonly height: number\n readonly planeX0: number\n readonly planeY0: number\n readonly planeX1: number\n readonly planeY1: number\n readonly descent: number\n readonly advance: number\n readonly drawOffsetX: number\n /**\n * The ink box of a text glyph in plane units (x0, y0, x1, y1, y up from the baseline), from\n * the canvas's own metrics; absent where the slot is drawn whole.\n */\n readonly ink?: readonly [number, number, number, number]\n x: number\n y: number\n flags?: number\n}\n\n/**\n * @internal The first atlas row of the monochrome shapes, when the raster holds any. They are\n * packed below the text so that a material can tell them from text by their place in the atlas.\n */\nexport interface ShapeRows {\n readonly shapeTop?: number\n}\n\n/**\n * @internal Where later text glyphs fit in an atlas without moving any slot: a shelf cursor\n * over its text rows, which end at `bottom`, the first row of its shapes or colour band (or its\n * height). Every slot that reaches row `y` or below ends left of `x`; below `y + rowHeight`\n * the text rows are free.\n */\nexport interface AppendCursor {\n readonly width: number\n readonly height: number\n readonly bakeSize: number\n readonly pxRange: number\n readonly colorGlyphs: ColorGlyphMode\n readonly bottom: number\n readonly x: number\n readonly y: number\n readonly rowHeight: number\n}\n\n/**\n * @internal The cursors of the rasters built with `appendable`, keyed by their glyph map, which\n * every `SdfAtlas` built from the raster shares. A few numbers each: no canvas is kept.\n */\nexport const appendCursors = new WeakMap<ReadonlyMap<string, GlyphSlot>, AppendCursor>()\n\ninterface PackedGlyphs {\n width: number\n height: number\n}\n\nexport interface RasterizeOptions {\n /** Colour-glyph detection; defaults to 'emoji'. */\n colorGlyphs?: ColorGlyphMode\n /** Canvas font raster size in pixels; must be at least `16`. Defaults to `96`. */\n bakeSize?: number\n /**\n * Retry overflowing atlases at a smaller bake size, down to 16px.\n * Defaults to `false`; fitting atlases keep their requested resolution.\n */\n adaptiveBakeSize?: boolean\n /**\n * Glyph slot padding in texels; must be at least `2`. Defaults to `12`. The\n * padding doubles as the SDF pixel range (`RasterAtlas.pxRange`).\n */\n padding?: number\n /**\n * Maximum atlas dimension in texels; must be an integer of at least `64`.\n * Defaults to `2048`. Glyphs that cannot pack reject instead of dropping. Text, monochrome\n * shapes and colour glyphs take rows of their own, one kind below the other.\n */\n maxAtlasSize?: number\n /** Aborts the rasterization between font waits and glyph draws. */\n signal?: AbortSignal\n /**\n * An atlas built earlier for the same fonts, with this `bakeSize` and `padding`\n * (`pxRange`): a colour candidate whose slot there already carries `GlyphSlot.color` keeps\n * that classification, instead of being drawn twice on a scratch canvas and read back.\n * Bitmap SVG shapes and glyphs it lacks are classified as usual, and every glyph is still\n * measured, packed and drawn: only the classification is reused. Omit it after a webfont\n * swap. `DomSdf` passes its retained atlas when a capture's new glyphs rebuild it in full.\n */\n previousAtlas?: Pick<RasterAtlas, 'glyphs' | 'bakeSize' | 'pxRange'> | undefined\n /**\n * @internal Set by `DomSdf` for its own SDF atlases. The raster then records its\n * `AppendCursor` in `appendCursors`, so that `appendAtlas.ts` can draw later text glyphs\n * into the live texture. `'headroom'` also leaves free text rows for them, within\n * `maxAtlasSize`: a tallest text slot, or a quarter of the text rows when more, between\n * the text and the shapes and colour band, which therefore keep their rows across appends,\n * in an atlas at least two of its widest text glyphs wide. DomSdf asks for it once an\n * instance has gained glyphs; a capture that never gains any stays tight.\n */\n appendable?: boolean | 'headroom' | undefined\n /**\n * @internal Set by `DomSdf` when only a WebGPU atlas uploads the raster. Without colour\n * candidates, which are read back, the bake canvas is then GPU-backed (no\n * `willReadFrequently`): its first draw on a page skips the software canvas's set-up, 7 to\n * 12 ms on an M3 Max, and the atlas copies it on the GPU. Reading such a canvas back takes\n * hundreds of milliseconds, which only the CPU fallback of a failed GPU build pays.\n */\n gpuUpload?: boolean | undefined\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The atlas build was aborted', 'AbortError')\n }\n}\n\nfunction nextPowerOfTwo(value: number): number {\n return 2 ** Math.ceil(Math.log2(Math.max(1, value)))\n}\n\nfunction align4(value: number): number {\n return Math.max(4, Math.ceil(value / 4) * 4)\n}\n\n/** @internal Measures one text glyph's slot; `appendAtlas.ts` shares it with the cold build. */\nexport function measureGlyph(\n context: CanvasRenderingContext2D,\n request: GlyphRequest,\n padding: number,\n shaping: ShapingContext | undefined,\n candidate = false,\n lastFont: GlyphRequest['font'] | null = null,\n): MeasuredGlyph {\n setFontContext(context, request, shaping, lastFont)\n const metrics = context.measureText(request.character)\n const slice = request.shaping?.slice\n const from = slice?.[0] ?? 0\n const to = slice?.[1] ?? 1\n const advance = metrics.width * (to - from)\n const left = from === 0 ? Math.max(0, metrics.actualBoundingBoxLeft) : 0\n const right = slice\n ? advance + (to === 1 ? Math.max(0, metrics.actualBoundingBoxRight - metrics.width) : 0)\n : Math.max(metrics.width, metrics.actualBoundingBoxRight)\n const ascent = Math.max(1, metrics.fontBoundingBoxAscent || metrics.actualBoundingBoxAscent)\n const descent = Math.max(1, metrics.fontBoundingBoxDescent || metrics.actualBoundingBoxDescent)\n // A canvas draws text on a whole pixel row and, across, on a quarter pixel at best, whatever\n // origin it is given. The slot's origin is therefore a whole pixel: ink left of the origin\n // or taller than the font box was otherwise baked up to half a texel off, and the tiles of\n // a sliced run a quarter texel off each other.\n const drawOffsetX = metrics.width * from\n const planeX0 = -Math.ceil(left + padding - drawOffsetX) - drawOffsetX\n const planeX1 = right + padding\n const inkBounds =\n request.shaping !== undefined || candidate || isEmojiCandidate(request.character)\n const planeY0 = -Math.max(descent, inkBounds ? metrics.actualBoundingBoxDescent : 0) - padding\n const planeY1 = Math.ceil(\n Math.max(ascent, inkBounds ? metrics.actualBoundingBoxAscent : 0) + padding,\n )\n // Only whole, plain text glyphs trim their quads: a tile of a shaped line is clipped to its\n // slice, and colour candidates are bitmaps whose ink the metrics need not bound.\n const ink: MeasuredGlyph['ink'] =\n inkBounds || slice\n ? undefined\n : [\n -metrics.actualBoundingBoxLeft,\n -metrics.actualBoundingBoxDescent,\n metrics.actualBoundingBoxRight,\n metrics.actualBoundingBoxAscent,\n ]\n\n return {\n request,\n width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),\n height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent,\n advance,\n drawOffsetX,\n ...(ink?.every(Number.isFinite) ? { ink } : {}),\n x: 0,\n y: 0,\n flags: 0,\n }\n}\n\n/**\n * @internal The slot of a glyph drawn at (glyph.x, glyph.y) of a `width`×`height` atlas. The\n * full build and an append patch both take their slots from here, so they cannot drift apart.\n * A `banded` glyph is a colour candidate in the band; an `uncoloured` one a candidate that\n * classified as text.\n */\nexport function slotOf(\n glyph: MeasuredGlyph,\n padding: number,\n bakeSize: number,\n width: number,\n height: number,\n banded: boolean,\n uncoloured: boolean,\n): GlyphSlot {\n // The sampled window must follow the drawn plane box, not the shelf slot:\n // the slot is `ceil(extent) + 2` texels wide and the glyph origin above is\n // offset by one, so the plane spans texels 1 .. 1 + extent. Both bounds move\n // inward by half a texel so bilinear filtering cannot reach a neighbour.\n const slice = glyph.request.shaping?.slice\n const planeX0 = glyph.planeX0 + (slice && slice[0] > 0 ? -glyph.planeX0 : 0.5)\n const planeY0 = glyph.planeY0 + 0.5\n const planeX1 = glyph.planeX1 - (slice && slice[1] < 1 ? glyph.planeX1 - glyph.advance : 0.5)\n const planeY1 = glyph.planeY1 - 0.5\n const baseU = glyph.x + 1 - glyph.planeX0\n const baseV = glyph.y + 1 + glyph.planeY1\n const invW = 1 / width\n const invH = 1 / height\n const ink = banded ? undefined : glyph.ink\n let support: GlyphSlot['support']\n if (ink) {\n const reach = padding / 2 + 2 + 0.006 * bakeSize\n const sx0 = Math.max(planeX0, Math.floor(ink[0] - reach))\n const sy0 = Math.max(planeY0, Math.floor(ink[1] - reach))\n const sx1 = Math.min(planeX1, Math.ceil(ink[2] + reach))\n const sy1 = Math.min(planeY1, Math.ceil(ink[3] + reach))\n if (sx1 > sx0 && sy1 > sy0) {\n support = {\n u0: (baseU + sx0) * invW,\n v0: (baseV - sy1) * invH,\n u1: (baseU + sx1) * invW,\n v1: (baseV - sy0) * invH,\n }\n }\n }\n return {\n ...(uncoloured ? { color: false } : {}),\n key: glyph.request.key,\n character: glyph.request.character,\n fontKey: glyph.request.font.key,\n u0: (baseU + planeX0) * invW,\n v0: (baseV - planeY1) * invH,\n u1: (baseU + planeX1) * invW,\n v1: (baseV - planeY0) * invH,\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent: glyph.descent,\n advance: glyph.advance,\n ...(support ? { support } : {}),\n }\n}\n\n/**\n * @internal Draws glyphs into their slots of one canvas, by the rules of the full build and of\n * an append patch alike. `reset()` forgets the context state cached here: call it whenever\n * the canvas is resized, which resets that state.\n */\nexport function glyphPainter(\n context: CanvasRenderingContext2D,\n shaping: ShapingContext | undefined,\n signal: AbortSignal | undefined,\n drawShape?: (glyph: MeasuredGlyph) => void,\n): { draw(glyph: MeasuredGlyph, text: boolean, fill?: string): void; reset(): void } {\n // A text mask must be the outline itself on every platform. The bake canvas has font\n // smoothing off; where the engine has the property, text also asks for exact geometry,\n // and it takes a mid grey fill, the neutral middle of a rasterizer's contrast table.\n // Colour glyphs keep the default rendering and the fills their classification compares;\n // shapes are paths, which none of this affects.\n const exactText = 'textRendering' in context\n let lastFont: GlyphRequest['font'] | null = null\n let lastFill = ''\n let lastTextRendering = ''\n return {\n reset() {\n lastFont = null\n lastFill = ''\n lastTextRendering = ''\n },\n draw(glyph, text, fill = '#fff') {\n throwIfAborted(signal)\n const targetFill = text ? '#606060' : fill\n if (lastFill !== targetFill) {\n context.fillStyle = targetFill\n lastFill = targetFill\n }\n if (glyph.request.shape) {\n drawShape!(glyph)\n lastFill = ''\n return\n }\n lastFont = setFontContext(context, glyph.request, shaping, lastFont)\n if (exactText) {\n const targetRendering = text ? 'geometricPrecision' : 'auto'\n if (lastTextRendering !== targetRendering) {\n context.textRendering = targetRendering\n lastTextRendering = targetRendering\n }\n }\n const originX = glyph.x - glyph.planeX0 + 1\n const baselineY = glyph.y + glyph.planeY1 + 1\n if (glyph.request.shaping?.slice) {\n context.save()\n context.beginPath()\n context.rect(\n glyph.x + 1,\n glyph.y + 1,\n glyph.planeX1 - glyph.planeX0,\n glyph.planeY1 - glyph.planeY0,\n )\n context.clip()\n context.fillText(glyph.request.character, originX - glyph.drawOffsetX, baselineY)\n context.restore()\n } else context.fillText(glyph.request.character, originX, baselineY)\n },\n }\n}\n\n/** The first row of a non-empty run of packed glyphs. */\nfunction topOf(rows: readonly MeasuredGlyph[]): number {\n return rows.reduce((top, glyph) => (glyph.y < top ? glyph.y : top), rows[0]!.y)\n}\n\nlet lastOverflowWidth = Infinity\n\n/** @internal Row-major shelf packing; also lays out the colour candidates of an append. */\nexport function packShelves(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n let x = 0\n let y = 0\n let rowHeight = 0\n let usedWidth = 0\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gw > width) {\n if (gw < lastOverflowWidth) lastOverflowWidth = gw\n return null\n }\n if (gh > maxSize) return null\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (y + gh > maxSize) return null\n glyph.x = x\n glyph.y = y\n x += gw\n if (gh > rowHeight) rowHeight = gh\n if (x > usedWidth) usedWidth = x\n }\n\n return {\n width: align4(usedWidth),\n height: align4(y + rowHeight),\n }\n}\n\nlet skylineX = new Int32Array(256)\nlet skylineY = new Int32Array(256)\nlet skylineW = new Int32Array(256)\n\nfunction shiftSkyline(to: number, from: number, len: number): void {\n skylineX.copyWithin(to, from, len)\n skylineY.copyWithin(to, from, len)\n skylineW.copyWithin(to, from, len)\n}\n\nfunction recordSkylineOverflow(width: number, maxSize: number, wasteBudget: number): null {\n lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize))\n return null\n}\n\n/** Bottom-left skyline packing fills the vertical gaps that fixed-height shelves leave behind. */\nfunction packSkyline(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n const needed = glyphs.length + 2\n if (skylineX.length < needed) {\n skylineX = new Int32Array(needed)\n skylineY = new Int32Array(needed)\n skylineW = new Int32Array(needed)\n }\n const sx = skylineX\n const sy = skylineY\n const sw = skylineW\n sx[0] = 0\n sy[0] = 0\n sw[0] = width\n let skylineLen = 1\n let usedWidth = 0\n let usedHeight = 0\n\n const minH = glyphs[glyphs.length - 1]!.height\n let wasteBudget = width * maxSize\n for (const g of glyphs) wasteBudget -= g.width * g.height\n if (wasteBudget < 0) return recordSkylineOverflow(width, maxSize, wasteBudget)\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gh > maxSize) return null\n let bestIndex = -1\n let bestBottom = Infinity\n let bestWaste = Infinity\n const tail = skylineLen - 1\n let maxAllowedY = sw[tail]! >= gw && sy[tail]! < maxSize - gh ? sy[tail]! : maxSize - gh\n\n for (let index = 0; index < skylineLen; index++) {\n const firstY = sy[index]!\n if (firstY > maxAllowedY) continue\n const x = sx[index]!\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n break\n }\n\n let remaining = gw - sw[index]!\n let y = firstY\n let waste = 0\n if (remaining > 0) {\n let coveredArea = sw[index]! * firstY\n for (let cursor = index + 1; ; cursor++) {\n const nodeY = sy[cursor]!\n if (nodeY > maxAllowedY) {\n index = cursor\n remaining = 1\n break\n }\n if (nodeY > y) y = nodeY\n const nodeW = sw[cursor]!\n coveredArea += (remaining < nodeW ? remaining : nodeW) * nodeY\n if ((remaining -= nodeW) <= 0) break\n }\n if (remaining > 0) continue\n waste = y * gw - coveredArea\n }\n const bottom = y + gh\n if (bottom < bestBottom || waste < bestWaste) {\n bestIndex = index\n bestBottom = bottom\n bestWaste = waste\n maxAllowedY = waste === 0 ? y - 1 : y\n if (maxAllowedY < 0) break\n }\n }\n if (maxAllowedY >= 0 && usedWidth + gw < lastOverflowWidth) lastOverflowWidth = usedWidth + gw\n\n if (\n bestIndex < 0 ||\n (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) <\n 0\n )\n return bestIndex < 0 ? null : recordSkylineOverflow(width, maxSize, wasteBudget)\n const gx = sx[bestIndex]!\n const right = gx + gw\n glyph.x = gx\n glyph.y = bestBottom - gh\n let cursor = bestIndex\n while (cursor < skylineLen && sx[cursor]! + sw[cursor]! <= right) cursor++\n if (cursor < skylineLen && sx[cursor]! < right) {\n sw[cursor] = sx[cursor]! + sw[cursor]! - right\n sx[cursor] = right\n }\n let newCount = 1\n if (bestIndex > 0 && sy[bestIndex - 1] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + gw\n newCount = 0\n if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + sw[cursor]!\n cursor++\n }\n } else if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sx[cursor] = gx\n sw[cursor] = sw[cursor]! + gw\n newCount = 0\n }\n const delta = newCount - (cursor - bestIndex)\n if (delta !== 0 && cursor < skylineLen) shiftSkyline(cursor + delta, cursor, skylineLen)\n skylineLen += delta\n if (newCount) {\n sx[bestIndex] = gx\n sy[bestIndex] = bestBottom\n sw[bestIndex] = gw\n }\n\n if (right > usedWidth) usedWidth = right\n if (bestBottom > usedHeight) usedHeight = bestBottom\n }\n\n return { width: align4(usedWidth), height: align4(usedHeight) }\n}\n\n/** Packs each group into rows of its own, one group below the other. */\nfunction packStacked(\n groups: readonly MeasuredGlyph[][],\n width: number,\n limit: number,\n pack: typeof packShelves,\n): { width: number; height: number } | null {\n let packedWidth = 0\n let height = 0\n for (const group of groups) {\n const packed = pack(group, width, limit - height)\n if (!packed || height + packed.height > limit) return null\n for (const glyph of group) glyph.y += height\n packedWidth = Math.max(packedWidth, packed.width)\n height += packed.height\n }\n return { width: packedWidth, height }\n}\n\nfunction rememberPacking(\n glyphs: readonly MeasuredGlyph[],\n size: { width: number; height: number },\n positions: Int32Array,\n): PackedGlyphs {\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n positions[index * 2] = glyph.x\n positions[index * 2 + 1] = glyph.y\n }\n return { width: size.width, height: size.height }\n}\n\nfunction isBetterPacking(\n candidate: Pick<PackedGlyphs, 'width' | 'height'>,\n current: PackedGlyphs,\n): boolean {\n return (\n (candidate.width * candidate.height - current.width * current.height ||\n Math.max(candidate.width, candidate.height) - Math.max(current.width, current.height) ||\n candidate.width - current.width) < 0\n )\n}\n\n/**\n * Rasterizes every required font-face/character or emoji-sequence pair into one tightly packed\n * alpha atlas. The output is a transient mask; the retained texture is a\n * single-channel distance field produced by the CPU or WebGPU compute backend.\n */\nexport async function rasterizeGlyphAtlas(\n document: Document,\n requests: readonly GlyphRequest[],\n options: RasterizeOptions = {},\n): Promise<RasterAtlas> {\n const bakeSize = options.bakeSize ?? 96\n const padding = options.padding ?? 12\n const maxAtlasSize = options.maxAtlasSize ?? 2048\n if (!Number.isFinite(bakeSize) || bakeSize < 16) {\n throw new RangeError('rasterizeGlyphAtlas: bakeSize must be at least 16')\n }\n if (!Number.isFinite(padding) || padding < 2) {\n throw new RangeError('rasterizeGlyphAtlas: padding must be at least 2')\n }\n if (!Number.isInteger(maxAtlasSize) || maxAtlasSize < 64) {\n throw new RangeError('rasterizeGlyphAtlas: maxAtlasSize must be an integer of at least 64')\n }\n\n throwIfAborted(options.signal)\n const [, shapingModule, shapes] = await Promise.all([\n waitForFonts(document, requests, options.signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n requests.some((request) => request.shape) ? import('./shapeRaster.js') : undefined,\n ])\n const shaping = shapingModule?.setShapingContext\n throwIfAborted(options.signal)\n\n const canvas = createCanvas(document)\n let returned = false\n try {\n // A glyph a matching previous atlas has classified keeps its classification. A bitmap\n // shape always keeps its place in the band, as on a cold build: never history-dependent.\n const previous =\n options.previousAtlas?.bakeSize === bakeSize && options.previousAtlas.pxRange === padding\n ? options.previousAtlas.glyphs\n : undefined\n const willReadFrequently =\n !options.gpuUpload ||\n requests.some(\n (request) =>\n isColorCandidate(request, options.colorGlyphs) &&\n (request.shape !== undefined ||\n ((options.colorGlyphs === 'all' || isEmojiGrapheme(request.character)) &&\n previous?.get(request.key)?.color !== false)),\n )\n const context = canvas.getContext('2d', { willReadFrequently })\n if (!context) throw new Error('rasterizeGlyphAtlas: Canvas 2D is unavailable')\n\n const packingLimit = maxAtlasSize - (maxAtlasSize % 4)\n let lastFont: GlyphRequest['font'] | null = null\n const measured = requests.map((request) => {\n if (request.shape) return shapes!.measureShape(request, bakeSize, padding)\n const glyph = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, options.colorGlyphs),\n lastFont,\n )\n lastFont = request.font\n return glyph\n })\n measured.sort(\n (a, b) =>\n b.height - a.height ||\n b.width - a.width ||\n (a.request.key < b.request.key ? -1 : a.request.key > b.request.key ? 1 : 0),\n )\n\n let bandedCount = 0\n const tested: MeasuredGlyph[] = []\n for (const glyph of measured) {\n if (!isColorCandidate(glyph.request, options.colorGlyphs)) continue\n const known = glyph.request.shape ? undefined : previous?.get(glyph.request.key)?.color\n if (known === false) glyph.flags = 2\n else {\n glyph.flags = 1\n bandedCount++\n if (!glyph.request.shape && known === undefined) tested.push(glyph)\n }\n }\n const painter = glyphPainter(context, shaping, options.signal, (glyph) => {\n shapes!.drawShapeSlot(context, glyph, bakeSize)\n })\n const drawGlyph = (glyph: MeasuredGlyph, fill?: string): void => {\n painter.draw(glyph, !glyph.request.shape && (glyph.flags! & 1) === 0, fill)\n }\n\n // A candidate the font draws in the fill colour alone is text, whatever Unicode lists it\n // as: a copyright sign, an arrow, the tiles of a shaped line beside the one that holds\n // its emoji. Each font candidate is drawn in black and in white on a pack of their own,\n // and only one with ink that ignores the fill keeps its place in the band; the others are\n // baked, packed and flagged with the text.\n const colorGlyphs = bandedCount ? await import('./colorGlyphs.js') : undefined\n throwIfAborted(options.signal)\n const scratch = tested.length ? packShelves(tested, packingLimit, packingLimit) : null\n if (scratch) {\n const scratchCanvas = willReadFrequently ? null : createCanvas(document)\n try {\n const targetCanvas = scratchCanvas ?? canvas\n targetCanvas.width = scratch.width\n targetCanvas.height = scratch.height\n const targetContext = scratchCanvas\n ? scratchCanvas.getContext('2d', { willReadFrequently: true })\n : context\n if (!targetContext) throw new Error('rasterizeGlyphAtlas: Canvas 2D is unavailable')\n const targetPainter = scratchCanvas\n ? glyphPainter(targetContext, shaping, options.signal)\n : painter\n targetPainter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n targetContext.clearRect(0, 0, scratch.width, scratch.height)\n for (const glyph of tested) targetPainter.draw(glyph, false, fill)\n return targetContext.getImageData(0, 0, scratch.width, scratch.height).data\n }\n const dark = paint('#000')\n const { colored } = colorGlyphs!.encodeColorBand(\n paint('#fff'),\n dark,\n scratch.width,\n scratch.height,\n 0,\n tested,\n )\n tested.forEach((glyph, index) => {\n if (colored[index]) return\n glyph.flags = 2\n })\n } finally {\n if (scratchCanvas) {\n scratchCanvas.width = 0\n scratchCanvas.height = 0\n scratchCanvas.remove()\n }\n }\n }\n\n // Three kinds of rows, top to bottom: text, monochrome shapes, colour.\n const textRows: MeasuredGlyph[] = []\n const shapeRows: MeasuredGlyph[] = []\n const band: MeasuredGlyph[] = []\n let totalArea = 0\n let widestGlyph = 4\n let exceedsLimit = false\n for (const glyph of measured) {\n totalArea += glyph.width * glyph.height\n if (glyph.width > widestGlyph) widestGlyph = glyph.width\n if (glyph.width > packingLimit || glyph.height > packingLimit) exceedsLimit = true\n if (glyph.flags! & 1) band.push(glyph)\n else if (glyph.request.shape) shapeRows.push(glyph)\n else textRows.push(glyph)\n }\n const groups = [textRows, shapeRows, band].filter((group) => group.length)\n const packGlyphs = (pack: typeof packShelves, width: number, limit: number) =>\n groups.length > 1 ? packStacked(groups, width, limit, pack) : pack(measured, width, limit)\n const impossible = totalArea > packingLimit * packingLimit || exceedsLimit\n const bestPositions = new Int32Array(measured.length * 2)\n let shelfWidth = Math.min(packingLimit, Math.max(64, nextPowerOfTwo(Math.sqrt(totalArea))))\n let packed = impossible ? null : packGlyphs(packShelves, shelfWidth, packingLimit)\n while (!packed && shelfWidth < packingLimit) {\n shelfWidth = Math.min(packingLimit, shelfWidth * 2)\n packed = packGlyphs(packShelves, shelfWidth, packingLimit)\n }\n let best = packed && !impossible ? rememberPacking(measured, packed, bestPositions) : null\n\n if (!impossible && measured.length > 0) {\n const minRequiredLimit = groups.reduce((sum, g) => sum + align4(g[0]!.height), 0)\n const minimumWidth = Math.min(\n packingLimit,\n align4(Math.max(widestGlyph, Math.ceil(totalArea / packingLimit))),\n )\n // Skip skyline when every group has uniform heights so shelf packing is already tight.\n const packerCount = groups.some((g) => g[0]!.height !== g[g.length - 1]!.height) ? 2 : 1\n const maxHeightFor = (width: number): number =>\n best ? Math.min(packingLimit, Math.floor((best.width * best.height) / width)) : packingLimit\n const nextW = [minimumWidth, minimumWidth]\n for (let width = minimumWidth; width <= packingLimit; width += 4) {\n throwIfAborted(options.signal)\n if (maxHeightFor(width) < minRequiredLimit) break\n const minH = align4(Math.max(minRequiredLimit, Math.ceil(totalArea / width)))\n for (let i = 0; i < packerCount; i++) {\n if (width < nextW[i]!) continue\n const maxCandidateHeight = maxHeightFor(width)\n if (minH > maxCandidateHeight) break\n lastOverflowWidth = Infinity\n const candidate = packGlyphs(i ? packSkyline : packShelves, width, maxCandidateHeight)\n nextW[i] = lastOverflowWidth\n if (candidate && (!best || isBetterPacking(candidate, best))) {\n best = rememberPacking(measured, candidate, bestPositions)\n }\n }\n }\n }\n\n if (!best) {\n if (options.adaptiveBakeSize === true && bakeSize > 16) {\n const nextSize = Math.max(16, Math.floor(bakeSize * 0.8))\n const scaled = requests.map((request) => ({\n ...request,\n font: {\n ...request.font,\n canvasFont: request.font.canvasFont.replace(\n /[\\d.]+px/,\n (size) => `${(Number.parseFloat(size) * nextSize) / bakeSize}px`,\n ),\n },\n }))\n return await rasterizeGlyphAtlas(document, scaled, { ...options, bakeSize: nextSize })\n }\n throw new Error(\n `rasterizeGlyphAtlas: ${requests.length} glyphs exceed the ${maxAtlasSize}×${maxAtlasSize} atlas limit`,\n )\n }\n for (let index = 0; index < measured.length; index++) {\n measured[index]!.x = bestPositions[index * 2]!\n measured[index]!.y = bestPositions[index * 2 + 1]!\n }\n\n // The text rows, packed first, end where the shapes or else the colour band begin. Headroom\n // for later appends goes there, so the rows below move down once, now, never on an append.\n let textBottom = !textRows.length ? 0 : groups.length > 1 ? topOf(groups[1]!) : best.height\n if (options.appendable === 'headroom' && textRows.length) {\n // Rows of at least two of the widest text glyphs: a one-column atlas has no row that\n // takes a glyph wider than its own.\n let widestText = 0\n for (const glyph of textRows) if (glyph.width > widestText) widestText = glyph.width\n best.width = Math.min(packingLimit, Math.max(best.width, align4(2 * widestText)))\n const room = Math.min(\n packingLimit - best.height,\n align4(Math.max(textRows[0]!.height, textBottom / 4)),\n )\n if (room > 0) {\n for (const glyph of measured) if (glyph.y >= textBottom) glyph.y += room\n best.height += room\n textBottom += room\n }\n }\n\n canvas.width = best.width\n canvas.height = best.height\n painter.reset()\n if (scratch && willReadFrequently) context.clearRect(0, 0, canvas.width, canvas.height)\n const bandTop = band.length ? topOf(band) : 0\n const bandHeight = canvas.height - bandTop\n let black: Uint8ClampedArray | undefined\n if (band.length) {\n for (const glyph of band) drawGlyph(glyph, '#000')\n black = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n context.clearRect(0, bandTop, canvas.width, bandHeight)\n }\n const glyphSlots = new Map<string, GlyphSlot>()\n const byFont = new Map<string, MeasuredGlyph[]>()\n const shapeGlyphs: MeasuredGlyph[] = []\n for (const glyph of measured) {\n if (glyph.request.shape) {\n shapeGlyphs.push(glyph)\n continue\n }\n let group = byFont.get(glyph.request.font.key)\n if (!group) byFont.set(glyph.request.font.key, (group = []))\n group.push(glyph)\n }\n const drawAndRecord = (glyph: MeasuredGlyph): void => {\n drawGlyph(glyph)\n glyphSlots.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n canvas.width,\n canvas.height,\n (glyph.flags! & 1) !== 0,\n (glyph.flags! & 2) !== 0,\n ),\n )\n }\n for (const group of byFont.values()) {\n for (const glyph of group) drawAndRecord(glyph)\n }\n for (const glyph of shapeGlyphs) drawAndRecord(glyph)\n\n let colorBand: RasterColorBand | undefined\n if (black) {\n const white = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n const encoded = colorGlyphs!.encodeColorBand(\n white,\n black,\n canvas.width,\n bandHeight,\n padding,\n band.map((glyph) => ({ ...glyph, y: glyph.y - bandTop })),\n )\n for (const [index, glyph] of band.entries()) {\n const slot = glyphSlots.get(glyph.request.key)!\n glyphSlots.set(glyph.request.key, { ...slot, color: encoded.colored[index]! })\n }\n if (encoded.colored.some(Boolean))\n colorBand = { top: bandTop, height: bandHeight, data: encoded.data }\n }\n const shapeTop = shapeRows.length ? topOf(shapeRows) : undefined\n if (options.appendable) {\n // The last text row is the one the lowest-starting slot begins on; whatever reaches\n // that row or below bounds where the cursor starts and how far the row runs down.\n let x = 0\n let y = 0\n let rowHeight = 0\n for (const glyph of textRows)\n if (glyph.y > y && glyph.y + textRows[0]!.height <= textBottom) y = glyph.y\n for (const glyph of textRows) {\n const reach = glyph.y + glyph.height - y\n if (reach > 0) {\n if (glyph.x + glyph.width > x) x = glyph.x + glyph.width\n if (reach > rowHeight) rowHeight = reach\n }\n }\n appendCursors.set(glyphSlots, {\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n colorGlyphs: options.colorGlyphs ?? 'emoji',\n bottom: textBottom,\n x,\n y,\n rowHeight,\n })\n }\n returned = true\n return {\n ...(colorBand ? { colorBand } : {}),\n ...(shapeTop !== undefined ? { shapeTop } : {}),\n canvas,\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n glyphs: glyphSlots,\n }\n } finally {\n if (!returned) {\n canvas.width = 0\n canvas.height = 0\n }\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;AAsEA,IAAa,gCAAgB,IAAI,QAAsD;AA2DvF,SAAS,eAAe,QAA4B;CAClD,IAAI,QAAQ,SACV,MAAM,OAAO,UAAU,IAAI,aAAa,+BAA+B,YAAY;AAEvF;AAEA,SAAS,eAAe,OAAuB;CAC7C,OAAO,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG,KAAK,CAAC,CAAC;AACrD;AAEA,SAAS,OAAO,OAAuB;CACrC,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,CAAC,IAAI,CAAC;AAC7C;;AAGA,SAAgB,aACd,SACA,SACA,SACA,SACA,YAAY,OACZ,WAAwC,MACzB;CACf,eAAe,SAAS,SAAS,SAAS,QAAQ;CAClD,MAAM,UAAU,QAAQ,YAAY,QAAQ,SAAS;CACrD,M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C7C;GACA,OAAO,OAAO;GACd,QAAQ,OAAO;GACf;GACA,SAAS;GACT,QAAQ;EACV;CACF,UAAU;EACR,IAAI,CAAC,UAAU;GACb,OAAO,QAAQ;GACf,OAAO,SAAS;EAClB;EACA,OAAO,OAAO;CAChB;AACF"}
@@ -20,7 +20,8 @@ function measureShape(request, bakeSize, padding) {
20
20
  advance: 0,
21
21
  drawOffsetX: 0,
22
22
  x: 0,
23
- y: 0
23
+ y: 0,
24
+ flags: 0
24
25
  };
25
26
  }
26
27
  /** Draw one retained mask; bitmap requests supply authored per-path colours. */
@@ -1 +1 @@
1
- {"version":3,"file":"shapeRaster.js","names":[],"sources":["../../src/atlas/shapeRaster.ts"],"sourcesContent":["import type { GlyphRequest, GlyphShapePath } from '../types.js'\nimport type { MeasuredGlyph } from './rasterize.js'\n\n/** Shapes use the same texel-plane contract as font glyphs, with their baseline at box bottom. */\nexport function measureShape(\n request: GlyphRequest,\n bakeSize: number,\n padding: number,\n): MeasuredGlyph {\n const shape = request.shape!\n const scale = bakeSize / 1000\n const [x0, y0, x1, y1] = shape.bounds\n const planeX0 = x0 * scale - padding\n const planeX1 = x1 * scale + padding\n const planeY0 = (shape.box[1] - y1) * scale - padding\n const planeY1 = (shape.box[1] - y0) * scale + padding\n return {\n request,\n width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),\n height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),\n planeX0,\n planeX1,\n planeY0,\n planeY1,\n descent: 0,\n advance: 0,\n drawOffsetX: 0,\n x: 0,\n y: 0,\n }\n}\n\n/** Draw one retained mask; bitmap requests supply authored per-path colours. */\nexport function drawShapeSlot(\n context: CanvasRenderingContext2D,\n glyph: MeasuredGlyph,\n bakeSize: number,\n): void {\n const shape = glyph.request.shape!\n const scale = bakeSize / 1000\n const prepare = (target: CanvasRenderingContext2D, x: number, y: number) => {\n target.setTransform(\n scale,\n 0,\n 0,\n scale,\n x - glyph.planeX0 + 1,\n y + glyph.planeY1 + 1 - shape.box[1] * scale,\n )\n // The ink bounds may be cropped by a viewport; never spill into adjacent atlas slots.\n target.beginPath()\n target.rect(\n shape.bounds[0],\n shape.bounds[1],\n shape.bounds[2] - shape.bounds[0],\n shape.bounds[3] - shape.bounds[1],\n )\n target.clip()\n }\n const draw = (context: CanvasRenderingContext2D, item: GlyphShapePath) => {\n context.save()\n try {\n if (item.clip) {\n context.beginPath()\n context.rect(\n item.clip[0],\n item.clip[1],\n item.clip[2] - item.clip[0],\n item.clip[3] - item.clip[1],\n )\n context.clip()\n }\n if (shape.bitmap && item.color) {\n const [r, g, b, a] = item.color\n context.fillStyle = `rgba(${r * 255},${g * 255},${b * 255},${a})`\n }\n context.strokeStyle = context.fillStyle\n let path = new Path2D(item.d)\n const stroke = item.stroke\n if (stroke?.nonScaling) {\n const transformed = new Path2D()\n const [a, b, c, d, e, f] = item.transform\n transformed.addPath(path, { a, b, c, d, e, f })\n path = transformed\n } else context.transform(...item.transform)\n if (stroke) {\n context.lineWidth = stroke.width\n context.lineCap = stroke.lineCap\n context.lineJoin = stroke.lineJoin\n context.miterLimit = stroke.miterLimit\n context.setLineDash(stroke.dash ? [...stroke.dash] : [])\n context.lineDashOffset = stroke.dashOffset ?? 0\n context.stroke(path)\n } else context.fill(path, item.fillRule ?? 'nonzero')\n } finally {\n context.restore()\n }\n }\n context.save()\n try {\n prepare(context, glyph.x, glyph.y)\n if (shape.image) context.drawImage(shape.image, 0, 0, ...shape.box)\n else if (shape.bitmap && shape.paths.some((path) => path.opacityGroups?.length)) {\n // Canvas applies opacity to each paint. Isolate SVG element/group opacity so\n // overlapping children and fill/stroke are composited before the alpha scales.\n const stack: { id: number; alpha: number; context: CanvasRenderingContext2D }[] = []\n const close = () => {\n const group = stack.pop()!\n const parent = stack.at(-1)?.context ?? context\n parent.save()\n try {\n parent.setTransform(1, 0, 0, 1, 0, 0)\n parent.globalAlpha = group.alpha\n parent.drawImage(\n group.context.canvas,\n stack.length ? 0 : glyph.x,\n stack.length ? 0 : glyph.y,\n )\n } finally {\n parent.restore()\n group.context.canvas.width = group.context.canvas.height = 0\n }\n }\n try {\n for (const item of shape.paths) {\n const groups = item.opacityGroups ?? []\n let shared = 0\n while (shared < stack.length && stack[shared]!.id === groups[shared]?.[0]) shared++\n while (stack.length > shared) close()\n for (let i = shared; i < groups.length; i++) {\n const canvas = context.canvas.ownerDocument.createElement('canvas')\n canvas.width = glyph.width\n canvas.height = glyph.height\n const target = canvas.getContext('2d')\n if (!target) throw new Error('SVG opacity compositing requires Canvas 2D')\n prepare(target, 0, 0)\n stack.push({ id: groups[i]![0], alpha: groups[i]![1], context: target })\n }\n draw(stack.at(-1)?.context ?? context, item)\n }\n while (stack.length) close()\n } finally {\n for (const group of stack) group.context.canvas.width = group.context.canvas.height = 0\n }\n } else for (const item of shape.paths) draw(context, item)\n } finally {\n context.restore()\n }\n}\n"],"mappings":";;AAIA,SAAgB,aACd,SACA,UACA,SACe;CACf,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,WAAW;CACzB,MAAM,CAAC,IAAI,IAAI,IAAI,MAAM,MAAM;CAC/B,MAAM,UAAU,KAAK,QAAQ;CAC7B,MAAM,UAAU,KAAK,QAAQ;CAC7B,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,QAAQ;CAC9C,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,QAAQ;CAC9C,OAAO;EACL;EACA,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,UAAU,OAAO,IAAI,CAAC;EACnD,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAK,UAAU,OAAO,IAAI,CAAC;EACpD;EACA;EACA;EACA;EACA,SAAS;EACT,SAAS;EACT,aAAa;EACb,GAAG;EACH,GAAG;CACL;AACF;;AAGA,SAAgB,cACd,SACA,OACA,UACM;CACN,MAAM,QAAQ,MAAM,QAAQ;CAC5B,MAAM,QAAQ,WAAW;CACzB,MAAM,WAAW,QAAkC,GAAW,MAAc;EAC1E,OAAO,aACL,OACA,GACA,G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AAI,MAAM,4CAA4C;MACzE,QAAQ,QAAQ,GAAG,CAAC;MACpB,MAAM,KAAK;OAAE,IAAI,OAAO,EAAE,CAAE;OAAI,OAAO,OAAO,EAAE,CAAE;OAAI,SAAS;MAAO,CAAC;KACzE;KACA,KAAK,MAAM,GAAG,EAAE,CAAC,EAAE,WAAW,SAAS,IAAI;IAC7C;IACA,OAAO,MAAM,QAAQ,MAAM;GAC7B,UAAU;IACR,KAAK,MAAM,SAAS,OAAO,MAAM,QAAQ,OAAO,QAAQ,MAAM,QAAQ,OAAO,SAAS;GACxF;EACF,OAAO,KAAK,MAAM,QAAQ,MAAM,OAAO,KAAK,SAAS,IAAI;CAC3D,UAAU;EACR,QAAQ,QAAQ;CAClB;AACF"}
1
+ {"version":3,"file":"shapeRaster.js","names":[],"sources":["../../src/atlas/shapeRaster.ts"],"sourcesContent":["import type { GlyphRequest, GlyphShapePath } from '../types.js'\nimport type { MeasuredGlyph } from './rasterize.js'\n\n/** Shapes use the same texel-plane contract as font glyphs, with their baseline at box bottom. */\nexport function measureShape(\n request: GlyphRequest,\n bakeSize: number,\n padding: number,\n): MeasuredGlyph {\n const shape = request.shape!\n const scale = bakeSize / 1000\n const [x0, y0, x1, y1] = shape.bounds\n const planeX0 = x0 * scale - padding\n const planeX1 = x1 * scale + padding\n const planeY0 = (shape.box[1] - y1) * scale - padding\n const planeY1 = (shape.box[1] - y0) * scale + padding\n return {\n request,\n width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),\n height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),\n planeX0,\n planeX1,\n planeY0,\n planeY1,\n descent: 0,\n advance: 0,\n drawOffsetX: 0,\n x: 0,\n y: 0,\n flags: 0,\n }\n}\n\n/** Draw one retained mask; bitmap requests supply authored per-path colours. */\nexport function drawShapeSlot(\n context: CanvasRenderingContext2D,\n glyph: MeasuredGlyph,\n bakeSize: number,\n): void {\n const shape = glyph.request.shape!\n const scale = bakeSize / 1000\n const prepare = (target: CanvasRenderingContext2D, x: number, y: number) => {\n target.setTransform(\n scale,\n 0,\n 0,\n scale,\n x - glyph.planeX0 + 1,\n y + glyph.planeY1 + 1 - shape.box[1] * scale,\n )\n // The ink bounds may be cropped by a viewport; never spill into adjacent atlas slots.\n target.beginPath()\n target.rect(\n shape.bounds[0],\n shape.bounds[1],\n shape.bounds[2] - shape.bounds[0],\n shape.bounds[3] - shape.bounds[1],\n )\n target.clip()\n }\n const draw = (context: CanvasRenderingContext2D, item: GlyphShapePath) => {\n context.save()\n try {\n if (item.clip) {\n context.beginPath()\n context.rect(\n item.clip[0],\n item.clip[1],\n item.clip[2] - item.clip[0],\n item.clip[3] - item.clip[1],\n )\n context.clip()\n }\n if (shape.bitmap && item.color) {\n const [r, g, b, a] = item.color\n context.fillStyle = `rgba(${r * 255},${g * 255},${b * 255},${a})`\n }\n context.strokeStyle = context.fillStyle\n let path = new Path2D(item.d)\n const stroke = item.stroke\n if (stroke?.nonScaling) {\n const transformed = new Path2D()\n const [a, b, c, d, e, f] = item.transform\n transformed.addPath(path, { a, b, c, d, e, f })\n path = transformed\n } else context.transform(...item.transform)\n if (stroke) {\n context.lineWidth = stroke.width\n context.lineCap = stroke.lineCap\n context.lineJoin = stroke.lineJoin\n context.miterLimit = stroke.miterLimit\n context.setLineDash(stroke.dash ? [...stroke.dash] : [])\n context.lineDashOffset = stroke.dashOffset ?? 0\n context.stroke(path)\n } else context.fill(path, item.fillRule ?? 'nonzero')\n } finally {\n context.restore()\n }\n }\n context.save()\n try {\n prepare(context, glyph.x, glyph.y)\n if (shape.image) context.drawImage(shape.image, 0, 0, ...shape.box)\n else if (shape.bitmap && shape.paths.some((path) => path.opacityGroups?.length)) {\n // Canvas applies opacity to each paint. Isolate SVG element/group opacity so\n // overlapping children and fill/stroke are composited before the alpha scales.\n const stack: { id: number; alpha: number; context: CanvasRenderingContext2D }[] = []\n const close = () => {\n const group = stack.pop()!\n const parent = stack.at(-1)?.context ?? context\n parent.save()\n try {\n parent.setTransform(1, 0, 0, 1, 0, 0)\n parent.globalAlpha = group.alpha\n parent.drawImage(\n group.context.canvas,\n stack.length ? 0 : glyph.x,\n stack.length ? 0 : glyph.y,\n )\n } finally {\n parent.restore()\n group.context.canvas.width = group.context.canvas.height = 0\n }\n }\n try {\n for (const item of shape.paths) {\n const groups = item.opacityGroups ?? []\n let shared = 0\n while (shared < stack.length && stack[shared]!.id === groups[shared]?.[0]) shared++\n while (stack.length > shared) close()\n for (let i = shared; i < groups.length; i++) {\n const canvas = context.canvas.ownerDocument.createElement('canvas')\n canvas.width = glyph.width\n canvas.height = glyph.height\n const target = canvas.getContext('2d')\n if (!target) throw new Error('SVG opacity compositing requires Canvas 2D')\n prepare(target, 0, 0)\n stack.push({ id: groups[i]![0], alpha: groups[i]![1], context: target })\n }\n draw(stack.at(-1)?.context ?? context, item)\n }\n while (stack.length) close()\n } finally {\n for (const group of stack) group.context.canvas.width = group.context.canvas.height = 0\n }\n } else for (const item of shape.paths) draw(context, item)\n } finally {\n context.restore()\n }\n}\n"],"mappings":";;AAIA,SAAgB,aACd,SACA,UACA,SACe;CACf,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,WAAW;CACzB,MAAM,CAAC,IAAI,IAAI,IAAI,MAAM,MAAM;CAC/B,MAAM,UAAU,KAAK,QAAQ;CAC7B,MAAM,UAAU,KAAK,QAAQ;CAC7B,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,QAAQ;CAC9C,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,QAAQ;CAC9C,OAAO;EACL;EACA,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,UAAU,OAAO,IAAI,CAAC;EACnD,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAK,UAAU,OAAO,IAAI,CAAC;EACpD;EACA;EACA;EACA;EACA,SAAS;EACT,SAAS;EACT,aAAa;EACb,GAAG;EACH,GAAG;EACH,OAAO;CACT;AACF;;AAGA,SAAgB,cACd,SACA,OACA,UACM;CACN,MAAM,QA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