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.
- package/README.md +267 -962
- package/THIRD_PARTY_NOTICES.md +3 -0
- package/dist/assets/{cpuSdf.worker-Du9o8q4p.js → cpuSdf.worker--X1Qpmdp.js} +148 -57
- package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
- package/dist/atlas/appendAtlas.js +69 -26
- package/dist/atlas/appendAtlas.js.map +1 -1
- package/dist/atlas/buildAtlas.js +5 -15
- package/dist/atlas/buildAtlas.js.map +1 -1
- package/dist/atlas/cpuAtlas.d.ts +4 -1
- package/dist/atlas/cpuAtlas.js +8 -6
- package/dist/atlas/cpuAtlas.js.map +1 -1
- package/dist/atlas/cpuSdf.js +164 -50
- package/dist/atlas/cpuSdf.js.map +1 -1
- package/dist/atlas/cpuWorker.d.ts +5 -3
- package/dist/atlas/cpuWorker.js +119 -12
- package/dist/atlas/cpuWorker.js.map +1 -1
- package/dist/atlas/gpuAtlas.d.ts +7 -6
- package/dist/atlas/gpuAtlas.js +206 -247
- package/dist/atlas/gpuAtlas.js.map +1 -1
- package/dist/atlas/gpuCommon.d.ts +135 -0
- package/dist/atlas/gpuCommon.js +223 -0
- package/dist/atlas/gpuCommon.js.map +1 -0
- package/dist/atlas/jfaWgsl.js +59 -125
- package/dist/atlas/jfaWgsl.js.map +1 -1
- package/dist/atlas/rasterize.d.ts +2 -0
- package/dist/atlas/rasterize.js +104 -144
- package/dist/atlas/rasterize.js.map +1 -1
- package/dist/atlas/shapeRaster.js +2 -1
- package/dist/atlas/shapeRaster.js.map +1 -1
- package/dist/atlas/vanillaBounds.d.ts +64 -0
- package/dist/atlas/vanillaBounds.js +42 -0
- package/dist/atlas/vanillaBounds.js.map +1 -0
- package/dist/atlas/vanillaCore.d.ts +100 -0
- package/dist/atlas/vanillaCore.js +1012 -0
- package/dist/atlas/vanillaCore.js.map +1 -0
- package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
- package/dist/atlas/vanillaCpuAtlas.js +87 -0
- package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
- package/dist/atlas/vanillaExtras.d.ts +8 -0
- package/dist/atlas/vanillaExtras.js +166 -0
- package/dist/atlas/vanillaExtras.js.map +1 -0
- package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
- package/dist/atlas/vanillaGpuHelpers.js +119 -0
- package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
- package/dist/dom/DomSdf.js +263 -272
- package/dist/dom/DomSdf.js.map +1 -1
- package/dist/dom/DomSlug.d.ts +26 -0
- package/dist/dom/DomSlug.js +564 -0
- package/dist/dom/DomSlug.js.map +1 -0
- package/dist/dom/SlugText.d.ts +18 -0
- package/dist/dom/SlugText.js +94 -0
- package/dist/dom/SlugText.js.map +1 -0
- package/dist/dom/Text.js +4 -67
- package/dist/dom/Text.js.map +1 -1
- package/dist/dom/domAnalytic.d.ts +54 -0
- package/dist/dom/domAnalytic.js +282 -0
- package/dist/dom/domAnalytic.js.map +1 -0
- package/dist/dom/domExtras.d.ts +27 -0
- package/dist/dom/domExtras.js +137 -0
- package/dist/dom/domExtras.js.map +1 -0
- package/dist/dom/fontCanvas.d.ts +2 -0
- package/dist/dom/fontCanvas.js +119 -0
- package/dist/dom/fontCanvas.js.map +1 -0
- package/dist/dom/layoutSignature.js +156 -27
- package/dist/dom/layoutSignature.js.map +1 -1
- package/dist/dom/pretextLayout.js +55 -13
- package/dist/dom/pretextLayout.js.map +1 -1
- package/dist/dom/snapshot.js +563 -243
- package/dist/dom/snapshot.js.map +1 -1
- package/dist/dom/svgCapture.d.ts +8 -1
- package/dist/dom/svgCapture.js +75 -1
- package/dist/dom/svgCapture.js.map +1 -1
- package/dist/dom/textHost.d.ts +11 -0
- package/dist/dom/textHost.js +68 -0
- package/dist/dom/textHost.js.map +1 -0
- package/dist/dom/tone.js +76 -36
- package/dist/dom/tone.js.map +1 -1
- package/dist/index.js +4 -3
- package/dist/slug/SlugMaterial.d.ts +13 -4
- package/dist/slug/SlugMaterial.js +82 -12
- package/dist/slug/SlugMaterial.js.map +1 -1
- package/dist/slug/coverage.d.ts +17 -13
- package/dist/slug/coverage.js +195 -222
- package/dist/slug/coverage.js.map +1 -1
- package/dist/slug/preprocessCore.d.ts +6 -3
- package/dist/slug/preprocessCore.js +149 -95
- package/dist/slug/preprocessCore.js.map +1 -1
- package/dist/slug/runtime.d.ts +1 -0
- package/dist/slug/runtime.js +94 -46
- package/dist/slug/runtime.js.map +1 -1
- package/dist/slug/standaloneRuntime.d.ts +40 -0
- package/dist/slug/standaloneRuntime.js +175 -0
- package/dist/slug/standaloneRuntime.js.map +1 -0
- package/dist/slug/truetype.d.ts +22 -0
- package/dist/slug/truetype.js +467 -0
- package/dist/slug/truetype.js.map +1 -0
- package/dist/slug/vanillaCore.d.ts +340 -0
- package/dist/slug/vanillaCore.js +1621 -0
- package/dist/slug/vanillaCore.js.map +1 -0
- package/dist/slug-vanilla.d.ts +13 -0
- package/dist/slug-vanilla.js +13 -0
- package/dist/slug.d.ts +21 -0
- package/dist/slug.js +19 -0
- package/dist/text/GlyphTextMaterial.d.ts +11 -11
- package/dist/text/GlyphTextMaterial.js +102 -33
- package/dist/text/GlyphTextMaterial.js.map +1 -1
- package/dist/text/SdfTextMaterial.d.ts +5 -4
- package/dist/text/SdfTextMaterial.js +29 -9
- package/dist/text/SdfTextMaterial.js.map +1 -1
- package/dist/text/decorations.js +36 -19
- package/dist/text/decorations.js.map +1 -1
- package/dist/text/geometry.d.ts +3 -22
- package/dist/text/geometryUtils.d.ts +11 -1
- package/dist/text/geometryUtils.js +22 -1
- package/dist/text/geometryUtils.js.map +1 -1
- package/dist/text/glyphGeometry.d.ts +9 -0
- package/dist/text/glyphGeometry.js +353 -0
- package/dist/text/glyphGeometry.js.map +1 -0
- package/dist/text/index.d.ts +2 -1
- package/dist/text/rectGeometry.d.ts +13 -0
- package/dist/text/rectGeometry.js +97 -0
- package/dist/text/rectGeometry.js.map +1 -0
- package/dist/text/reflow.d.ts +18 -1
- package/dist/text/reflow.js +108 -38
- package/dist/text/reflow.js.map +1 -1
- package/dist/text/snap.d.ts +1 -0
- package/dist/text/snap.js +26 -0
- package/dist/text/snap.js.map +1 -0
- package/dist/types.d.ts +63 -14
- package/dist/vanilla.d.ts +13 -360
- package/dist/vanilla.js +8 -1402
- package/dist/windfoil/WindfoilMaterial.d.ts +2 -1
- package/dist/windfoil/WindfoilMaterial.js +8 -1
- package/dist/windfoil/WindfoilMaterial.js.map +1 -1
- package/dist/windfoil/abortable.d.ts +2 -0
- package/dist/windfoil/abortable.js +26 -0
- package/dist/windfoil/abortable.js.map +1 -0
- package/dist/windfoil/color.js +2 -1
- package/dist/windfoil/color.js.map +1 -1
- package/dist/windfoil/coverage.d.ts +3 -20
- package/dist/windfoil/coverage.js +7 -20
- package/dist/windfoil/coverage.js.map +1 -1
- package/dist/windfoil/emoji.js +1 -1
- package/dist/windfoil/emoji.js.map +1 -1
- package/dist/windfoil/emojiMetrics.js +1 -1
- package/dist/windfoil/emojiMetrics.js.map +1 -1
- package/dist/windfoil/geometry.d.ts +2 -2
- package/dist/windfoil/geometry.js +204 -64
- package/dist/windfoil/geometry.js.map +1 -1
- package/dist/windfoil/layerGrid.js +14 -10
- package/dist/windfoil/layerGrid.js.map +1 -1
- package/dist/windfoil/layerNormalization.d.ts +1 -1
- package/dist/windfoil/layerNormalization.js +1 -1
- package/dist/windfoil/layerNormalization.js.map +1 -1
- package/dist/windfoil/mixed.d.ts +1 -0
- package/dist/windfoil/mixed.js +44 -25
- package/dist/windfoil/mixed.js.map +1 -1
- package/dist/windfoil/outlineValidation.d.ts +86 -0
- package/dist/windfoil/outlineValidation.js +65 -0
- package/dist/windfoil/outlineValidation.js.map +1 -0
- package/dist/windfoil/preprocess.js +3 -2
- package/dist/windfoil/preprocess.js.map +1 -1
- package/dist/windfoil/preprocessCore.d.ts +5 -85
- package/dist/windfoil/preprocessCore.js +218 -209
- package/dist/windfoil/preprocessCore.js.map +1 -1
- package/dist/windfoil/requests.js +1 -1
- package/dist/windfoil/requests.js.map +1 -1
- package/dist/windfoil/runtime.d.ts +5 -2
- package/dist/windfoil/runtime.js +63 -40
- package/dist/windfoil/runtime.js.map +1 -1
- package/dist/windfoil/shapeResources.js +2 -1
- package/dist/windfoil/shapeResources.js.map +1 -1
- package/dist/windfoil/shapes.js +1 -1
- package/dist/windfoil/skirt.d.ts +22 -0
- package/dist/windfoil/skirt.js +20 -0
- package/dist/windfoil/skirt.js.map +1 -0
- package/dist/windfoil/storage.d.ts +62 -4
- package/dist/windfoil/storage.js +143 -28
- package/dist/windfoil/storage.js.map +1 -1
- package/dist/windfoil/trace/contours.d.ts +3 -3
- package/dist/windfoil/trace/contours.js +228 -137
- package/dist/windfoil/trace/contours.js.map +1 -1
- package/dist/windfoil/trace/fit.d.ts +3 -7
- package/dist/windfoil/trace/fit.js +668 -376
- package/dist/windfoil/trace/fit.js.map +1 -1
- package/dist/windfoil/trace/outline.js +60 -35
- package/dist/windfoil/trace/outline.js.map +1 -1
- package/dist/windfoil/trace/types.d.ts +15 -3
- package/dist/windfoil/tracedOutlines.d.ts +37 -1
- package/dist/windfoil/tracedOutlines.js +228 -64
- package/dist/windfoil/tracedOutlines.js.map +1 -1
- package/package.json +60 -11
- package/skills/ultra-text/SKILL.md +114 -0
- package/skills/ultra-text/references/frameworks.md +43 -0
- package/skills/ultra-text/references/three-tsl.md +78 -0
- package/skills/ultra-text/references/vanilla-webgpu.md +96 -0
- package/dist/assets/cpuSdf.worker-Du9o8q4p.js.map +0 -1
- package/dist/text/geometry.js +0 -348
- package/dist/text/geometry.js.map +0 -1
- package/dist/vanilla.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"appendAtlas.js","names":[],"sources":["../../src/atlas/appendAtlas.ts"],"sourcesContent":["import {\n Box2,\n DataTexture,\n RedFormat,\n UnsignedByteType,\n Vector2,\n type Texture,\n type WebGPURenderer,\n} from 'three/webgpu'\n\nimport type { DomSdfOptions, GlyphRequest, SdfAtlas } from '../types.js'\nimport { alphaOfRgba, encodeSdfFromAlpha } from './cpuSdf.js'\nimport { atlasDevice, encodeGpuSdf, generateAtlasMips, type AtlasGpuTexture } from './gpuAtlas.js'\nimport {\n appendCursors,\n createCanvas,\n glyphPainter,\n isColorCandidate,\n measureGlyph,\n packShelves,\n slotOf,\n waitForFonts,\n type MeasuredGlyph,\n} from './rasterize.js'\n\n/**\n * A larger patch is left to a full rebuild, which spreads its work better: the patch's exact\n * transform runs on the page's thread, where 2^18 texels (about twenty 96 px glyphs) take a\n * few milliseconds.\n */\nconst PATCH_TEXELS = 1 << 18\n\n/** The new glyphs of one atlas row and where they go: never a box that spans two rows. */\ninterface Run {\n readonly x: number\n readonly y: number\n /** First row of the run on the patch canvas, where the runs are stacked. */\n readonly top: number\n width: number\n height: number\n readonly glyphs: MeasuredGlyph[]\n}\n\n/**\n * @internal Draws the text glyphs of a `capture` that `atlas` lacks into the free text rows of\n * its live texture, so a rebuild keeps the texture and every material that samples it. Only\n * the new glyphs are measured and drawn, row by row of the atlas, on one small canvas, by the\n * full build's rules and slot formulas (`glyphPainter`, `slotOf`). Their distance field comes\n * from the atlas's own encoder, a jump flood of the patch alone for a GPU atlas and the exact\n * transform for a CPU one, so the new slots hold the bytes a full build would give them; each\n * row's box is then copied into the texture, whose mipmaps three regenerates, and a CPU\n * atlas's bytes follow.\n *\n * Resolves with the next wrapper: the same texture, colour layer, shape rows and `dispose`,\n * with the old slots and the new ones; its own cursor is recorded under its glyph map, so it\n * becomes the live one only when the caller commits that wrapper. Slots the capture no longer\n * uses stay in the texture until the next full build compacts it. Resolves `null`, having\n * written nothing the caller must undo, when the caller must rebuild in full instead: a shape,\n * a glyph that classifies as colour, an atlas without a cursor or with a lowered adaptive bake\n * size, a patch past its texel budget, or glyphs that do not fit. What an aborted patch already\n * copied lies in rows no slot samples, and the next patch overwrites it.\n */\nexport async function appendGlyphs(\n renderer: WebGPURenderer,\n document: Document,\n atlas: SdfAtlas,\n capture: readonly GlyphRequest[],\n options: Pick<DomSdfOptions, 'colorGlyphs' | 'bakeSize'>,\n signal: AbortSignal,\n): Promise<SdfAtlas | null> {\n const cursor = appendCursors.get(atlas.glyphs)\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const requests = capture.filter((request) => !atlas.glyphs.has(request.key))\n if (\n cursor?.bakeSize !== (options.bakeSize ?? 96) ||\n cursor.colorGlyphs !== colorGlyphs ||\n cursor.width !== atlas.width ||\n cursor.height !== atlas.height ||\n !requests.length ||\n requests.some((request) => request.shape !== undefined)\n )\n return null\n const [, shapingModule] = await Promise.all([\n waitForFonts(document, requests, signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n ])\n signal.throwIfAborted()\n const shaping = shapingModule?.setShapingContext\n const { width, height, bakeSize, pxRange: padding } = cursor\n const canvas = createCanvas(document)\n try {\n // A GPU patch reads at most a tiny candidate scratch pack and uploads the patch texture.\n const context = canvas.getContext('2d', {\n willReadFrequently: atlas.mode !== 'gpu',\n })\n if (!context) return null\n let lastFont: GlyphRequest['font'] | null = null\n const fresh = requests.map((request) => {\n const [glyph, font] = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, colorGlyphs),\n lastFont,\n )\n lastFont = font\n return glyph\n })\n fresh.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 // The patch stacks its glyphs' rows, so it is never smaller than their summed area: a batch\n // past the budget is refused before its colour candidates are drawn and read back.\n let area = 0\n for (const glyph of fresh) area += glyph.width * glyph.height\n if (area > PATCH_TEXELS) return null\n const painter = glyphPainter(context, shaping, signal)\n\n // Colour candidates are classified as in a full build, on a pack of their own: one that\n // keeps its colour needs the colour band, which only a full build can grow.\n const candidates = fresh.filter((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n if (candidates.length) {\n const scratch = packShelves(candidates, width, 1 << 14)\n if (!scratch) return null\n const { encodeColorBand } = await import('./colorGlyphs.js')\n signal.throwIfAborted()\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n context.clearRect(0, 0, scratch.width, scratch.height)\n for (const glyph of candidates) painter.draw(glyph, false, fill)\n return context.getImageData(0, 0, scratch.width, scratch.height).data\n }\n const dark = paint('#000')\n const { colored } = encodeColorBand(\n paint('#fff'),\n dark,\n scratch.width,\n scratch.height,\n 0,\n candidates,\n )\n if (colored.some(Boolean)) return null\n }\n\n // The full build's shelf, continued from its last text row.\n let { x, y, rowHeight } = cursor\n const runs: Run[] = []\n let patchWidth = 0\n let patchHeight = 0\n for (const glyph of fresh) {\n if (x + glyph.width > width) {\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (glyph.width > width || y + glyph.height > cursor.bottom) return null\n let run = runs.at(-1)\n if (run?.y !== y) {\n if (run) patchHeight += run.height\n runs.push((run = { x, y, top: patchHeight, width: 0, height: 0, glyphs: [] }))\n }\n glyph.x = x\n glyph.y = y\n run.glyphs.push(glyph)\n x += glyph.width\n run.width = x - run.x\n if (glyph.height > run.height) run.height = glyph.height\n if (glyph.height > rowHeight) rowHeight = glyph.height\n if (run.width > patchWidth) patchWidth = run.width\n }\n patchHeight += runs.at(-1)!.height\n if (patchWidth * patchHeight > PATCH_TEXELS) return null\n\n canvas.width = patchWidth\n canvas.height = patchHeight\n painter.reset()\n context.clearRect(0, 0, patchWidth, patchHeight)\n for (const run of runs) {\n for (const glyph of run.glyphs) {\n painter.draw({ ...glyph, x: glyph.x - run.x, y: glyph.y - run.y + run.top }, true)\n }\n }\n\n const target: Texture & { mipmapsAutoUpdate?: boolean; sourceTexture?: unknown } = atlas.texture\n if (atlas.mode === 'gpu') {\n // A patch takes the encoder its atlas was baked with. The jump flood and the exact\n // transform disagree by up to 25/255 of the range even at the edge, so a CPU patch\n // in a GPU atlas would draw its glyphs a shade off a full build's. The patch's field\n // and its copies into the live texture go out in one submission on the device's cached\n // passes, then three regenerates the texture's mips. A device that fails here leaves\n // the full build to fall back, as `auto` does, or to throw.\n const live = target.sourceTexture as AtlasGpuTexture | null | undefined\n if (!live) return null\n const field = await encodeGpuSdf(\n atlasDevice(renderer),\n { canvas, width: patchWidth, height: patchHeight, pxRange: padding },\n 1,\n (encoder, patch) => {\n for (const run of runs) {\n encoder.copyTextureToTexture(\n { texture: patch, origin: [0, run.top] },\n { texture: live, origin: [run.x, run.y] },\n [run.width, run.height],\n )\n }\n },\n ).catch(() => null)\n if (!field) return null\n field.destroy()\n try {\n if (live.mipLevelCount > 1) await generateAtlasMips(renderer, target)\n } catch {\n return null\n }\n signal.throwIfAborted()\n } else {\n // A CPU atlas keeps its bytes, which a later upload sends whole: they take the patch too.\n // (`mipmapsAutoUpdate` is r187's; r186 regenerates the mipmaps after every copy.)\n const image = target.image as { data?: unknown } | null\n const bytes =\n image?.data instanceof Uint8Array && image.data.length === width * height\n ? image.data\n : undefined\n const pixels = context.getImageData(0, 0, patchWidth, patchHeight).data\n const field = encodeSdfFromAlpha(\n alphaOfRgba(pixels, patchWidth * patchHeight),\n patchWidth,\n patchHeight,\n padding,\n )\n signal.throwIfAborted()\n\n // Everything from here on is synchronous, so a newer build cannot interleave its own patch.\n if (bytes) {\n for (const run of runs) {\n for (let row = 0; row < run.height; row++) {\n const from = (run.top + row) * patchWidth\n bytes.set(field.subarray(from, from + run.width), (run.y + row) * width + run.x)\n }\n }\n }\n const patch = new DataTexture(field, patchWidth, patchHeight, RedFormat, UnsignedByteType)\n patch.needsUpdate = true\n const autoMipmaps = target.mipmapsAutoUpdate\n try {\n runs.forEach((run, index) => {\n // Each copy regenerates the whole mip chain: only the last needs to.\n if (autoMipmaps) target.mipmapsAutoUpdate = index === runs.length - 1\n renderer.copyTextureToTexture(\n patch,\n target,\n new Box2(new Vector2(0, run.top), new Vector2(run.width, run.top + run.height)),\n new Vector2(run.x, run.y),\n )\n })\n } catch {\n // A renderer that cannot copy between textures uploads the atlas's bytes again, whole.\n if (!bytes) return null\n target.needsUpdate = true\n } finally {\n if (autoMipmaps) target.mipmapsAutoUpdate = true\n patch.dispose()\n }\n }\n\n const glyphs = new Map(atlas.glyphs)\n for (const glyph of fresh) {\n glyphs.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n width,\n height,\n false,\n isColorCandidate(glyph.request, colorGlyphs),\n ),\n )\n }\n appendCursors.set(glyphs, { ...cursor, x, y, rowHeight })\n return { ...atlas, glyphs }\n } finally {\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;;;;AA8BA,IAAM,eAAe,KAAK;;;;;;;;;;;;;;;;;;;;AAgC1B,eAAsB,aACpB,UACA,UACA,OACA,SACA,SACA,QAC0B;CAC1B,MAAM,SAAS,cAAc,IAAI,MAAM,MAAM;CAC7C,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,WAAW,QAAQ,QAAQ,YAAY,CAAC,MAAM,OAAO,IAAI,QAAQ,GAAG,CAAC;CAC3E,IACE,QAAQ,cAAc,QAAQ,YAAY,OAC1C,OAAO,gBAAgB,eACvB,OAAO,UAAU,MAAM,SACvB,OAAO,WAAW,MAAM,UACxB,CAAC,SAAS,UACV,SAAS,MAAM,YAAY,QAAQ,UAAU,KAAA,CAAS,GAEtD,OAAO;CACT,MAAM,GAAG,iBAAiB,MAAM,QAAQ,IAAI,CAC1C,aAAa,UAAU,UAAU,MAAM,GACvC,SAAS,MAAM,YAAY,QAAQ,OAAO,IAAI,OAAO,8BAA8B,KAAA,CACrF,CAAC;CACD,OAAO,eAAe;CACtB,MAAM,UAAU,eAAe;CAC/B,MAAM,EAAE,OAAO,QAAQ,UAAU,SAAS,YAAY;CACtD,MAAM,SAAS,aAAa,QAAQ;CACpC,IAAI;EAEF,MAAM,UAAU,OAAO,WAAW,MAAM,EACtC,oBAAoB,MAAM,SAAS,MACrC,CAAC;EACD,IAAI,CAAC,SAAS,OAAO;EACrB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GAAG,GAAG,IAAI,QAAQ,IAAI,OAAO,IAAI,MAAM,IAAI,MAAM,CAAC,GAC9E,IAAI,QAAQ,IAAI,GAAG,IAAI,CAAC,CAC1B;IACF,CAAC;GACH,QAAQ;IAEN,IAAI,CAAC,OAAO,OAAO;IACnB,OAAO,cAAc;GACvB,UAAU;IACR,IAAI,aAAa,OAAO,oBAAoB;IAC5C,MAAM,QAAQ;GAChB;EACF;EAEA,MAAM,SAAS,IAAI,IAAI,MAAM,MAAM;EACnC,KAAK,MAAM,SAAS,OAClB,OAAO,IACL,MAAM,QAAQ,KACd,OACE,OACA,SACA,UACA,OACA,QACA,OACA,iBAAiB,MAAM,SAAS,WAAW,CAC7C,CACF;EAEF,cAAc,IAAI,QAAQ;GAAE,GAAG;GAAQ;GAAG;GAAG;EAAU,CAAC;EACxD,OAAO;GAAE,GAAG;GAAO;EAAO;CAC5B,UAAU;EACR,OAAO,OAAO;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"appendAtlas.js","names":[],"sources":["../../src/atlas/appendAtlas.ts"],"sourcesContent":["import {\n Box2,\n DataTexture,\n RedFormat,\n UnsignedByteType,\n Vector2,\n type Texture,\n type WebGPURenderer,\n} from 'three/webgpu'\n\nimport type { DomSdfOptions, GlyphRequest, SdfAtlas } from '../types.js'\nimport { encodeSdfFromRgba } from './cpuSdf.js'\nimport { atlasDevice, encodeGpuSdf, generateAtlasMips, type AtlasGpuTexture } from './gpuAtlas.js'\nimport {\n appendCursors,\n createCanvas,\n glyphPainter,\n isColorCandidate,\n measureGlyph,\n packShelves,\n slotOf,\n waitForFonts,\n type MeasuredGlyph,\n} from './rasterize.js'\n\n/**\n * A larger patch is left to a full rebuild, which spreads its work better: the patch's exact\n * transform runs on the page's thread, where 2^18 texels (about twenty 96 px glyphs) take a\n * few milliseconds.\n */\nconst PATCH_TEXELS = 1 << 18\n\n/** The new glyphs of one atlas row and where they go: never a box that spans two rows. */\ninterface Run {\n readonly x: number\n readonly y: number\n /** First row of the run on the patch canvas, where the runs are stacked. */\n readonly top: number\n width: number\n height: number\n readonly glyphs: MeasuredGlyph[]\n}\n\n/**\n * @internal Draws the text glyphs of a `capture` that `atlas` lacks into the free text rows of\n * its live texture, so a rebuild keeps the texture and every material that samples it. Only\n * the new glyphs are measured and drawn, row by row of the atlas, on one small canvas, by the\n * full build's rules and slot formulas (`glyphPainter`, `slotOf`). Their distance field comes\n * from the atlas's own encoder, a jump flood of the patch alone for a GPU atlas and the exact\n * transform for a CPU one, so the new slots hold the bytes a full build would give them; each\n * row's box is then copied into the texture, whose mipmaps three regenerates, and a CPU\n * atlas's bytes follow.\n *\n * Resolves with the next wrapper: the same texture, colour layer, shape rows and `dispose`,\n * with the old slots and the new ones; its own cursor is recorded under its glyph map, so it\n * becomes the live one only when the caller commits that wrapper. Slots the capture no longer\n * uses stay in the texture until the next full build compacts it. Resolves `null`, having\n * written nothing the caller must undo, when the caller must rebuild in full instead: a shape,\n * a glyph that classifies as colour, an atlas without a cursor or with a lowered adaptive bake\n * size, a patch past its texel budget, or glyphs that do not fit. What an aborted patch already\n * copied lies in rows no slot samples, and the next patch overwrites it.\n */\nexport async function appendGlyphs(\n renderer: WebGPURenderer,\n document: Document,\n atlas: SdfAtlas,\n capture: readonly GlyphRequest[],\n options: Pick<DomSdfOptions, 'colorGlyphs' | 'bakeSize'>,\n signal: AbortSignal,\n): Promise<SdfAtlas | null> {\n const cursor = appendCursors.get(atlas.glyphs)\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const requests = capture.filter((request) => !atlas.glyphs.has(request.key))\n if (\n cursor?.bakeSize !== (options.bakeSize ?? 96) ||\n cursor.colorGlyphs !== colorGlyphs ||\n cursor.width !== atlas.width ||\n cursor.height !== atlas.height ||\n !requests.length ||\n requests.some((request) => request.shape !== undefined)\n )\n return null\n const [, shapingModule] = await Promise.all([\n waitForFonts(document, requests, signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n ])\n signal.throwIfAborted()\n const shaping = shapingModule?.setShapingContext\n const { width, height, bakeSize, pxRange: padding } = cursor\n const canvas = createCanvas(document)\n try {\n // A GPU patch reads at most a tiny candidate scratch pack and uploads the patch texture.\n const context = canvas.getContext('2d', {\n willReadFrequently: atlas.mode !== 'gpu',\n })\n if (!context) return null\n let lastFont: GlyphRequest['font'] | null = null\n const fresh = requests.map((request) => {\n const glyph = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, colorGlyphs),\n lastFont,\n )\n lastFont = request.font\n return glyph\n })\n fresh.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 // The patch stacks its glyphs' rows, so it is never smaller than their summed area: a batch\n // past the budget is refused before its colour candidates are drawn and read back.\n let area = 0\n for (const glyph of fresh) area += glyph.width * glyph.height\n if (area > PATCH_TEXELS) return null\n const painter = glyphPainter(context, shaping, signal)\n\n // Colour candidates are classified as in a full build, on a pack of their own: one that\n // keeps its colour needs the colour band, which only a full build can grow.\n const candidates = fresh.filter((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n if (candidates.length) {\n const scratch = packShelves(candidates, width, 1 << 14)\n if (!scratch) return null\n const { encodeColorBand } = await import('./colorGlyphs.js')\n signal.throwIfAborted()\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string, clear: boolean): Uint8ClampedArray => {\n if (clear) context.clearRect(0, 0, scratch.width, scratch.height)\n for (const glyph of candidates) painter.draw(glyph, false, fill)\n return context.getImageData(0, 0, scratch.width, scratch.height).data\n }\n const dark = paint('#000', false)\n const { colored } = encodeColorBand(\n paint('#fff', true),\n dark,\n scratch.width,\n scratch.height,\n 0,\n candidates,\n )\n if (colored.some(Boolean)) return null\n }\n\n // The full build's shelf, continued from its last text row.\n let { x, y, rowHeight } = cursor\n const runs: Run[] = []\n let patchWidth = 0\n let patchHeight = 0\n for (const glyph of fresh) {\n if (x + glyph.width > width) {\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (glyph.width > width || y + glyph.height > cursor.bottom) return null\n let run = runs.at(-1)\n if (run?.y !== y) {\n if (run) patchHeight += run.height\n runs.push((run = { x, y, top: patchHeight, width: 0, height: 0, glyphs: [] }))\n }\n glyph.x = x\n glyph.y = y\n run.glyphs.push(glyph)\n x += glyph.width\n run.width = x - run.x\n if (glyph.height > run.height) run.height = glyph.height\n if (glyph.height > rowHeight) rowHeight = glyph.height\n if (run.width > patchWidth) patchWidth = run.width\n }\n patchHeight += runs.at(-1)!.height\n if (patchWidth * patchHeight > PATCH_TEXELS) return null\n\n const samePatchSize = canvas.width === patchWidth && canvas.height === patchHeight\n canvas.width = patchWidth\n canvas.height = patchHeight\n painter.reset()\n if (candidates.length && samePatchSize) context.clearRect(0, 0, patchWidth, patchHeight)\n for (const run of runs) {\n for (const glyph of run.glyphs) {\n const gx = glyph.x\n const gy = glyph.y\n glyph.x = gx - run.x\n glyph.y = gy - run.y + run.top\n try {\n painter.draw(glyph, true)\n } finally {\n glyph.x = gx\n glyph.y = gy\n }\n }\n }\n\n const target: Texture & { mipmapsAutoUpdate?: boolean; sourceTexture?: unknown } = atlas.texture\n if (atlas.mode === 'gpu') {\n // A patch takes the encoder its atlas was baked with. The jump flood and the exact\n // transform disagree by up to 25/255 of the range even at the edge, so a CPU patch\n // in a GPU atlas would draw its glyphs a shade off a full build's. The patch's field\n // and its copies into the live texture go out in one submission on the device's cached\n // passes, then three regenerates the texture's mips. A device that fails here leaves\n // the full build to fall back, as `auto` does, or to throw.\n const live = target.sourceTexture as AtlasGpuTexture | null | undefined\n if (!live) return null\n const field = await encodeGpuSdf(\n atlasDevice(renderer),\n { canvas, width: patchWidth, height: patchHeight, pxRange: padding },\n 1,\n (encoder, patch) => {\n for (const run of runs) {\n encoder.copyTextureToTexture(\n { texture: patch, origin: [0, run.top] },\n { texture: live, origin: [run.x, run.y] },\n [run.width, run.height],\n )\n }\n },\n ).catch(() => null)\n canvas.width = 0\n canvas.height = 0\n if (!field) return null\n field.destroy()\n try {\n if (live.mipLevelCount > 1) await generateAtlasMips(renderer, target)\n } catch {\n return null\n }\n signal.throwIfAborted()\n } else {\n // A CPU atlas keeps its bytes, which a later upload sends whole: they take the patch too.\n // (`mipmapsAutoUpdate` is r187's; r186 regenerates the mipmaps after every copy.)\n const image = target.image as { data?: unknown } | null\n const bytes =\n image?.data instanceof Uint8Array && image.data.length === width * height\n ? image.data\n : undefined\n const pixels = context.getImageData(0, 0, patchWidth, patchHeight).data\n canvas.width = 0\n canvas.height = 0\n const field = encodeSdfFromRgba(pixels, patchWidth, patchHeight, padding)\n signal.throwIfAborted()\n\n // Everything from here on is synchronous, so a newer build cannot interleave its own patch.\n if (bytes) {\n for (const run of runs) {\n for (let row = 0; row < run.height; row++) {\n const from = (run.top + row) * patchWidth\n bytes.set(field.subarray(from, from + run.width), (run.y + row) * width + run.x)\n }\n }\n }\n const backend = (\n renderer as unknown as {\n backend?: {\n get?(texture: Texture): { texture?: unknown } | undefined\n generateMipmaps?(texture: Texture): void\n device?: {\n queue?: {\n writeTexture?(\n destination: {\n texture: unknown\n mipLevel?: number\n origin?: [number, number, number]\n },\n data: Uint8Array,\n dataLayout: { offset?: number; bytesPerRow: number; rowsPerImage?: number },\n size: [number, number, number],\n ): void\n }\n }\n }\n }\n ).backend\n const targetGpu = backend?.get?.(target)?.texture\n const queue = backend?.device?.queue\n if (targetGpu && typeof queue?.writeTexture === 'function') {\n try {\n for (const run of runs) {\n queue.writeTexture(\n { texture: targetGpu, mipLevel: 0, origin: [run.x, run.y, 0] },\n field,\n { offset: run.top * patchWidth, bytesPerRow: patchWidth, rowsPerImage: run.height },\n [run.width, run.height, 1],\n )\n }\n if (target.generateMipmaps) backend.generateMipmaps?.(target)\n } catch {\n if (!bytes) return null\n target.needsUpdate = true\n }\n } else {\n const patch = new DataTexture(field, patchWidth, patchHeight, RedFormat, UnsignedByteType)\n patch.needsUpdate = true\n const autoMipmaps = target.mipmapsAutoUpdate\n try {\n runs.forEach((run, index) => {\n // Each copy regenerates the whole mip chain: only the last needs to.\n if (autoMipmaps) target.mipmapsAutoUpdate = index === runs.length - 1\n renderer.copyTextureToTexture(\n patch,\n target,\n new Box2(new Vector2(0, run.top), new Vector2(run.width, run.top + run.height)),\n new Vector2(run.x, run.y),\n )\n })\n } catch {\n // A renderer that cannot copy between textures uploads the atlas's bytes again, whole.\n if (!bytes) return null\n target.needsUpdate = true\n } finally {\n if (autoMipmaps) target.mipmapsAutoUpdate = true\n patch.dispose()\n }\n }\n }\n\n const glyphs = new Map(atlas.glyphs)\n for (const glyph of fresh) {\n glyphs.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n width,\n height,\n false,\n isColorCandidate(glyph.request, colorGlyphs),\n ),\n )\n }\n appendCursors.set(glyphs, { ...cursor, x, y, rowHeight })\n return { ...atlas, glyphs }\n } finally {\n canvas.width = 0\n canvas.height = 0\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,IAAM,eAAe,KAAK;;;;;;;;;;;;;;;;;;;;AAgC1B,eAAsB,aACpB,UACA,UACA,OACA,SACA,SACA,QAC0B;CAC1B,MAAM,SAAS,cAAc,IAAI,MAAM,MAAM;CAC7C,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,WAAW,QAAQ,QAAQ,YAAY,CAAC,MAAM,OAAO,IAAI,QAAQ,GAAG,CAAC;CAC3E,IACE,QAAQ,cAAc,QAAQ,YAAY,OAC1C,OAAO,gBAAgB,eACvB,OAAO,UAAU,MAAM,SACvB,OAAO,WAAW,MAAM,UACxB,CAAC,SAAS,UACV,SAAS,MAAM,YAAY,QAAQ,UAAU,KAAA,CAAS,GAEtD,OAAO;CACT,MAAM,GAAG,iBAAiB,MAAM,QAAQ,IAAI,CAC1C,aAAa,UAAU,UAAU,MAAM,GACvC,SAAS,MAAM,YAAY,QAAQ,OAAO,IAAI,OAAO,8BAA8B,KAAA,CACrF,CAAC;CACD,OAAO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AAa,OAAO,oBAAoB;KAC5C,MAAM,QAAQ;IAChB;GACF;EACF;EAEA,MAAM,SAAS,IAAI,IAAI,MAAM,MAAM;EACnC,KAAK,MAAM,SAAS,OAClB,OAAO,IACL,MAAM,QAAQ,KACd,OACE,OACA,SACA,UACA,OACA,QACA,OACA,iBAAiB,MAAM,SAAS,WAAW,CAC7C,CACF;EAEF,cAAc,IAAI,QAAQ;GAAE,GAAG;GAAQ;GAAG;GAAG;EAAU,CAAC;EACxD,OAAO;GAAE,GAAG;GAAO;EAAO;CAC5B,UAAU;EACR,OAAO,QAAQ;EACf,OAAO,SAAS;EAChB,OAAO,OAAO;CAChB;AACF"}
|
package/dist/atlas/buildAtlas.js
CHANGED
|
@@ -39,31 +39,21 @@ async function withColorLayer(atlas, raster, renderer, options) {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
var warnedGpuFallback = false;
|
|
42
|
-
|
|
43
|
-
* Builds the retained single-channel SDF atlas from a packed glyph mask.
|
|
44
|
-
*
|
|
45
|
-
* `mode: 'gpu'` runs the WebGPU compute encoder and rethrows if a real WebGPU
|
|
46
|
-
* backend is unavailable, if the device's limits cannot hold the passes, or if
|
|
47
|
-
* the device reports an error for them; `'cpu'` runs the exact Euclidean
|
|
48
|
-
* distance transform; the default `'auto'` tries the GPU path first and falls
|
|
49
|
-
* back to the CPU encoder, warning once per page because the fallback is
|
|
50
|
-
* 10-100× slower.
|
|
51
|
-
* An aborted `signal` rejects with the abort reason and disposes any atlas
|
|
52
|
-
* that was already produced. The caller owns the returned atlas.
|
|
53
|
-
*/
|
|
54
|
-
async function buildSdfAtlas(renderer, raster, options = {}) {
|
|
42
|
+
async function buildSdfAtlas(renderer, raster, options = {}, provisional, preparedWorker) {
|
|
55
43
|
const mode = options.mode;
|
|
56
44
|
options.signal?.throwIfAborted();
|
|
57
45
|
const buildCpu = async () => {
|
|
58
46
|
const { buildCpuSdfAtlas } = await import("./cpuAtlas.js");
|
|
47
|
+
const worker = preparedWorker ? await preparedWorker : void 0;
|
|
59
48
|
options.signal?.throwIfAborted();
|
|
60
|
-
return retainAtlas(await buildCpuSdfAtlas(raster, options), options.signal);
|
|
49
|
+
return retainAtlas(await (worker ? buildCpuSdfAtlas(raster, options, worker) : buildCpuSdfAtlas(raster, options)), options.signal);
|
|
61
50
|
};
|
|
62
51
|
let atlas;
|
|
63
52
|
if (mode === "cpu") atlas = await buildCpu();
|
|
64
53
|
else try {
|
|
65
|
-
atlas = retainAtlas(await buildGpuSdfAtlas(renderer, raster, options), options.signal);
|
|
54
|
+
atlas = retainAtlas(provisional && !raster.colorBand && !options.mipmaps ? await buildGpuSdfAtlas(renderer, raster, options, (candidate) => provisional.stage(candidate)) : await buildGpuSdfAtlas(renderer, raster, options), options.signal);
|
|
66
55
|
} catch (error) {
|
|
56
|
+
provisional?.rollback();
|
|
67
57
|
if (mode === "gpu") throw error;
|
|
68
58
|
options.signal?.throwIfAborted();
|
|
69
59
|
if (!warnedGpuFallback) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildAtlas.js","names":[],"sources":["../../src/atlas/buildAtlas.ts"],"sourcesContent":["import type { WebGPURenderer } from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport { buildGpuSdfAtlas } from './gpuAtlas.js'\n\nfunction retainAtlas(atlas: SdfAtlas, signal?: AbortSignal): SdfAtlas {\n if (signal?.aborted) {\n atlas.dispose()\n signal.throwIfAborted()\n }\n return atlas\n}\n\nasync function withColorLayer(\n atlas: SdfAtlas,\n raster: RasterAtlas,\n renderer: WebGPURenderer,\n options: BuildSdfAtlasOptions,\n): Promise<SdfAtlas> {\n if (!raster.colorBand) return atlas\n let colorLayer: SdfAtlas['colorLayer']\n try {\n const { createColorLayer } = await import('./colorGlyphs.js')\n options.signal?.throwIfAborted()\n colorLayer = createColorLayer(\n raster.colorBand,\n raster.width,\n options,\n renderer.getMaxAnisotropy(),\n )\n options.signal?.throwIfAborted()\n let disposed = false\n return {\n ...atlas,\n colorLayer,\n dispose() {\n if (disposed) return\n disposed = true\n try {\n atlas.dispose()\n } finally {\n colorLayer!.texture.dispose()\n }\n },\n }\n } catch (error) {\n try {\n atlas.dispose()\n } finally {\n colorLayer?.texture.dispose()\n }\n throw error\n }\n}\n\nlet warnedGpuFallback = false\n\n/**\n * Builds the retained single-channel SDF atlas from a packed glyph mask.\n *\n * `mode: 'gpu'` runs the WebGPU compute encoder and rethrows if a real WebGPU\n * backend is unavailable, if the device's limits cannot hold the passes, or if\n * the device reports an error for them; `'cpu'` runs the exact Euclidean\n * distance transform; the default `'auto'` tries the GPU path first and falls\n * back to the CPU encoder, warning once per page because the fallback is\n * 10-100× slower.\n * An aborted `signal` rejects with the abort reason and disposes any atlas\n * that was already produced. The caller owns the returned atlas.\n */\nexport async function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: BuildSdfAtlasOptions = {},\n): Promise<SdfAtlas> {\n const mode = options.mode\n options.signal?.throwIfAborted()\n\n const buildCpu = async (): Promise<SdfAtlas> => {\n const { buildCpuSdfAtlas } = await import('./cpuAtlas.js')\n options.signal?.throwIfAborted()\n return retainAtlas(await buildCpuSdfAtlas(raster, options), options.signal)\n }\n let atlas: SdfAtlas\n if (mode === 'cpu') atlas = await buildCpu()\n else {\n try {\n
|
|
1
|
+
{"version":3,"file":"buildAtlas.js","names":[],"sources":["../../src/atlas/buildAtlas.ts"],"sourcesContent":["import type { WebGPURenderer } from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport type { PreparedCpuWorker } from './cpuWorker.js'\nimport { buildGpuSdfAtlas } from './gpuAtlas.js'\n\nfunction retainAtlas(atlas: SdfAtlas, signal?: AbortSignal): SdfAtlas {\n if (signal?.aborted) {\n atlas.dispose()\n signal.throwIfAborted()\n }\n return atlas\n}\n\nasync function withColorLayer(\n atlas: SdfAtlas,\n raster: RasterAtlas,\n renderer: WebGPURenderer,\n options: BuildSdfAtlasOptions,\n): Promise<SdfAtlas> {\n if (!raster.colorBand) return atlas\n let colorLayer: SdfAtlas['colorLayer']\n try {\n const { createColorLayer } = await import('./colorGlyphs.js')\n options.signal?.throwIfAborted()\n colorLayer = createColorLayer(\n raster.colorBand,\n raster.width,\n options,\n renderer.getMaxAnisotropy(),\n )\n options.signal?.throwIfAborted()\n let disposed = false\n return {\n ...atlas,\n colorLayer,\n dispose() {\n if (disposed) return\n disposed = true\n try {\n atlas.dispose()\n } finally {\n colorLayer!.texture.dispose()\n }\n },\n }\n } catch (error) {\n try {\n atlas.dispose()\n } finally {\n colorLayer?.texture.dispose()\n }\n throw error\n }\n}\n\nlet warnedGpuFallback = false\n\n/** @internal Hook for overlapping GPU SDF validation with downstream geometry creation. */\nexport interface ProvisionalAtlasHook {\n stage(atlas: SdfAtlas): void\n rollback(): void\n}\n\n/**\n * Builds the retained single-channel SDF atlas from a packed glyph mask.\n *\n * `mode: 'gpu'` runs the WebGPU compute encoder and rethrows if a real WebGPU\n * backend is unavailable, if the device's limits cannot hold the passes, or if\n * the device reports an error for them; `'cpu'` runs the exact Euclidean\n * distance transform; the default `'auto'` tries the GPU path first and falls\n * back to the CPU encoder, warning once per page because the fallback is\n * 10-100× slower.\n * An aborted `signal` rejects with the abort reason and disposes any atlas\n * that was already produced. The caller owns the returned atlas.\n */\nexport function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options?: BuildSdfAtlasOptions,\n): Promise<SdfAtlas>\n/** @internal */\nexport function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: BuildSdfAtlasOptions | undefined,\n provisional: ProvisionalAtlasHook | undefined,\n preparedWorker?: PreparedCpuWorker | Promise<PreparedCpuWorker | null> | null,\n): Promise<SdfAtlas>\nexport async function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: BuildSdfAtlasOptions = {},\n provisional?: ProvisionalAtlasHook,\n preparedWorker?: PreparedCpuWorker | Promise<PreparedCpuWorker | null> | null,\n): Promise<SdfAtlas> {\n const mode = options.mode\n options.signal?.throwIfAborted()\n\n const buildCpu = async (): Promise<SdfAtlas> => {\n const { buildCpuSdfAtlas } = await import('./cpuAtlas.js')\n const worker = preparedWorker ? await preparedWorker : undefined\n options.signal?.throwIfAborted()\n return retainAtlas(\n await (worker\n ? buildCpuSdfAtlas(raster, options, worker)\n : buildCpuSdfAtlas(raster, options)),\n options.signal,\n )\n }\n let atlas: SdfAtlas\n if (mode === 'cpu') atlas = await buildCpu()\n else {\n try {\n const built =\n provisional && !raster.colorBand && !options.mipmaps\n ? await buildGpuSdfAtlas(renderer, raster, options, (candidate) =>\n provisional.stage(candidate),\n )\n : await buildGpuSdfAtlas(renderer, raster, options)\n atlas = retainAtlas(built, options.signal)\n } catch (error) {\n provisional?.rollback()\n if (mode === 'gpu') throw error\n options.signal?.throwIfAborted()\n if (!warnedGpuFallback) {\n warnedGpuFallback = true\n console.warn('ultra-text: falling back to CPU SDF', error)\n }\n atlas = await buildCpu()\n }\n }\n // `SdfAtlas.shapeTop` names the rows of the monochrome shapes. The texture repeats it for\n // a material that is handed the texture without that field.\n if (atlas.shapeTop !== undefined) atlas.texture.userData['ultraShapeTop'] = atlas.shapeTop\n return withColorLayer(atlas, raster, renderer, options)\n}\n"],"mappings":";;AAMA,SAAS,YAAY,OAAiB,QAAgC;CACpE,IAAI,QAAQ,SAAS;EACnB,MAAM,QAAQ;EACd,OAAO,eAAe;CACxB;CACA,OAAO;AACT;AAEA,eAAe,eACb,OACA,QACA,UACA,SACmB;CACnB,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,IAAI;CACJ,IAAI;EACF,MAAM,EAAE,qBAAqB,MAAM,OAAO;EAC1C,QAAQ,QAAQ,eAAe;EAC/B,aAAa,iBACX,OAAO,WACP,OAAO,OACP,SACA,SAAS,iBAAiB,CAC5B;EACA,QAAQ,QAAQ,eAAe;EAC/B,IAAI,WAAW;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las/cpuAtlas.d.ts
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
1
|
import type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js';
|
|
2
|
-
|
|
2
|
+
import type { PreparedCpuWorker } from './cpuWorker.js';
|
|
3
|
+
export declare function buildCpuSdfAtlas(raster: RasterAtlas, options?: Omit<BuildSdfAtlasOptions, 'mode'>,
|
|
4
|
+
/** @internal */
|
|
5
|
+
preparedWorker?: PreparedCpuWorker | null): Promise<SdfAtlas>;
|
package/dist/atlas/cpuAtlas.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { encodeSdfFromRgba } from "./cpuSdf.js";
|
|
2
2
|
import { DataTexture, LinearFilter, LinearMipmapLinearFilter, NoColorSpace, RedFormat, UnsignedByteType } from "three/webgpu";
|
|
3
3
|
// src/atlas/cpuAtlas.ts
|
|
4
4
|
function readPixels(raster) {
|
|
@@ -6,21 +6,23 @@ function readPixels(raster) {
|
|
|
6
6
|
if (!context) throw new Error("buildCpuSdfAtlas: Canvas 2D is unavailable");
|
|
7
7
|
return context.getImageData(0, 0, raster.width, raster.height).data;
|
|
8
8
|
}
|
|
9
|
-
async function buildCpuSdfAtlas(raster, options = {}) {
|
|
9
|
+
async function buildCpuSdfAtlas(raster, options = {}, preparedWorker) {
|
|
10
10
|
const { width, height, pxRange, bakeSize, glyphs, shapeTop } = raster;
|
|
11
11
|
const { signal, mipmaps = false, anisotropy = 1, cpuWorker } = options;
|
|
12
12
|
signal?.throwIfAborted();
|
|
13
|
+
const workerImport = cpuWorker !== false && typeof Worker !== "undefined" ? import("./cpuWorker.js") : void 0;
|
|
13
14
|
let rgba = readPixels(raster);
|
|
14
15
|
let sdf;
|
|
15
|
-
if (
|
|
16
|
-
const { encodeInWorker } = await
|
|
17
|
-
sdf = await encodeInWorker(rgba, width, height, pxRange, signal);
|
|
16
|
+
if (workerImport) try {
|
|
17
|
+
const { encodeInWorker } = await workerImport;
|
|
18
|
+
sdf = await encodeInWorker(rgba, width, height, pxRange, signal, preparedWorker);
|
|
18
19
|
} catch {
|
|
19
20
|
signal?.throwIfAborted();
|
|
20
21
|
if (rgba.byteLength === 0) rgba = readPixels(raster);
|
|
21
22
|
}
|
|
23
|
+
else preparedWorker?.dispose();
|
|
22
24
|
signal?.throwIfAborted();
|
|
23
|
-
sdf ??=
|
|
25
|
+
sdf ??= encodeSdfFromRgba(rgba, width, height, pxRange);
|
|
24
26
|
const texture = new DataTexture(sdf, width, height, RedFormat, UnsignedByteType);
|
|
25
27
|
texture.name = "ultra-text runtime SDF atlas (CPU EDT)";
|
|
26
28
|
texture.colorSpace = NoColorSpace;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cpuAtlas.js","names":[],"sources":["../../src/atlas/cpuAtlas.ts"],"sourcesContent":["import {\n DataTexture,\n LinearFilter,\n LinearMipmapLinearFilter,\n NoColorSpace,\n RedFormat,\n UnsignedByteType,\n} from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport {
|
|
1
|
+
{"version":3,"file":"cpuAtlas.js","names":[],"sources":["../../src/atlas/cpuAtlas.ts"],"sourcesContent":["import {\n DataTexture,\n LinearFilter,\n LinearMipmapLinearFilter,\n NoColorSpace,\n RedFormat,\n UnsignedByteType,\n} from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport { encodeSdfFromRgba } from './cpuSdf.js'\nimport type { PreparedCpuWorker } from './cpuWorker.js'\nimport type { ShapeRows } from './rasterize.js'\n\nfunction readPixels(raster: RasterAtlas): Uint8ClampedArray {\n const context = raster.canvas.getContext('2d', { willReadFrequently: true })\n if (!context) throw new Error('buildCpuSdfAtlas: Canvas 2D is unavailable')\n return context.getImageData(0, 0, raster.width, raster.height).data\n}\n\nexport async function buildCpuSdfAtlas(\n raster: RasterAtlas,\n options: Omit<BuildSdfAtlasOptions, 'mode'> = {},\n /** @internal */\n preparedWorker?: PreparedCpuWorker | null,\n): Promise<SdfAtlas> {\n const { width, height, pxRange, bakeSize, glyphs, shapeTop } = raster as RasterAtlas & ShapeRows\n const { signal, mipmaps = false, anisotropy = 1, cpuWorker } = options\n signal?.throwIfAborted()\n const useWorker = cpuWorker !== false && typeof Worker !== 'undefined'\n const workerImport = useWorker ? import('./cpuWorker.js') : undefined\n let rgba = readPixels(raster)\n let sdf: Uint8Array | undefined\n if (workerImport) {\n try {\n const { encodeInWorker } = await workerImport\n // The worker takes the alpha out of the pixels directly via encodeSdfFromRgba.\n sdf = await encodeInWorker(rgba, width, height, pxRange, signal, preparedWorker)\n } catch {\n signal?.throwIfAborted()\n // A worker can fail to load under CSP or an older bundler. Its transferred\n // input may already be detached, so recapture before the synchronous fallback.\n if (rgba.byteLength === 0) rgba = readPixels(raster)\n }\n } else {\n preparedWorker?.dispose()\n }\n signal?.throwIfAborted()\n sdf ??= encodeSdfFromRgba(rgba, width, height, pxRange)\n const texture = new DataTexture(sdf, width, height, RedFormat, UnsignedByteType)\n texture.name = 'ultra-text runtime SDF atlas (CPU EDT)'\n texture.colorSpace = NoColorSpace\n texture.flipY = false\n texture.generateMipmaps = mipmaps\n texture.minFilter = mipmaps ? LinearMipmapLinearFilter : LinearFilter\n texture.magFilter = LinearFilter\n texture.anisotropy = mipmaps ? Math.max(1, anisotropy) : 1\n texture.needsUpdate = true\n\n let disposed = false\n return {\n ...(shapeTop === undefined ? {} : { shapeTop }),\n texture,\n width,\n height,\n pxRange,\n bakeSize,\n glyphs,\n mode: 'cpu',\n dispose(): void {\n if (disposed) return\n disposed = true\n texture.dispose()\n },\n }\n}\n"],"mappings":";;;AAcA,SAAS,WAAW,QAAwC;CAC1D,MAAM,UAAU,OAAO,OAAO,WAAW,MAAM,EAAE,oBAAoB,KAAK,CAAC;CAC3E,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,4CAA4C;CAC1E,OAAO,QAAQ,aAAa,GAAG,G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TANCE_SQUARED = 0x56bc75e2d63100000;
|
|
11
|
+
var LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
|
|
11
12
|
/** The alpha byte of each RGBA pixel, as the encoder reads coverage. */
|
|
12
13
|
function alphaOfRgba(rgba, pixelCount) {
|
|
13
14
|
const alpha = new Uint8Array(pixelCount);
|
|
14
15
|
for (let source = 3, target = 0; target < pixelCount; source += 4, target++) alpha[target] = rgba[source];
|
|
15
16
|
return alpha;
|
|
16
17
|
}
|
|
17
|
-
function assertInputs(
|
|
18
|
-
if (!(
|
|
19
|
-
if (!Number.isInteger(width) || width <= 0) throw new RangeError(
|
|
20
|
-
if (!Number.isInteger(height) || height <= 0) throw new RangeError(
|
|
18
|
+
function assertInputs(pixels, width, height, pxRange, stride, name) {
|
|
19
|
+
if (!(pixels instanceof Uint8Array) && !(pixels instanceof Uint8ClampedArray)) throw new TypeError(`${name}: alpha must be a Uint8Array or Uint8ClampedArray`);
|
|
20
|
+
if (!Number.isInteger(width) || width <= 0) throw new RangeError(`${name}: width must be a positive integer`);
|
|
21
|
+
if (!Number.isInteger(height) || height <= 0) throw new RangeError(`${name}: height must be a positive integer`);
|
|
21
22
|
const pixelCount = width * height;
|
|
22
|
-
if (!Number.isSafeInteger(pixelCount)) throw new RangeError(
|
|
23
|
-
if (
|
|
24
|
-
if (!Number.isFinite(pxRange) || pxRange <= 0) throw new RangeError(
|
|
23
|
+
if (!Number.isSafeInteger(pixelCount)) throw new RangeError(`${name}: width * height exceeds the safe integer range`);
|
|
24
|
+
if (pixels.length !== pixelCount * stride) throw new RangeError(`${name}: alpha length ${pixels.length} does not match ${stride === 1 ? "width * height" : "width * height * 4"} (${pixelCount * stride})`);
|
|
25
|
+
if (!Number.isFinite(pxRange) || pxRange <= 0) throw new RangeError(`${name}: pxRange must be a positive finite number`);
|
|
25
26
|
return pixelCount;
|
|
26
27
|
}
|
|
27
28
|
var edtMinOut = 0;
|
|
@@ -73,20 +74,20 @@ function edt1d(grid, startSeed, endSeed, outStart, outEnd, clampSqDist, maxRadiu
|
|
|
73
74
|
cost = grid[q];
|
|
74
75
|
} else if (cost === grid[q - 1]) while (q < endSeed && grid[q + 1] === cost) q++;
|
|
75
76
|
const costPlusQSquared = cost + q * q;
|
|
76
|
-
while (envelopeEnd > 0 &&
|
|
77
|
-
const
|
|
77
|
+
while (envelopeEnd > 0 && costPlusQSquared - parabolaOffsets[envelopeEnd] <= boundaries[envelopeEnd] * (q - parabolaIndices[envelopeEnd])) envelopeEnd--;
|
|
78
|
+
const twiceIntersection = (costPlusQSquared - parabolaOffsets[envelopeEnd]) / (q - parabolaIndices[envelopeEnd]);
|
|
78
79
|
envelopeEnd++;
|
|
79
80
|
parabolaIndices[envelopeEnd] = q;
|
|
80
81
|
parabolaCosts[envelopeEnd] = cost;
|
|
81
82
|
parabolaOffsets[envelopeEnd] = costPlusQSquared;
|
|
82
|
-
boundaries[envelopeEnd] =
|
|
83
|
+
boundaries[envelopeEnd] = twiceIntersection;
|
|
83
84
|
}
|
|
84
85
|
const minOut = first - maxRadius > outStart ? first - maxRadius : outStart;
|
|
85
86
|
const lastSeed = parabolaIndices[envelopeEnd];
|
|
86
87
|
const maxOut = lastSeed + maxRadius < outEnd ? lastSeed + maxRadius : outEnd;
|
|
87
88
|
let b0 = minOut;
|
|
88
89
|
for (let e = 0; e <= envelopeEnd; e++) {
|
|
89
|
-
const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1]);
|
|
90
|
+
const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1] * .5);
|
|
90
91
|
if (b1 >= b0) {
|
|
91
92
|
const nearest = parabolaIndices[e];
|
|
92
93
|
const cost = parabolaCosts[e];
|
|
@@ -111,7 +112,8 @@ function edt1d(grid, startSeed, endSeed, outStart, outEnd, clampSqDist, maxRadiu
|
|
|
111
112
|
}
|
|
112
113
|
var SEED_COST = Float32Array.from({ length: 256 }, (_, coverage) => {
|
|
113
114
|
const edgeOffset = .5 - coverage / 255;
|
|
114
|
-
|
|
115
|
+
const sq = Math.fround(edgeOffset * edgeOffset);
|
|
116
|
+
return coverage < 128 ? sq : -sq;
|
|
115
117
|
});
|
|
116
118
|
var scratchDistances = /* @__PURE__ */ new Float32Array(0);
|
|
117
119
|
var scratchParabolaIndices = /* @__PURE__ */ new Int32Array(0);
|
|
@@ -140,34 +142,89 @@ function horizontalRowDistances(alpha, alphaRow, distances, distRow, width, firs
|
|
|
140
142
|
const sign = isZero ? 1 : -1;
|
|
141
143
|
const lCov = a > 0 ? alpha[alphaRow + a - 1] : -1;
|
|
142
144
|
const rCov = x + 1 < width ? alpha[alphaRow + x + 1] : -1;
|
|
143
|
-
const
|
|
144
|
-
const
|
|
145
|
+
const lSc = lCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[lCov];
|
|
146
|
+
const rSc = rCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[rCov];
|
|
147
|
+
const lCost = lSc > 0 ? lSc : 0;
|
|
148
|
+
const rCost = rSc > 0 ? rSc : 0;
|
|
145
149
|
const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : a + x - (rCost < lCost ? 1 : 0) >> 1;
|
|
146
150
|
const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1;
|
|
147
151
|
const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1;
|
|
148
152
|
for (let p = a, d = 1; p <= lEnd; p++, d++) distances[distRow + p] = sign * (d * d + lCost);
|
|
149
|
-
if (lEnd + 1 < rStart)
|
|
153
|
+
if (lEnd + 1 < rStart) {
|
|
154
|
+
const far = sign * FAR_DISTANCE_SQUARED;
|
|
155
|
+
if (rStart - lEnd <= 17) for (let p = lEnd + 1; p < rStart; p++) distances[distRow + p] = far;
|
|
156
|
+
else distances.fill(far, distRow + lEnd + 1, distRow + rStart);
|
|
157
|
+
}
|
|
150
158
|
for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) distances[distRow + p] = sign * (d * d + rCost);
|
|
151
|
-
} else distances[distRow + x] =
|
|
159
|
+
} else distances[distRow + x] = SEED_COST[coverage];
|
|
152
160
|
}
|
|
153
161
|
return lastNonZero;
|
|
154
162
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
163
|
+
function horizontalRgbaRowDistancesU32(u32, pixelRow, distances, distRow, width, firstNonZero, maxRadius) {
|
|
164
|
+
let lastNonZero = width - 1;
|
|
165
|
+
for (let x = 0; x < width; x++) {
|
|
166
|
+
const coverage = u32[pixelRow + x] >>> 24;
|
|
167
|
+
if (coverage === 0 || coverage === 255) {
|
|
168
|
+
const a = x;
|
|
169
|
+
if (x === 0 && firstNonZero > 0) x = firstNonZero - 1;
|
|
170
|
+
else while (x + 1 < width && u32[pixelRow + x + 1] >>> 24 === coverage) x++;
|
|
171
|
+
const isZero = coverage === 0;
|
|
172
|
+
if (isZero && x === width - 1) lastNonZero = a - 1;
|
|
173
|
+
const sign = isZero ? 1 : -1;
|
|
174
|
+
const lCov = a > 0 ? u32[pixelRow + a - 1] >>> 24 : -1;
|
|
175
|
+
const rCov = x + 1 < width ? u32[pixelRow + x + 1] >>> 24 : -1;
|
|
176
|
+
const lSc = lCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[lCov];
|
|
177
|
+
const rSc = rCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[rCov];
|
|
178
|
+
const lCost = lSc > 0 ? lSc : 0;
|
|
179
|
+
const rCost = rSc > 0 ? rSc : 0;
|
|
180
|
+
const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : a + x - (rCost < lCost ? 1 : 0) >> 1;
|
|
181
|
+
const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1;
|
|
182
|
+
const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1;
|
|
183
|
+
for (let p = a, d = 1; p <= lEnd; p++, d++) distances[distRow + p] = sign * (d * d + lCost);
|
|
184
|
+
if (lEnd + 1 < rStart) {
|
|
185
|
+
const far = sign * FAR_DISTANCE_SQUARED;
|
|
186
|
+
if (rStart - lEnd <= 17) for (let p = lEnd + 1; p < rStart; p++) distances[distRow + p] = far;
|
|
187
|
+
else distances.fill(far, distRow + lEnd + 1, distRow + rStart);
|
|
188
|
+
}
|
|
189
|
+
for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) distances[distRow + p] = sign * (d * d + rCost);
|
|
190
|
+
} else distances[distRow + x] = SEED_COST[coverage];
|
|
191
|
+
}
|
|
192
|
+
return lastNonZero;
|
|
193
|
+
}
|
|
194
|
+
function horizontalRgbaRowDistances(rgba, rgbaRowBase, distances, distRow, width, firstNonZero, maxRadius) {
|
|
195
|
+
let lastNonZero = width - 1;
|
|
196
|
+
for (let x = 0; x < width; x++) {
|
|
197
|
+
const coverage = rgba[rgbaRowBase + (x << 2) + 3];
|
|
198
|
+
if (coverage === 0 || coverage === 255) {
|
|
199
|
+
const a = x;
|
|
200
|
+
if (x === 0 && firstNonZero > 0) x = firstNonZero - 1;
|
|
201
|
+
else while (x + 1 < width && rgba[rgbaRowBase + (x + 1 << 2) + 3] === coverage) x++;
|
|
202
|
+
const isZero = coverage === 0;
|
|
203
|
+
if (isZero && x === width - 1) lastNonZero = a - 1;
|
|
204
|
+
const sign = isZero ? 1 : -1;
|
|
205
|
+
const lCov = a > 0 ? rgba[rgbaRowBase + (a - 1 << 2) + 3] : -1;
|
|
206
|
+
const rCov = x + 1 < width ? rgba[rgbaRowBase + (x + 1 << 2) + 3] : -1;
|
|
207
|
+
const lSc = lCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[lCov];
|
|
208
|
+
const rSc = rCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[rCov];
|
|
209
|
+
const lCost = lSc > 0 ? lSc : 0;
|
|
210
|
+
const rCost = rSc > 0 ? rSc : 0;
|
|
211
|
+
const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : a + x - (rCost < lCost ? 1 : 0) >> 1;
|
|
212
|
+
const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1;
|
|
213
|
+
const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1;
|
|
214
|
+
for (let p = a, d = 1; p <= lEnd; p++, d++) distances[distRow + p] = sign * (d * d + lCost);
|
|
215
|
+
if (lEnd + 1 < rStart) {
|
|
216
|
+
const far = sign * FAR_DISTANCE_SQUARED;
|
|
217
|
+
if (rStart - lEnd <= 17) for (let p = lEnd + 1; p < rStart; p++) distances[distRow + p] = far;
|
|
218
|
+
else distances.fill(far, distRow + lEnd + 1, distRow + rStart);
|
|
219
|
+
}
|
|
220
|
+
for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) distances[distRow + p] = sign * (d * d + rCost);
|
|
221
|
+
} else distances[distRow + x] = SEED_COST[coverage];
|
|
222
|
+
}
|
|
223
|
+
return lastNonZero;
|
|
224
|
+
}
|
|
225
|
+
function encodeSdf(pixels, width, height, pxRange, stride) {
|
|
226
|
+
const pixelCount = assertInputs(pixels, width, height, pxRange, stride, stride === 1 ? "encodeSdfFromAlpha" : "encodeSdfFromRgba");
|
|
227
|
+
const isRgba = stride === 4;
|
|
171
228
|
const encoded = new Uint8Array(pixelCount);
|
|
172
229
|
const scale255 = 255 / pxRange;
|
|
173
230
|
const clampSqDist = .25 * pxRange * pxRange * (1 + 1e-6);
|
|
@@ -193,7 +250,7 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
193
250
|
inside.fill(sentinel, 0, height);
|
|
194
251
|
outside.fill(0, 0, height);
|
|
195
252
|
const lastRow = height - 1;
|
|
196
|
-
const u32 = (
|
|
253
|
+
const u32 = (!isRgba || LITTLE_ENDIAN) && (pixels.byteOffset & 3) === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, pixels.byteLength >>> 2) : null;
|
|
197
254
|
let anyNonZero = false;
|
|
198
255
|
let scanY = 0;
|
|
199
256
|
while (scanY < height) {
|
|
@@ -202,16 +259,35 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
202
259
|
let bandMaxX = -1;
|
|
203
260
|
let lastActiveY = -1;
|
|
204
261
|
for (; scanY < height; scanY++) {
|
|
205
|
-
const
|
|
262
|
+
const pixelRow = scanY * width;
|
|
206
263
|
let firstNonZero = 0;
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
264
|
+
let lastNonZero = -1;
|
|
265
|
+
if (!isRgba) {
|
|
266
|
+
if (u32 !== null && (pixelRow & 3) === 0) {
|
|
267
|
+
const wStart = pixelRow >>> 2;
|
|
268
|
+
const wEnd = wStart + (width >>> 2);
|
|
269
|
+
let w = wStart;
|
|
270
|
+
while (w < wEnd && u32[w] === 0) w++;
|
|
271
|
+
firstNonZero = w - wStart << 2;
|
|
272
|
+
}
|
|
273
|
+
while (firstNonZero < width && pixels[pixelRow + firstNonZero] === 0) firstNonZero++;
|
|
274
|
+
if (firstNonZero < width) {
|
|
275
|
+
anyNonZero = true;
|
|
276
|
+
lastNonZero = horizontalRowDistances(pixels, pixelRow, distances, bandCount * distStride, width, firstNonZero, maxRadius);
|
|
277
|
+
}
|
|
278
|
+
} else {
|
|
279
|
+
const rgbaRowBase = pixelRow << 2;
|
|
280
|
+
if (u32 !== null) {
|
|
281
|
+
const pEnd = pixelRow + width;
|
|
282
|
+
let p = pixelRow;
|
|
283
|
+
while (p < pEnd && u32[p] >>> 24 === 0) p++;
|
|
284
|
+
firstNonZero = p - pixelRow;
|
|
285
|
+
} else while (firstNonZero < width && pixels[rgbaRowBase + (firstNonZero << 2) + 3] === 0) firstNonZero++;
|
|
286
|
+
if (firstNonZero < width) {
|
|
287
|
+
anyNonZero = true;
|
|
288
|
+
lastNonZero = u32 !== null ? horizontalRgbaRowDistancesU32(u32, pixelRow, distances, bandCount * distStride, width, firstNonZero, maxRadius) : horizontalRgbaRowDistances(pixels, rgbaRowBase, distances, bandCount * distStride, width, firstNonZero, maxRadius);
|
|
289
|
+
}
|
|
213
290
|
}
|
|
214
|
-
while (firstNonZero < width && alpha[alphaRow + firstNonZero] === 0) firstNonZero++;
|
|
215
291
|
if (firstNonZero === width) {
|
|
216
292
|
if (!skipEmptyRows) {
|
|
217
293
|
const distRow = bandCount * distStride;
|
|
@@ -224,8 +300,6 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
224
300
|
}
|
|
225
301
|
continue;
|
|
226
302
|
}
|
|
227
|
-
anyNonZero = true;
|
|
228
|
-
const lastNonZero = horizontalRowDistances(alpha, alphaRow, distances, bandCount * distStride, width, firstNonZero, maxRadius);
|
|
229
303
|
activeRows[bandCount++] = scanY;
|
|
230
304
|
lastActiveY = scanY;
|
|
231
305
|
if (firstNonZero < bandMinX) bandMinX = firstNonZero;
|
|
@@ -240,6 +314,7 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
240
314
|
return encoded;
|
|
241
315
|
}
|
|
242
316
|
const firstActiveY = activeRows[0];
|
|
317
|
+
const contiguousBand = lastActiveY - firstActiveY === bandCount - 1;
|
|
243
318
|
const bandMinY = skipEmptyRows ? firstActiveY > maxRadius ? firstActiveY - maxRadius : 0 : 0;
|
|
244
319
|
const bandMaxY = skipEmptyRows ? lastActiveY + maxRadius < lastRow ? lastActiveY + maxRadius : lastRow : lastRow;
|
|
245
320
|
const bandHeight = bandMaxY - bandMinY + 1;
|
|
@@ -253,12 +328,26 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
253
328
|
offset += distStride;
|
|
254
329
|
}
|
|
255
330
|
if (r === bandCount) continue;
|
|
256
|
-
const firstInSeed = activeRows[r];
|
|
331
|
+
const firstInSeed = contiguousBand ? firstActiveY + r : activeRows[r];
|
|
257
332
|
let lastInSeed = firstInSeed;
|
|
258
333
|
let firstNeg = -1;
|
|
259
334
|
let lastNeg = -1;
|
|
260
335
|
let negCount = 0;
|
|
261
|
-
for (; r < bandCount; r++, offset += distStride) {
|
|
336
|
+
if (contiguousBand) for (; r < bandCount; r++, offset += distStride) {
|
|
337
|
+
const distance = distances[offset];
|
|
338
|
+
if (distance >= clampSqDist) continue;
|
|
339
|
+
const y = firstActiveY + r;
|
|
340
|
+
lastInSeed = y;
|
|
341
|
+
if (distance >= 0) inside[y] = distance;
|
|
342
|
+
else {
|
|
343
|
+
inside[y] = 0;
|
|
344
|
+
outside[y] = -distance;
|
|
345
|
+
if (firstNeg < 0) firstNeg = y;
|
|
346
|
+
lastNeg = y;
|
|
347
|
+
negCount++;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
else for (; r < bandCount; r++, offset += distStride) {
|
|
262
351
|
const distance = distances[offset];
|
|
263
352
|
if (distance >= clampSqDist) continue;
|
|
264
353
|
const y = activeRows[r];
|
|
@@ -272,10 +361,9 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
272
361
|
negCount++;
|
|
273
362
|
}
|
|
274
363
|
}
|
|
275
|
-
const hasPositive = negCount < bandHeight;
|
|
276
364
|
let yStart = bandMinY;
|
|
277
365
|
let yEnd = bandMaxY;
|
|
278
|
-
if (
|
|
366
|
+
if (negCount < bandHeight) {
|
|
279
367
|
edt1d(inside, firstInSeed, lastInSeed, bandMinY, bandMaxY, clampSqDist, maxRadius);
|
|
280
368
|
yStart = edtMinOut;
|
|
281
369
|
yEnd = edtMaxOut;
|
|
@@ -302,14 +390,40 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
302
390
|
const inSq = inside[y];
|
|
303
391
|
if (inSq < clampSqDist) encoded[idx] = 128 - Math.sqrt(inSq) * scale255 | 0;
|
|
304
392
|
}
|
|
305
|
-
|
|
393
|
+
if (lastNeg - firstNeg < 16) for (let c = firstNeg; c <= lastNeg; c++) outside[c] = 0;
|
|
394
|
+
else outside.fill(0, firstNeg, lastNeg + 1);
|
|
306
395
|
}
|
|
307
|
-
|
|
396
|
+
if (yEnd - yStart < 16) for (let c = yStart; c <= yEnd; c++) inside[c] = sentinel;
|
|
397
|
+
else inside.fill(sentinel, yStart, yEnd + 1);
|
|
308
398
|
}
|
|
309
399
|
}
|
|
310
400
|
if (scratchDistances.length > 45e5) scratchDistances = /* @__PURE__ */ new Float32Array(0);
|
|
311
401
|
return encoded;
|
|
312
402
|
}
|
|
313
|
-
|
|
403
|
+
/**
|
|
404
|
+
* Encode an alpha coverage mask as a single-channel signed distance field.
|
|
405
|
+
*
|
|
406
|
+
* The returned byte uses the conventional SDF encoding:
|
|
407
|
+
*
|
|
408
|
+
* - the edge is 0.5 (the nearest byte representation is 128),
|
|
409
|
+
* - inside pixels are greater than 0.5,
|
|
410
|
+
* - outside pixels are less than 0.5,
|
|
411
|
+
* - `pxRange` pixels of signed distance span one encoded unit.
|
|
412
|
+
*
|
|
413
|
+
* Fractional source alpha is retained as a sub-pixel seed cost rather than
|
|
414
|
+
* thresholded away. The two exact Euclidean distance transforms are O(width *
|
|
415
|
+
* height); temporary storage is one grid plus O(height) scratch.
|
|
416
|
+
*/
|
|
417
|
+
function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
418
|
+
return encodeSdf(alpha, width, height, pxRange, 1);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* @internal Equivalent to `encodeSdfFromAlpha(alphaOfRgba(rgba, width * height), ...)`,
|
|
422
|
+
* reading the alpha channel directly from packed RGBA bytes without an intermediate buffer.
|
|
423
|
+
*/
|
|
424
|
+
function encodeSdfFromRgba(rgba, width, height, pxRange) {
|
|
425
|
+
return encodeSdf(rgba, width, height, pxRange, 4);
|
|
426
|
+
}
|
|
427
|
+
export { alphaOfRgba, encodeSdfFromAlpha, encodeSdfFromRgba };
|
|
314
428
|
|
|
315
429
|
//# sourceMappingURL=cpuSdf.js.map
|