ultra-text 1.0.0 → 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 (200) hide show
  1. package/README.md +267 -962
  2. package/THIRD_PARTY_NOTICES.md +3 -0
  3. package/dist/assets/{cpuSdf.worker-Du9o8q4p.js → cpuSdf.worker--X1Qpmdp.js} +148 -57
  4. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  5. package/dist/atlas/appendAtlas.js +69 -26
  6. package/dist/atlas/appendAtlas.js.map +1 -1
  7. package/dist/atlas/buildAtlas.js +5 -15
  8. package/dist/atlas/buildAtlas.js.map +1 -1
  9. package/dist/atlas/cpuAtlas.d.ts +4 -1
  10. package/dist/atlas/cpuAtlas.js +8 -6
  11. package/dist/atlas/cpuAtlas.js.map +1 -1
  12. package/dist/atlas/cpuSdf.js +164 -50
  13. package/dist/atlas/cpuSdf.js.map +1 -1
  14. package/dist/atlas/cpuWorker.d.ts +5 -3
  15. package/dist/atlas/cpuWorker.js +119 -12
  16. package/dist/atlas/cpuWorker.js.map +1 -1
  17. package/dist/atlas/gpuAtlas.d.ts +7 -6
  18. package/dist/atlas/gpuAtlas.js +206 -247
  19. package/dist/atlas/gpuAtlas.js.map +1 -1
  20. package/dist/atlas/gpuCommon.d.ts +135 -0
  21. package/dist/atlas/gpuCommon.js +223 -0
  22. package/dist/atlas/gpuCommon.js.map +1 -0
  23. package/dist/atlas/jfaWgsl.js +59 -125
  24. package/dist/atlas/jfaWgsl.js.map +1 -1
  25. package/dist/atlas/rasterize.d.ts +2 -0
  26. package/dist/atlas/rasterize.js +104 -144
  27. package/dist/atlas/rasterize.js.map +1 -1
  28. package/dist/atlas/shapeRaster.js +2 -1
  29. package/dist/atlas/shapeRaster.js.map +1 -1
  30. package/dist/atlas/vanillaBounds.d.ts +64 -0
  31. package/dist/atlas/vanillaBounds.js +42 -0
  32. package/dist/atlas/vanillaBounds.js.map +1 -0
  33. package/dist/atlas/vanillaCore.d.ts +100 -0
  34. package/dist/atlas/vanillaCore.js +1012 -0
  35. package/dist/atlas/vanillaCore.js.map +1 -0
  36. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  37. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  38. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  39. package/dist/atlas/vanillaExtras.d.ts +8 -0
  40. package/dist/atlas/vanillaExtras.js +166 -0
  41. package/dist/atlas/vanillaExtras.js.map +1 -0
  42. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  43. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  44. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  45. package/dist/dom/DomSdf.js +263 -272
  46. package/dist/dom/DomSdf.js.map +1 -1
  47. package/dist/dom/DomSlug.d.ts +26 -0
  48. package/dist/dom/DomSlug.js +564 -0
  49. package/dist/dom/DomSlug.js.map +1 -0
  50. package/dist/dom/SlugText.d.ts +18 -0
  51. package/dist/dom/SlugText.js +94 -0
  52. package/dist/dom/SlugText.js.map +1 -0
  53. package/dist/dom/Text.js +4 -67
  54. package/dist/dom/Text.js.map +1 -1
  55. package/dist/dom/domAnalytic.d.ts +54 -0
  56. package/dist/dom/domAnalytic.js +282 -0
  57. package/dist/dom/domAnalytic.js.map +1 -0
  58. package/dist/dom/domExtras.d.ts +27 -0
  59. package/dist/dom/domExtras.js +137 -0
  60. package/dist/dom/domExtras.js.map +1 -0
  61. package/dist/dom/fontCanvas.d.ts +2 -0
  62. package/dist/dom/fontCanvas.js +119 -0
  63. package/dist/dom/fontCanvas.js.map +1 -0
  64. package/dist/dom/layoutSignature.js +156 -27
  65. package/dist/dom/layoutSignature.js.map +1 -1
  66. package/dist/dom/pretextLayout.js +55 -13
  67. package/dist/dom/pretextLayout.js.map +1 -1
  68. package/dist/dom/snapshot.js +563 -243
  69. package/dist/dom/snapshot.js.map +1 -1
  70. package/dist/dom/svgCapture.d.ts +8 -1
  71. package/dist/dom/svgCapture.js +75 -1
  72. package/dist/dom/svgCapture.js.map +1 -1
  73. package/dist/dom/textHost.d.ts +11 -0
  74. package/dist/dom/textHost.js +68 -0
  75. package/dist/dom/textHost.js.map +1 -0
  76. package/dist/dom/tone.js +76 -36
  77. package/dist/dom/tone.js.map +1 -1
  78. package/dist/index.js +4 -3
  79. package/dist/slug/SlugMaterial.d.ts +13 -4
  80. package/dist/slug/SlugMaterial.js +82 -12
  81. package/dist/slug/SlugMaterial.js.map +1 -1
  82. package/dist/slug/coverage.d.ts +17 -13
  83. package/dist/slug/coverage.js +195 -222
  84. package/dist/slug/coverage.js.map +1 -1
  85. package/dist/slug/preprocessCore.d.ts +6 -3
  86. package/dist/slug/preprocessCore.js +149 -95
  87. package/dist/slug/preprocessCore.js.map +1 -1
  88. package/dist/slug/runtime.d.ts +1 -0
  89. package/dist/slug/runtime.js +94 -46
  90. package/dist/slug/runtime.js.map +1 -1
  91. package/dist/slug/standaloneRuntime.d.ts +40 -0
  92. package/dist/slug/standaloneRuntime.js +175 -0
  93. package/dist/slug/standaloneRuntime.js.map +1 -0
  94. package/dist/slug/truetype.d.ts +22 -0
  95. package/dist/slug/truetype.js +467 -0
  96. package/dist/slug/truetype.js.map +1 -0
  97. package/dist/slug/vanillaCore.d.ts +340 -0
  98. package/dist/slug/vanillaCore.js +1621 -0
  99. package/dist/slug/vanillaCore.js.map +1 -0
  100. package/dist/slug-vanilla.d.ts +13 -0
  101. package/dist/slug-vanilla.js +13 -0
  102. package/dist/slug.d.ts +21 -0
  103. package/dist/slug.js +19 -0
  104. package/dist/text/GlyphTextMaterial.d.ts +11 -11
  105. package/dist/text/GlyphTextMaterial.js +102 -33
  106. package/dist/text/GlyphTextMaterial.js.map +1 -1
  107. package/dist/text/SdfTextMaterial.d.ts +5 -4
  108. package/dist/text/SdfTextMaterial.js +29 -9
  109. package/dist/text/SdfTextMaterial.js.map +1 -1
  110. package/dist/text/decorations.js +36 -19
  111. package/dist/text/decorations.js.map +1 -1
  112. package/dist/text/geometry.d.ts +3 -22
  113. package/dist/text/geometryUtils.d.ts +11 -1
  114. package/dist/text/geometryUtils.js +22 -1
  115. package/dist/text/geometryUtils.js.map +1 -1
  116. package/dist/text/glyphGeometry.d.ts +9 -0
  117. package/dist/text/glyphGeometry.js +353 -0
  118. package/dist/text/glyphGeometry.js.map +1 -0
  119. package/dist/text/index.d.ts +2 -1
  120. package/dist/text/rectGeometry.d.ts +13 -0
  121. package/dist/text/rectGeometry.js +97 -0
  122. package/dist/text/rectGeometry.js.map +1 -0
  123. package/dist/text/reflow.d.ts +18 -1
  124. package/dist/text/reflow.js +108 -38
  125. package/dist/text/reflow.js.map +1 -1
  126. package/dist/text/snap.d.ts +1 -0
  127. package/dist/text/snap.js +26 -0
  128. package/dist/text/snap.js.map +1 -0
  129. package/dist/types.d.ts +63 -14
  130. package/dist/vanilla.d.ts +13 -360
  131. package/dist/vanilla.js +8 -1402
  132. package/dist/windfoil/WindfoilMaterial.d.ts +2 -1
  133. package/dist/windfoil/WindfoilMaterial.js +8 -1
  134. package/dist/windfoil/WindfoilMaterial.js.map +1 -1
  135. package/dist/windfoil/abortable.d.ts +2 -0
  136. package/dist/windfoil/abortable.js +26 -0
  137. package/dist/windfoil/abortable.js.map +1 -0
  138. package/dist/windfoil/color.js +2 -1
  139. package/dist/windfoil/color.js.map +1 -1
  140. package/dist/windfoil/coverage.d.ts +3 -20
  141. package/dist/windfoil/coverage.js +7 -20
  142. package/dist/windfoil/coverage.js.map +1 -1
  143. package/dist/windfoil/emoji.js +1 -1
  144. package/dist/windfoil/emoji.js.map +1 -1
  145. package/dist/windfoil/emojiMetrics.js +1 -1
  146. package/dist/windfoil/emojiMetrics.js.map +1 -1
  147. package/dist/windfoil/geometry.d.ts +2 -2
  148. package/dist/windfoil/geometry.js +204 -64
  149. package/dist/windfoil/geometry.js.map +1 -1
  150. package/dist/windfoil/layerGrid.js +14 -10
  151. package/dist/windfoil/layerGrid.js.map +1 -1
  152. package/dist/windfoil/layerNormalization.d.ts +1 -1
  153. package/dist/windfoil/layerNormalization.js +1 -1
  154. package/dist/windfoil/layerNormalization.js.map +1 -1
  155. package/dist/windfoil/mixed.d.ts +1 -0
  156. package/dist/windfoil/mixed.js +44 -25
  157. package/dist/windfoil/mixed.js.map +1 -1
  158. package/dist/windfoil/outlineValidation.d.ts +86 -0
  159. package/dist/windfoil/outlineValidation.js +65 -0
  160. package/dist/windfoil/outlineValidation.js.map +1 -0
  161. package/dist/windfoil/preprocess.js +3 -2
  162. package/dist/windfoil/preprocess.js.map +1 -1
  163. package/dist/windfoil/preprocessCore.d.ts +5 -85
  164. package/dist/windfoil/preprocessCore.js +218 -209
  165. package/dist/windfoil/preprocessCore.js.map +1 -1
  166. package/dist/windfoil/requests.js +1 -1
  167. package/dist/windfoil/requests.js.map +1 -1
  168. package/dist/windfoil/runtime.d.ts +5 -2
  169. package/dist/windfoil/runtime.js +63 -40
  170. package/dist/windfoil/runtime.js.map +1 -1
  171. package/dist/windfoil/shapeResources.js +2 -1
  172. package/dist/windfoil/shapeResources.js.map +1 -1
  173. package/dist/windfoil/shapes.js +1 -1
  174. package/dist/windfoil/skirt.d.ts +22 -0
  175. package/dist/windfoil/skirt.js +20 -0
  176. package/dist/windfoil/skirt.js.map +1 -0
  177. package/dist/windfoil/storage.d.ts +62 -4
  178. package/dist/windfoil/storage.js +143 -28
  179. package/dist/windfoil/storage.js.map +1 -1
  180. package/dist/windfoil/trace/contours.d.ts +3 -3
  181. package/dist/windfoil/trace/contours.js +228 -137
  182. package/dist/windfoil/trace/contours.js.map +1 -1
  183. package/dist/windfoil/trace/fit.d.ts +3 -7
  184. package/dist/windfoil/trace/fit.js +668 -376
  185. package/dist/windfoil/trace/fit.js.map +1 -1
  186. package/dist/windfoil/trace/outline.js +60 -35
  187. package/dist/windfoil/trace/outline.js.map +1 -1
  188. package/dist/windfoil/trace/types.d.ts +15 -3
  189. package/dist/windfoil/tracedOutlines.d.ts +37 -1
  190. package/dist/windfoil/tracedOutlines.js +228 -64
  191. package/dist/windfoil/tracedOutlines.js.map +1 -1
  192. package/package.json +60 -11
  193. package/skills/ultra-text/SKILL.md +114 -0
  194. package/skills/ultra-text/references/frameworks.md +43 -0
  195. package/skills/ultra-text/references/three-tsl.md +78 -0
  196. package/skills/ultra-text/references/vanilla-webgpu.md +96 -0
  197. package/dist/assets/cpuSdf.worker-Du9o8q4p.js.map +0 -1
  198. package/dist/text/geometry.js +0 -348
  199. package/dist/text/geometry.js.map +0 -1
  200. package/dist/vanilla.js.map +0 -1
@@ -1,131 +1,130 @@
1
- import { JFA_WGSL } from "./jfaWgsl.js";
1
+ import { checkCommonAtlasLimits, encodeJfaWork, jfaSteps, openErrorScopes, prefersTiledJfa, selectWorkgroupDimension, supportsDirectStore } from "./gpuCommon.js";
2
+ import { buildJfaWgsl } from "./jfaWgsl.js";
2
3
  import { ExternalTexture, LinearFilter, LinearMipmapLinearFilter, NoColorSpace, RedFormat, WebGPUBackend } from "three/webgpu";
3
4
  // src/atlas/gpuAtlas.ts
4
- var COMPUTE_WORKGROUP_DIMENSION = 8;
5
- var KERNEL_NEEDS = [
6
- ["maxComputeInvocationsPerWorkgroup", COMPUTE_WORKGROUP_DIMENSION ** 2],
7
- ["maxComputeWorkgroupSizeX", COMPUTE_WORKGROUP_DIMENSION],
8
- ["maxComputeWorkgroupSizeY", COMPUTE_WORKGROUP_DIMENSION],
9
- ["maxStorageBuffersPerShaderStage", 2],
10
- ["maxStorageBuffersInFragmentStage", 1]
11
- ];
12
- /** A texture-to-buffer copy aligns each row to 256 bytes; the raster keeps 4 bytes a texel. */
13
- function rasterRowBytes(width) {
14
- return Math.ceil(width / 64) * 256;
5
+ var devicePipelines = /* @__PURE__ */ new WeakMap();
6
+ function asAtlasPipelines(workgroupDim, directStore, tiledStore, multi) {
7
+ return {
8
+ workgroupDim,
9
+ directStore,
10
+ seed: multi?.seed ?? null,
11
+ jump: multi?.jump ?? null,
12
+ jumpStore: multi?.jumpStore ?? null,
13
+ tiledStore,
14
+ resolve: multi?.resolve ?? null
15
+ };
15
16
  }
16
- /**
17
- * Past a device limit the passes are invalid, which WebGPU reports only asynchronously:
18
- * checking first lets `auto` fall back without GPU work and `gpu` fail with a reason.
19
- */
20
- function checkAtlasLimits(limits, width, height) {
21
- for (const [name, need] of KERNEL_NEEDS) {
22
- const value = limits[name];
23
- if (value !== void 0 && value < need) throw new RangeError(`buildGpuSdfAtlas: ${name}=${value}, needs ${need}; use atlasMode "cpu"`);
24
- }
25
- const largest = limits.maxTextureDimension2D;
26
- if (largest !== void 0 && Math.max(width, height) > largest) throw new RangeError(`buildGpuSdfAtlas: ${width}×${height} exceeds maxTextureDimension2D=${largest}; lower maxAtlasSize`);
27
- const bytes = Math.max(width * height * 8, rasterRowBytes(width) * height);
28
- if (bytes > limits.maxStorageBufferBindingSize || bytes > limits.maxBufferSize) throw new RangeError(`buildGpuSdfAtlas: ${width}×${height} exceeds storage-buffer limits; use atlasMode "cpu" or lower maxAtlasSize`);
17
+ function getDeviceCache(device, workgroupDim, directStore) {
18
+ const existing = devicePipelines.get(device);
19
+ if (existing?.workgroupDim === workgroupDim && existing.directStore === directStore) return existing;
20
+ const cache = {
21
+ workgroupDim,
22
+ directStore,
23
+ module: device.createShaderModule({
24
+ label: "ultra-text atlas",
25
+ code: buildJfaWgsl(workgroupDim, directStore)
26
+ })
27
+ };
28
+ devicePipelines.set(device, cache);
29
+ return cache;
29
30
  }
30
- var ERROR_FILTERS = [
31
- "validation",
32
- "out-of-memory",
33
- "internal"
34
- ];
35
- /**
36
- * Captures what the device reports about the calls made until `close()`. Without a scope an
37
- * invalid pass would surface only as a console warning, and the atlas would come back blank
38
- * or wrong while `auto` saw nothing to fall back from. `close()` pops synchronously, so
39
- * concurrent builds cannot interleave scopes, and never rejects.
40
- */
41
- function openErrorScopes(device) {
42
- const push = device.pushErrorScope;
43
- const pop = device.popErrorScope;
44
- if (!push || !pop) return { close: () => Promise.resolve(null) };
45
- for (const filter of ERROR_FILTERS) push.call(device, filter);
46
- return { close() {
47
- return Promise.all(ERROR_FILTERS.map(() => pop.call(device))).then((errors) => {
48
- const error = errors.find(Boolean);
49
- return error ? error.message ?? "unknown GPU error" : null;
50
- }, (error) => String(error));
51
- } };
31
+ function cachedAtlasPipelines(device, workgroupDim, directStore, tiledOnly) {
32
+ const cache = devicePipelines.get(device);
33
+ if (cache?.workgroupDim !== workgroupDim || cache.directStore !== directStore) return void 0;
34
+ if (tiledOnly) return cache.tiledStore ? asAtlasPipelines(workgroupDim, directStore, cache.tiledStore) : void 0;
35
+ return cache.multi ? asAtlasPipelines(workgroupDim, directStore, null, cache.multi) : void 0;
52
36
  }
53
- /**
54
- * The jump-flood ladder only has to reach as far as the encoding can represent.
55
- *
56
- * A byte stores `0.5 - signedDistance / pxRange`, so everything beyond
57
- * `pxRange / 2` pixels from an edge saturates to 0 or 1 no matter what distance
58
- * the field holds there. A ladder `S, S/2, … 1` propagates at most `2S - 1`
59
- * pixels per axis, so the smallest sufficient first step is `(radius + 1) / 2`
60
- * rounded up to a power of two.
61
- *
62
- * Sizing the ladder from `pxRange` instead of the atlas extent is what keeps this
63
- * at three or four passes rather than one per octave of the atlas: at 2048² and
64
- * the default padding that is 4 passes instead of 12.
65
- */
66
- function jfaSteps(pxRange) {
67
- const radius = Math.ceil(pxRange * .5) + 1;
68
- let step = 1;
69
- while (step * 2 - 1 < radius) step <<= 1;
70
- const steps = [];
71
- for (; step >= 1; step >>= 1) steps.push(step);
72
- return steps;
37
+ function supportsAsyncAtlasPipelines(device, directStore) {
38
+ return typeof device.createComputePipelineAsync === "function" && (directStore || typeof device.createRenderPipelineAsync === "function");
73
39
  }
74
- /**
75
- * One shader module and pipeline set per device, made on its first atlas and kept for its
76
- * lifetime: a few native objects, while the buffers of a build live only through its
77
- * submission. Writing the passes in WGSL spares every page three's node graph build of
78
- * three passes on its first atlas, and every later build and patch the rebuild of their
79
- * graphs (about 15 and 3 ms on an M3 Max).
80
- */
81
- var devicePipelines = /* @__PURE__ */ new WeakMap();
82
- function atlasPipelines(device) {
83
- let pipelines = devicePipelines.get(device);
84
- if (!pipelines) {
85
- const module = device.createShaderModule({
86
- label: "ultra-text atlas",
87
- code: JFA_WGSL
88
- });
89
- const compute = (entryPoint) => device.createComputePipeline({
90
- layout: "auto",
91
- compute: {
92
- module,
93
- entryPoint
94
- }
95
- });
96
- pipelines = {
97
- seed: compute("seedMain"),
98
- jump: compute("jumpMain"),
99
- resolve: device.createRenderPipeline({
100
- layout: "auto",
101
- vertex: {
102
- module,
103
- entryPoint: "fullscreenVert"
104
- },
105
- fragment: {
106
- module,
107
- entryPoint: "resolveFrag",
108
- targets: [{ format: "r8unorm" }]
109
- }
110
- })
40
+ function buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, async) {
41
+ const cached = cachedAtlasPipelines(device, workgroupDim, directStore, tiledOnly);
42
+ if (cached) return async ? Promise.resolve(cached) : cached;
43
+ const existing = devicePipelines.get(device);
44
+ const sameConfig = existing?.workgroupDim === workgroupDim && existing.directStore === directStore;
45
+ if (async && sameConfig) {
46
+ const inFlight = tiledOnly ? existing.tiledPromise : existing.multiPromise;
47
+ if (inFlight) return inFlight;
48
+ }
49
+ const cache = getDeviceCache(device, workgroupDim, directStore);
50
+ const module = cache.module;
51
+ const computeSync = (entryPoint) => device.createComputePipeline({
52
+ layout: "auto",
53
+ compute: {
54
+ module,
55
+ entryPoint
56
+ }
57
+ });
58
+ const computeAsync = (entryPoint) => device.createComputePipelineAsync({
59
+ layout: "auto",
60
+ compute: {
61
+ module,
62
+ entryPoint
63
+ }
64
+ });
65
+ if (tiledOnly) {
66
+ const store = (tiledStore) => {
67
+ cache.tiledStore = tiledStore;
68
+ return asAtlasPipelines(workgroupDim, directStore, tiledStore);
111
69
  };
112
- devicePipelines.set(device, pipelines);
70
+ if (!async) return store(computeSync("tiledStoreMain"));
71
+ const promise = computeAsync("tiledStoreMain").then((tiledStore) => store(tiledStore), (error) => {
72
+ if (cache.tiledPromise === promise) cache.tiledPromise = void 0;
73
+ throw error;
74
+ });
75
+ cache.tiledPromise = promise;
76
+ return promise;
113
77
  }
114
- return pipelines;
78
+ const resolveDesc = {
79
+ layout: "auto",
80
+ vertex: {
81
+ module,
82
+ entryPoint: "fullscreenVert"
83
+ },
84
+ fragment: {
85
+ module,
86
+ entryPoint: "resolveFrag",
87
+ targets: [{ format: "r8unorm" }]
88
+ }
89
+ };
90
+ const store = (seed, jump, jumpStore, resolve) => {
91
+ const multi = {
92
+ seed,
93
+ jump,
94
+ jumpStore,
95
+ resolve
96
+ };
97
+ cache.multi = multi;
98
+ return asAtlasPipelines(workgroupDim, directStore, null, multi);
99
+ };
100
+ if (!async) return store(computeSync("seedMain"), computeSync("jumpMain"), directStore ? computeSync("jumpStoreMain") : null, directStore ? null : device.createRenderPipeline(resolveDesc));
101
+ const promise = Promise.all([
102
+ computeAsync("seedMain"),
103
+ computeAsync("jumpMain"),
104
+ directStore ? computeAsync("jumpStoreMain") : Promise.resolve(null),
105
+ directStore ? Promise.resolve(null) : device.createRenderPipelineAsync(resolveDesc)
106
+ ]).then(([seed, jump, jumpStore, resolve]) => store(seed, jump, jumpStore, resolve), (error) => {
107
+ if (cache.multiPromise === promise) cache.multiPromise = void 0;
108
+ throw error;
109
+ });
110
+ cache.multiPromise = promise;
111
+ return promise;
115
112
  }
116
113
  /**
117
114
  * @internal Starts the native compile of the device's atlas passes ahead of its first atlas,
118
- * while the caller reads the DOM: the device compiles them meanwhile (about 2.5 ms on an M3 Max
119
- * with a warm shader cache), and the atlas then waits for its own work only. Making them
120
- * cannot throw; a device that rejects them fails the first atlas's submission instead, in its
121
- * error scopes, and that build makes them again.
115
+ * while the caller reads the DOM.
122
116
  */
123
- function prepareAtlasPasses(renderer) {
117
+ function prepareAtlasPasses(renderer, pxRange) {
124
118
  const device = atlasDevice(renderer);
125
- if (device?.createShaderModule && !devicePipelines.has(device)) {
126
- atlasPipelines(device);
127
- device.queue.submit([]);
128
- }
119
+ if (!device?.createShaderModule) return;
120
+ const directStore = supportsDirectStore(device.features);
121
+ const workgroupDim = selectWorkgroupDimension(device.limits);
122
+ const tiledOnly = prefersTiledJfa(directStore, pxRange);
123
+ const cached = devicePipelines.get(device);
124
+ if (cached?.workgroupDim === workgroupDim && cached.directStore === directStore && (tiledOnly ? cached.tiledStore || cached.tiledPromise : cached.multi || cached.multiPromise)) return;
125
+ if (supportsAsyncAtlasPipelines(device, directStore)) buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, true).catch(() => void 0);
126
+ else buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, false);
127
+ device.queue.submit([]);
129
128
  }
130
129
  /**
131
130
  * @internal Regenerates the mips of an atlas texture from its level 0 with three's own mip
@@ -149,118 +148,44 @@ function atlasDevice(renderer) {
149
148
  }
150
149
  /**
151
150
  * @internal Runs the atlas passes over `raster` into level 0 of a new r8unorm texture of
152
- * `mipLevelCount` levels, all in one command buffer: the canvas is uploaded and copied into a storage buffer
153
- * of 256-byte rows, the seeds are found and flooded in two ping-pong buffers, and the resolve
154
- * pass encodes the distances. `finish` may add commands that use the texture before it is
155
- * submitted, as a patch does. Resolves with the texture once the device has accepted every
156
- * call; rejects, holding nothing, when the device's limits cannot hold the passes, lacks
157
- * these calls or reports an error for them. The buffers and the upload live only through the
158
- * submission: destroying them waits for the submitted work.
151
+ * `mipLevelCount` levels, all in one command buffer.
159
152
  */
160
- async function encodeGpuSdf(device, raster, mipLevelCount, finish) {
161
- const { width, height, pxRange } = raster;
153
+ async function encodeGpuSdf(device, raster, mipLevelCount, finish, onSubmitted) {
154
+ const { width, height, pxRange, canvas } = raster;
162
155
  const { GPUBufferUsage: buffers, GPUTextureUsage: textures } = globalThis;
163
156
  if (!device?.createCommandEncoder || !buffers || !textures) throw new Error("buildGpuSdfAtlas: device cannot run the atlas passes");
164
- if (device.limits) checkAtlasLimits(device.limits, width, height);
157
+ const steps = jfaSteps(pxRange);
158
+ const directStore = supportsDirectStore(device.features);
159
+ checkCommonAtlasLimits("buildGpuSdfAtlas", device.limits, width, height, steps[0], directStore, "; use atlasMode \"cpu\"");
160
+ const workgroupDim = selectWorkgroupDimension(device.limits);
161
+ const tiledOnly = directStore && steps[0] === 4;
162
+ let prebuilt = cachedAtlasPipelines(device, workgroupDim, directStore, tiledOnly);
163
+ if (!prebuilt && supportsAsyncAtlasPipelines(device, directStore)) try {
164
+ prebuilt = await buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, true);
165
+ } catch (error) {
166
+ throw new Error(`buildGpuSdfAtlas: the device rejected the atlas passes: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
167
+ }
165
168
  const transient = [];
166
169
  let output;
167
170
  try {
168
171
  const scopes = openErrorScopes(device);
169
172
  let reported;
170
173
  try {
171
- const pipelines = atlasPipelines(device);
172
- const steps = jfaSteps(pxRange);
173
- const rowBytes = rasterRowBytes(width);
174
- const buffer = (size, usage) => {
175
- const created = device.createBuffer({
176
- size,
177
- usage
178
- });
179
- transient.push(created);
180
- return created;
181
- };
182
- const upload = device.createTexture({
183
- size: [width, height],
184
- format: "rgba8unorm",
185
- usage: textures.COPY_SRC | textures.COPY_DST | textures.RENDER_ATTACHMENT
186
- });
187
- transient.push(upload);
188
- const words = buffer(rowBytes * height, buffers.STORAGE | buffers.COPY_DST);
189
- const seeds = [buffer(width * height * 8, buffers.STORAGE), buffer(width * height * 8, buffers.STORAGE)];
190
- const params = buffer(steps.length * 256 + 16, buffers.UNIFORM | buffers.COPY_DST);
191
- const values = new Int32Array(steps.length * 64 + 4);
192
- values.set([
193
- width,
194
- height,
195
- rowBytes / 4
196
- ]);
197
- new Float32Array(values.buffer, 12, 1)[0] = 1 / pxRange;
198
- steps.forEach((step, index) => values.set([
199
- width,
200
- height,
201
- step
202
- ], (index + 1) * 64));
203
- device.queue.writeBuffer(params, 0, values);
204
- device.queue.copyExternalImageToTexture({
205
- source: raster.canvas,
206
- flipY: false
207
- }, {
208
- texture: upload,
209
- premultipliedAlpha: false
210
- }, [width, height]);
174
+ const pipelines = prebuilt ?? buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, false);
211
175
  output = device.createTexture({
212
176
  size: [width, height],
213
177
  mipLevelCount,
214
178
  format: "r8unorm",
215
- usage: textures.RENDER_ATTACHMENT | textures.TEXTURE_BINDING | textures.COPY_SRC | textures.COPY_DST
216
- });
217
- const bind = (pipeline, offset, ...storageBuffers) => device.createBindGroup({
218
- layout: pipeline.getBindGroupLayout(0),
219
- entries: [{
220
- binding: 0,
221
- resource: {
222
- buffer: params,
223
- offset,
224
- size: 16
225
- }
226
- }, ...storageBuffers.map((resource, index) => ({
227
- binding: index + 1,
228
- resource: { buffer: resource }
229
- }))]
179
+ usage: textures.RENDER_ATTACHMENT | textures.TEXTURE_BINDING | textures.COPY_SRC | textures.COPY_DST | (pipelines.directStore ? textures.STORAGE_BINDING ?? 0 : 0)
230
180
  });
231
181
  const encoder = device.createCommandEncoder();
232
- encoder.copyTextureToBuffer({ texture: upload }, {
233
- buffer: words,
234
- bytesPerRow: rowBytes,
235
- rowsPerImage: height
236
- }, [width, height]);
237
- const groupsX = Math.ceil(width / COMPUTE_WORKGROUP_DIMENSION);
238
- const groupsY = Math.ceil(height / COMPUTE_WORKGROUP_DIMENSION);
239
- const flood = encoder.beginComputePass();
240
- flood.setPipeline(pipelines.seed);
241
- flood.setBindGroup(0, bind(pipelines.seed, 0, words, seeds[0]));
242
- flood.dispatchWorkgroups(groupsX, groupsY);
243
- flood.setPipeline(pipelines.jump);
244
- steps.forEach((_, index) => {
245
- const into = seeds[(index + 1) % 2];
246
- flood.setBindGroup(0, bind(pipelines.jump, (index + 1) * 256, seeds[index % 2], into));
247
- flood.dispatchWorkgroups(groupsX, groupsY);
248
- });
249
- flood.end();
250
- const resolve = encoder.beginRenderPass({ colorAttachments: [{
251
- view: output.createView({ mipLevelCount: 1 }),
252
- loadOp: "clear",
253
- storeOp: "store"
254
- }] });
255
- resolve.setPipeline(pipelines.resolve);
256
- resolve.setBindGroup(0, bind(pipelines.resolve, 0, seeds[steps.length % 2]));
257
- resolve.draw(3);
258
- resolve.end();
182
+ encodeJfaWork(device, encoder, pipelines, canvas, width, height, pxRange, steps, output, transient, buffers, textures);
259
183
  finish?.(encoder, output);
260
184
  device.queue.submit([encoder.finish()]);
261
185
  } finally {
262
186
  reported = scopes.close();
263
187
  }
188
+ onSubmitted?.(output);
264
189
  const rejection = await reported;
265
190
  if (rejection !== null) {
266
191
  devicePipelines.delete(device);
@@ -275,59 +200,93 @@ async function encodeGpuSdf(device, raster, mipLevelCount, finish) {
275
200
  }
276
201
  }
277
202
  /**
278
- * Generates a compact R8 runtime SDF on the renderer's WebGPU device: boundary seeding and a
279
- * storage-buffer jump flood in compute passes, then a resolve render pass (`JFA_WGSL`). The
280
- * texture is an `ExternalTexture` the atlas owns, with three's mips when `mipmaps`. It
281
- * rejects, instead of returning a blank or wrong atlas, when the device's limits cannot hold
282
- * the passes, the backend lacks the calls, or the device reports an error for them.
203
+ * Generates a compact R8 runtime SDF on the renderer's WebGPU device: boundary seeding and
204
+ * 4-byte relative fixed-point jump flooding in compute passes, writing directly into `r8unorm`
205
+ * when `'texture-formats-tier1'` is active on the device or resolving via a fullscreen render
206
+ * pass on Core WebGPU 1.0 devices.
283
207
  */
284
- async function buildGpuSdfAtlas(renderer, raster, options = {}) {
208
+ async function buildGpuSdfAtlas(renderer, raster, options = {}, onProvisional) {
285
209
  await renderer.init();
286
210
  if (!(renderer.backend instanceof WebGPUBackend)) throw new Error("buildGpuSdfAtlas: requires the WebGPU backend; use mode \"cpu\"");
287
211
  const { width, height } = raster;
288
212
  const mipmaps = options.mipmaps === true;
289
213
  const levels = mipmaps ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1;
290
- const gpuTexture = await encodeGpuSdf(atlasDevice(renderer), raster, levels);
291
- const texture = new ExternalTexture(gpuTexture);
292
- let disposed = false;
293
- const dispose = () => {
294
- if (disposed) return;
295
- disposed = true;
214
+ const { shapeTop } = raster;
215
+ const maxAnisotropy = mipmaps ? renderer.getMaxAnisotropy() : 1;
216
+ const wrapAtlas = (gpuTexture) => {
217
+ const texture = new ExternalTexture(gpuTexture);
218
+ let disposed = false;
219
+ let gpuDestroyed = false;
220
+ const dispose = () => {
221
+ if (disposed) return;
222
+ disposed = true;
223
+ try {
224
+ texture.dispose();
225
+ } finally {
226
+ if (!gpuDestroyed) {
227
+ gpuDestroyed = true;
228
+ gpuTexture.destroy();
229
+ }
230
+ }
231
+ };
296
232
  try {
297
- texture.dispose();
298
- } finally {
299
- gpuTexture.destroy();
233
+ texture.image = {
234
+ width,
235
+ height
236
+ };
237
+ texture.name = "ultra-text SDF atlas";
238
+ texture.format = RedFormat;
239
+ texture.colorSpace = NoColorSpace;
240
+ texture.generateMipmaps = mipmaps;
241
+ texture.minFilter = mipmaps ? LinearMipmapLinearFilter : LinearFilter;
242
+ texture.magFilter = LinearFilter;
243
+ texture.anisotropy = mipmaps ? Math.min(Math.max(1, options.anisotropy ?? 1), maxAnisotropy) : 1;
244
+ if (shapeTop !== void 0) texture.userData["ultraShapeTop"] = shapeTop;
245
+ } catch (error) {
246
+ dispose();
247
+ throw error;
300
248
  }
249
+ return {
250
+ atlas: {
251
+ ...shapeTop === void 0 ? {} : { shapeTop },
252
+ texture,
253
+ width,
254
+ height,
255
+ pxRange: raster.pxRange,
256
+ bakeSize: raster.bakeSize,
257
+ glyphs: raster.glyphs,
258
+ mode: "gpu",
259
+ dispose
260
+ },
261
+ markGpuDestroyed: () => {
262
+ gpuDestroyed = true;
263
+ }
264
+ };
301
265
  };
266
+ if (onProvisional && !mipmaps) {
267
+ let wrapped;
268
+ try {
269
+ const gpuTexture = await encodeGpuSdf(atlasDevice(renderer), raster, levels, void 0, (candidate) => {
270
+ wrapped = wrapAtlas(candidate);
271
+ onProvisional(wrapped.atlas);
272
+ });
273
+ return wrapped ? wrapped.atlas : wrapAtlas(gpuTexture).atlas;
274
+ } catch (error) {
275
+ if (wrapped) {
276
+ wrapped.markGpuDestroyed();
277
+ wrapped.atlas.dispose();
278
+ }
279
+ throw error;
280
+ }
281
+ }
282
+ const { atlas } = wrapAtlas(await encodeGpuSdf(atlasDevice(renderer), raster, levels));
302
283
  try {
303
- texture.image = {
304
- width,
305
- height
306
- };
307
- texture.name = "ultra-text SDF atlas";
308
- texture.format = RedFormat;
309
- texture.colorSpace = NoColorSpace;
310
- texture.generateMipmaps = mipmaps;
311
- texture.minFilter = mipmaps ? LinearMipmapLinearFilter : LinearFilter;
312
- texture.magFilter = LinearFilter;
313
- texture.anisotropy = mipmaps ? Math.min(Math.max(1, options.anisotropy ?? 1), renderer.getMaxAnisotropy()) : 1;
314
- if (mipmaps) await generateAtlasMips(renderer, texture);
284
+ if (mipmaps) await generateAtlasMips(renderer, atlas.texture);
315
285
  } catch (error) {
316
- dispose();
286
+ atlas.dispose();
317
287
  throw error;
318
288
  }
319
- const { shapeTop } = raster;
320
- return {
321
- ...shapeTop === void 0 ? {} : { shapeTop },
322
- texture,
323
- width,
324
- height,
325
- pxRange: raster.pxRange,
326
- bakeSize: raster.bakeSize,
327
- glyphs: raster.glyphs,
328
- mode: "gpu",
329
- dispose
330
- };
289
+ return atlas;
331
290
  }
332
291
  export { atlasDevice, buildGpuSdfAtlas, encodeGpuSdf, generateAtlasMips, prepareAtlasPasses };
333
292
 
@@ -1 +1 @@
1
- {"version":3,"file":"gpuAtlas.js","names":[],"sources":["../../src/atlas/gpuAtlas.ts"],"sourcesContent":["import {\n ExternalTexture,\n LinearFilter,\n LinearMipmapLinearFilter,\n NoColorSpace,\n RedFormat,\n WebGPUBackend,\n type Texture,\n type WebGPURenderer,\n} from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport { JFA_WGSL } from './jfaWgsl.js'\nimport type { ShapeRows } from './rasterize.js'\n\n// 8×8 = 64 invocations fits the compatibility-mode default of 128 as well as the core 256.\n// Every invocation reads its neighbours from one buffer and writes only its own texel to\n// another, so the workgroup shape changes scheduling, never a byte of the atlas.\nconst COMPUTE_WORKGROUP_DIMENSION = 8\n// The seed kernel reads the raster words and writes seeds; the jump kernel binds a read-only\n// input and a writable output. The resolve pass reads only the final seeds (with the inside\n// bit carried in the sign of seed.x) in its fragment stage.\nconst COMPUTE_STORAGE_BUFFERS = 2\nconst FRAGMENT_STORAGE_BUFFERS = 1\n\ninterface AtlasDeviceLimits {\n readonly maxStorageBufferBindingSize: number\n readonly maxBufferSize: number\n readonly maxComputeInvocationsPerWorkgroup?: number\n readonly maxComputeWorkgroupSizeX?: number\n readonly maxComputeWorkgroupSizeY?: number\n readonly maxStorageBuffersPerShaderStage?: number\n readonly maxStorageBuffersInFragmentStage?: number\n readonly maxTextureDimension2D?: number\n}\n\ntype AtlasErrorFilter = 'validation' | 'out-of-memory' | 'internal'\n\n/** @internal The WebGPU texture calls the atlas makes (no `@webgpu/types` needed). */\nexport interface AtlasGpuTexture {\n readonly mipLevelCount: number\n createView(descriptor?: { baseMipLevel?: number; mipLevelCount?: number }): unknown\n destroy(): void\n}\n\ninterface AtlasGpuBuffer {\n destroy(): void\n}\n\ninterface AtlasPipeline {\n getBindGroupLayout(index: number): unknown\n}\n\ninterface AtlasPass {\n setPipeline(pipeline: AtlasPipeline): void\n setBindGroup(index: number, bindGroup: unknown): void\n end(): void\n}\n\n/** @internal One command encoder of the atlas passes, which a patch adds its copies to. */\nexport interface AtlasEncoder {\n copyTextureToBuffer(\n source: { texture: AtlasGpuTexture },\n destination: { buffer: AtlasGpuBuffer; bytesPerRow: number; rowsPerImage: number },\n size: [number, number],\n ): void\n copyTextureToTexture(\n source: { texture: AtlasGpuTexture; origin: [number, number] },\n destination: { texture: AtlasGpuTexture; origin: [number, number] },\n size: [number, number],\n ): void\n beginComputePass(): AtlasPass & { dispatchWorkgroups(x: number, y: number): void }\n beginRenderPass(descriptor: {\n colorAttachments: { view: unknown; loadOp: 'clear'; storeOp: 'store' }[]\n }): AtlasPass & { draw(vertexCount: number): void }\n finish(): unknown\n}\n\n/** @internal The device calls of the atlas passes, called with the device as `this`. */\nexport interface AtlasDevice {\n readonly limits?: AtlasDeviceLimits\n createTexture(descriptor: {\n size: [number, number]\n mipLevelCount?: number\n format: string\n usage: number\n }): AtlasGpuTexture\n createBuffer(descriptor: { size: number; usage: number }): AtlasGpuBuffer\n createShaderModule(descriptor: { label: string; code: string }): unknown\n createComputePipeline(descriptor: {\n layout: 'auto'\n compute: { module: unknown; entryPoint: string }\n }): AtlasPipeline\n createRenderPipeline(descriptor: {\n layout: 'auto'\n vertex: { module: unknown; entryPoint: string }\n fragment: { module: unknown; entryPoint: string; targets: { format: string }[] }\n }): AtlasPipeline\n createBindGroup(descriptor: {\n layout: unknown\n entries: { binding: number; resource: unknown }[]\n }): unknown\n createCommandEncoder(): AtlasEncoder\n readonly queue: {\n copyExternalImageToTexture(\n source: { source: HTMLCanvasElement; flipY: boolean },\n destination: { texture: AtlasGpuTexture; premultipliedAlpha: boolean },\n size: [number, number],\n ): void\n writeBuffer(buffer: AtlasGpuBuffer, offset: number, data: Int32Array): void\n submit(commandBuffers: unknown[]): void\n }\n readonly pushErrorScope?: (filter: AtlasErrorFilter) => void\n readonly popErrorScope?: () => Promise<{ readonly message?: string } | null>\n}\n\ninterface UsageFlags {\n GPUBufferUsage?: { STORAGE: number; UNIFORM: number; COPY_DST: number }\n GPUTextureUsage?: {\n COPY_SRC: number\n COPY_DST: number\n TEXTURE_BINDING: number\n RENDER_ATTACHMENT: number\n }\n}\n\nconst KERNEL_NEEDS = [\n ['maxComputeInvocationsPerWorkgroup', COMPUTE_WORKGROUP_DIMENSION ** 2],\n ['maxComputeWorkgroupSizeX', COMPUTE_WORKGROUP_DIMENSION],\n ['maxComputeWorkgroupSizeY', COMPUTE_WORKGROUP_DIMENSION],\n ['maxStorageBuffersPerShaderStage', COMPUTE_STORAGE_BUFFERS],\n ['maxStorageBuffersInFragmentStage', FRAGMENT_STORAGE_BUFFERS],\n] as const satisfies readonly (readonly [keyof AtlasDeviceLimits, number])[]\n\n/** A texture-to-buffer copy aligns each row to 256 bytes; the raster keeps 4 bytes a texel. */\nfunction rasterRowBytes(width: number): number {\n return Math.ceil(width / 64) * 256\n}\n\n/**\n * Past a device limit the passes are invalid, which WebGPU reports only asynchronously:\n * checking first lets `auto` fall back without GPU work and `gpu` fail with a reason.\n */\nfunction checkAtlasLimits(limits: AtlasDeviceLimits, width: number, height: number): void {\n for (const [name, need] of KERNEL_NEEDS) {\n const value = limits[name]\n // A browser that predates a limit does not report it, and then has nothing to check.\n if (value !== undefined && value < need) {\n throw new RangeError(`buildGpuSdfAtlas: ${name}=${value}, needs ${need}; use atlasMode \"cpu\"`)\n }\n }\n const largest = limits.maxTextureDimension2D\n if (largest !== undefined && Math.max(width, height) > largest) {\n throw new RangeError(\n `buildGpuSdfAtlas: ${width}×${height} exceeds maxTextureDimension2D=${largest}; lower maxAtlasSize`,\n )\n }\n // Each ping-pong seed buffer holds one vec2<f32> per texel and is bound whole, as is the\n // raster copy, whose rows are padded to 256 bytes (more than the seeds below 64 texels wide).\n const bytes = Math.max(width * height * 8, rasterRowBytes(width) * height)\n if (bytes > limits.maxStorageBufferBindingSize || bytes > limits.maxBufferSize) {\n throw new RangeError(\n `buildGpuSdfAtlas: ${width}×${height} exceeds storage-buffer limits; use atlasMode \"cpu\" or lower maxAtlasSize`,\n )\n }\n}\n\nconst ERROR_FILTERS: readonly AtlasErrorFilter[] = ['validation', 'out-of-memory', 'internal']\n\n/**\n * Captures what the device reports about the calls made until `close()`. Without a scope an\n * invalid pass would surface only as a console warning, and the atlas would come back blank\n * or wrong while `auto` saw nothing to fall back from. `close()` pops synchronously, so\n * concurrent builds cannot interleave scopes, and never rejects.\n */\nfunction openErrorScopes(device: AtlasDevice): { close(): Promise<string | null> } {\n const push = device.pushErrorScope\n const pop = device.popErrorScope\n if (!push || !pop) {\n return { close: () => Promise.resolve(null) }\n }\n for (const filter of ERROR_FILTERS) push.call(device, filter)\n return {\n close() {\n return Promise.all(ERROR_FILTERS.map(() => pop.call(device))).then(\n (errors) => {\n const error = errors.find(Boolean)\n return error ? (error.message ?? 'unknown GPU error') : null\n },\n (error: unknown) => String(error),\n )\n },\n }\n}\n\n/**\n * The jump-flood ladder only has to reach as far as the encoding can represent.\n *\n * A byte stores `0.5 - signedDistance / pxRange`, so everything beyond\n * `pxRange / 2` pixels from an edge saturates to 0 or 1 no matter what distance\n * the field holds there. A ladder `S, S/2, … 1` propagates at most `2S - 1`\n * pixels per axis, so the smallest sufficient first step is `(radius + 1) / 2`\n * rounded up to a power of two.\n *\n * Sizing the ladder from `pxRange` instead of the atlas extent is what keeps this\n * at three or four passes rather than one per octave of the atlas: at 2048² and\n * the default padding that is 4 passes instead of 12.\n */\nfunction jfaSteps(pxRange: number): number[] {\n const radius = Math.ceil(pxRange * 0.5) + 1\n let step = 1\n while (step * 2 - 1 < radius) step <<= 1\n const steps: number[] = []\n for (; step >= 1; step >>= 1) steps.push(step)\n return steps\n}\n\ninterface AtlasPipelines {\n readonly seed: AtlasPipeline\n readonly jump: AtlasPipeline\n readonly resolve: AtlasPipeline\n}\n\n/**\n * One shader module and pipeline set per device, made on its first atlas and kept for its\n * lifetime: a few native objects, while the buffers of a build live only through its\n * submission. Writing the passes in WGSL spares every page three's node graph build of\n * three passes on its first atlas, and every later build and patch the rebuild of their\n * graphs (about 15 and 3 ms on an M3 Max).\n */\nconst devicePipelines = new WeakMap<AtlasDevice, AtlasPipelines>()\n\nfunction atlasPipelines(device: AtlasDevice): AtlasPipelines {\n let pipelines = devicePipelines.get(device)\n if (!pipelines) {\n const module = device.createShaderModule({ label: 'ultra-text atlas', code: JFA_WGSL })\n const compute = (entryPoint: string): AtlasPipeline =>\n device.createComputePipeline({ layout: 'auto', compute: { module, entryPoint } })\n pipelines = {\n seed: compute('seedMain'),\n jump: compute('jumpMain'),\n resolve: device.createRenderPipeline({\n layout: 'auto',\n vertex: { module, entryPoint: 'fullscreenVert' },\n fragment: { module, entryPoint: 'resolveFrag', targets: [{ format: 'r8unorm' }] },\n }),\n }\n devicePipelines.set(device, pipelines)\n }\n return pipelines\n}\n\n/**\n * @internal Starts the native compile of the device's atlas passes ahead of its first atlas,\n * while the caller reads the DOM: the device compiles them meanwhile (about 2.5 ms on an M3 Max\n * with a warm shader cache), and the atlas then waits for its own work only. Making them\n * cannot throw; a device that rejects them fails the first atlas's submission instead, in its\n * error scopes, and that build makes them again.\n */\nexport function prepareAtlasPasses(renderer: WebGPURenderer): void {\n const device = atlasDevice(renderer)\n if (device?.createShaderModule && !devicePipelines.has(device)) {\n atlasPipelines(device)\n device.queue.submit([])\n }\n}\n\n/**\n * @internal Regenerates the mips of an atlas texture from its level 0 with three's own mip\n * pass, as three does for a render target, after the submissions that wrote it.\n */\nexport async function generateAtlasMips(renderer: WebGPURenderer, texture: Texture): Promise<void> {\n const scopes = openErrorScopes(atlasDevice(renderer)!)\n let reported: Promise<string | null>\n try {\n renderer.initTexture(texture)\n ;(renderer.backend as unknown as { generateMipmaps(texture: Texture): void }).generateMipmaps(\n texture,\n )\n } finally {\n reported = scopes.close()\n }\n const rejection = await reported\n if (rejection !== null) throw new Error(`buildGpuSdfAtlas: mip generation failed: ${rejection}`)\n}\n\n/** @internal The device behind a WebGPU-backend renderer, or `undefined`. */\nexport function atlasDevice(renderer: WebGPURenderer): AtlasDevice | undefined {\n return (renderer.backend as unknown as { device?: AtlasDevice }).device\n}\n\n/**\n * @internal Runs the atlas passes over `raster` into level 0 of a new r8unorm texture of\n * `mipLevelCount` levels, all in one command buffer: the canvas is uploaded and copied into a storage buffer\n * of 256-byte rows, the seeds are found and flooded in two ping-pong buffers, and the resolve\n * pass encodes the distances. `finish` may add commands that use the texture before it is\n * submitted, as a patch does. Resolves with the texture once the device has accepted every\n * call; rejects, holding nothing, when the device's limits cannot hold the passes, lacks\n * these calls or reports an error for them. The buffers and the upload live only through the\n * submission: destroying them waits for the submitted work.\n */\nexport async function encodeGpuSdf(\n device: AtlasDevice | undefined,\n raster: Pick<RasterAtlas, 'canvas' | 'width' | 'height' | 'pxRange'>,\n mipLevelCount: number,\n finish?: (encoder: AtlasEncoder, texture: AtlasGpuTexture) => void,\n): Promise<AtlasGpuTexture> {\n const { width, height, pxRange } = raster\n const { GPUBufferUsage: buffers, GPUTextureUsage: textures } = globalThis as UsageFlags\n if (!device?.createCommandEncoder || !buffers || !textures)\n throw new Error('buildGpuSdfAtlas: device cannot run the atlas passes')\n if (device.limits) checkAtlasLimits(device.limits, width, height)\n const transient: { destroy(): void }[] = []\n let output: AtlasGpuTexture | undefined\n try {\n const scopes = openErrorScopes(device)\n let reported: Promise<string | null>\n try {\n const pipelines = atlasPipelines(device)\n const steps = jfaSteps(pxRange)\n const rowBytes = rasterRowBytes(width)\n const buffer = (size: number, usage: number): AtlasGpuBuffer => {\n const created = device.createBuffer({ size, usage })\n transient.push(created)\n return created\n }\n const upload = device.createTexture({\n size: [width, height],\n format: 'rgba8unorm',\n usage: textures.COPY_SRC | textures.COPY_DST | textures.RENDER_ATTACHMENT,\n })\n transient.push(upload)\n const words = buffer(rowBytes * height, buffers.STORAGE | buffers.COPY_DST)\n const seeds = [\n buffer(width * height * 8, buffers.STORAGE),\n buffer(width * height * 8, buffers.STORAGE),\n ]\n // Uniform slots 256 bytes apart: the seed and resolve parameters, then one per step.\n const params = buffer(steps.length * 256 + 16, buffers.UNIFORM | buffers.COPY_DST)\n const values = new Int32Array(steps.length * 64 + 4)\n values.set([width, height, rowBytes / 4])\n new Float32Array(values.buffer, 12, 1)[0] = 1 / pxRange\n steps.forEach((step, index) => values.set([width, height, step], (index + 1) * 64))\n device.queue.writeBuffer(params, 0, values)\n // Exactly as three uploads a CanvasTexture: rgba8unorm, no flip, straight alpha.\n device.queue.copyExternalImageToTexture(\n { source: raster.canvas, flipY: false },\n { texture: upload, premultipliedAlpha: false },\n [width, height],\n )\n output = device.createTexture({\n size: [width, height],\n mipLevelCount,\n format: 'r8unorm',\n usage:\n textures.RENDER_ATTACHMENT |\n textures.TEXTURE_BINDING |\n textures.COPY_SRC |\n textures.COPY_DST,\n })\n const bind = (\n pipeline: AtlasPipeline,\n offset: number,\n ...storageBuffers: AtlasGpuBuffer[]\n ): unknown =>\n device.createBindGroup({\n layout: pipeline.getBindGroupLayout(0),\n entries: [\n { binding: 0, resource: { buffer: params, offset, size: 16 } },\n ...storageBuffers.map((resource, index) => ({\n binding: index + 1,\n resource: { buffer: resource },\n })),\n ],\n })\n const encoder = device.createCommandEncoder()\n encoder.copyTextureToBuffer(\n { texture: upload },\n { buffer: words, bytesPerRow: rowBytes, rowsPerImage: height },\n [width, height],\n )\n const groupsX = Math.ceil(width / COMPUTE_WORKGROUP_DIMENSION)\n const groupsY = Math.ceil(height / COMPUTE_WORKGROUP_DIMENSION)\n const flood = encoder.beginComputePass()\n flood.setPipeline(pipelines.seed)\n flood.setBindGroup(0, bind(pipelines.seed, 0, words, seeds[0]!))\n flood.dispatchWorkgroups(groupsX, groupsY)\n flood.setPipeline(pipelines.jump)\n steps.forEach((_, index) => {\n const into = seeds[(index + 1) % 2]!\n flood.setBindGroup(0, bind(pipelines.jump, (index + 1) * 256, seeds[index % 2]!, into))\n flood.dispatchWorkgroups(groupsX, groupsY)\n })\n flood.end()\n // The full-screen triangle writes every texel of level 0.\n const resolve = encoder.beginRenderPass({\n colorAttachments: [\n { view: output.createView({ mipLevelCount: 1 }), loadOp: 'clear', storeOp: 'store' },\n ],\n })\n resolve.setPipeline(pipelines.resolve)\n resolve.setBindGroup(0, bind(pipelines.resolve, 0, seeds[steps.length % 2]!))\n resolve.draw(3)\n resolve.end()\n finish?.(encoder, output)\n device.queue.submit([encoder.finish()])\n } finally {\n reported = scopes.close()\n }\n const rejection = await reported\n if (rejection !== null) {\n // A later build makes its pipelines again rather than reusing ones the device rejected.\n devicePipelines.delete(device)\n throw new Error(`buildGpuSdfAtlas: the device rejected the atlas passes: ${rejection}`)\n }\n const retained = output\n output = undefined\n return retained\n } finally {\n for (const resource of transient) resource.destroy()\n output?.destroy()\n }\n}\n\n/**\n * Generates a compact R8 runtime SDF on the renderer's WebGPU device: boundary seeding and a\n * storage-buffer jump flood in compute passes, then a resolve render pass (`JFA_WGSL`). The\n * texture is an `ExternalTexture` the atlas owns, with three's mips when `mipmaps`. It\n * rejects, instead of returning a blank or wrong atlas, when the device's limits cannot hold\n * the passes, the backend lacks the calls, or the device reports an error for them.\n */\nexport async function buildGpuSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: Pick<BuildSdfAtlasOptions, 'mipmaps' | 'anisotropy'> = {},\n): Promise<SdfAtlas> {\n await renderer.init()\n if (!(renderer.backend instanceof WebGPUBackend)) {\n throw new Error('buildGpuSdfAtlas: requires the WebGPU backend; use mode \"cpu\"')\n }\n const { width, height } = raster\n const mipmaps = options.mipmaps === true\n // three's full mip chain when `mipmaps`.\n const levels = mipmaps ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1\n const gpuTexture = await encodeGpuSdf(atlasDevice(renderer), raster, levels)\n const texture = new ExternalTexture(gpuTexture)\n let disposed = false\n const dispose = (): void => {\n if (disposed) return\n disposed = true\n // three never destroys an external texture's GPU texture: its owner does.\n try {\n texture.dispose()\n } finally {\n gpuTexture.destroy()\n }\n }\n try {\n // three sizes the texture's memory from its image.\n ;(texture as { image: unknown }).image = { width, height }\n texture.name = 'ultra-text SDF atlas'\n texture.format = RedFormat\n texture.colorSpace = NoColorSpace\n // Read by the material, which keeps whole quads over mipmaps; three never generates an\n // external texture's mips itself (`generateAtlasMips` does).\n texture.generateMipmaps = mipmaps\n texture.minFilter = mipmaps ? LinearMipmapLinearFilter : LinearFilter\n texture.magFilter = LinearFilter\n texture.anisotropy = mipmaps\n ? Math.min(Math.max(1, options.anisotropy ?? 1), renderer.getMaxAnisotropy())\n : 1\n if (mipmaps) await generateAtlasMips(renderer, texture)\n } catch (error) {\n dispose()\n throw error\n }\n const { shapeTop } = raster as RasterAtlas & ShapeRows\n return {\n ...(shapeTop === undefined ? {} : { shapeTop }),\n texture,\n width,\n height,\n pxRange: raster.pxRange,\n bakeSize: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AAS,mBAAmB,gBAChC,MAAM,IAAI,MAAM,iEAA+D;CAEjF,MAAM,EAAE,OAAO,WAAW;CAC1B,MAAM,UAAU,QAAQ,YAAY;CAEpC,MAAM,SAAS,UAAU,KAAK,MAAM,KAAK,KAAK,KAAK,IAAI,OAAO,MAAM,CAAC,CAAC,IAAI,IAAI;CAC9E,MAAM,aAAa,MAAM,aAAa,YAAY,QAAQ,GAAG,QAAQ,MAAM;CAC3E,MAAM,UAAU,IAAI,gBAAgB,UAAU;CAC9C,IAAI,WAAW;CACf,MAAM,gBAAsB;EAC1B,IAAI,UAAU;EACd,WAAW;EAEX,IAAI;GACF,QAAQ,QAAQ;EAClB,UAAU;GACR,WAAW,QAAQ;EACrB;CACF;CACA,IAAI;EAED,QAAgC,QAAQ;GAAE;GAAO;EAAO;EACzD,QAAQ,OAAO;EACf,QAAQ,SAAS;EACjB,QAAQ,aAAa;EAGrB,QAAQ,kBAAkB;EAC1B,QAAQ,YAAY,UAAU,2BAA2B;EACzD,QAAQ,YAAY;EACpB,QAAQ,aAAa,UACjB,KAAK,IAAI,KAAK,IAAI,GAAG,QAAQ,cAAc,CAAC,GAAG,SAAS,iBAAiB,CAAC,IAC1E;EACJ,IAAI,SAAS,MAAM,kBAAkB,UAAU,OAAO;CACxD,SAAS,OAAO;EACd,QAAQ;EACR,MAAM;CACR;CACA,MAAM,EAAE,aAAa;CACrB,OAAO;EACL,GAAI,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS;EAC7C;EACA;EACA;EACA,SAAS,OAAO;EAChB,UAAU,OAAO;EACjB,QAAQ,OAAO;EACf,MAAM;EACN;CACF;AACF"}
1
+ {"version":3,"file":"gpuAtlas.js","names":["hasDirectStoreFeature"],"sources":["../../src/atlas/gpuAtlas.ts"],"sourcesContent":["import {\n ExternalTexture,\n LinearFilter,\n LinearMipmapLinearFilter,\n NoColorSpace,\n RedFormat,\n WebGPUBackend,\n type Texture,\n type WebGPURenderer,\n} from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport {\n checkCommonAtlasLimits,\n encodeJfaWork,\n jfaSteps,\n openErrorScopes,\n prefersTiledJfa,\n selectWorkgroupDimension,\n supportsDirectStore as hasDirectStoreFeature,\n type AtlasDeviceLimitsLike,\n type AtlasErrorFilter,\n type CommonJfaPipelines,\n type UsageGlobals,\n} from './gpuCommon.js'\nimport { buildJfaWgsl } from './jfaWgsl.js'\nimport type { ShapeRows } from './rasterize.js'\n\ntype AtlasDeviceLimits = AtlasDeviceLimitsLike & {\n readonly maxStorageBufferBindingSize: number\n readonly maxBufferSize: number\n}\n\n/** @internal The WebGPU texture calls the atlas makes (no `@webgpu/types` needed). */\nexport interface AtlasGpuTexture {\n readonly mipLevelCount: number\n createView(descriptor?: { baseMipLevel?: number; mipLevelCount?: number }): unknown\n destroy(): void\n}\n\ninterface AtlasGpuBuffer {\n destroy(): void\n}\n\ninterface AtlasPipeline {\n getBindGroupLayout(index: number): unknown\n}\n\ninterface AtlasPass {\n setPipeline(pipeline: AtlasPipeline): void\n setBindGroup(index: number, bindGroup: unknown): void\n end(): void\n}\n\n/** @internal One command encoder of the atlas passes, which a patch adds its copies to. */\nexport interface AtlasEncoder {\n copyTextureToBuffer(\n source: { texture: AtlasGpuTexture },\n destination: { buffer: AtlasGpuBuffer; bytesPerRow: number; rowsPerImage: number },\n size: [number, number],\n ): void\n copyTextureToTexture(\n source: { texture: AtlasGpuTexture; origin: [number, number] },\n destination: { texture: AtlasGpuTexture; origin: [number, number] },\n size: [number, number],\n ): void\n beginComputePass(): AtlasPass & { dispatchWorkgroups(x: number, y: number): void }\n beginRenderPass(descriptor: {\n colorAttachments: { view: unknown; loadOp: 'clear'; storeOp: 'store' }[]\n }): AtlasPass & { draw(vertexCount: number): void }\n finish(): unknown\n}\n\n/** @internal The device calls of the atlas passes, called with the device as `this`. */\nexport interface AtlasDevice {\n readonly features?: { has(name: string): boolean }\n readonly limits?: AtlasDeviceLimits\n createTexture(descriptor: {\n size: [number, number]\n mipLevelCount?: number\n format: string\n usage: number\n }): AtlasGpuTexture\n createBuffer(descriptor: { size: number; usage: number }): AtlasGpuBuffer\n createShaderModule(descriptor: { label: string; code: string }): unknown\n createComputePipeline(descriptor: {\n layout: 'auto'\n compute: { module: unknown; entryPoint: string }\n }): AtlasPipeline\n readonly createComputePipelineAsync?: (descriptor: {\n layout: 'auto'\n compute: { module: unknown; entryPoint: string }\n }) => Promise<AtlasPipeline>\n createRenderPipeline(descriptor: {\n layout: 'auto'\n vertex: { module: unknown; entryPoint: string }\n fragment: { module: unknown; entryPoint: string; targets: { format: string }[] }\n }): AtlasPipeline\n readonly createRenderPipelineAsync?: (descriptor: {\n layout: 'auto'\n vertex: { module: unknown; entryPoint: string }\n fragment: { module: unknown; entryPoint: string; targets: { format: string }[] }\n }) => Promise<AtlasPipeline>\n createBindGroup(descriptor: {\n layout: unknown\n entries: { binding: number; resource: unknown }[]\n }): unknown\n createCommandEncoder(): AtlasEncoder\n readonly queue: {\n copyExternalImageToTexture(\n source: { source: HTMLCanvasElement; flipY: boolean },\n destination: { texture: AtlasGpuTexture; premultipliedAlpha: boolean },\n size: [number, number],\n ): void\n writeBuffer(buffer: AtlasGpuBuffer, offset: number, data: Int32Array): void\n submit(commandBuffers: unknown[]): void\n }\n readonly pushErrorScope?: (filter: AtlasErrorFilter) => void\n readonly popErrorScope?: () => Promise<{ readonly message?: string } | null>\n}\n\ntype AtlasPipelines = CommonJfaPipelines<AtlasPipeline, AtlasPipeline>\n\ninterface MultiPassPipelines {\n readonly seed: AtlasPipeline\n readonly jump: AtlasPipeline\n readonly jumpStore: AtlasPipeline | null\n readonly resolve: AtlasPipeline | null\n}\n\ninterface DevicePipelineCache {\n readonly workgroupDim: 8 | 16\n readonly directStore: boolean\n readonly module: unknown\n tiledStore?: AtlasPipeline\n tiledPromise?: Promise<AtlasPipelines> | undefined\n multi?: MultiPassPipelines\n multiPromise?: Promise<AtlasPipelines> | undefined\n}\n\nconst devicePipelines = new WeakMap<AtlasDevice, DevicePipelineCache>()\n\nfunction asAtlasPipelines(\n workgroupDim: 8 | 16,\n directStore: boolean,\n tiledStore: AtlasPipeline | null,\n multi?: MultiPassPipelines,\n): AtlasPipelines {\n return {\n workgroupDim,\n directStore,\n seed: multi?.seed ?? null,\n jump: multi?.jump ?? null,\n jumpStore: multi?.jumpStore ?? null,\n tiledStore,\n resolve: multi?.resolve ?? null,\n }\n}\n\nfunction getDeviceCache(\n device: AtlasDevice,\n workgroupDim: 8 | 16,\n directStore: boolean,\n): DevicePipelineCache {\n const existing = devicePipelines.get(device)\n if (existing?.workgroupDim === workgroupDim && existing.directStore === directStore) {\n return existing\n }\n const cache: DevicePipelineCache = {\n workgroupDim,\n directStore,\n module: device.createShaderModule({\n label: 'ultra-text atlas',\n code: buildJfaWgsl(workgroupDim, directStore),\n }),\n }\n devicePipelines.set(device, cache)\n return cache\n}\n\nfunction cachedAtlasPipelines(\n device: AtlasDevice,\n workgroupDim: 8 | 16,\n directStore: boolean,\n tiledOnly: boolean,\n): AtlasPipelines | undefined {\n const cache = devicePipelines.get(device)\n if (cache?.workgroupDim !== workgroupDim || cache.directStore !== directStore) return undefined\n if (tiledOnly) {\n return cache.tiledStore\n ? asAtlasPipelines(workgroupDim, directStore, cache.tiledStore)\n : undefined\n }\n return cache.multi ? asAtlasPipelines(workgroupDim, directStore, null, cache.multi) : undefined\n}\n\nfunction supportsAsyncAtlasPipelines(device: AtlasDevice, directStore: boolean): boolean {\n return (\n typeof device.createComputePipelineAsync === 'function' &&\n (directStore || typeof device.createRenderPipelineAsync === 'function')\n )\n}\n\nfunction buildAtlasPipelines(\n device: AtlasDevice,\n workgroupDim: 8 | 16,\n directStore: boolean,\n tiledOnly: boolean,\n async: true,\n): Promise<AtlasPipelines>\nfunction buildAtlasPipelines(\n device: AtlasDevice,\n workgroupDim: 8 | 16,\n directStore: boolean,\n tiledOnly: boolean,\n async: false,\n): AtlasPipelines\nfunction buildAtlasPipelines(\n device: AtlasDevice,\n workgroupDim: 8 | 16,\n directStore: boolean,\n tiledOnly: boolean,\n async: boolean,\n): AtlasPipelines | Promise<AtlasPipelines> {\n const cached = cachedAtlasPipelines(device, workgroupDim, directStore, tiledOnly)\n if (cached) return async ? Promise.resolve(cached) : cached\n\n const existing = devicePipelines.get(device)\n const sameConfig = existing?.workgroupDim === workgroupDim && existing.directStore === directStore\n if (async && sameConfig) {\n const inFlight = tiledOnly ? existing.tiledPromise : existing.multiPromise\n if (inFlight) return inFlight\n }\n\n const cache = getDeviceCache(device, workgroupDim, directStore)\n const module = cache.module\n const computeSync = (entryPoint: string) =>\n device.createComputePipeline({ layout: 'auto', compute: { module, entryPoint } })\n const computeAsync = (entryPoint: string) =>\n device.createComputePipelineAsync!({ layout: 'auto', compute: { module, entryPoint } })\n\n if (tiledOnly) {\n const store = (tiledStore: AtlasPipeline): AtlasPipelines => {\n cache.tiledStore = tiledStore\n return asAtlasPipelines(workgroupDim, directStore, tiledStore)\n }\n if (!async) return store(computeSync('tiledStoreMain'))\n const promise = computeAsync('tiledStoreMain').then(\n (tiledStore) => store(tiledStore),\n (error: unknown) => {\n if (cache.tiledPromise === promise) cache.tiledPromise = undefined\n throw error\n },\n )\n cache.tiledPromise = promise\n return promise\n }\n\n const resolveDesc = {\n layout: 'auto' as const,\n vertex: { module, entryPoint: 'fullscreenVert' },\n fragment: { module, entryPoint: 'resolveFrag', targets: [{ format: 'r8unorm' }] },\n }\n const store = (\n seed: AtlasPipeline,\n jump: AtlasPipeline,\n jumpStore: AtlasPipeline | null,\n resolve: AtlasPipeline | null,\n ): AtlasPipelines => {\n const multi: MultiPassPipelines = { seed, jump, jumpStore, resolve }\n cache.multi = multi\n return asAtlasPipelines(workgroupDim, directStore, null, multi)\n }\n\n if (!async) {\n return store(\n computeSync('seedMain'),\n computeSync('jumpMain'),\n directStore ? computeSync('jumpStoreMain') : null,\n directStore ? null : device.createRenderPipeline(resolveDesc),\n )\n }\n\n const promise = Promise.all([\n computeAsync('seedMain'),\n computeAsync('jumpMain'),\n directStore ? computeAsync('jumpStoreMain') : Promise.resolve(null),\n directStore ? Promise.resolve(null) : device.createRenderPipelineAsync!(resolveDesc),\n ]).then(\n ([seed, jump, jumpStore, resolve]) => store(seed, jump, jumpStore, resolve),\n (error: unknown) => {\n if (cache.multiPromise === promise) cache.multiPromise = undefined\n throw error\n },\n )\n cache.multiPromise = promise\n return promise\n}\n\n/**\n * @internal Starts the native compile of the device's atlas passes ahead of its first atlas,\n * while the caller reads the DOM.\n */\nexport function prepareAtlasPasses(renderer: WebGPURenderer, pxRange?: number): void {\n const device = atlasDevice(renderer)\n if (!device?.createShaderModule) return\n const directStore = hasDirectStoreFeature(device.features)\n const workgroupDim = selectWorkgroupDimension(device.limits)\n const tiledOnly = prefersTiledJfa(directStore, pxRange)\n const cached = devicePipelines.get(device)\n const matches = cached?.workgroupDim === workgroupDim && cached.directStore === directStore\n if (\n matches &&\n (tiledOnly ? cached.tiledStore || cached.tiledPromise : cached.multi || cached.multiPromise)\n ) {\n return\n }\n if (supportsAsyncAtlasPipelines(device, directStore)) {\n void buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, true).catch(\n () => undefined,\n )\n } else {\n buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, false)\n }\n device.queue.submit([])\n}\n\n/**\n * @internal Regenerates the mips of an atlas texture from its level 0 with three's own mip\n * pass, as three does for a render target, after the submissions that wrote it.\n */\nexport async function generateAtlasMips(renderer: WebGPURenderer, texture: Texture): Promise<void> {\n const scopes = openErrorScopes(atlasDevice(renderer)!)\n let reported: Promise<string | null>\n try {\n renderer.initTexture(texture)\n ;(renderer.backend as unknown as { generateMipmaps(texture: Texture): void }).generateMipmaps(\n texture,\n )\n } finally {\n reported = scopes.close()\n }\n const rejection = await reported\n if (rejection !== null) throw new Error(`buildGpuSdfAtlas: mip generation failed: ${rejection}`)\n}\n\n/** @internal The device behind a WebGPU-backend renderer, or `undefined`. */\nexport function atlasDevice(renderer: WebGPURenderer): AtlasDevice | undefined {\n return (renderer.backend as unknown as { device?: AtlasDevice }).device\n}\n\n/**\n * @internal Runs the atlas passes over `raster` into level 0 of a new r8unorm texture of\n * `mipLevelCount` levels, all in one command buffer.\n */\nexport async function encodeGpuSdf(\n device: AtlasDevice | undefined,\n raster: Pick<RasterAtlas, 'canvas' | 'width' | 'height' | 'pxRange'>,\n mipLevelCount: number,\n finish?: (encoder: AtlasEncoder, texture: AtlasGpuTexture) => void,\n onSubmitted?: (texture: AtlasGpuTexture) => void,\n): Promise<AtlasGpuTexture> {\n const { width, height, pxRange, canvas } = raster\n const { GPUBufferUsage: buffers, GPUTextureUsage: textures } = globalThis as UsageGlobals\n if (!device?.createCommandEncoder || !buffers || !textures)\n throw new Error('buildGpuSdfAtlas: device cannot run the atlas passes')\n const steps = jfaSteps(pxRange)\n const directStore = hasDirectStoreFeature(device.features)\n checkCommonAtlasLimits(\n 'buildGpuSdfAtlas',\n device.limits,\n width,\n height,\n steps[0]!,\n directStore,\n '; use atlasMode \"cpu\"',\n )\n const workgroupDim = selectWorkgroupDimension(device.limits)\n const tiledOnly = directStore && steps[0] === 4\n let prebuilt = cachedAtlasPipelines(device, workgroupDim, directStore, tiledOnly)\n if (!prebuilt && supportsAsyncAtlasPipelines(device, directStore)) {\n try {\n prebuilt = await buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, true)\n } catch (error: unknown) {\n throw new Error(\n `buildGpuSdfAtlas: the device rejected the atlas passes: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n )\n }\n }\n const transient: { destroy(): void }[] = []\n let output: AtlasGpuTexture | undefined\n try {\n const scopes = openErrorScopes(device)\n let reported: Promise<string | null>\n try {\n const pipelines =\n prebuilt ?? buildAtlasPipelines(device, workgroupDim, directStore, tiledOnly, false)\n output = device.createTexture({\n size: [width, height],\n mipLevelCount,\n format: 'r8unorm',\n usage:\n textures.RENDER_ATTACHMENT |\n textures.TEXTURE_BINDING |\n textures.COPY_SRC |\n textures.COPY_DST |\n (pipelines.directStore ? (textures.STORAGE_BINDING ?? 0) : 0),\n })\n const encoder = device.createCommandEncoder()\n encodeJfaWork(\n device,\n encoder,\n pipelines,\n canvas,\n width,\n height,\n pxRange,\n steps,\n output,\n transient,\n buffers,\n textures,\n )\n finish?.(encoder, output)\n device.queue.submit([encoder.finish()])\n } finally {\n reported = scopes.close()\n }\n onSubmitted?.(output)\n const rejection = await reported\n if (rejection !== null) {\n devicePipelines.delete(device)\n throw new Error(`buildGpuSdfAtlas: the device rejected the atlas passes: ${rejection}`)\n }\n const retained = output\n output = undefined\n return retained\n } finally {\n for (const resource of transient) resource.destroy()\n output?.destroy()\n }\n}\n\n/**\n * Generates a compact R8 runtime SDF on the renderer's WebGPU device: boundary seeding and\n * 4-byte relative fixed-point jump flooding in compute passes, writing directly into `r8unorm`\n * when `'texture-formats-tier1'` is active on the device or resolving via a fullscreen render\n * pass on Core WebGPU 1.0 devices.\n */\nexport async function buildGpuSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: Pick<BuildSdfAtlasOptions, 'mipmaps' | 'anisotropy'> = {},\n /** @internal */\n onProvisional?: (atlas: SdfAtlas) => void,\n): Promise<SdfAtlas> {\n await renderer.init()\n if (!(renderer.backend instanceof WebGPUBackend)) {\n throw new Error('buildGpuSdfAtlas: requires the WebGPU backend; use mode \"cpu\"')\n }\n const { width, height } = raster\n const mipmaps = options.mipmaps === true\n const levels = mipmaps ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1\n const { shapeTop } = raster as RasterAtlas & ShapeRows\n const maxAnisotropy = mipmaps ? renderer.getMaxAnisotropy() : 1\n const wrapAtlas = (gpuTexture: AtlasGpuTexture) => {\n const texture = new ExternalTexture(gpuTexture)\n let disposed = false\n let gpuDestroyed = false\n const dispose = (): void => {\n if (disposed) return\n disposed = true\n try {\n texture.dispose()\n } finally {\n if (!gpuDestroyed) {\n gpuDestroyed = true\n gpuTexture.destroy()\n }\n }\n }\n try {\n ;(texture as { image: unknown }).image = { width, height }\n texture.name = 'ultra-text SDF atlas'\n texture.format = RedFormat\n texture.colorSpace = NoColorSpace\n texture.generateMipmaps = mipmaps\n texture.minFilter = mipmaps ? LinearMipmapLinearFilter : LinearFilter\n texture.magFilter = LinearFilter\n texture.anisotropy = mipmaps\n ? Math.min(Math.max(1, options.anisotropy ?? 1), maxAnisotropy)\n : 1\n if (shapeTop !== undefined) texture.userData['ultraShapeTop'] = shapeTop\n } catch (error) {\n dispose()\n throw error\n }\n const atlas: SdfAtlas = {\n ...(shapeTop === undefined ? {} : { shapeTop }),\n texture,\n width,\n height,\n pxRange: raster.pxRange,\n bakeSize: raster.bakeSize,\n glyphs: raster.glyphs,\n mode: 'gpu',\n dispose,\n }\n return {\n atlas,\n markGpuDestroyed: () => {\n gpuDestroyed = true\n },\n }\n }\n\n if (onProvisional && !mipmaps) {\n let wrapped: ReturnType<typeof wrapAtlas> | undefined\n try {\n const gpuTexture = await encodeGpuSdf(\n atlasDevice(renderer),\n raster,\n levels,\n undefined,\n (candidate) => {\n wrapped = wrapAtlas(candidate)\n onProvisional(wrapped.atlas)\n },\n )\n return wrapped ? wrapped.atlas : wrapAtlas(gpuTexture).atlas\n } catch (error) {\n if (wrapped) {\n wrapped.markGpuDestroyed()\n wrapped.atlas.dispose()\n }\n throw error\n }\n }\n\n const gpuTexture = await encodeGpuSdf(atlasDevice(renderer), raster, levels)\n const { atlas } = wrapAtlas(gpuTexture)\n try {\n if (mipmaps) await generateAtlasMips(renderer, atlas.texture)\n } catch (error) {\n atlas.dispose()\n throw error\n }\n return atlas\n}\n"],"mappings":";;;;AA4IA,IAAM,kCAAkB,IAAI,QAA0C;AAEtE,SAAS,iBACP,cACA,aACA,YACA,OACgB;CAChB,OAAO;EACL;EACA;EACA,MAAM,OAAO,QAAQ;EACrB,MAAM,OAAO,QAAQ;EACrB,WAAW,OAAO,aAAa;EAC/B;EACA,SAAS,OAAO,WAAW;CAC7B;AACF;AAEA,SAAS,eACP,QAC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