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 +1 @@
1
- {"version":3,"file":"GlyphTextMaterial.js","names":[],"sources":["../../src/text/GlyphTextMaterial.ts"],"sourcesContent":["import {\n DoubleSide,\n FrontSide,\n Material,\n MeshBasicNodeMaterial,\n Node,\n SRGBColorSpace,\n type NodeBuilder,\n type Side,\n type UniformNode,\n} from 'three/webgpu'\nimport {\n Fn,\n attribute,\n bool,\n clamp,\n colorSpaceToWorking,\n cos,\n float,\n instanceIndex,\n int,\n luminance,\n max,\n min,\n mix,\n mod,\n positionGeometry,\n sin,\n time,\n uniform,\n varying,\n varyingProperty,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl'\n\nimport type {\n SdfAnimationMode,\n SdfMotionOptions,\n TextFill,\n TextToneOptions,\n TextVertex,\n} from '../types.js'\nimport { resolveTextTone, TextTone, type ResolvedTextTone } from './tone.js'\n\n/** Shared construction options for the retained SDF and Windfoil text materials. */\nexport interface GlyphTextMaterialOptions {\n /** Match a snapshot captured with browser shaping; enables shared run motion. */\n textShaping?: 'none' | 'browser'\n /** Share motion centres and ordinals supplied by geometry. */\n runMotion?: boolean\n /** Custom linear-color TSL fill; opacity is multiplied by glyph coverage and DOM opacity. */\n fill?: TextFill | undefined\n /** Custom TSL vertex position in capture-local coordinates. */\n vertex?: TextVertex | undefined\n /** Face culling side. Defaults to `FrontSide`. */\n side?: Side | undefined\n /**\n * Initial motion state; adjustable later through `setMotion()`. `false` builds static text:\n * the vertex stage has no motion graph (no clock, waves or slide timeline) and the fragment\n * no motion alpha, `animated` is false, and `setMotion()` throws. Draws like motion with\n * mode `'none'`.\n */\n motion?: SdfMotionOptions | false\n /** Largest per-line stagger index in the geometry. Defaults to `0`. */\n maxSequence?: number\n /**\n * Shows text ink at the weight a browser gives it; see `TextToneOptions`. There is no\n * source element here: an `'auto'` model is the exact outline, and an `'auto'` backdrop is\n * unknown, which tones dark ink against white and keeps light ink at its exact coverage\n * whatever the model. Name the `backdrop` colour the scene shows behind the text for the\n * full conversion. `false` leaves the conversion out of the shader graph. Defaults to on.\n */\n tone?: TextToneOptions | ResolvedTextTone | false\n /**\n * @internal Size switch. Decides from per-instance data and per-pass uniforms only, so a\n * quad's four vertices agree; `false` collapses the quad onto its motion anchor, which\n * rasterizes nothing in beauty or shadow passes. Requires `sdfMeta` as\n * (sequence, depth, switch em).\n */\n keepGlyph?: GlyphKeepHook\n}\n\nexport type GlyphMotionSource =\n Node<'float'> | { readonly index: Node<'float'>; readonly center: Node<'vec2'> }\n\nexport type GlyphVertexExtension = (\n quad: Node<'vec2'>,\n rect: Node<'vec4'>,\n position: Node<'vec2'>,\n depth: Node<'float'>,\n motionScale: Node<'float'>,\n fillUv: Node<'vec2'> | null,\n // A coverage backend may only attach varyings and intentionally return nothing.\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n) => Node<'vec2'> | void\n\n/** Per-glyph keep test for the size switch; see `GlyphTextMaterialOptions.keepGlyph`. */\nexport type GlyphKeepHook = (anchor: Node<'vec2'>, meta: Node<'vec3'>) => Node<'bool'>\n\n/** @internal Fragment paint hook, evaluated before the caller's custom fill. */\nexport type GlyphPaintExtension = (cssColor: Node<'vec3'>) => {\n readonly rgb: Node<'vec3'>\n readonly weight: Node<'float'>\n}\n\nconst MODE_CODES: Readonly<Record<SdfAnimationMode, number>> = Object.freeze({\n none: 0,\n opacity: 1,\n scale: 2,\n offset: 3,\n 'slide-up': 4,\n 'slide-down': 5,\n 'slide-left': 6,\n 'slide-right': 7,\n all: 8,\n})\n\n/** @internal Whether this motion state needs the motion graph: any mode but `'none'`. */\nexport function isAnimatedMotion(motion: SdfMotionOptions | false | undefined): boolean {\n return motion !== false && motion?.mode !== 'none'\n}\n\n/** Convert normalized DOM sRGB attributes into Three's working colour space. */\nexport function srgbAttributeToWorking(node: Node<'vec3'>): Node<'vec3'> {\n // ColorSpaceNode reports vec4 in r185, so truncate with a real conversion.\n return vec3(colorSpaceToWorking(node, SRGBColorSpace) as unknown as Node<'vec3'>)\n}\n\nclass PassNode extends Node {\n static readonly type: string = 'UltraTextPassNode'\n\n constructor(\n readonly beautyNode: Node,\n readonly shadowNode: Node,\n ) {\n super()\n }\n\n // generateNodeType, not getNodeType: three caches the result per builder.\n override generateNodeType(builder: NodeBuilder): string {\n return this.beautyNode.getNodeType(builder)\n }\n\n override setup(builder: NodeBuilder): Node {\n return (builder.material as { isShadowPassMaterial?: boolean }).isShadowPassMaterial\n ? this.shadowNode\n : this.beautyNode\n }\n}\n\n/** `beauty`, giving way to `shadow` in the pass three derives for a shadow map. */\nexport function outsideShadowPass<T extends Node>(beauty: T, shadow: T): T {\n return new PassNode(beauty, shadow) as Node as T\n}\n\nclass WireframeNode extends PassNode {\n static override readonly type = 'UltraTextWireframeNode'\n\n override setup(builder: NodeBuilder): Node {\n const m = builder.material as { wireframe?: boolean; isShadowPassMaterial?: boolean }\n return m.wireframe === true && !m.isShadowPassMaterial ? this.shadowNode : this.beautyNode\n }\n}\n\nconst WIREFRAME_LINE_LUMINANCE = 0.4\n\n/** `solid`, giving way to `lines` when the material draws wireframe. */\nfunction outsideWireframe<T extends Node>(solid: T, lines: T): T {\n return new WireframeNode(solid, lines) as Node as T\n}\n\n/**\n * Shared retained-glyph vertex, motion, clipping, colour, and shadow plumbing.\n *\n * The two text backends differ only in how they produce coverage. Keeping the\n * rest in one graph makes switching backend preserve layout and animation\n * semantics, and avoids shipping the motion graph twice.\n */\nexport class GlyphTextMaterial extends MeshBasicNodeMaterial {\n readonly motionEnabled: UniformNode<'float', number> = uniform(1)\n readonly motionMode: UniformNode<'int', number> = uniform(MODE_CODES['slide-up'], 'int')\n readonly motionStrength: UniformNode<'float', number> = uniform(18)\n readonly motionSpeed: UniformNode<'float', number> = uniform(1.35)\n readonly motionStagger: UniformNode<'float', number> = uniform(0.045)\n readonly maxSequence: UniformNode<'float', number> = uniform(0)\n /** Uniforms of the tone conversion; null when the material was built with `tone: false`. */\n readonly tone: TextTone | null\n /**\n * False for static text, built with `motion: false`: its shader has no motion graph, its\n * motion uniforms read as disabled, and `setMotion()` throws.\n */\n readonly animated: boolean\n\n protected readonly colorVarying = varyingProperty('vec4', 'vUltraTextColor')\n protected readonly insideClip: Node<'bool'>\n protected readonly fillNode: Node<'vec4'> | null\n protected readonly baseColor: Node<'vec3'>\n protected readonly colorWeight: Node<'float'>\n\n #av = varyingProperty('float', 'vUltraTextMotionAlpha')\n #gt: Node<'vec3'> | null\n #rm: (motion?: SdfMotionOptions) => this\n\n constructor(\n options: GlyphTextMaterialOptions,\n extendVertex?: GlyphVertexExtension,\n motionIndex?: GlyphMotionSource,\n paint?: GlyphPaintExtension,\n ) {\n super()\n this.#rm = (motion) =>\n new (\n this.constructor as new (\n remakeOptions: GlyphTextMaterialOptions,\n remakeExtension?: GlyphVertexExtension,\n remakeIndex?: GlyphMotionSource,\n remakePaint?: GlyphPaintExtension,\n ) => this\n )(motion ? { ...options, motion } : options, extendVertex, motionIndex, paint)\n const animated = (this.animated = options.motion !== false)\n this.lights = false\n this.transparent = true\n this.depthWrite = false\n this.depthTest = true\n this.side = options.side ?? FrontSide\n this.shadowSide = this.side\n this.forceSinglePass = this.side === DoubleSide\n this.toneMapped = false\n this.maxSequence.value = options.maxSequence ?? 0\n const tone = resolveTextTone(options.tone)\n this.tone = tone && new TextTone(tone)\n\n const localVarying = varyingProperty('vec2', 'vUltraTextLocal')\n const clipVarying = varyingProperty('vec4', 'vUltraTextClip')\n const glyphRect = attribute<'vec4'>('sdfRect', 'vec4')\n const glyphClip = attribute<'vec4'>('sdfClip', 'vec4')\n const glyphColor = attribute<'vec4'>('sdfColor', 'vec4')\n this.#gt =\n this.tone &&\n varying(\n this.tone.inkTerms(srgbAttributeToWorking(vec3(glyphColor.rgb))),\n 'vUltraTextTone',\n ).setInterpolation('flat', 'either')\n // Sequence and depth are the only per-glyph metadata. The compacted draw's\n // global index is already supplied by the GPU, including after blank glyphs.\n const keepGlyph = options.keepGlyph\n const glyphMeta = keepGlyph\n ? attribute<'vec3'>('sdfMeta', 'vec3')\n : attribute<'vec2'>('sdfMeta', 'vec2')\n const runMotion =\n (options.runMotion ?? options.textShaping === 'browser')\n ? attribute<'vec3'>('sdfRunMotion', 'vec3')\n : null\n const source = motionIndex && 'index' in motionIndex ? motionIndex : null\n const indexSource = source?.index ?? (motionIndex as Node<'float'> | undefined)\n const fillUv = options.fill ? varyingProperty('vec2', 'vUltraFillUv') : null\n // Switched batches share global ordinals, so glyphIndex stays continuous across a switch.\n // Fills truncate it to read per-glyph data. Interpolated, an instance's constant can arrive\n // a hair under itself (Safari's relaxed math on Apple GPUs) and read the previous glyph's\n // entry: flat keeps it exact.\n const fillIndex = options.fill\n ? varying(\n (keepGlyph ? (runMotion?.z ?? source?.index) : source?.index) ?? float(instanceIndex),\n 'vUltraFillIndex',\n ).setInterpolation('flat', 'either')\n : null\n\n // The anchor motion scales about, and the size switch's anchor.\n const motionCenter = (): Node<'vec2'> =>\n (runMotion?.xy ?? source?.center ?? glyphRect.xy.add(glyphRect.zw).mul(0.5)).toConst()\n const basePositionOf = (quad: Node<'vec2'>): Node<'vec2'> =>\n glyphRect.xy.add(glyphRect.zw.sub(glyphRect.xy).mul(quad)).toConst()\n // What both graphs do with the moved position: the backend's extension, the size switch\n // and the shared varyings. Returns the drawn position.\n const finishVertex = (\n quad: Node<'vec2'>,\n center: Node<'vec2'> | null,\n position: Node<'vec2'>,\n motionScale: Node<'float'>,\n glyphIndex?: Node<'float'>,\n ): Node<'vec3'> => {\n const uv = fillUv ?? (options.vertex ? vec2(quad).toVar() : null)\n const extendedPosition =\n extendVertex?.(quad, glyphRect, position, glyphMeta.y, motionScale, uv) ?? position\n // The un-animated anchor and the unscaled em decide, so motion never moves a glyph\n // between the two batches of a size switch.\n const keep = center && keepGlyph?.(center, glyphMeta as unknown as Node<'vec3'>)\n const drawnPosition = keep\n ? vec2(keep.select(extendedPosition, center)).toConst()\n : extendedPosition\n localVarying.assign(drawnPosition)\n this.colorVarying.assign(vec4(srgbAttributeToWorking(vec3(glyphColor.rgb)), glyphColor.a))\n clipVarying.assign(glyphClip)\n const localPosition = vec3(drawnPosition, glyphMeta.y)\n if (!options.vertex) return localPosition\n const displaced = options.vertex({\n position: localPosition,\n center: center!,\n uv: uv!,\n glyphIndex: glyphIndex ?? (runMotion?.z ?? indexSource ?? float(instanceIndex)).toConst(),\n sequence: glyphMeta.x,\n rect: glyphRect,\n clip: glyphClip,\n })\n return keep ? vec3(keep.select(displaced, vec3(center, glyphMeta.y))) : displaced\n }\n\n // Static text: the motion graph's disabled branch alone, without its clock, waves and\n // slide timeline. Only the size switch or a custom vertex hook reads the anchor.\n const staticPosition = (): Node<'vec3'> => {\n const quad = positionGeometry.xy\n fillUv?.assign(quad)\n const center = keepGlyph || options.vertex ? motionCenter() : null\n return finishVertex(quad, center, basePositionOf(quad), float(1))\n }\n // Reused expressions need shader locals as well as shared JavaScript nodes;\n // otherwise the motion/clip expressions expand repeatedly in generated WGSL.\n // Immutable intermediates use toConst(); only the accumulated position mutates.\n const animatedPosition = (): Node<'vec3'> => {\n const quad = positionGeometry.xy\n fillUv?.assign(quad)\n const center = motionCenter()\n const basePosition = basePositionOf(quad)\n const sequence = glyphMeta.x\n const glyphIndex = (runMotion?.z ?? indexSource ?? float(instanceIndex)).toConst()\n const clock = time.mul(this.motionSpeed).toConst()\n const wave = sin(\n clock.mul(Math.PI * 2).sub(glyphIndex.mul(this.motionStagger).mul(Math.PI * 2)),\n )\n const pulse = wave.mul(0.5).add(0.5).toConst()\n\n const mode = (code: number) => int(this.motionMode).equal(code)\n const isOpacity = mode(MODE_CODES.opacity)\n const isScale = mode(MODE_CODES.scale)\n const isOffset = mode(MODE_CODES.offset)\n const isSlideUp = mode(MODE_CODES['slide-up'])\n const isSlideDown = mode(MODE_CODES['slide-down'])\n const isSlideLeft = mode(MODE_CODES['slide-left'])\n const isSlideRight = mode(MODE_CODES['slide-right'])\n const isAll = mode(MODE_CODES.all).toConst()\n\n const scale = isScale\n .select(\n float(0.86).add(pulse.mul(0.22)),\n isAll.select(float(0.94).add(pulse.mul(0.08)), float(1)),\n )\n .toConst()\n const animated = vec2(center.add(basePosition.sub(center).mul(scale))).toVar()\n const offsetX = sin(clock.mul(3.1).add(glyphIndex.mul(0.55)))\n .mul(this.motionStrength)\n .mul(0.32)\n const offsetY = cos(clock.mul(2.7).add(glyphIndex.mul(0.45)))\n .mul(this.motionStrength)\n .mul(0.18)\n animated.x.addAssign(isOffset.select(offsetX, 0))\n animated.y.addAssign(\n isOffset.select(\n offsetY,\n isAll.select(\n sin(clock.mul(2.5).add(glyphIndex.mul(0.35)))\n .mul(this.motionStrength)\n .mul(0.16),\n 0,\n ),\n ),\n )\n\n const enterDuration = 0.58\n const holdDuration = 1.15\n const exitDuration = 0.24\n const sequenceSpan = this.maxSequence.mul(this.motionStagger).toConst()\n const cycle = max(\n sequenceSpan.add(enterDuration + holdDuration + exitDuration),\n 0.001,\n ).toConst()\n const slidePhase = mod(clock, cycle).toConst()\n const localPhase = slidePhase.sub(sequence.mul(this.motionStagger)).toConst()\n const enterT = clamp(localPhase.div(enterDuration), 0, 1)\n const inverseEnter = float(1).sub(enterT).toConst()\n const easeOut = float(1).sub(inverseEnter.mul(inverseEnter).mul(inverseEnter))\n const exitStart = sequenceSpan.add(enterDuration + holdDuration).toConst()\n const exitT = clamp(slidePhase.sub(exitStart).div(exitDuration), 0, 1).toConst()\n const travelRatio = localPhase\n .lessThan(0)\n .select(\n float(1),\n localPhase\n .lessThan(enterDuration)\n .select(\n float(1).sub(easeOut),\n slidePhase.lessThan(exitStart).select(float(0), exitT.mul(exitT).mul(exitT).negate()),\n ),\n )\n .toConst()\n const clipSize = glyphClip.zw.sub(glyphClip.xy).toConst()\n const verticalTravel = max(this.motionStrength, clipSize.y.mul(1.18))\n .mul(travelRatio)\n .toConst()\n const horizontalTravel = max(this.motionStrength, clipSize.x.mul(1.18))\n .mul(travelRatio)\n .toConst()\n animated.x.addAssign(\n isSlideLeft.select(horizontalTravel, isSlideRight.select(horizontalTravel.negate(), 0)),\n )\n animated.y.addAssign(\n isSlideUp.select(verticalTravel.negate(), isSlideDown.select(verticalTravel, 0)),\n )\n\n const animationEnabled = this.motionEnabled\n .greaterThan(0.5)\n .and(int(this.motionMode).notEqual(MODE_CODES.none))\n .toConst()\n const finalPosition = vec2(animationEnabled.select(animated, basePosition)).toConst()\n const animatedAlpha = isOpacity.select(\n float(0.25).add(pulse.mul(0.75)),\n isAll.select(float(0.55).add(pulse.mul(0.45)), float(1)),\n )\n\n const motionScale = animationEnabled.select(scale, 1)\n const drawnPosition = finishVertex(quad, center, finalPosition, motionScale, glyphIndex)\n this.#av.assign(animationEnabled.select(animatedAlpha, 1))\n return drawnPosition\n }\n const positionNode = Fn<Node<'vec3'>>(animated ? animatedPosition : staticPosition)()\n this.positionNode = positionNode\n this.castShadowPositionNode = positionNode\n const painted = paint?.(this.colorVarying.rgb)\n this.baseColor = painted?.rgb ?? this.colorVarying.rgb\n this.colorWeight = painted?.weight ?? float(0)\n this.fillNode =\n options.fill && fillUv && fillIndex\n ? options.fill({\n uv: fillUv,\n position: localVarying,\n color: this.baseColor,\n colorWeight: this.colorWeight,\n glyphIndex: fillIndex,\n })\n : null\n\n // A quad's padding reaches past its block, so the clip would cut its wireframe's edges.\n this.insideClip = outsideWireframe(\n localVarying.x\n .greaterThanEqual(clipVarying.x)\n .and(localVarying.y.greaterThanEqual(clipVarying.y))\n .and(localVarying.x.lessThanEqual(clipVarying.z))\n .and(localVarying.y.lessThanEqual(clipVarying.w)),\n bool(true),\n )\n if (options.motion !== false) this.setMotion(options.motion ?? {})\n else {\n // What a caller reads off a static material: motion disabled, mode none.\n this.motionEnabled.value = 0\n this.motionMode.value = MODE_CODES.none\n }\n }\n\n /** @internal The ink's alpha: the CSS colour's, times the motion's for animated text. */\n protected inkAlpha(): Node<'float'> {\n return this.animated ? this.colorVarying.a.mul(this.#av) : this.colorVarying.a\n }\n\n /**\n * Attach one backend's beauty and shadow coverage to the shared graph. `folded` says the\n * beauty coverage holds the factor `toned()` returns for the ink's own alpha.\n */\n protected applyCoverage(\n coverage: Node<'float'>,\n shadowCoverage: Node<'float'>,\n shadowCutoff: Node<'float'>,\n paint?: Node<'vec4'>,\n folded = false,\n ): void {\n const fill = this.fillNode\n const paintedAlpha = paint?.a ?? (fill ? coverage.mul(clamp(fill.a, 0, 1)) : coverage)\n const castCoverage = fill && !paint ? shadowCoverage.mul(clamp(fill.a, 0, 1)) : shadowCoverage\n const inked = (covered: Node<'float'>): Node<'float'> => {\n const ink = covered.mul(this.colorVarying.a)\n return this.animated ? ink.mul(this.#av) : ink\n }\n // A folded factor times the ink's alpha is the converted coverage, clamped as one.\n // Shadow passes keep the exact product.\n const alpha = (\n folded\n ? outsideShadowPass(min(1, inked(paintedAlpha)), inked(castCoverage))\n : inked(outsideShadowPass(paintedAlpha, castCoverage))\n ).toConst()\n // Wireframe lines take the ink with none of the coverage, which is zero along a quad's\n // edges. A paint's colour means nothing outside its shape, so lines keep the CSS colour,\n // lifted toward white until it reaches the line floor.\n const lineAlpha = this.inkAlpha().toConst()\n const lineInk = vec3(fill?.rgb ?? this.baseColor).toConst()\n const lineInkLuminance = luminance(lineInk).toConst()\n const lineLift = clamp(\n float(WIREFRAME_LINE_LUMINANCE)\n .sub(lineInkLuminance)\n .div(max(float(1).sub(lineInkLuminance), 1e-4)),\n 0,\n 1,\n )\n this.colorNode = outsideWireframe(\n vec4(outsideShadowPass(paint?.rgb ?? fill?.rgb ?? this.baseColor, vec3(0)), alpha),\n vec4(mix(lineInk, vec3(1), lineLift), lineAlpha),\n )\n this.maskNode = this.insideClip.and(outsideWireframe(alpha, lineAlpha).greaterThan(0.001))\n this.maskShadowNode = this.insideClip\n .and(castCoverage.greaterThan(shadowCutoff))\n .and(this.inkAlpha().greaterThan(shadowCutoff))\n }\n\n /**\n * Beauty coverage of text ink as a browser would show it, or the same node when the\n * material has no tone. The ink is the instance colour, whose terms reach the fragment\n * through one flat varying, unless a fill graph supplies the colour per fragment.\n * `tableGate` is for a model whose table stops at a size. Shadow masks, colour layers and\n * shape paint must keep the exact coverage.\n *\n * The ink's own alpha is part of the mask a browser blends: the CSS colour's alpha and\n * opacity, the motion's, a fill's. The result is the factor that `applyCoverage` multiplies\n * by that alpha, so the caller passes it `folded`. `fold` false converts as for opaque ink,\n * for a caller that composes the result with other coverages first.\n */\n protected toned(\n coverage: Node<'float'>,\n ink?: Node<'vec3'>,\n tableGate?: Node<'float'>,\n fold = true,\n ): Node<'float'> {\n const tone = this.tone\n if (!tone) return coverage\n let opacity: Node<'float'> | undefined\n if (fold) {\n opacity = this.inkAlpha()\n if (this.fillNode) opacity = opacity.mul(clamp(this.fillNode.a, 0, 1))\n }\n return tone.apply(coverage, ink ? tone.inkTerms(ink).toConst() : this.#gt!, tableGate, opacity)\n }\n\n /**\n * Follows a recaptured tone through the uniforms. False means this material was built for\n * a tone of another kind, because the conversion or a model's extra nodes would have to\n * appear or go: the caller rebuilds the material.\n */\n setTone(tone: ResolvedTextTone | null): boolean {\n const current = this.tone\n if (!current || !tone || !current.fits(tone)) return !current && !tone\n current.update(tone)\n return true\n }\n\n /**\n * Rebuilds an equivalent material from this one's original construction options.\n *\n * Three's `Material.clone()` constructs the concrete class with **no arguments** and\n * copies properties across. This graph cannot survive that: it closes over required\n * options — an atlas and its metrics on the SDF backend, outline tables on Windfoil —\n * so the argument-less twin threw before `copy()` ever ran, and three's generic node\n * property copy would hand the twin a graph still wired to the *source's* uniforms,\n * leaving its own knobs connected to nothing. {@link remake} re-runs the constructor\n * with the stored options instead, rebuilding a private graph over the same shared\n * resources (the atlas texture is shared on purpose); the loop then carries the current\n * value of every numeric uniform knob — this class's and any subclass's, discovered as\n * own properties — into the twin's own uniforms, and the classic scalar-flag copy brings\n * side, opacity, blending, visibility, wireframe and friends. The tone's uniforms live on\n * its own object, so its current values are handed over whole. The one non-numeric uniform\n * in the family, the SDF unit range, is derived from the options and already correct in\n * the twin. Hand edits made to the node graph after construction are deliberately not\n * carried, and subclasses inherit all of this untouched because each passes its own\n * options object through `super()`. A static material's clone is static.\n */\n override clone(): this {\n return this.withMotion()\n }\n\n /**\n * @internal The animated twin of a static material: rebuilt like `clone()` with the\n * motion graph and `motion`, carrying every other state. Motion knobs `motion` leaves out\n * take their defaults.\n */\n withMotion(motion?: SdfMotionOptions): this {\n const twin = this.#rm(motion)\n // The classic fixed-list scalar copy — side, opacity, blending, visibility and friends —\n // not NodeMaterial's generic property pass, which would re-wire this rebuilt graph back\n // into the source's nodes. Wireframe sits above the base list, so it rides separately.\n Material.prototype.copy.call(twin, this)\n twin.wireframe = this.wireframe\n for (const key in twin) {\n const target = twin[key as keyof this] as { isUniformNode?: boolean; value: unknown } | null\n if (\n target?.isUniformNode &&\n typeof target.value === 'number' &&\n !(motion && key.startsWith('motion'))\n ) {\n target.value = (this[key as keyof this] as { value: number }).value\n }\n }\n if (this.tone) twin.tone?.update(this.tone.resolved)\n return twin\n }\n\n /**\n * Writes the given motion fields into the uniforms; safe to call every frame. Throws on a\n * static material (`motion: false`), which has no motion graph to drive.\n */\n setMotion(options: SdfMotionOptions): this {\n if (!this.animated) throw new Error('ultra-text: setMotion() cannot run with motion: false')\n if (options.enabled !== undefined) this.motionEnabled.value = options.enabled ? 1 : 0\n if (options.mode !== undefined) this.motionMode.value = MODE_CODES[options.mode]\n if (options.strength !== undefined) this.motionStrength.value = Math.max(0, options.strength)\n if (options.speed !== undefined) this.motionSpeed.value = Math.max(0, options.speed)\n if (options.stagger !== undefined) this.motionStagger.value = Math.max(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Q,UAAU,KAAA,GAAW,KAAK,YAAY,QAAQ,KAAK,IAAI,GAAG,QAAQ,KAAK;EACnF,IAAI,QAAQ,YAAY,KAAA,GAAW,KAAK,cAAc,QAAQ,KAAK,IAAI,GAAG,QAAQ,OAAO;EACzF,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"GlyphTextMaterial.js","names":[],"sources":["../../src/text/GlyphTextMaterial.ts"],"sourcesContent":["import {\n DoubleSide,\n FrontSide,\n Material,\n MeshBasicNodeMaterial,\n Node,\n SRGBColorSpace,\n type NodeBuilder,\n type Side,\n type UniformNode,\n} from 'three/webgpu'\nimport {\n Fn,\n attribute,\n bool,\n clamp,\n colorSpaceToWorking,\n cos,\n float,\n instanceIndex,\n int,\n luminance,\n max,\n min,\n mix,\n mod,\n positionGeometry,\n sin,\n time,\n uniform,\n varying,\n varyingProperty,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl'\n\nimport type {\n SdfAnimationMode,\n SdfMotionOptions,\n TextFill,\n TextToneOptions,\n TextVertex,\n} from '../types.js'\nimport { resolveTextTone, TextTone, type ResolvedTextTone } from './tone.js'\n\n/** Shared construction options for the retained SDF and Windfoil text materials. */\nexport interface GlyphTextMaterialOptions {\n /** Match a snapshot captured with browser shaping; enables shared run motion. */\n textShaping?: 'none' | 'browser'\n /** Share motion centres and ordinals supplied by geometry. */\n runMotion?: boolean\n /** Custom linear-color TSL fill; opacity is multiplied by glyph coverage and DOM opacity. */\n fill?: TextFill | undefined\n /** Custom TSL vertex position in capture-local coordinates. */\n vertex?: TextVertex | undefined\n /** Face culling side. Defaults to `FrontSide`. */\n side?: Side | undefined\n /**\n * Initial motion state; adjustable later through `setMotion()`. `false` builds static text:\n * the vertex stage has no motion graph (no clock, waves or slide timeline) and the fragment\n * no motion alpha, `animated` is false, and `setMotion()` throws. Draws like motion with\n * mode `'none'`.\n */\n motion?: SdfMotionOptions | false\n /** Largest per-line stagger index in the geometry. Defaults to `0`. */\n maxSequence?: number\n /**\n * Shows text ink at the weight a browser gives it; see `TextToneOptions`. There is no\n * source element here: an `'auto'` model is the exact outline, and an `'auto'` backdrop is\n * unknown, which tones dark ink against white and keeps light ink at its exact coverage\n * whatever the model. Name the `backdrop` colour the scene shows behind the text for the\n * full conversion. `false` leaves the conversion out of the shader graph. Defaults to on.\n */\n tone?: TextToneOptions | ResolvedTextTone | false\n /**\n * @internal Size switch. Decides from per-instance data and per-pass uniforms only, so a\n * quad's four vertices agree; `false` collapses the quad onto its motion anchor, which\n * rasterizes nothing in beauty or shadow passes. Requires `sdfMeta` as\n * (sequence, depth, switch em).\n */\n keepGlyph?: GlyphKeepHook\n}\n\nexport type GlyphMotionSource =\n Node<'float'> | { readonly index: Node<'float'>; readonly center: Node<'vec2'> }\n\nexport type GlyphVertexExtension = (\n quad: Node<'vec2'>,\n rect: Node<'vec4'>,\n position: Node<'vec2'>,\n depth: Node<'float'>,\n motionScale: Node<'float'>,\n fillUv: Node<'vec2'> | null,\n // A coverage backend may only attach varyings and intentionally return nothing.\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n) => Node<'vec2'> | void\n\n/** Per-glyph keep test for the size switch; see `GlyphTextMaterialOptions.keepGlyph`. */\nexport type GlyphKeepHook = (anchor: Node<'vec2'>, meta: Node<'vec3'>) => Node<'bool'>\n\n/** @internal Fragment paint hook, evaluated before the caller's custom fill. */\nexport type GlyphPaintExtension = (cssColor: Node<'vec3'>) => {\n readonly rgb: Node<'vec3'>\n readonly weight: Node<'float'>\n}\n\nconst MODE_CODES: Readonly<Record<SdfAnimationMode, number>> = Object.freeze({\n none: 0,\n opacity: 1,\n scale: 2,\n offset: 3,\n 'slide-up': 4,\n 'slide-down': 5,\n 'slide-left': 6,\n 'slide-right': 7,\n all: 8,\n})\n\n/** @internal Whether this motion state needs the motion graph: any mode but `'none'`. */\nexport function isAnimatedMotion(motion: SdfMotionOptions | false | undefined): boolean {\n return motion !== false && motion?.mode !== 'none'\n}\n\n/** Convert normalized DOM sRGB attributes into Three's working colour space. */\nexport function srgbAttributeToWorking(node: Node<'vec3'>): Node<'vec3'> {\n // ColorSpaceNode reports vec4 in r185, so truncate with a real conversion.\n return vec3(colorSpaceToWorking(node, SRGBColorSpace) as unknown as Node<'vec3'>)\n}\n\nclass PassNode extends Node {\n static readonly type: string = 'UltraTextPassNode'\n\n constructor(\n readonly beautyNode: Node,\n readonly shadowNode: Node,\n ) {\n super()\n }\n\n // generateNodeType, not getNodeType: three caches the result per builder.\n override generateNodeType(builder: NodeBuilder): string {\n return this.beautyNode.getNodeType(builder)\n }\n\n override setup(builder: NodeBuilder): Node {\n return (builder.material as { isShadowPassMaterial?: boolean }).isShadowPassMaterial\n ? this.shadowNode\n : this.beautyNode\n }\n}\n\n/** `beauty`, giving way to `shadow` in the pass three derives for a shadow map. */\nexport function outsideShadowPass<T extends Node>(beauty: T, shadow: T): T {\n return new PassNode(beauty, shadow) as Node as T\n}\n\nclass WireframeNode extends Node {\n static readonly type = 'UltraTextWireframeNode'\n readonly #s: Node\n readonly #ml: () => Node\n #l: Node | null = null\n\n constructor(solid: Node, makeLines: () => Node) {\n super()\n this.#s = solid\n this.#ml = makeLines\n }\n\n override generateNodeType(builder: NodeBuilder): string {\n return this.#s.getNodeType(builder)\n }\n\n override setup(builder: NodeBuilder): Node {\n const m = builder.material as { wireframe?: boolean; isShadowPassMaterial?: boolean }\n return m.wireframe === true && !m.isShadowPassMaterial ? (this.#l ??= this.#ml()) : this.#s\n }\n\n override getChildren(): Node[] {\n return this.#l ? [this.#s, this.#l] : [this.#s]\n }\n}\n\nconst WIREFRAME_LINE_LUMINANCE = 0.4\n\n/** `solid`, giving way to `lines` when the material draws wireframe. */\nfunction outsideWireframe<T extends Node>(solid: T, makeLines: () => T): T {\n return new WireframeNode(solid, makeLines) as Node as T\n}\n\n/**\n * Shared retained-glyph vertex, motion, clipping, colour, and shadow plumbing.\n *\n * The two text backends differ only in how they produce coverage. Keeping the\n * rest in one graph makes switching backend preserve layout and animation\n * semantics, and avoids shipping the motion graph twice.\n */\nexport class GlyphTextMaterial extends MeshBasicNodeMaterial {\n /** Uniforms of the tone conversion; null when the material was built with `tone: false`. */\n readonly tone: TextTone | null\n /**\n * False for static text, built with `motion: false`: its shader has no motion graph, its\n * motion uniforms read as disabled, and `setMotion()` throws.\n */\n readonly animated: boolean\n\n #me: UniformNode<'float', number> | null\n #mm: UniformNode<'int', number> | null\n #mstr: UniformNode<'float', number> | null\n #mspd: UniformNode<'float', number> | null\n #mstg: UniformNode<'float', number> | null\n readonly #maxSeq: UniformNode<'float', number> = uniform(0)\n readonly #cv: Node<'vec4'>\n readonly #ic: Node<'bool'>\n readonly #fn: Node<'vec4'> | null\n readonly #bc: Node<'vec3'>\n readonly #cw: Node<'float'>\n #av = varyingProperty('float', 'vUltraTextMotionAlpha')\n #gt: Node<'vec3'> | null\n #rm: (motion?: SdfMotionOptions) => this\n\n get motionEnabled(): UniformNode<'float', number> {\n return (this.#me ??= uniform(0))\n }\n get motionMode(): UniformNode<'int', number> {\n return (this.#mm ??= uniform(MODE_CODES.none, 'int'))\n }\n get motionStrength(): UniformNode<'float', number> {\n return (this.#mstr ??= uniform(18))\n }\n get motionSpeed(): UniformNode<'float', number> {\n return (this.#mspd ??= uniform(1.35))\n }\n get motionStagger(): UniformNode<'float', number> {\n return (this.#mstg ??= uniform(0.045))\n }\n get maxSequence(): UniformNode<'float', number> {\n return this.#maxSeq\n }\n protected get colorVarying() {\n return this.#cv\n }\n protected get insideClip(): Node<'bool'> {\n return this.#ic\n }\n protected get fillNode(): Node<'vec4'> | null {\n return this.#fn\n }\n protected get baseColor(): Node<'vec3'> {\n return this.#bc\n }\n protected get colorWeight(): Node<'float'> {\n return this.#cw\n }\n\n constructor(\n options: GlyphTextMaterialOptions,\n extendVertex?: GlyphVertexExtension,\n motionIndex?: GlyphMotionSource,\n paint?: GlyphPaintExtension,\n ) {\n super()\n this.#rm = (motion) =>\n new (\n this.constructor as new (\n remakeOptions: GlyphTextMaterialOptions,\n remakeExtension?: GlyphVertexExtension,\n remakeIndex?: GlyphMotionSource,\n remakePaint?: GlyphPaintExtension,\n ) => this\n )(motion ? { ...options, motion } : options, extendVertex, motionIndex, paint)\n const animated = (this.animated = options.motion !== false)\n if (animated) {\n this.#me = uniform(1)\n this.#mm = uniform(MODE_CODES['slide-up'], 'int')\n this.#mstr = uniform(18)\n this.#mspd = uniform(1.35)\n this.#mstg = uniform(0.045)\n } else {\n this.#me = this.#mm = this.#mstr = this.#mspd = this.#mstg = null\n }\n this.lights = false\n this.transparent = true\n this.depthWrite = false\n this.depthTest = true\n this.side = options.side ?? FrontSide\n this.shadowSide = this.side\n this.forceSinglePass = this.side === DoubleSide\n this.toneMapped = false\n this.maxSequence.value = options.maxSequence ?? 0\n const tone = resolveTextTone(options.tone)\n this.tone = tone && new TextTone(tone)\n\n const localVarying = varyingProperty('vec2', 'vUltraTextLocal')\n const glyphRect = attribute<'vec4'>('sdfRect', 'vec4')\n const glyphClip = attribute<'vec4'>('sdfClip', 'vec4')\n const glyphColor = attribute<'vec4'>('sdfColor', 'vec4')\n const workingColor = srgbAttributeToWorking(vec3(glyphColor.rgb)).toConst()\n const clipVarying = varying(glyphClip, 'vUltraTextClip').setInterpolation('flat', 'either')\n this.#cv = varying(vec4(workingColor, glyphColor.a), 'vUltraTextColor').setInterpolation(\n 'flat',\n 'either',\n )\n this.#gt =\n this.tone &&\n varying(this.tone.inkTerms(workingColor), 'vUltraTextTone').setInterpolation('flat', 'either')\n // Sequence and depth are the only per-glyph metadata. The compacted draw's\n // global index is already supplied by the GPU, including after blank glyphs.\n const keepGlyph = options.keepGlyph\n const glyphMeta = keepGlyph\n ? attribute<'vec3'>('sdfMeta', 'vec3')\n : attribute<'vec2'>('sdfMeta', 'vec2')\n const runMotion =\n (options.runMotion ?? options.textShaping === 'browser')\n ? attribute<'vec3'>('sdfRunMotion', 'vec3')\n : null\n const source = motionIndex && 'index' in motionIndex ? motionIndex : null\n const indexSource = source?.index ?? (motionIndex as Node<'float'> | undefined)\n const fillUv = options.fill ? varyingProperty('vec2', 'vUltraFillUv') : null\n // Switched batches share global ordinals, so glyphIndex stays continuous across a switch.\n // Fills truncate it to read per-glyph data. Interpolated, an instance's constant can arrive\n // a hair under itself (Safari's relaxed math on Apple GPUs) and read the previous glyph's\n // entry: flat keeps it exact.\n const fillIndex = options.fill\n ? varying(\n (keepGlyph ? (runMotion?.z ?? source?.index) : source?.index) ?? float(instanceIndex),\n 'vUltraFillIndex',\n ).setInterpolation('flat', 'either')\n : null\n\n // The anchor motion scales about, and the size switch's anchor.\n const motionCenter = (): Node<'vec2'> =>\n (runMotion?.xy ?? source?.center ?? glyphRect.xy.add(glyphRect.zw).mul(0.5)).toConst()\n const basePositionOf = (quad: Node<'vec2'>): Node<'vec2'> =>\n glyphRect.xy.add(glyphRect.zw.sub(glyphRect.xy).mul(quad)).toConst()\n // What both graphs do with the moved position: the backend's extension, the size switch\n // and the shared varyings. Returns the drawn position.\n const finishVertex = (\n quad: Node<'vec2'>,\n center: Node<'vec2'> | null,\n position: Node<'vec2'>,\n motionScale: Node<'float'>,\n glyphIndex?: Node<'float'>,\n ): Node<'vec3'> => {\n const uv = fillUv ?? (options.vertex ? vec2(quad).toVar() : null)\n const extendedPosition =\n extendVertex?.(quad, glyphRect, position, glyphMeta.y, motionScale, uv) ?? position\n // The un-animated anchor and the unscaled em decide, so motion never moves a glyph\n // between the two batches of a size switch.\n const keep = center && keepGlyph?.(center, glyphMeta as unknown as Node<'vec3'>)\n const drawnPosition = keep\n ? vec2(keep.select(extendedPosition, center)).toConst()\n : extendedPosition\n localVarying.assign(drawnPosition)\n const localPosition = vec3(drawnPosition, glyphMeta.y)\n if (!options.vertex) return localPosition\n const displaced = options.vertex({\n position: localPosition,\n center: center!,\n uv: uv!,\n glyphIndex: glyphIndex ?? (runMotion?.z ?? indexSource ?? float(instanceIndex)).toConst(),\n sequence: glyphMeta.x,\n rect: glyphRect,\n clip: glyphClip,\n })\n return keep ? vec3(keep.select(displaced, vec3(center, glyphMeta.y))) : displaced\n }\n\n // Static text: the motion graph's disabled branch alone, without its clock, waves and\n // slide timeline. Only the size switch or a custom vertex hook reads the anchor.\n const staticPosition = (): Node<'vec3'> => {\n const quad = positionGeometry.xy\n fillUv?.assign(quad)\n const center = keepGlyph || options.vertex ? motionCenter() : null\n return finishVertex(quad, center, basePositionOf(quad), float(1))\n }\n // Reused expressions need shader locals as well as shared JavaScript nodes;\n // otherwise the motion/clip expressions expand repeatedly in generated WGSL.\n // Immutable intermediates use toConst(); only the accumulated position mutates.\n const animatedPosition = (): Node<'vec3'> => {\n const quad = positionGeometry.xy\n fillUv?.assign(quad)\n const center = motionCenter()\n const basePosition = basePositionOf(quad)\n const sequence = glyphMeta.x\n const glyphIndex = (runMotion?.z ?? indexSource ?? float(instanceIndex)).toConst()\n const clock = time.mul(this.motionSpeed).toConst()\n const wave = sin(\n clock.mul(Math.PI * 2).sub(glyphIndex.mul(this.motionStagger).mul(Math.PI * 2)),\n )\n const pulse = wave.mul(0.5).add(0.5).toConst()\n\n const mode = (code: number) => int(this.motionMode).equal(code)\n const isOpacity = mode(MODE_CODES.opacity)\n const isScale = mode(MODE_CODES.scale)\n const isOffset = mode(MODE_CODES.offset)\n const isSlideUp = mode(MODE_CODES['slide-up'])\n const isSlideDown = mode(MODE_CODES['slide-down'])\n const isSlideLeft = mode(MODE_CODES['slide-left'])\n const isSlideRight = mode(MODE_CODES['slide-right'])\n const isAll = mode(MODE_CODES.all).toConst()\n\n const scale = isScale\n .select(\n float(0.86).add(pulse.mul(0.22)),\n isAll.select(float(0.94).add(pulse.mul(0.08)), float(1)),\n )\n .toConst()\n const animated = vec2(center.add(basePosition.sub(center).mul(scale))).toVar()\n const offsetX = sin(clock.mul(3.1).add(glyphIndex.mul(0.55)))\n .mul(this.motionStrength)\n .mul(0.32)\n const offsetY = cos(clock.mul(2.7).add(glyphIndex.mul(0.45)))\n .mul(this.motionStrength)\n .mul(0.18)\n animated.x.addAssign(isOffset.select(offsetX, 0))\n animated.y.addAssign(\n isOffset.select(\n offsetY,\n isAll.select(\n sin(clock.mul(2.5).add(glyphIndex.mul(0.35)))\n .mul(this.motionStrength)\n .mul(0.16),\n 0,\n ),\n ),\n )\n\n const enterDuration = 0.58\n const holdDuration = 1.15\n const exitDuration = 0.24\n const sequenceSpan = this.maxSequence.mul(this.motionStagger).toConst()\n const cycle = max(\n sequenceSpan.add(enterDuration + holdDuration + exitDuration),\n 0.001,\n ).toConst()\n const slidePhase = mod(clock, cycle).toConst()\n const localPhase = slidePhase.sub(sequence.mul(this.motionStagger)).toConst()\n const enterT = clamp(localPhase.div(enterDuration), 0, 1)\n const inverseEnter = float(1).sub(enterT).toConst()\n const easeOut = float(1).sub(inverseEnter.mul(inverseEnter).mul(inverseEnter))\n const exitStart = sequenceSpan.add(enterDuration + holdDuration).toConst()\n const exitT = clamp(slidePhase.sub(exitStart).div(exitDuration), 0, 1).toConst()\n const travelRatio = localPhase\n .lessThan(0)\n .select(\n float(1),\n localPhase\n .lessThan(enterDuration)\n .select(\n float(1).sub(easeOut),\n slidePhase.lessThan(exitStart).select(float(0), exitT.mul(exitT).mul(exitT).negate()),\n ),\n )\n .toConst()\n const clipSize = glyphClip.zw.sub(glyphClip.xy).toConst()\n const verticalTravel = max(this.motionStrength, clipSize.y.mul(1.18))\n .mul(travelRatio)\n .toConst()\n const horizontalTravel = max(this.motionStrength, clipSize.x.mul(1.18))\n .mul(travelRatio)\n .toConst()\n animated.x.addAssign(\n isSlideLeft.select(horizontalTravel, isSlideRight.select(horizontalTravel.negate(), 0)),\n )\n animated.y.addAssign(\n isSlideUp.select(verticalTravel.negate(), isSlideDown.select(verticalTravel, 0)),\n )\n\n const animationEnabled = this.motionEnabled\n .greaterThan(0.5)\n .and(int(this.motionMode).notEqual(MODE_CODES.none))\n .toConst()\n const finalPosition = vec2(animationEnabled.select(animated, basePosition)).toConst()\n const animatedAlpha = isOpacity.select(\n float(0.25).add(pulse.mul(0.75)),\n isAll.select(float(0.55).add(pulse.mul(0.45)), float(1)),\n )\n\n const motionScale = animationEnabled.select(scale, 1)\n const drawnPosition = finishVertex(quad, center, finalPosition, motionScale, glyphIndex)\n this.#av.assign(animationEnabled.select(animatedAlpha, 1))\n return drawnPosition\n }\n const positionNode = Fn<Node<'vec3'>>(animated ? animatedPosition : staticPosition)()\n this.positionNode = positionNode\n this.castShadowPositionNode = positionNode\n const painted = paint?.(this.colorVarying.rgb)\n this.#bc = painted?.rgb ?? this.colorVarying.rgb\n this.#cw = painted?.weight ?? float(0)\n this.#fn =\n options.fill && fillUv && fillIndex\n ? options.fill({\n uv: fillUv,\n position: localVarying,\n color: this.baseColor,\n colorWeight: this.colorWeight,\n glyphIndex: fillIndex,\n })\n : null\n\n // A quad's padding reaches past its block, so the clip would cut its wireframe's edges.\n this.#ic = outsideWireframe(\n localVarying.x\n .greaterThanEqual(clipVarying.x)\n .and(localVarying.y.greaterThanEqual(clipVarying.y))\n .and(localVarying.x.lessThanEqual(clipVarying.z))\n .and(localVarying.y.lessThanEqual(clipVarying.w)),\n () => bool(true),\n )\n if (options.motion !== false) this.setMotion(options.motion ?? {})\n }\n\n /** @internal The ink's alpha: the CSS colour's, times the motion's for animated text. */\n protected inkAlpha(): Node<'float'> {\n return this.animated ? this.colorVarying.a.mul(this.#av) : this.colorVarying.a\n }\n\n /**\n * Attach one backend's beauty and shadow coverage to the shared graph. `folded` says the\n * beauty coverage holds the factor `toned()` returns for the ink's own alpha.\n */\n protected applyCoverage(\n coverage: Node<'float'>,\n shadowCoverage: Node<'float'>,\n shadowCutoff: Node<'float'>,\n paint?: Node<'vec4'>,\n folded = false,\n ): void {\n const fill = this.fillNode\n const paintedAlpha = paint?.a ?? (fill ? coverage.mul(clamp(fill.a, 0, 1)) : coverage)\n const castCoverage = fill && !paint ? shadowCoverage.mul(clamp(fill.a, 0, 1)) : shadowCoverage\n const inked = (covered: Node<'float'>): Node<'float'> => {\n const ink = covered.mul(this.colorVarying.a)\n return this.animated ? ink.mul(this.#av) : ink\n }\n // A folded factor times the ink's alpha is the converted coverage, clamped as one.\n // Shadow passes keep the exact product.\n const alpha = (\n folded\n ? outsideShadowPass(min(1, inked(paintedAlpha)), inked(castCoverage))\n : inked(outsideShadowPass(paintedAlpha, castCoverage))\n ).toConst()\n // Wireframe lines take the ink with none of the coverage, which is zero along a quad's\n // edges. A paint's colour means nothing outside its shape, so lines keep the CSS colour,\n // lifted toward white until it reaches the line floor. Built lazily on first wireframe use.\n let wire: { readonly color: Node<'vec4'>; readonly alpha: Node<'float'> } | null = null\n const getWire = () => {\n if (!wire) {\n const lineAlpha = this.inkAlpha().toConst()\n const lineInk = vec3(fill?.rgb ?? this.baseColor).toConst()\n const lineInkLuminance = luminance(lineInk).toConst()\n const lineLift = clamp(\n float(WIREFRAME_LINE_LUMINANCE)\n .sub(lineInkLuminance)\n .div(max(float(1).sub(lineInkLuminance), 1e-4)),\n 0,\n 1,\n )\n wire = {\n color: vec4(mix(lineInk, vec3(1), lineLift), lineAlpha),\n alpha: lineAlpha,\n }\n }\n return wire\n }\n this.colorNode = outsideWireframe(\n vec4(outsideShadowPass(paint?.rgb ?? fill?.rgb ?? this.baseColor, vec3(0)), alpha),\n () => getWire().color,\n )\n this.maskNode = this.insideClip.and(\n outsideWireframe(alpha, () => getWire().alpha).greaterThan(0.001),\n )\n this.maskShadowNode = this.insideClip\n .and(castCoverage.greaterThan(shadowCutoff))\n .and(this.inkAlpha().greaterThan(shadowCutoff))\n }\n\n /**\n * Beauty coverage of text ink as a browser would show it, or the same node when the\n * material has no tone. The ink is the instance colour, whose terms reach the fragment\n * through one flat varying, unless a fill graph supplies the colour per fragment.\n * `tableGate` is for a model whose table stops at a size. Shadow masks, colour layers and\n * shape paint must keep the exact coverage.\n *\n * The ink's own alpha is part of the mask a browser blends: the CSS colour's alpha and\n * opacity, the motion's, a fill's. The result is the factor that `applyCoverage` multiplies\n * by that alpha, so the caller passes it `folded`. `fold` false converts as for opaque ink,\n * for a caller that composes the result with other coverages first.\n */\n protected toned(\n coverage: Node<'float'>,\n ink?: Node<'vec3'>,\n tableGate?: Node<'float'>,\n fold = true,\n ): Node<'float'> {\n const tone = this.tone\n if (!tone) return coverage\n let opacity: Node<'float'> | undefined\n if (fold) {\n opacity = this.inkAlpha()\n if (this.fillNode) opacity = opacity.mul(clamp(this.fillNode.a, 0, 1))\n }\n return tone.apply(coverage, ink ? tone.inkTerms(ink).toConst() : this.#gt!, tableGate, opacity)\n }\n\n /**\n * Follows a recaptured tone through the uniforms. False means this material was built for\n * a tone of another kind, because the conversion or a model's extra nodes would have to\n * appear or go: the caller rebuilds the material.\n */\n setTone(tone: ResolvedTextTone | null): boolean {\n const current = this.tone\n if (!current || !tone || !current.fits(tone)) return !current && !tone\n current.update(tone)\n return true\n }\n\n /**\n * Rebuilds an equivalent material from this one's original construction options.\n *\n * Three's `Material.clone()` constructs the concrete class with **no arguments** and\n * copies properties across. This graph cannot survive that: it closes over required\n * options — an atlas and its metrics on the SDF backend, outline tables on Windfoil —\n * so the argument-less twin threw before `copy()` ever ran, and three's generic node\n * property copy would hand the twin a graph still wired to the *source's* uniforms,\n * leaving its own knobs connected to nothing. {@link remake} re-runs the constructor\n * with the stored options instead, rebuilding a private graph over the same shared\n * resources (the atlas texture is shared on purpose); the loop then carries the current\n * value of every numeric uniform knob — this class's and any subclass's, discovered as\n * own properties — into the twin's own uniforms, and the classic scalar-flag copy brings\n * side, opacity, blending, visibility, wireframe and friends. The tone's uniforms live on\n * its own object, so its current values are handed over whole. The one non-numeric uniform\n * in the family, the SDF unit range, is derived from the options and already correct in\n * the twin. Hand edits made to the node graph after construction are deliberately not\n * carried, and subclasses inherit all of this untouched because each passes its own\n * options object through `super()`. A static material's clone is static.\n */\n override clone(): this {\n return this.withMotion()\n }\n\n /** @internal */\n protected copySubclassUniforms?(target: this): void\n\n /**\n * @internal The animated twin of a static material: rebuilt like `clone()` with the\n * motion graph and `motion`, carrying every other state. Motion knobs `motion` leaves out\n * take their defaults.\n */\n withMotion(motion?: SdfMotionOptions): this {\n const twin = this.#rm(motion)\n // The classic fixed-list scalar copy — side, opacity, blending, visibility and friends —\n // not NodeMaterial's generic property pass, which would re-wire this rebuilt graph back\n // into the source's nodes. Wireframe sits above the base list, so it rides separately.\n Material.prototype.copy.call(twin, this)\n twin.wireframe = this.wireframe\n twin.maxSequence.value = this.#maxSeq.value\n if (!motion) {\n if (this.#me !== null) twin.motionEnabled.value = this.#me.value\n if (this.#mm !== null) twin.motionMode.value = this.#mm.value\n if (this.#mstr !== null) twin.motionStrength.value = this.#mstr.value\n if (this.#mspd !== null) twin.motionSpeed.value = this.#mspd.value\n if (this.#mstg !== null) twin.motionStagger.value = this.#mstg.value\n }\n this.copySubclassUniforms?.(twin)\n for (const key in twin) {\n const target = twin[key as keyof this] as { isUniformNode?: boolean; value: unknown } | null\n if (\n target?.isUniformNode &&\n typeof target.value === 'number' &&\n !(motion && key.startsWith('motion'))\n ) {\n target.value = (this[key as keyof this] as { value: number }).value\n }\n }\n if (this.tone) twin.tone?.update(this.tone.resolved)\n return twin\n }\n\n /**\n * Writes the given motion fields into the uniforms; safe to call every frame. Throws on a\n * static material (`motion: false`), which has no motion graph to drive.\n */\n setMotion(options: SdfMotionOptions): this {\n if (!this.animated) throw new Error('ultra-text: setMotion() cannot run with motion: false')\n if (options.enabled !== undefined) this.motionEnabled.value = options.enabled ? 1 : 0\n if (options.mode !== undefined) this.motionMode.value = MODE_CODES[options.mode]\n if (options.strength !== undefined) this.motionStrength.value = Math.max(0, options.strength)\n if (options.speed !== undefined) this.motionSpeed.value = Math.max(0, options.speed)\n if (options.stagger !== undefined) this.motionStagger.value = Math.max(0, options.stagger)\n return this\n }\n}\n"],"mappings":";;;;;AA2GA,IAAM,aAAyD,OAAO,OAAO;CAC3E,MAAM;CACN,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACZ,cAAc;CACd,cAAc;CACd,eAAe;CACf,KAAK;AACP,CAAC;;AAGD,SAAgB,iBAAiB,QAAuD;CACtF,OAAO,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AAK,eAAe,QAAQ,KAAK,IAAI,GAAG,QAAQ,QAAQ;EAC5F,IAAI,QAAQ,UAAU,KAAA,GAAW,KAAK,YAAY,QAAQ,KAAK,IAAI,GAAG,QAAQ,KAAK;EACnF,IAAI,QAAQ,YAAY,KAAA,GAAW,KAAK,cAAc,QAAQ,KAAK,IAAI,GAAG,QAAQ,OAAO;EACzF,OAAO;CACT;AACF"}
@@ -35,10 +35,11 @@ export interface SdfTextMaterialOptions extends GlyphTextMaterialOptions {
35
35
  }
36
36
  /** Retained single-channel SDF text with TSL motion, clipping, and shadows. */
37
37
  export declare class SdfTextMaterial extends GlyphTextMaterial {
38
- readonly threshold: UniformNode<'float', number>;
39
- readonly shadowCutoff: UniformNode<'float', number>;
40
- readonly stemDarkening: UniformNode<'float', number>;
41
- readonly unitRange: UniformNode<'vec2', Vector2>;
38
+ #private;
42
39
  readonly quality: SdfTextQuality;
40
+ get threshold(): UniformNode<'float', number>;
41
+ get shadowCutoff(): UniformNode<'float', number>;
42
+ get stemDarkening(): UniformNode<'float', number>;
43
+ get unitRange(): UniformNode<'vec2', Vector2>;
43
44
  constructor(options: SdfTextMaterialOptions);
44
45
  }
@@ -31,11 +31,29 @@ var GeometryProbeNode = class extends Node {
31
31
  };
32
32
  /** Retained single-channel SDF text with TSL motion, clipping, and shadows. */
33
33
  var SdfTextMaterial = class extends GlyphTextMaterial {
34
- threshold = uniform(.5);
35
- shadowCutoff = uniform(.5);
36
- stemDarkening = uniform(0);
37
- unitRange = uniform(new Vector2());
34
+ #th = uniform(.5);
35
+ #sc = uniform(.5);
36
+ #sd = uniform(0);
37
+ #ur = uniform(new Vector2());
38
38
  quality;
39
+ get threshold() {
40
+ return this.#th;
41
+ }
42
+ get shadowCutoff() {
43
+ return this.#sc;
44
+ }
45
+ get stemDarkening() {
46
+ return this.#sd;
47
+ }
48
+ get unitRange() {
49
+ return this.#ur;
50
+ }
51
+ /** @internal */
52
+ copySubclassUniforms(target) {
53
+ target.threshold.value = this.#th.value;
54
+ target.shadowCutoff.value = this.#sc.value;
55
+ target.stemDarkening.value = this.#sd.value;
56
+ }
39
57
  constructor(options) {
40
58
  const outline = options.outline;
41
59
  const shadow = options.dropShadow;
@@ -105,8 +123,9 @@ var SdfTextMaterial = class extends GlyphTextMaterial {
105
123
  const trimmed = inside.select(mix(limits.xy, limits.zw, quad), quad).context({ uniformFlow: true }).toConst();
106
124
  fillUv?.assign(trimmed);
107
125
  uvVarying.assign(glyphUvRect.xy.add(span.mul(trimmed)));
126
+ if (options.motion === false) return rect.xy.add(rect.zw.sub(rect.xy).mul(trimmed));
108
127
  const step = rect.zw.sub(rect.xy).mul(trimmed.sub(quad));
109
- return position.add(options.motion === false ? step : step.mul(motionScale));
128
+ return position.add(step.mul(motionScale));
110
129
  }
111
130
  uvVarying.assign(glyphUvRect.xy.add(uvSpan.mul(quad)));
112
131
  }, void 0, paint);
@@ -147,11 +166,12 @@ var SdfTextMaterial = class extends GlyphTextMaterial {
147
166
  smoothed = local(exact ? small.mul(exact.oneMinus()) : small);
148
167
  rise = local(min(emPx.mul(tone.dilation.x), tone.dilation.y).mul(smoothed));
149
168
  }
150
- const rampAtEmptyField = (edge, lift = stemBoost, slope) => local(min(slope ? slope.mul(lift.div(screenPxRange).sub(edge)).add(.5) : lift.add(.5).sub(screenPxRange.mul(edge)), 0));
169
+ const rampAtEmptyField = (edge, lift = stemBoost, steep) => local(min(steep ? steep.mul(lift.sub(screenPxRange.mul(edge))).add(.5) : lift.add(.5).sub(screenPxRange.mul(edge)), 0));
151
170
  const lift = rise ? stemBoost.add(rise) : stemBoost;
152
- const inkSlope = rise ? local(max(screenPxRange, screenPxRange.div(max(screenPxRange.sub(rise.mul(2)), .25)))) : void 0;
171
+ const invClamp = rise ? local(float(1).div(clamp(screenPxRange.sub(rise.mul(2)), .25, 1))) : void 0;
172
+ const inkSlope = invClamp ? local(screenPxRange.mul(invClamp)) : void 0;
153
173
  const castRamp = rampAtEmptyField(contour);
154
- const fillRamp = rise || colour ? rampAtEmptyField(inkContour, lift, inkSlope) : castRamp;
174
+ const fillRamp = rise || colour ? rampAtEmptyField(inkContour, lift, invClamp) : castRamp;
155
175
  const inkUv = rise ? uvVarying.sub(dFdy(uvVarying).mul(rise)) : uvVarying;
156
176
  const coverageAt = (sampleUv) => {
157
177
  return distanceCoverage(sampleUv, castRamp, inBand, screenPxRange);
@@ -190,7 +210,7 @@ var SdfTextMaterial = class extends GlyphTextMaterial {
190
210
  return exact && tone ? mix(toned, baked, exact) : toned;
191
211
  };
192
212
  const expansion = outline && uvPerLocal ? min(uvPerLocal.x.abs().mul(options.atlasWidth * width / options.pxRange), .49) : null;
193
- const outlineRamp = expansion ? rampAtEmptyField(inkContour.sub(expansion), lift, inkSlope) : fillRamp;
213
+ const outlineRamp = expansion ? rampAtEmptyField(inkContour.sub(expansion), lift, invClamp) : fillRamp;
194
214
  let coverage;
195
215
  let outlined = null;
196
216
  if (expansion && uvBounds) {
@@ -1 +1 @@
1
- {"version":3,"file":"SdfTextMaterial.js","names":[],"sources":["../../src/text/SdfTextMaterial.ts"],"sourcesContent":["import {\n Color,\n LinearFilter,\n NearestFilter,\n Node,\n Vector2,\n type NodeBuilder,\n type Texture,\n type UniformNode,\n} from 'three/webgpu'\nimport {\n attribute,\n clamp,\n dFdx,\n dFdy,\n dot,\n float,\n max,\n min,\n mix,\n smoothstep,\n step,\n texture,\n uniform,\n varying,\n varyingProperty,\n vec2,\n vec4,\n} from 'three/tsl'\n\nimport type {\n SdfColorLayer,\n SdfDropShadowOptions,\n SdfOutlineOptions,\n SdfTextQuality,\n} from '../types.js'\nimport {\n GlyphTextMaterial,\n type GlyphTextMaterialOptions,\n type GlyphPaintExtension,\n} from './GlyphTextMaterial.js'\n\n// Effect composition and atlas-cell clamping adapted from pmndrs/glyph (MIT).\n// Copyright (c) 2026 Poimandres. See THIRD_PARTY_NOTICES.md and licenses/GLYPH-MIT.txt.\n\nexport interface SdfTextMaterialOptions extends GlyphTextMaterialOptions {\n /** Companion colour band from SdfAtlas; omitted keeps the original shader graph. */\n colorLayer?: SdfColorLayer\n outline?: SdfOutlineOptions\n dropShadow?: SdfDropShadowOptions\n /** The single-channel distance-field texture, from `SdfAtlas.texture`. */\n atlas: Texture\n /** Atlas width in texels, from `SdfAtlas.width`. */\n atlasWidth: number\n /** Atlas height in texels, from `SdfAtlas.height`. */\n atlasHeight: number\n /** Distance-field pixel range, from `SdfAtlas.pxRange`. */\n pxRange: number\n /** Font size of the atlas bake in texels, from `SdfAtlas.bakeSize`. Defaults to `96`. */\n bakeSize?: number\n /**\n * First texel row of the atlas's monochrome shapes, from `SdfAtlas.shapeTop`: glyphs from\n * that row down keep their baked coverage where text takes a tone. Defaults to none.\n */\n shapeTop?: number | undefined\n /**\n * SDF contour in the atlas encoding. Defaults to `0.5`, the baked outline; colour glyphs\n * then keep `0.515`, which hides the faint shading around some emoji strikes.\n */\n threshold?: number\n /** Coverage required by the shadow silhouette. Defaults to `0.5`. */\n shadowCutoff?: number\n /** `'high'` adds four derivative-offset samples. Defaults to `'standard'`. */\n quality?: SdfTextQuality\n /** Extra weight in screen pixels for glyphs under 16 pixels per em. Defaults to `0`. */\n stemDarkening?: number\n /**\n * @internal Draws the outline ring and drop shadow alone, under analytic text drawn after\n * it with the same coverage: the underlay of the Windfoil and Slug backends. Needs an\n * outline or a drop shadow.\n */\n underlay?: boolean\n}\n\ntype GlyphGeometry = { hasAttribute(name: string): boolean } | null\n\n/**\n * Whether minified text samples the atlas's mipmaps, whose texels blur the field beyond the\n * support box of a slot: about a pixel of faint halo around small glyphs, which only whole\n * quads keep.\n */\nconst blurred = (atlas: Texture): boolean =>\n atlas.minFilter !== LinearFilter &&\n atlas.minFilter !== NearestFilter &&\n (atlas.generateMipmaps || atlas.mipmaps.length > 1)\n\n/**\n * The position graph, with the geometry of the build it is set up in handed over first: the\n * vertex extension is JavaScript run while the graph is set up, and reads the attributes there.\n */\nclass GeometryProbeNode extends Node {\n static readonly type = 'UltraTextGeometryProbeNode'\n\n constructor(\n readonly positionNode: Node,\n readonly probe: (geometry: GlyphGeometry) => void,\n ) {\n super()\n }\n\n override getNodeType(builder: NodeBuilder): string {\n return this.positionNode.getNodeType(builder)\n }\n\n override setup(builder: NodeBuilder): Node {\n this.probe((builder as { geometry?: GlyphGeometry }).geometry ?? null)\n return this.positionNode\n }\n}\n\n/** Retained single-channel SDF text with TSL motion, clipping, and shadows. */\nexport class SdfTextMaterial extends GlyphTextMaterial {\n readonly threshold: UniformNode<'float', number> = uniform(0.5)\n readonly shadowCutoff: UniformNode<'float', number> = uniform(0.5)\n readonly stemDarkening: UniformNode<'float', number> = uniform(0)\n readonly unitRange: UniformNode<'vec2', Vector2> = uniform(new Vector2())\n readonly quality: SdfTextQuality\n\n constructor(options: SdfTextMaterialOptions) {\n const outline = options.outline\n const shadow = options.dropShadow\n const width = outline ? (outline.width ?? 1) : 0\n const offsetX = shadow ? (shadow.offsetX ?? 2) : 0\n const offsetY = shadow ? (shadow.offsetY ?? -2) : 0\n const outlineOpacity = outline?.opacity ?? 1\n const shadowOpacity = shadow?.opacity ?? 0.5\n if (\n ![width, offsetX, offsetY, outlineOpacity, shadowOpacity].every(Number.isFinite) ||\n width < 0\n ) {\n throw new RangeError(\n 'SdfTextMaterial: effects require finite values and a non-negative outline width',\n )\n }\n const effects = outline !== undefined || shadow !== undefined\n // Whether quads may shrink to their glyphs' support boxes (`sdfTrim`): effect quads reach\n // past the cell, run motion's vertex buffer leaves none for the trim, and mipmaps blur the\n // field past the box.\n const trimmable =\n !effects &&\n !(options.runMotion ?? options.textShaping === 'browser') &&\n !blurred(options.atlas)\n const glyphUvRect = attribute<'vec4'>('sdfUvRect', 'vec4')\n const uvVarying = varyingProperty('vec2', 'vUltraSdfUv')\n const uvBounds = effects ? varyingProperty('vec4', 'vUltraSdfUvBounds') : null\n const uvPerLocal = effects ? varyingProperty('vec2', 'vUltraSdfUvPerLocal') : null\n const layer = options.colorLayer\n const inBand = layer ? varyingProperty('float', 'vUltraColorGlyph') : null\n const bandTop = layer ? uniform((layer.top + 0.5) / options.atlasHeight) : null\n const bandMap = layer\n ? uniform(new Vector2(options.atlasHeight / layer.height, layer.top / layer.height))\n : null\n // Monochrome shapes keep their baked coverage where text takes a tone. Their rows lie\n // below the text and above the colour band, from the one the atlas names; a texture from\n // `buildSdfAtlas` repeats it for a caller that passes no `shapeTop`. Only a shader whose\n // fragment reads the flag carries it, flat from `either` vertex like GlyphTextMaterial's.\n // A toned shader that can trim its quads carries it whether or not the atlas has shapes:\n // without them the row is one below the atlas, which no glyph reaches, so the flag is 0 and\n // the shader is the one a shape atlas uses (the row is a uniform), mixing the exact\n // coverage in at weight 0. Whole quads would pay for that per fragment with nothing back.\n const shapeTop: unknown = options.shapeTop ?? options.atlas.userData['ultraShapeTop']\n const shaped = typeof shapeTop === 'number'\n const inShapes =\n options.tone !== false && (shaped || trimmable)\n ? varying(\n step(\n uniform(((shaped ? shapeTop : options.atlasHeight) + 0.5) / options.atlasHeight),\n min(glyphUvRect.y, glyphUvRect.w),\n ),\n 'vUltraShapeGlyph',\n ).setInterpolation('flat', 'either')\n : null\n const paint: GlyphPaintExtension | undefined = layer\n ? (css) => {\n const halfTexel = vec2(0.5 / options.atlasWidth, 0.5 / options.atlasHeight)\n const safeUv = uvBounds\n ? clamp(uvVarying, uvBounds.xy.add(halfTexel), uvBounds.zw.sub(halfTexel))\n : uvVarying\n const bandUv = vec2(safeUv.x, safeUv.y.mul(bandMap!.x).sub(bandMap!.y))\n const sample = texture(layer.texture, bandUv)\n const scale = vec2(1, bandMap!.x)\n const texel = (\n uvBounds ? sample.grad(dFdx(uvVarying).mul(scale), dFdy(uvVarying).mul(scale)) : sample\n ).toConst()\n const glyph = step(0.5, inBand!).toConst()\n const weight = texel.a.mul(glyph).toConst()\n return { rgb: css.mul(weight.oneMinus()).add(texel.rgb.mul(glyph)), weight }\n }\n : undefined\n // Set once constructed and per build, before the vertex extension below runs.\n const built: { material?: SdfTextMaterial; geometry?: GlyphGeometry; cast?: boolean } = {}\n super(\n options,\n (quad, rect, position, _depth, motionScale, fillUv) => {\n inBand?.assign(step(bandTop!, min(glyphUvRect.y, glyphUvRect.w)))\n const uvSpan = glyphUvRect.zw.sub(glyphUvRect.xy)\n if (uvBounds && uvPerLocal) {\n const size = rect.zw.sub(rect.xy).max(1e-6)\n const padding = vec2(width + Math.abs(offsetX), width + Math.abs(offsetY))\n const extra = quad.mul(2).sub(1).mul(padding)\n uvPerLocal.assign(uvSpan.div(size))\n uvBounds.assign(\n vec4(min(glyphUvRect.xy, glyphUvRect.zw), max(glyphUvRect.xy, glyphUvRect.zw)),\n )\n const expandedQuad = quad.add(extra.div(size))\n fillUv?.assign(expandedQuad)\n uvVarying.assign(glyphUvRect.xy.add(uvSpan.mul(expandedQuad)))\n return position.add(options.motion === false ? extra : extra.mul(motionScale))\n }\n const material = built.material\n if (material && built.geometry?.hasAttribute('sdfTrim') && !blurred(options.atlas)) {\n // Most of a glyph's quad is empty field, which every fragment there samples to no\n // coverage. `sdfTrim` is the slot's support box in the order and units of the UV\n // rect, the macOS rise included: the quad shrinks to it, in quad units. A box outside\n // this instance's slot (a UV rect rewritten to another glyph) leaves the whole quad.\n // 'high' samples a quarter pixel around each fragment: half the field's range more\n // covers that down to about 6 pixels per em at the default bake.\n const trim = attribute<'vec4'>('sdfTrim', 'vec4')\n const span = uvSpan.toConst()\n const bounds = trim.sub(glyphUvRect.xyxy).div(vec4(span, span)).toConst()\n const sum = bounds.xy.add(bounds.zw).sub(1).abs().toConst()\n const inside = max(sum.x, sum.y).lessThan(1)\n const reach =\n !built.cast && material.quality === 'high'\n ? material.unitRange.mul(0.5).div(span.abs()).toConst()\n : null\n const limits = clamp(\n reach ? bounds.add(vec4(reach.negate(), reach)) : bounds,\n 0,\n 1,\n ).toConst()\n const trimmed = inside\n .select(mix(limits.xy, limits.zw, quad), quad)\n .context({ uniformFlow: true })\n .toConst()\n fillUv?.assign(trimmed)\n uvVarying.assign(glyphUvRect.xy.add(span.mul(trimmed)))\n // The quad's own size times the motion's scale: exact for every motion mode, whose\n // centre stays the untrimmed rect's.\n const step = rect.zw.sub(rect.xy).mul(trimmed.sub(quad))\n return position.add(options.motion === false ? step : step.mul(motionScale))\n }\n uvVarying.assign(glyphUvRect.xy.add(uvSpan.mul(quad)))\n },\n undefined,\n paint,\n )\n built.material = this\n // Where quads may be trimmed, the geometry decides: a custom geometry without `sdfTrim`\n // keeps the whole quads and the vertex stage it always had. Glyph geometry with run motion\n // has none. A shadow map samples each fragment's own UV, so its quads keep to the support\n // box itself.\n if (trimmable) {\n const graph = this.positionNode!\n this.positionNode = new GeometryProbeNode(graph, (geometry) => {\n built.geometry = geometry\n built.cast = false\n })\n this.castShadowPositionNode = new GeometryProbeNode(graph, (geometry) => {\n built.geometry = geometry\n built.cast = true\n })\n }\n this.name = 'ultra-text TSL runtime SDF text'\n this.threshold.value = options.threshold ?? 0.5\n this.shadowCutoff.value = Math.min(1, Math.max(0, options.shadowCutoff ?? 0.5))\n this.stemDarkening.value = Math.max(0, options.stemDarkening ?? 0)\n this.quality = options.quality ?? 'standard'\n this.unitRange.value.set(\n options.pxRange / options.atlasWidth,\n options.pxRange / options.atlasHeight,\n )\n\n // Texels per pixel along each atlas axis: one over the length of that axis's screen\n // gradient, as Windfoil's pixel box measures it. `fwidth()` is the footprint's bounding box,\n // which reads text turned in its plane up to √2 smaller than it is: a wider ramp, and a\n // stem darkening and tone size gate that moved with the angle. Axis-aligned text gets the\n // same value. Each derivative is its own node, so the shader gains no local and the vertex\n // stage, which shares their numbering, keeps its text.\n // The floor only guards a zero footprint. A larger one, such as 1e-5 on the gradient, capped\n // the range once a texel spanned more than 1e5 / atlasWidth pixels and blurred magnified\n // edges over several pixels, unevenly on a non-square atlas.\n const squared = (derivative: typeof dFdx) => derivative(uvVarying).mul(derivative(uvVarying))\n const screenTextureSize = squared(dFdx).add(squared(dFdy)).max(1e-18).inverseSqrt()\n // Effect contours revisit shared coverage nodes in several conditional branches.\n // Three r186 can redeclare a toConst() local twice in the same branch; mutable\n // locals hoist that shared calculation. Keep the ordinary text graph unchanged.\n const local = (node: Node<'float'>): Node<'float'> => (effects ? node.toVar() : node.toConst())\n const screenPxRange = local(max(dot(this.unitRange, screenTextureSize).mul(0.5), 1))\n const rawStemBoost = this.stemDarkening.mul(clamp(float(2).sub(screenPxRange), 0, 1))\n const stemBoost = local(inBand ? rawStemBoost.mul(inBand.oneMinus()) : rawStemBoost)\n // Colour glyphs sit a little inside the default contour; an explicit threshold moves both.\n const contour = inBand\n ? this.threshold.add(inBand.mul(uniform(options.threshold === undefined ? 0.015 : 0)))\n : this.threshold\n // A slot of the colour band can hold text beside its colour ink, as a shaped line does\n // beside its emoji. The beauty pass therefore tells the two apart per fragment, by the\n // band's own alpha: 1 around colour ink, 0 around foreground ink. Shadow maps keep the\n // row flag.\n const colour = layer ? this.colorWeight : null\n const inkContour = colour\n ? this.threshold.add(colour.mul(uniform(options.threshold === undefined ? 0.015 : 0)))\n : contour\n // 1 where the baked coverage is kept: a shape's rows or colour ink.\n const exact =\n colour && inShapes && inBand\n ? max(inShapes.mul(inBand.oneMinus()), colour)\n : (colour ?? inShapes)\n // macOS font smoothing, for text ink below the size where the browser stops applying it:\n // the outline grows by d = min(dilationEm ems, dilationPx pixels) to each side, by 2 d\n // upwards and not at all downwards, which is a dilation by d and a rise by d. `smoothed`\n // is 1 where that holds, `rise` is d in screen pixels. Other models add no node here.\n const tone = this.tone\n let smoothed: Node<'float'> | undefined\n let rise: Node<'float'> | undefined\n if (tone?.dilates) {\n const emPx = screenPxRange.mul(uniform((options.bakeSize ?? 96) / options.pxRange)).toConst()\n const small = step(tone.dilation.z, emPx).oneMinus()\n smoothed = local(exact ? small.mul(exact.oneMinus()) : small)\n rise = local(min(emPx.mul(tone.dilation.x), tone.dilation.y).mul(smoothed))\n }\n // The ramp input where the field saturates to 0, the empty rest of the atlas cell, capped\n // at the ramp's foot so that background keeps exactly zero coverage. Uncapped, a glyph a\n // few pixels tall lifted its whole quad to ~3% alpha through stem darkening, and an outline\n // near the range limit to over a third; the mask then kept every fragment of the quad.\n // `lift` moves the contour outwards by that many screen pixels.\n const rampAtEmptyField = (\n edge: Node<'float'>,\n lift: Node<'float'> = stemBoost,\n slope?: Node<'float'>,\n ) =>\n local(\n min(\n slope\n ? slope.mul(lift.div(screenPxRange).sub(edge)).add(0.5)\n : lift.add(0.5).sub(screenPxRange.mul(edge)),\n 0,\n ),\n )\n // Shadow maps keep the baked contour; only the beauty contour is dilated. A distance field\n // has one offset for every edge: d, which is exact on upright and level strokes.\n const lift = rise ? stemBoost.add(rise) : stemBoost\n // The field reaches zero screenPxRange / 2 pixels outside the contour. Where that is less\n // than the half pixel of ramp plus the dilation, the ramp steepens so that it still starts\n // at the empty field and its middle still lies `rise` outside: s / (s - 2 rise) for s.\n const inkSlope = rise\n ? local(max(screenPxRange, screenPxRange.div(max(screenPxRange.sub(rise.mul(2)), 0.25))))\n : undefined\n const castRamp = rampAtEmptyField(contour)\n const fillRamp = rise || colour ? rampAtEmptyField(inkContour, lift, inkSlope) : castRamp\n // The rise samples the field that many pixels lower on screen.\n const inkUv = rise ? uvVarying.sub(dFdy(uvVarying).mul(rise)) : uvVarying\n const coverageAt = (sampleUv: Node<'vec2'>): Node<'float'> => {\n return distanceCoverage(sampleUv, castRamp, inBand, screenPxRange)\n }\n // The atlas texel under one sample, read with the glyph's own footprint.\n const fieldAt = (sampleUv: Node<'vec2'>): Node<'float'> => {\n const halfTexel = vec2(0.5 / options.atlasWidth, 0.5 / options.atlasHeight)\n const safeUv = uvBounds\n ? clamp(sampleUv, uvBounds.xy.add(halfTexel), uvBounds.zw.sub(halfTexel))\n : sampleUv\n const sample = texture(options.atlas, safeUv)\n // Clamping changes the implicit derivatives at a cell boundary. Preserve\n // the original footprint so mip/anisotropic filtering cannot form seams.\n return (uvBounds ? sample.grad(dFdx(uvVarying), dFdy(uvVarying)) : sample).r\n }\n // One pixel of linear ramp across the contour: the coverage of a straight edge. Colour\n // glyphs keep the eased ramp, whose shorter foot hides the ink colour around their texels.\n const contourAt = (\n field: Node<'float'>,\n ramp: Node<'float'> = fillRamp,\n eased: Node<'float'> | null = colour ?? inBand,\n slope: Node<'float'> = inkSlope ?? screenPxRange,\n ): Node<'float'> => {\n const across = slope.mul(field).add(ramp)\n const linear = clamp(across, 0, 1)\n return eased ? mix(linear, smoothstep(0, 1, across), eased) : linear\n }\n // Effect quads reach past the glyph's cell; samples there read nothing.\n const insideCell = (sampleUv: Node<'vec2'>, bounds: Node<'vec4'>): Node<'bool'> =>\n sampleUv.x\n .greaterThanEqual(bounds.x)\n .and(sampleUv.y.greaterThanEqual(bounds.y))\n .and(sampleUv.x.lessThanEqual(bounds.z))\n .and(sampleUv.y.lessThanEqual(bounds.w))\n const distanceCoverage = (\n sampleUv: Node<'vec2'>,\n ramp?: Node<'float'>,\n eased: Node<'float'> | null = colour ?? inBand,\n slope?: Node<'float'>,\n ): Node<'float'> => {\n const alpha = contourAt(fieldAt(sampleUv), ramp, eased, slope)\n return uvBounds ? insideCell(sampleUv, uvBounds).select(alpha, 0) : alpha\n }\n const uvDx = this.quality === 'high' ? dFdx(uvVarying).mul(0.125).toConst() : null\n const uvDy = this.quality === 'high' ? dFdy(uvVarying).mul(0.125).toConst() : null\n // 'high' filters a contour over a 4-rook rotated grid (±1/8, ±3/8 px) so horizontal,\n // vertical and diagonal strokes each see four distinct subpixel strata instead of two.\n const tapsAround = (sampleUv: Node<'vec2'>): Node<'vec2'>[] =>\n uvDx && uvDy\n ? [\n sampleUv.sub(uvDx).sub(uvDy.mul(3)),\n sampleUv.add(uvDx.mul(3)).sub(uvDy),\n sampleUv.sub(uvDx.mul(3)).add(uvDy),\n sampleUv.add(uvDx).add(uvDy.mul(3)),\n ]\n : [sampleUv]\n // Filter every beauty contour alike: subtracting differently filtered\n // silhouettes produces a jagged ring, even when its requested width is zero.\n const filteredCoverage = (sampleUv: Node<'vec2'>, ramp?: Node<'float'>): Node<'float'> => {\n const taps = tapsAround(sampleUv).map((tap) => distanceCoverage(tap, ramp))\n if (taps.length === 1) return taps[0]!\n return taps.reduce((sum, tap) => sum.add(tap)).mul(0.25)\n }\n // Text ink is shown at the weight a browser gives it. Shapes, colour glyphs, outline rings,\n // drop shadows and shadow maps keep the exact coverage. `fold` false where the result is\n // composed with a ring and a drop shadow before the ink's alpha.\n const ink = (baked: Node<'float'>, fold = true): Node<'float'> => {\n const toned = this.toned(baked, this.fillNode?.rgb, smoothed, fold)\n return exact && tone ? mix(toned, baked, exact) : toned\n }\n // The field encodes only half of pxRange outside the contour. Clamp the\n // requested expansion so the outline's contour stays inside it; its ramp\n // is capped at the empty field like the fill's.\n const expansion =\n outline && uvPerLocal\n ? min(uvPerLocal.x.abs().mul((options.atlasWidth * width) / options.pxRange), 0.49)\n : null\n const outlineRamp = expansion\n ? rampAtEmptyField(inkContour.sub(expansion), lift, inkSlope)\n : fillRamp\n let coverage: Node<'float'>\n let outlined: Node<'float'> | null = null\n if (expansion && uvBounds) {\n // The fill and the outline's silhouette are two contours of the same taps. Each tap is\n // read once, in the one branch that skips taps outside the glyph's cell (most of an\n // effect quad), and gives both contours: component for component the sums of\n // filteredCoverage, in the same order.\n const pairs = tapsAround(inkUv).map((tap) => {\n const field = fieldAt(tap)\n return insideCell(tap, uvBounds).select(\n vec2(contourAt(field), contourAt(field, outlineRamp)),\n vec2(0),\n )\n })\n const sums = (\n pairs.length === 1 ? pairs[0]! : pairs.reduce((sum, pair) => sum.add(pair)).mul(0.25)\n ).toVar()\n coverage = sums.x\n outlined = sums.y\n } else coverage = filteredCoverage(inkUv)\n // Shadow maps filter the finished silhouette; don't supersample that path.\n if (effects && uvPerLocal) {\n coverage = coverage.toConst()\n const inked = tone ? ink(coverage, false).toConst() : coverage\n const fillOpacity = this.fillNode ? clamp(this.fillNode.a, 0, 1) : float(1)\n const fillAlpha = inked.mul(fillOpacity).toConst()\n const fillColor = this.fillNode?.rgb ?? this.baseColor\n const silhouette = outlined ? outlined.toConst() : inked\n const ringOpacity = Math.min(1, Math.max(0, outlineOpacity))\n // The ring is what the exact silhouette shows around the fill as it is drawn.\n let ring = max(silhouette.sub(inked), 0).mul(ringOpacity).toConst()\n const glyphAlpha = fillAlpha.add(ring).toConst()\n // An underlay draws the ring and shadow alone; analytic text then fills the glyph at the\n // alpha k this coverage gives, toned and folded with the ink's alpha as that fill is, and\n // hides k of whatever lies under it. Drawn over the rest, 1 - k, the two draws blend as\n // the one above does, at any ink alpha. Where k is about 1 the fill hides the underlay,\n // and the ring floods the outline's whole silhouette: it covers what an analytic edge\n // leaves bare where the field rounds a corner.\n const rest = options.underlay\n ? float(1)\n .sub(min((tone ? ink(coverage) : coverage).mul(this.inkAlpha()).mul(fillOpacity), 1))\n .toConst()\n : null\n const flood = rest?.lessThan(1e-3)\n if (flood) ring = flood.select(outline ? silhouette.mul(ringOpacity) : 0, ring).toConst()\n const shadowAlpha = (\n shadow\n ? filteredCoverage(inkUv.sub(uvPerLocal.mul(vec2(offsetX, offsetY))))\n .mul(Math.min(1, Math.max(0, shadowOpacity)))\n .mul(float(1).sub(flood ? flood.select(ring, glyphAlpha) : glyphAlpha))\n : float(0)\n ).toConst()\n const alpha = (flood ? ring : glyphAlpha).add(shadowAlpha).toConst()\n const outlineInk = uniform(new Color(outline?.color ?? 0x000000)).mul(ring)\n const rgb = (flood ? outlineInk : fillColor.mul(fillAlpha).add(outlineInk))\n .add(uniform(new Color(shadow?.color ?? 0x000000)).mul(shadowAlpha))\n .div(max(alpha, 1e-6))\n const shadowFill = coverageAt(uvVarying).toConst()\n const castOutlineRamp =\n expansion && (rise || colour) ? rampAtEmptyField(contour.sub(expansion)) : outlineRamp\n const shadowRing = outline\n ? max(\n distanceCoverage(uvVarying, castOutlineRamp, inBand, screenPxRange).sub(shadowFill),\n 0,\n ).mul(ringOpacity)\n : float(0)\n this.applyCoverage(\n coverage,\n shadowFill.mul(fillOpacity).add(shadowRing),\n this.shadowCutoff,\n vec4(rgb, flood && rest ? alpha.div(flood.select(1, rest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vector2,\n type NodeBuilder,\n type Texture,\n type UniformNode,\n} from 'three/webgpu'\nimport {\n attribute,\n clamp,\n dFdx,\n dFdy,\n dot,\n float,\n max,\n min,\n mix,\n smoothstep,\n step,\n texture,\n uniform,\n varying,\n varyingProperty,\n vec2,\n vec4,\n} from 'three/tsl'\n\nimport type {\n SdfColorLayer,\n SdfDropShadowOptions,\n SdfOutlineOptions,\n SdfTextQuality,\n} from '../types.js'\nimport {\n GlyphTextMaterial,\n type GlyphTextMaterialOptions,\n type GlyphPaintExtension,\n} from './GlyphTextMaterial.js'\n\n// Effect composition and atlas-cell clamping adapted from pmndrs/glyph (MIT).\n// Copyright (c) 2026 Poimandres. See THIRD_PARTY_NOTICES.md and licenses/GLYPH-MIT.txt.\n\nexport interface SdfTextMaterialOptions extends GlyphTextMaterialOptions {\n /** Companion colour band from SdfAtlas; omitted keeps the original shader graph. */\n colorLayer?: SdfColorLayer\n outline?: SdfOutlineOptions\n dropShadow?: SdfDropShadowOptions\n /** The single-channel distance-field texture, from `SdfAtlas.texture`. */\n atlas: Texture\n /** Atlas width in texels, from `SdfAtlas.width`. */\n atlasWidth: number\n /** Atlas height in texels, from `SdfAtlas.height`. */\n atlasHeight: number\n /** Distance-field pixel range, from `SdfAtlas.pxRange`. */\n pxRange: number\n /** Font size of the atlas bake in texels, from `SdfAtlas.bakeSize`. Defaults to `96`. */\n bakeSize?: number\n /**\n * First texel row of the atlas's monochrome shapes, from `SdfAtlas.shapeTop`: glyphs from\n * that row down keep their baked coverage where text takes a tone. Defaults to none.\n */\n shapeTop?: number | undefined\n /**\n * SDF contour in the atlas encoding. Defaults to `0.5`, the baked outline; colour glyphs\n * then keep `0.515`, which hides the faint shading around some emoji strikes.\n */\n threshold?: number\n /** Coverage required by the shadow silhouette. Defaults to `0.5`. */\n shadowCutoff?: number\n /** `'high'` adds four derivative-offset samples. Defaults to `'standard'`. */\n quality?: SdfTextQuality\n /** Extra weight in screen pixels for glyphs under 16 pixels per em. Defaults to `0`. */\n stemDarkening?: number\n /**\n * @internal Draws the outline ring and drop shadow alone, under analytic text drawn after\n * it with the same coverage: the underlay of the Windfoil and Slug backends. Needs an\n * outline or a drop shadow.\n */\n underlay?: boolean\n}\n\ntype GlyphGeometry = { hasAttribute(name: string): boolean } | null\n\n/**\n * Whether minified text samples the atlas's mipmaps, whose texels blur the field beyond the\n * support box of a slot: about a pixel of faint halo around small glyphs, which only whole\n * quads keep.\n */\nconst blurred = (atlas: Texture): boolean =>\n atlas.minFilter !== LinearFilter &&\n atlas.minFilter !== NearestFilter &&\n (atlas.generateMipmaps || atlas.mipmaps.length > 1)\n\n/**\n * The position graph, with the geometry of the build it is set up in handed over first: the\n * vertex extension is JavaScript run while the graph is set up, and reads the attributes there.\n */\nclass GeometryProbeNode extends Node {\n static readonly type = 'UltraTextGeometryProbeNode'\n\n constructor(\n readonly positionNode: Node,\n readonly probe: (geometry: GlyphGeometry) => void,\n ) {\n super()\n }\n\n override getNodeType(builder: NodeBuilder): string {\n return this.positionNode.getNodeType(builder)\n }\n\n override setup(builder: NodeBuilder): Node {\n this.probe((builder as { geometry?: GlyphGeometry }).geometry ?? null)\n return this.positionNode\n }\n}\n\n/** Retained single-channel SDF text with TSL motion, clipping, and shadows. */\nexport class SdfTextMaterial extends GlyphTextMaterial {\n readonly #th: UniformNode<'float', number> = uniform(0.5)\n readonly #sc: UniformNode<'float', number> = uniform(0.5)\n readonly #sd: UniformNode<'float', number> = uniform(0)\n readonly #ur: UniformNode<'vec2', Vector2> = uniform(new Vector2())\n readonly quality: SdfTextQuality\n\n get threshold(): UniformNode<'float', number> {\n return this.#th\n }\n get shadowCutoff(): UniformNode<'float', number> {\n return this.#sc\n }\n get stemDarkening(): UniformNode<'float', number> {\n return this.#sd\n }\n get unitRange(): UniformNode<'vec2', Vector2> {\n return this.#ur\n }\n\n /** @internal */\n protected override copySubclassUniforms(target: this): void {\n target.threshold.value = this.#th.value\n target.shadowCutoff.value = this.#sc.value\n target.stemDarkening.value = this.#sd.value\n }\n\n constructor(options: SdfTextMaterialOptions) {\n const outline = options.outline\n const shadow = options.dropShadow\n const width = outline ? (outline.width ?? 1) : 0\n const offsetX = shadow ? (shadow.offsetX ?? 2) : 0\n const offsetY = shadow ? (shadow.offsetY ?? -2) : 0\n const outlineOpacity = outline?.opacity ?? 1\n const shadowOpacity = shadow?.opacity ?? 0.5\n if (\n ![width, offsetX, offsetY, outlineOpacity, shadowOpacity].every(Number.isFinite) ||\n width < 0\n ) {\n throw new RangeError(\n 'SdfTextMaterial: effects require finite values and a non-negative outline width',\n )\n }\n const effects = outline !== undefined || shadow !== undefined\n // Whether quads may shrink to their glyphs' support boxes (`sdfTrim`): effect quads reach\n // past the cell, run motion's vertex buffer leaves none for the trim, and mipmaps blur the\n // field past the box.\n const trimmable =\n !effects &&\n !(options.runMotion ?? options.textShaping === 'browser') &&\n !blurred(options.atlas)\n const glyphUvRect = attribute<'vec4'>('sdfUvRect', 'vec4')\n const uvVarying = varyingProperty('vec2', 'vUltraSdfUv')\n const uvBounds = effects ? varyingProperty('vec4', 'vUltraSdfUvBounds') : null\n const uvPerLocal = effects ? varyingProperty('vec2', 'vUltraSdfUvPerLocal') : null\n const layer = options.colorLayer\n const inBand = layer ? varyingProperty('float', 'vUltraColorGlyph') : null\n const bandTop = layer ? uniform((layer.top + 0.5) / options.atlasHeight) : null\n const bandMap = layer\n ? uniform(new Vector2(options.atlasHeight / layer.height, layer.top / layer.height))\n : null\n // Monochrome shapes keep their baked coverage where text takes a tone. Their rows lie\n // below the text and above the colour band, from the one the atlas names; a texture from\n // `buildSdfAtlas` repeats it for a caller that passes no `shapeTop`. Only a shader whose\n // fragment reads the flag carries it, flat from `either` vertex like GlyphTextMaterial's.\n // A toned shader that can trim its quads carries it whether or not the atlas has shapes:\n // without them the row is one below the atlas, which no glyph reaches, so the flag is 0 and\n // the shader is the one a shape atlas uses (the row is a uniform), mixing the exact\n // coverage in at weight 0. Whole quads would pay for that per fragment with nothing back.\n const shapeTop: unknown = options.shapeTop ?? options.atlas.userData['ultraShapeTop']\n const shaped = typeof shapeTop === 'number'\n const inShapes =\n options.tone !== false && (shaped || trimmable)\n ? varying(\n step(\n uniform(((shaped ? shapeTop : options.atlasHeight) + 0.5) / options.atlasHeight),\n min(glyphUvRect.y, glyphUvRect.w),\n ),\n 'vUltraShapeGlyph',\n ).setInterpolation('flat', 'either')\n : null\n const paint: GlyphPaintExtension | undefined = layer\n ? (css) => {\n const halfTexel = vec2(0.5 / options.atlasWidth, 0.5 / options.atlasHeight)\n const safeUv = uvBounds\n ? clamp(uvVarying, uvBounds.xy.add(halfTexel), uvBounds.zw.sub(halfTexel))\n : uvVarying\n const bandUv = vec2(safeUv.x, safeUv.y.mul(bandMap!.x).sub(bandMap!.y))\n const sample = texture(layer.texture, bandUv)\n const scale = vec2(1, bandMap!.x)\n const texel = (\n uvBounds ? sample.grad(dFdx(uvVarying).mul(scale), dFdy(uvVarying).mul(scale)) : sample\n ).toConst()\n const glyph = step(0.5, inBand!).toConst()\n const weight = texel.a.mul(glyph).toConst()\n return { rgb: css.mul(weight.oneMinus()).add(texel.rgb.mul(glyph)), weight }\n }\n : undefined\n // Set once constructed and per build, before the vertex extension below runs.\n const built: { material?: SdfTextMaterial; geometry?: GlyphGeometry; cast?: boolean } = {}\n super(\n options,\n (quad, rect, position, _depth, motionScale, fillUv) => {\n inBand?.assign(step(bandTop!, min(glyphUvRect.y, glyphUvRect.w)))\n const uvSpan = glyphUvRect.zw.sub(glyphUvRect.xy)\n if (uvBounds && uvPerLocal) {\n const size = rect.zw.sub(rect.xy).max(1e-6)\n const padding = vec2(width + Math.abs(offsetX), width + Math.abs(offsetY))\n const extra = quad.mul(2).sub(1).mul(padding)\n uvPerLocal.assign(uvSpan.div(size))\n uvBounds.assign(\n vec4(min(glyphUvRect.xy, glyphUvRect.zw), max(glyphUvRect.xy, glyphUvRect.zw)),\n )\n const expandedQuad = quad.add(extra.div(size))\n fillUv?.assign(expandedQuad)\n uvVarying.assign(glyphUvRect.xy.add(uvSpan.mul(expandedQuad)))\n return position.add(options.motion === false ? extra : extra.mul(motionScale))\n }\n const material = built.material\n if (material && built.geometry?.hasAttribute('sdfTrim') && !blurred(options.atlas)) {\n // Most of a glyph's quad is empty field, which every fragment there samples to no\n // coverage. `sdfTrim` is the slot's support box in the order and units of the UV\n // rect, the macOS rise included: the quad shrinks to it, in quad units. A box outside\n // this instance's slot (a UV rect rewritten to another glyph) leaves the whole quad.\n // 'high' samples a quarter pixel around each fragment: half the field's range more\n // covers that down to about 6 pixels per em at the default bake.\n const trim = attribute<'vec4'>('sdfTrim', 'vec4')\n const span = uvSpan.toConst()\n const bounds = trim.sub(glyphUvRect.xyxy).div(vec4(span, span)).toConst()\n const sum = bounds.xy.add(bounds.zw).sub(1).abs().toConst()\n const inside = max(sum.x, sum.y).lessThan(1)\n const reach =\n !built.cast && material.quality === 'high'\n ? material.unitRange.mul(0.5).div(span.abs()).toConst()\n : null\n const limits = clamp(\n reach ? bounds.add(vec4(reach.negate(), reach)) : bounds,\n 0,\n 1,\n ).toConst()\n const trimmed = inside\n .select(mix(limits.xy, limits.zw, quad), quad)\n .context({ uniformFlow: true })\n .toConst()\n fillUv?.assign(trimmed)\n uvVarying.assign(glyphUvRect.xy.add(span.mul(trimmed)))\n // The quad's own size times the motion's scale: exact for every motion mode, whose\n // centre stays the untrimmed rect's.\n if (options.motion === false) return rect.xy.add(rect.zw.sub(rect.xy).mul(trimmed))\n const step = rect.zw.sub(rect.xy).mul(trimmed.sub(quad))\n return position.add(step.mul(motionScale))\n }\n uvVarying.assign(glyphUvRect.xy.add(uvSpan.mul(quad)))\n },\n undefined,\n paint,\n )\n built.material = this\n // Where quads may be trimmed, the geometry decides: a custom geometry without `sdfTrim`\n // keeps the whole quads and the vertex stage it always had. Glyph geometry with run motion\n // has none. A shadow map samples each fragment's own UV, so its quads keep to the support\n // box itself.\n if (trimmable) {\n const graph = this.positionNode!\n this.positionNode = new GeometryProbeNode(graph, (geometry) => {\n built.geometry = geometry\n built.cast = false\n })\n this.castShadowPositionNode = new GeometryProbeNode(graph, (geometry) => {\n built.geometry = geometry\n built.cast = true\n })\n }\n this.name = 'ultra-text TSL runtime SDF text'\n this.threshold.value = options.threshold ?? 0.5\n this.shadowCutoff.value = Math.min(1, Math.max(0, options.shadowCutoff ?? 0.5))\n this.stemDarkening.value = Math.max(0, options.stemDarkening ?? 0)\n this.quality = options.quality ?? 'standard'\n this.unitRange.value.set(\n options.pxRange / options.atlasWidth,\n options.pxRange / options.atlasHeight,\n )\n\n // Texels per pixel along each atlas axis: one over the length of that axis's screen\n // gradient, as Windfoil's pixel box measures it. `fwidth()` is the footprint's bounding box,\n // which reads text turned in its plane up to √2 smaller than it is: a wider ramp, and a\n // stem darkening and tone size gate that moved with the angle. Axis-aligned text gets the\n // same value. Each derivative is its own node, so the shader gains no local and the vertex\n // stage, which shares their numbering, keeps its text.\n // The floor only guards a zero footprint. A larger one, such as 1e-5 on the gradient, capped\n // the range once a texel spanned more than 1e5 / atlasWidth pixels and blurred magnified\n // edges over several pixels, unevenly on a non-square atlas.\n const squared = (derivative: typeof dFdx) => derivative(uvVarying).mul(derivative(uvVarying))\n const screenTextureSize = squared(dFdx).add(squared(dFdy)).max(1e-18).inverseSqrt()\n // Effect contours revisit shared coverage nodes in several conditional branches.\n // Three r186 can redeclare a toConst() local twice in the same branch; mutable\n // locals hoist that shared calculation. Keep the ordinary text graph unchanged.\n const local = (node: Node<'float'>): Node<'float'> => (effects ? node.toVar() : node.toConst())\n const screenPxRange = local(max(dot(this.unitRange, screenTextureSize).mul(0.5), 1))\n const rawStemBoost = this.stemDarkening.mul(clamp(float(2).sub(screenPxRange), 0, 1))\n const stemBoost = local(inBand ? rawStemBoost.mul(inBand.oneMinus()) : rawStemBoost)\n // Colour glyphs sit a little inside the default contour; an explicit threshold moves both.\n const contour = inBand\n ? this.threshold.add(inBand.mul(uniform(options.threshold === undefined ? 0.015 : 0)))\n : this.threshold\n // A slot of the colour band can hold text beside its colour ink, as a shaped line does\n // beside its emoji. The beauty pass therefore tells the two apart per fragment, by the\n // band's own alpha: 1 around colour ink, 0 around foreground ink. Shadow maps keep the\n // row flag.\n const colour = layer ? this.colorWeight : null\n const inkContour = colour\n ? this.threshold.add(colour.mul(uniform(options.threshold === undefined ? 0.015 : 0)))\n : contour\n // 1 where the baked coverage is kept: a shape's rows or colour ink.\n const exact =\n colour && inShapes && inBand\n ? max(inShapes.mul(inBand.oneMinus()), colour)\n : (colour ?? inShapes)\n // macOS font smoothing, for text ink below the size where the browser stops applying it:\n // the outline grows by d = min(dilationEm ems, dilationPx pixels) to each side, by 2 d\n // upwards and not at all downwards, which is a dilation by d and a rise by d. `smoothed`\n // is 1 where that holds, `rise` is d in screen pixels. Other models add no node here.\n const tone = this.tone\n let smoothed: Node<'float'> | undefined\n let rise: Node<'float'> | undefined\n if (tone?.dilates) {\n const emPx = screenPxRange.mul(uniform((options.bakeSize ?? 96) / options.pxRange)).toConst()\n const small = step(tone.dilation.z, emPx).oneMinus()\n smoothed = local(exact ? small.mul(exact.oneMinus()) : small)\n rise = local(min(emPx.mul(tone.dilation.x), tone.dilation.y).mul(smoothed))\n }\n // The ramp input where the field saturates to 0, the empty rest of the atlas cell, capped\n // at the ramp's foot so that background keeps exactly zero coverage. Uncapped, a glyph a\n // few pixels tall lifted its whole quad to ~3% alpha through stem darkening, and an outline\n // near the range limit to over a third; the mask then kept every fragment of the quad.\n // `lift` moves the contour outwards by that many screen pixels.\n const rampAtEmptyField = (\n edge: Node<'float'>,\n lift: Node<'float'> = stemBoost,\n steep?: Node<'float'>,\n ) =>\n local(\n min(\n steep\n ? steep.mul(lift.sub(screenPxRange.mul(edge))).add(0.5)\n : lift.add(0.5).sub(screenPxRange.mul(edge)),\n 0,\n ),\n )\n // Shadow maps keep the baked contour; only the beauty contour is dilated. A distance field\n // has one offset for every edge: d, which is exact on upright and level strokes.\n const lift = rise ? stemBoost.add(rise) : stemBoost\n // The field reaches zero screenPxRange / 2 pixels outside the contour. Where that is less\n // than the half pixel of ramp plus the dilation, the ramp steepens so that it still starts\n // at the empty field and its middle still lies `rise` outside: s / (s - 2 rise) for s.\n const invClamp = rise\n ? local(float(1).div(clamp(screenPxRange.sub(rise.mul(2)), 0.25, 1)))\n : undefined\n const inkSlope = invClamp ? local(screenPxRange.mul(invClamp)) : undefined\n const castRamp = rampAtEmptyField(contour)\n const fillRamp = rise || colour ? rampAtEmptyField(inkContour, lift, invClamp) : castRamp\n // The rise samples the field that many pixels lower on screen.\n const inkUv = rise ? uvVarying.sub(dFdy(uvVarying).mul(rise)) : uvVarying\n const coverageAt = (sampleUv: Node<'vec2'>): Node<'float'> => {\n return distanceCoverage(sampleUv, castRamp, inBand, screenPxRange)\n }\n // The atlas texel under one sample, read with the glyph's own footprint.\n const fieldAt = (sampleUv: Node<'vec2'>): Node<'float'> => {\n const halfTexel = vec2(0.5 / options.atlasWidth, 0.5 / options.atlasHeight)\n const safeUv = uvBounds\n ? clamp(sampleUv, uvBounds.xy.add(halfTexel), uvBounds.zw.sub(halfTexel))\n : sampleUv\n const sample = texture(options.atlas, safeUv)\n // Clamping changes the implicit derivatives at a cell boundary. Preserve\n // the original footprint so mip/anisotropic filtering cannot form seams.\n return (uvBounds ? sample.grad(dFdx(uvVarying), dFdy(uvVarying)) : sample).r\n }\n // One pixel of linear ramp across the contour: the coverage of a straight edge. Colour\n // glyphs keep the eased ramp, whose shorter foot hides the ink colour around their texels.\n const contourAt = (\n field: Node<'float'>,\n ramp: Node<'float'> = fillRamp,\n eased: Node<'float'> | null = colour ?? inBand,\n slope: Node<'float'> = inkSlope ?? screenPxRange,\n ): Node<'float'> => {\n const across = slope.mul(field).add(ramp)\n const linear = clamp(across, 0, 1)\n return eased ? mix(linear, smoothstep(0, 1, across), eased) : linear\n }\n // Effect quads reach past the glyph's cell; samples there read nothing.\n const insideCell = (sampleUv: Node<'vec2'>, bounds: Node<'vec4'>): Node<'bool'> =>\n sampleUv.x\n .greaterThanEqual(bounds.x)\n .and(sampleUv.y.greaterThanEqual(bounds.y))\n .and(sampleUv.x.lessThanEqual(bounds.z))\n .and(sampleUv.y.lessThanEqual(bounds.w))\n const distanceCoverage = (\n sampleUv: Node<'vec2'>,\n ramp?: Node<'float'>,\n eased: Node<'float'> | null = colour ?? inBand,\n slope?: Node<'float'>,\n ): Node<'float'> => {\n const alpha = contourAt(fieldAt(sampleUv), ramp, eased, slope)\n return uvBounds ? insideCell(sampleUv, uvBounds).select(alpha, 0) : alpha\n }\n const uvDx = this.quality === 'high' ? dFdx(uvVarying).mul(0.125).toConst() : null\n const uvDy = this.quality === 'high' ? dFdy(uvVarying).mul(0.125).toConst() : null\n // 'high' filters a contour over a 4-rook rotated grid (±1/8, ±3/8 px) so horizontal,\n // vertical and diagonal strokes each see four distinct subpixel strata instead of two.\n const tapsAround = (sampleUv: Node<'vec2'>): Node<'vec2'>[] =>\n uvDx && uvDy\n ? [\n sampleUv.sub(uvDx).sub(uvDy.mul(3)),\n sampleUv.add(uvDx.mul(3)).sub(uvDy),\n sampleUv.sub(uvDx.mul(3)).add(uvDy),\n sampleUv.add(uvDx).add(uvDy.mul(3)),\n ]\n : [sampleUv]\n // Filter every beauty contour alike: subtracting differently filtered\n // silhouettes produces a jagged ring, even when its requested width is zero.\n const filteredCoverage = (sampleUv: Node<'vec2'>, ramp?: Node<'float'>): Node<'float'> => {\n const taps = tapsAround(sampleUv).map((tap) => distanceCoverage(tap, ramp))\n if (taps.length === 1) return taps[0]!\n return taps.reduce((sum, tap) => sum.add(tap)).mul(0.25)\n }\n // Text ink is shown at the weight a browser gives it. Shapes, colour glyphs, outline rings,\n // drop shadows and shadow maps keep the exact coverage. `fold` false where the result is\n // composed with a ring and a drop shadow before the ink's alpha.\n const ink = (baked: Node<'float'>, fold = true): Node<'float'> => {\n const toned = this.toned(baked, this.fillNode?.rgb, smoothed, fold)\n return exact && tone ? mix(toned, baked, exact) : toned\n }\n // The field encodes only half of pxRange outside the contour. Clamp the\n // requested expansion so the outline's contour stays inside it; its ramp\n // is capped at the empty field like the fill's.\n const expansion =\n outline && uvPerLocal\n ? min(uvPerLocal.x.abs().mul((options.atlasWidth * width) / options.pxRange), 0.49)\n : null\n const outlineRamp = expansion\n ? rampAtEmptyField(inkContour.sub(expansion), lift, invClamp)\n : fillRamp\n let coverage: Node<'float'>\n let outlined: Node<'float'> | null = null\n if (expansion && uvBounds) {\n // The fill and the outline's silhouette are two contours of the same taps. Each tap is\n // read once, in the one branch that skips taps outside the glyph's cell (most of an\n // effect quad), and gives both contours: component for component the sums of\n // filteredCoverage, in the same order.\n const pairs = tapsAround(inkUv).map((tap) => {\n const field = fieldAt(tap)\n return insideCell(tap, uvBounds).select(\n vec2(contourAt(field), contourAt(field, outlineRamp)),\n vec2(0),\n )\n })\n const sums = (\n pairs.length === 1 ? pairs[0]! : pairs.reduce((sum, pair) => sum.add(pair)).mul(0.25)\n ).toVar()\n coverage = sums.x\n outlined = sums.y\n } else coverage = filteredCoverage(inkUv)\n // Shadow maps filter the finished silhouette; don't supersample that path.\n if (effects && uvPerLocal) {\n coverage = coverage.toConst()\n const inked = tone ? ink(coverage, false).toConst() : coverage\n const fillOpacity = this.fillNode ? clamp(this.fillNode.a, 0, 1) : float(1)\n const fillAlpha = inked.mul(fillOpacity).toConst()\n const fillColor = this.fillNode?.rgb ?? this.baseColor\n const silhouette = outlined ? outlined.toConst() : inked\n const ringOpacity = Math.min(1, Math.max(0, outlineOpacity))\n // The ring is what the exact silhouette shows around the fill as it is drawn.\n let ring = max(silhouette.sub(inked), 0).mul(ringOpacity).toConst()\n const glyphAlpha = fillAlpha.add(ring).toConst()\n // An underlay draws the ring and shadow alone; analytic text then fills the glyph at the\n // alpha k this coverage gives, toned and folded with the ink's alpha as that fill is, and\n // hides k of whatever lies under it. Drawn over the rest, 1 - k, the two draws blend as\n // the one above does, at any ink alpha. Where k is about 1 the fill hides the underlay,\n // and the ring floods the outline's whole silhouette: it covers what an analytic edge\n // leaves bare where the field rounds a corner.\n const rest = options.underlay\n ? float(1)\n .sub(min((tone ? ink(coverage) : coverage).mul(this.inkAlpha()).mul(fillOpacity), 1))\n .toConst()\n : null\n const flood = rest?.lessThan(1e-3)\n if (flood) ring = flood.select(outline ? silhouette.mul(ringOpacity) : 0, ring).toConst()\n const shadowAlpha = (\n shadow\n ? filteredCoverage(inkUv.sub(uvPerLocal.mul(vec2(offsetX, offsetY))))\n .mul(Math.min(1, Math.max(0, shadowOpacity)))\n .mul(float(1).sub(flood ? flood.select(ring, glyphAlpha) : glyphAlpha))\n : float(0)\n ).toConst()\n const alpha = (flood ? ring : glyphAlpha).add(shadowAlpha).toConst()\n const outlineInk = uniform(new Color(outline?.color ?? 0x000000)).mul(ring)\n const rgb = (flood ? outlineInk : fillColor.mul(fillAlpha).add(outlineInk))\n .add(uniform(new Color(shadow?.color ?? 0x000000)).mul(shadowAlpha))\n .div(max(alpha, 1e-6))\n const shadowFill = coverageAt(uvVarying).toConst()\n const castOutlineRamp =\n expansion && (rise || colour) ? rampAtEmptyField(contour.sub(expansion)) : outlineRamp\n const shadowRing = outline\n ? max(\n distanceCoverage(uvVarying, castOutlineRamp, inBand, screenPxRange).sub(shadowFill),\n 0,\n ).mul(ringOpacity)\n : float(0)\n this.applyCoverage(\n coverage,\n shadowFill.mul(fillOpacity).add(shadowRing),\n this.shadowCutoff,\n vec4(rgb, flood && rest ? alpha.div(flood.select(1, rest)) : alpha),\n !!flood,\n )\n } else {\n this.applyCoverage(\n tone ? ink(coverage.toConst()) : coverage,\n coverageAt(uvVarying),\n this.shadowCutoff,\n undefined,\n !!tone,\n )\n }\n }\n}\n"],"mappings":";;;;;;;;;AA2FA,IAAM,WAAW,UACf,MAAM,cAAc,gBACpB,MAAM,cAAc,kBACnB,MAAM,mBAAmB,MAAM,QAAQ,SAAS;;;;;AAMnD,IAAM,oBAAN,cAAgC,KAAK;CAIxB;CACA;CAJX,OAAgB,OAAO;CAEvB,YACE,cACA,OACA;EACA,MAAM;EAHG,KAAA,eAAA;EACA,KAAA,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snapshot, drawable) {
47
47
  if (next?.block === glyph.block && next.lineBottom === glyph.lineBottom && next.decorations?.some((candidate) => sameDecoration(decoration, candidate))) right = Math.max(right, next.originX);
48
48
  const y = glyph.lineBottom + decoration.offset;
49
49
  records.push([
50
- [
51
- glyph.originX,
52
- y - decoration.thickness / 2,
53
- right,
54
- y + decoration.thickness / 2
55
- ],
50
+ glyph.originX,
51
+ y - decoration.thickness / 2,
52
+ right,
53
+ y + decoration.thickness / 2,
56
54
  glyphIndex,
57
55
  glyph.motionOrigin?.[2] ?? motionIndex,
58
56
  decoration.color,
@@ -82,25 +80,44 @@ function decorationAttributesMatch(geometry, records) {
82
80
  if (!count || records.length !== count) return false;
83
81
  if (DECORATION_ATTRS.some((name) => geometry.getAttribute(name)?.count !== count)) return false;
84
82
  const run = geometry.getAttribute("sdfRunMotion");
85
- return records.some((r) => r[7]) ? run?.count === count : !run;
83
+ return records.some((r) => r[10]) ? run?.count === count : !run;
86
84
  }
87
85
  function writeDecorationBatch(records, sourceRects, rects, strokes, indices, colors, clips, metadata, runMotion) {
88
86
  let minZ = 0;
89
87
  let maxZ = 0;
90
88
  for (let index = 0; index < records.length; index++) {
91
- const [stroke, rectIndex, motionIndex, color, clip, sequence, z, motionOrigin] = records[index];
89
+ const rec = records[index];
92
90
  const offset = index * 4;
93
- const srcOffset = rectIndex * 4;
94
- for (let i = 0; i < 4; i++) {
95
- rects[offset + i] = sourceRects[srcOffset + i] ?? 0;
96
- colors[offset + i] = byte(color[i]);
97
- }
98
- strokes.set(stroke, offset);
99
- clips.set(clip, offset);
100
- indices[index] = motionIndex;
101
- metadata[index * 2] = sequence;
91
+ const srcOffset = rec[4] * 4;
92
+ rects[offset] = sourceRects[srcOffset] ?? 0;
93
+ rects[offset + 1] = sourceRects[srcOffset + 1] ?? 0;
94
+ rects[offset + 2] = sourceRects[srcOffset + 2] ?? 0;
95
+ rects[offset + 3] = sourceRects[srcOffset + 3] ?? 0;
96
+ const color = rec[6];
97
+ colors[offset] = byte(color[0]);
98
+ colors[offset + 1] = byte(color[1]);
99
+ colors[offset + 2] = byte(color[2]);
100
+ colors[offset + 3] = byte(color[3]);
101
+ strokes[offset] = rec[0];
102
+ strokes[offset + 1] = rec[1];
103
+ strokes[offset + 2] = rec[2];
104
+ strokes[offset + 3] = rec[3];
105
+ const clip = rec[7];
106
+ clips[offset] = clip[0];
107
+ clips[offset + 1] = clip[1];
108
+ clips[offset + 2] = clip[2];
109
+ clips[offset + 3] = clip[3];
110
+ indices[index] = rec[5];
111
+ metadata[index * 2] = rec[8];
112
+ const z = rec[9];
102
113
  metadata[index * 2 + 1] = z;
103
- if (runMotion && motionOrigin) runMotion.set(motionOrigin, index * 3);
114
+ const motionOrigin = rec[10];
115
+ if (runMotion && motionOrigin) {
116
+ const mOffset = index * 3;
117
+ runMotion[mOffset] = motionOrigin[0];
118
+ runMotion[mOffset + 1] = motionOrigin[1];
119
+ runMotion[mOffset + 2] = motionOrigin[2];
120
+ }
104
121
  if (z < minZ) minZ = z;
105
122
  if (z > maxZ) maxZ = z;
106
123
  }
@@ -136,7 +153,7 @@ function createDecorationGeometry(snapshot, textGeometry, drawable, motionPaddin
136
153
  const colors = new Uint8Array(count * 4);
137
154
  const clips = new Float32Array(count * 4);
138
155
  const metadata = new Float32Array(count * 2);
139
- const runMotion = records.some((record) => record[7] !== null) ? new Float32Array(count * 3) : null;
156
+ const runMotion = records.some((record) => record[10] !== null) ? new Float32Array(count * 3) : null;
140
157
  const [minZ, maxZ] = writeDecorationBatch(records, glyphRectTable(textGeometry), rects, strokes, indices, colors, clips, metadata, runMotion);
141
158
  const geometry = new InstancedBufferGeometry();
142
159
  geometry.name = "ultra-text instanced solid text decorations";
@@ -1 +1 @@
1
- {"version":3,"file":"decorations.js","names":[],"sources":["../../src/text/decorations.ts"],"sourcesContent":["import { InstancedBufferAttribute, InstancedBufferGeometry } from 'three/webgpu'\nimport { attribute, float, mix } from 'three/tsl'\n\nimport type { DomLayoutSnapshot, TextDecorationLayout } from '../types.js'\nimport { GlyphTextMaterial, type GlyphTextMaterialOptions } from './GlyphTextMaterial.js'\nimport { byte, setBounds, setUnitQuad } from './geometryUtils.js'\n\nexport const GLYPH_RECTS_KEY = 'ultraGlyphRects'\nexport function glyphRectTable(geometry: InstancedBufferGeometry): ArrayLike<number> {\n return (\n (geometry.userData[GLYPH_RECTS_KEY] as Float32Array | undefined) ??\n geometry.getAttribute('sdfRect').array\n )\n}\n\n/** Decoration quads share their source glyph's motion center, index, and clip. */\nexport class TextDecorationMaterial extends GlyphTextMaterial {\n constructor(options: GlyphTextMaterialOptions) {\n super(\n options,\n (quad, rect, position, _depth, scale) => {\n const decoration = attribute<'vec4'>('decorationRect', 'vec4')\n if (options.motion === false) return mix(decoration.xy, decoration.zw, quad)\n const delta = mix(decoration.xy.sub(rect.xy), decoration.zw.sub(rect.zw), quad)\n return position.add(delta.mul(scale))\n },\n attribute<'float'>('decorationIndex', 'float'),\n )\n this.name = 'ultra-text solid text decorations'\n this.applyCoverage(float(1), float(1), float(0.5))\n }\n}\n\nfunction sameDecoration(a: TextDecorationLayout, b: TextDecorationLayout): boolean {\n return (\n a.line === b.line &&\n a.offset === b.offset &&\n a.thickness === b.thickness &&\n a.color.every((v, i) => v === b.color[i])\n )\n}\n\ntype DecorationRecord = readonly [\n stroke: readonly [number, number, number, number],\n rectIndex: number,\n motionIndex: number,\n color: readonly [number, number, number, number],\n clip: readonly [number, number, number, number],\n sequence: number,\n z: number,\n motionOrigin: readonly [number, number, number] | null,\n]\n\nlet cachedSnapshot: DomLayoutSnapshot | null = null\nlet cachedDrawable: ((key: string) => boolean) | null = null\nlet cachedRecords: readonly DecorationRecord[] = []\n\nfunction decorationRecords(\n snapshot: DomLayoutSnapshot,\n drawable: (key: string) => boolean,\n): readonly DecorationRecord[] {\n if (snapshot === cachedSnapshot && drawable === cachedDrawable) return cachedRecords\n const glyphs = snapshot.glyphs\n const records: DecorationRecord[] = []\n if (glyphs.some((glyph) => glyph.decorations?.length)) {\n let glyphIndex = 0\n let motionIndex = -1\n let previousGroup: number | undefined\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n if (!drawable(glyph.glyphKey)) continue\n if (glyph.shapeGroup === undefined || glyph.shapeGroup !== previousGroup) motionIndex++\n previousGroup = glyph.shapeGroup\n const decorations = glyph.decorations\n if (decorations) {\n for (const decoration of decorations) {\n if (decoration.thickness <= 0 || decoration.color[3] <= 0) continue\n const next = glyphs[index + 1]\n let right = glyph.originX + (glyph.decorationWidth ?? Math.abs(glyph.advance))\n if (\n next?.block === glyph.block &&\n next.lineBottom === glyph.lineBottom &&\n next.decorations?.some((candidate) => sameDecoration(decoration, candidate))\n ) {\n right = Math.max(right, next.originX)\n }\n const y = glyph.lineBottom + decoration.offset\n records.push([\n [glyph.originX, y - decoration.thickness / 2, right, y + decoration.thickness / 2],\n glyphIndex,\n glyph.motionOrigin?.[2] ?? motionIndex,\n decoration.color,\n glyph.clip,\n glyph.sequence,\n glyph.z,\n glyph.motionOrigin ?? null,\n ])\n }\n }\n glyphIndex++\n }\n }\n cachedSnapshot = snapshot\n cachedDrawable = drawable\n return (cachedRecords = records)\n}\n\nconst DECORATION_ATTRS = [\n 'sdfRect',\n 'decorationRect',\n 'decorationIndex',\n 'sdfColor',\n 'sdfClip',\n 'sdfMeta',\n] as const\n\nfunction decorationAttributesMatch(\n geometry: InstancedBufferGeometry,\n records: readonly DecorationRecord[],\n): boolean {\n const count = geometry.instanceCount\n if (!count || records.length !== count) return false\n if (\n DECORATION_ATTRS.some(\n (name) => (geometry.getAttribute(name) as { count: number } | undefined)?.count !== count,\n )\n )\n return false\n const run = geometry.getAttribute('sdfRunMotion') as { count: number } | undefined\n return records.some((r) => r[7]) ? run?.count === count : !run\n}\n\nfunction writeDecorationBatch(\n records: readonly DecorationRecord[],\n sourceRects: ArrayLike<number>,\n rects: Float32Array,\n strokes: Float32Array,\n indices: Float32Array,\n colors: Uint8Array,\n clips: Float32Array,\n metadata: Float32Array,\n runMotion: Float32Array | null,\n): [number, number] {\n let minZ = 0\n let maxZ = 0\n for (let index = 0; index < records.length; index++) {\n const [stroke, rectIndex, motionIndex, color, clip, sequence, z, motionOrigin] = records[index]!\n const offset = index * 4\n const srcOffset = rectIndex * 4\n for (let i = 0; i < 4; i++) {\n rects[offset + i] = sourceRects[srcOffset + i] ?? 0\n colors[offset + i] = byte(color[i]!)\n }\n strokes.set(stroke, offset)\n clips.set(clip, offset)\n indices[index] = motionIndex\n metadata[index * 2] = sequence\n metadata[index * 2 + 1] = z\n if (runMotion && motionOrigin) runMotion.set(motionOrigin, index * 3)\n if (z < minZ) minZ = z\n if (z > maxZ) maxZ = z\n }\n return [minZ, maxZ]\n}\n\n/**\n * True when an existing decoration batch can be rewritten without allocating.\n * A null geometry matches only an empty decoration list.\n */\nexport function canUpdateDecorationGeometry(\n geometry: InstancedBufferGeometry | null,\n snapshot: DomLayoutSnapshot,\n drawable: (key: string) => boolean,\n): boolean {\n const records = decorationRecords(snapshot, drawable)\n return geometry ? decorationAttributesMatch(geometry, records) : !records.length\n}\n\n/** Rewrites a same-count decoration batch from the current glyph rects. */\nexport function updateDecorationGeometry(\n geometry: InstancedBufferGeometry,\n snapshot: DomLayoutSnapshot,\n textGeometry: InstancedBufferGeometry,\n drawable: (key: string) => boolean,\n motionPadding: number,\n): boolean {\n const records = decorationRecords(snapshot, drawable)\n if (!decorationAttributesMatch(geometry, records)) return false\n const run = geometry.getAttribute('sdfRunMotion') as InstancedBufferAttribute | undefined\n const arr = <T extends Float32Array | Uint8Array>(n: string): T =>\n geometry.getAttribute(n).array as T\n const [minZ, maxZ] = writeDecorationBatch(\n records,\n glyphRectTable(textGeometry),\n arr('sdfRect'),\n arr('decorationRect'),\n arr('decorationIndex'),\n arr('sdfColor'),\n arr('sdfClip'),\n arr('sdfMeta'),\n run ? (run.array as Float32Array) : null,\n )\n for (const name of DECORATION_ATTRS) {\n geometry.getAttribute(name).needsUpdate = true\n }\n if (run) run.needsUpdate = true\n setBounds(geometry, snapshot.width, snapshot.height, motionPadding, minZ, maxZ)\n return true\n}\n\nexport function createDecorationGeometry(\n snapshot: DomLayoutSnapshot,\n textGeometry: InstancedBufferGeometry,\n drawable: (key: string) => boolean,\n motionPadding: number,\n): InstancedBufferGeometry | null {\n const records = decorationRecords(snapshot, drawable)\n const count = records.length\n if (!count) return null\n const rects = new Float32Array(count * 4)\n const strokes = new Float32Array(count * 4)\n const indices = new Float32Array(count)\n const colors = new Uint8Array(count * 4)\n const clips = new Float32Array(count * 4)\n const metadata = new Float32Array(count * 2)\n const runMotion = records.some((record) => record[7] !== null)\n ? new Float32Array(count * 3)\n : null\n const [minZ, maxZ] = writeDecorationBatch(\n records,\n glyphRectTable(textGeometry),\n rects,\n strokes,\n indices,\n colors,\n clips,\n metadata,\n runMotion,\n )\n const geometry = new InstancedBufferGeometry()\n geometry.name = 'ultra-text instanced solid text decorations'\n setUnitQuad(geometry)\n const attr = (name: string, a: Float32Array | Uint8Array, n: number, norm = false): void => {\n geometry.setAttribute(name, new InstancedBufferAttribute(a, n, norm))\n }\n attr('sdfRect', rects, 4)\n attr('decorationRect', strokes, 4)\n attr('decorationIndex', indices, 1)\n attr('sdfColor', colors, 4, true)\n attr('sdfClip', clips, 4)\n attr('sdfMeta', metadata, 2)\n if (runMotion) attr('sdfRunMotion', runMotion, 3)\n geometry.instanceCount = count\n setBounds(geometry, snapshot.width, snapshot.height, motionPadding, minZ, maxZ)\n return geometry\n}\n"],"mappings":";;;;;AAOA,IAAa,kBAAkB;AAC/B,SAAgB,eAAe,UAAsD;CACnF,OACG,SAAS,SAAA,sBACV,SAAS,aAAa,SAAS,CAAC,CAAC;AAErC;;AAGA,IAAa,yBAAb,cAA4C,kBAAkB;CAC5D,YAAY,SAAmC;EAC7C,MACE,UACC,MAAM,MAAM,UAAU,QAAQ,UAAU;GACvC,MAAM,aAAa,UAAkB,kBAAkB,MAAM;GAC7D,IAAI,QAAQ,WAAW,OAAO,OAAO,IAAI,WAAW,IAAI,WA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AAU,IAAI,aAAa,QAAQ,CAAC;CAC1C,MAAM,UAAU,IAAI,aAAa,KAAK;CACtC,MAAM,SAAS,IAAI,WAAW,QAAQ,CAAC;CACvC,MAAM,QAAQ,IAAI,aAAa,QAAQ,CAAC;CACxC,MAAM,WAAW,IAAI,aAAa,QAAQ,CAAC;CAC3C,MAAM,YAAY,QAAQ,MAAM,WAAW,OAAO,OAAO,IAAI,IACzD,IAAI,aAAa,QAAQ,CAAC,IAC1B;CACJ,MAAM,CAAC,MAAM,QAAQ,qBACnB,SACA,eAAe,YAAY,GAC3B,OACA,SACA,SACA,QACA,OACA,UACA,SACF;CACA,MAAM,WAAW,IAAI,wBAAwB;CAC7C,SAAS,OAAO;CAChB,YAAY,QAAQ;CACpB,MAAM,QAAQ,MAAc,GAA8B,GAAW,OAAO,UAAgB;EAC1F,SAAS,aAAa,MAAM,IAAI,yBAAyB,GAAG,GAAG,IAAI,CAAC;CACtE;CACA,KAAK,WAAW,OAAO,CAAC;CACxB,KAAK,kBAAkB,SAAS,CAAC;CACjC,KAAK,mBAAmB,SAAS,CAAC;CAClC,KAAK,YAAY,QAAQ,GAAG,IAAI;CAChC,KAAK,WAAW,OAAO,CAAC;CACxB,KAAK,WAAW,UAAU,CAAC;CAC3B,IAAI,WAAW,KAAK,gBAAgB,WAAW,CAAC;CAChD,SAAS,gBAAgB;CACzB,UAAU,UAAU,SAAS,OAAO,SAAS,QAAQ,eAAe,MAAM,IAAI;CAC9E,OAAO;AACT"}
1
+ {"version":3,"file":"decorations.js","names":[],"sources":["../../src/text/decorations.ts"],"sourcesContent":["import { InstancedBufferAttribute, InstancedBufferGeometry } from 'three/webgpu'\nimport { attribute, float, mix } from 'three/tsl'\n\nimport type { DomLayoutSnapshot, TextDecorationLayout } from '../types.js'\nimport { GlyphTextMaterial, type GlyphTextMaterialOptions } from './GlyphTextMaterial.js'\nimport { byte, setBounds, setUnitQuad } from './geometryUtils.js'\n\nexport const GLYPH_RECTS_KEY = 'ultraGlyphRects'\nexport function glyphRectTable(geometry: InstancedBufferGeometry): ArrayLike<number> {\n return (\n (geometry.userData[GLYPH_RECTS_KEY] as Float32Array | undefined) ??\n geometry.getAttribute('sdfRect').array\n )\n}\n\n/** Decoration quads share their source glyph's motion center, index, and clip. */\nexport class TextDecorationMaterial extends GlyphTextMaterial {\n constructor(options: GlyphTextMaterialOptions) {\n super(\n options,\n (quad, rect, position, _depth, scale) => {\n const decoration = attribute<'vec4'>('decorationRect', 'vec4')\n if (options.motion === false) return mix(decoration.xy, decoration.zw, quad)\n const delta = mix(decoration.xy.sub(rect.xy), decoration.zw.sub(rect.zw), quad)\n return position.add(delta.mul(scale))\n },\n attribute<'float'>('decorationIndex', 'float'),\n )\n this.name = 'ultra-text solid text decorations'\n this.applyCoverage(float(1), float(1), float(0.5))\n }\n}\n\nfunction sameDecoration(a: TextDecorationLayout, b: TextDecorationLayout): boolean {\n return (\n a.line === b.line &&\n a.offset === b.offset &&\n a.thickness === b.thickness &&\n a.color.every((v, i) => v === b.color[i])\n )\n}\n\ntype DecorationRecord = readonly [\n s0: number,\n s1: number,\n s2: number,\n s3: number,\n rectIndex: number,\n motionIndex: number,\n color: readonly [number, number, number, number],\n clip: readonly [number, number, number, number],\n sequence: number,\n z: number,\n motionOrigin: readonly [number, number, number] | null,\n]\n\nlet cachedSnapshot: DomLayoutSnapshot | null = null\nlet cachedDrawable: ((key: string) => boolean) | null = null\nlet cachedRecords: readonly DecorationRecord[] = []\n\nfunction decorationRecords(\n snapshot: DomLayoutSnapshot,\n drawable: (key: string) => boolean,\n): readonly DecorationRecord[] {\n if (snapshot === cachedSnapshot && drawable === cachedDrawable) return cachedRecords\n const glyphs = snapshot.glyphs\n const records: DecorationRecord[] = []\n if (glyphs.some((glyph) => glyph.decorations?.length)) {\n let glyphIndex = 0\n let motionIndex = -1\n let previousGroup: number | undefined\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n if (!drawable(glyph.glyphKey)) continue\n if (glyph.shapeGroup === undefined || glyph.shapeGroup !== previousGroup) motionIndex++\n previousGroup = glyph.shapeGroup\n const decorations = glyph.decorations\n if (decorations) {\n for (const decoration of decorations) {\n if (decoration.thickness <= 0 || decoration.color[3] <= 0) continue\n const next = glyphs[index + 1]\n let right = glyph.originX + (glyph.decorationWidth ?? Math.abs(glyph.advance))\n if (\n next?.block === glyph.block &&\n next.lineBottom === glyph.lineBottom &&\n next.decorations?.some((candidate) => sameDecoration(decoration, candidate))\n ) {\n right = Math.max(right, next.originX)\n }\n const y = glyph.lineBottom + decoration.offset\n records.push([\n glyph.originX,\n y - decoration.thickness / 2,\n right,\n y + decoration.thickness / 2,\n glyphIndex,\n glyph.motionOrigin?.[2] ?? motionIndex,\n decoration.color,\n glyph.clip,\n glyph.sequence,\n glyph.z,\n glyph.motionOrigin ?? null,\n ])\n }\n }\n glyphIndex++\n }\n }\n cachedSnapshot = snapshot\n cachedDrawable = drawable\n return (cachedRecords = records)\n}\n\nconst DECORATION_ATTRS = [\n 'sdfRect',\n 'decorationRect',\n 'decorationIndex',\n 'sdfColor',\n 'sdfClip',\n 'sdfMeta',\n] as const\n\nfunction decorationAttributesMatch(\n geometry: InstancedBufferGeometry,\n records: readonly DecorationRecord[],\n): boolean {\n const count = geometry.instanceCount\n if (!count || records.length !== count) return false\n if (\n DECORATION_ATTRS.some(\n (name) => (geometry.getAttribute(name) as { count: number } | undefined)?.count !== count,\n )\n )\n return false\n const run = geometry.getAttribute('sdfRunMotion') as { count: number } | undefined\n return records.some((r) => r[10]) ? run?.count === count : !run\n}\n\nfunction writeDecorationBatch(\n records: readonly DecorationRecord[],\n sourceRects: ArrayLike<number>,\n rects: Float32Array,\n strokes: Float32Array,\n indices: Float32Array,\n colors: Uint8Array,\n clips: Float32Array,\n metadata: Float32Array,\n runMotion: Float32Array | null,\n): [number, number] {\n let minZ = 0\n let maxZ = 0\n for (let index = 0; index < records.length; index++) {\n const rec = records[index]!\n const offset = index * 4\n const srcOffset = rec[4] * 4\n rects[offset] = sourceRects[srcOffset] ?? 0\n rects[offset + 1] = sourceRects[srcOffset + 1] ?? 0\n rects[offset + 2] = sourceRects[srcOffset + 2] ?? 0\n rects[offset + 3] = sourceRects[srcOffset + 3] ?? 0\n const color = rec[6]\n colors[offset] = byte(color[0])\n colors[offset + 1] = byte(color[1])\n colors[offset + 2] = byte(color[2])\n colors[offset + 3] = byte(color[3])\n strokes[offset] = rec[0]\n strokes[offset + 1] = rec[1]\n strokes[offset + 2] = rec[2]\n strokes[offset + 3] = rec[3]\n const clip = rec[7]\n clips[offset] = clip[0]\n clips[offset + 1] = clip[1]\n clips[offset + 2] = clip[2]\n clips[offset + 3] = clip[3]\n indices[index] = rec[5]\n metadata[index * 2] = rec[8]\n const z = rec[9]\n metadata[index * 2 + 1] = z\n const motionOrigin = rec[10]\n if (runMotion && motionOrigin) {\n const mOffset = index * 3\n runMotion[mOffset] = motionOrigin[0]\n runMotion[mOffset + 1] = motionOrigin[1]\n runMotion[mOffset + 2] = motionOrigin[2]\n }\n if (z < minZ) minZ = z\n if (z > maxZ) maxZ = z\n }\n return [minZ, maxZ]\n}\n\n/**\n * True when an existing decoration batch can be rewritten without allocating.\n * A null geometry matches only an empty decoration list.\n */\nexport function canUpdateDecorationGeometry(\n geometry: InstancedBufferGeometry | null,\n snapshot: DomLayoutSnapshot,\n drawable: (key: string) => boolean,\n): boolean {\n const records = decorationRecords(snapshot, drawable)\n return geometry ? decorationAttributesMatch(geometry, records) : !records.length\n}\n\n/** Rewrites a same-count decoration batch from the current glyph rects. */\nexport function updateDecorationGeometry(\n geometry: InstancedBufferGeometry,\n snapshot: DomLayoutSnapshot,\n textGeometry: InstancedBufferGeometry,\n drawable: (key: string) => boolean,\n motionPadding: number,\n): boolean {\n const records = decorationRecords(snapshot, drawable)\n if (!decorationAttributesMatch(geometry, records)) return false\n const run = geometry.getAttribute('sdfRunMotion') as InstancedBufferAttribute | undefined\n const arr = <T extends Float32Array | Uint8Array>(n: string): T =>\n geometry.getAttribute(n).array as T\n const [minZ, maxZ] = writeDecorationBatch(\n records,\n glyphRectTable(textGeometry),\n arr('sdfRect'),\n arr('decorationRect'),\n arr('decorationIndex'),\n arr('sdfColor'),\n arr('sdfClip'),\n arr('sdfMeta'),\n run ? (run.array as Float32Array) : null,\n )\n for (const name of DECORATION_ATTRS) {\n geometry.getAttribute(name).needsUpdate = true\n }\n if (run) run.needsUpdate = true\n setBounds(geometry, snapshot.width, snapshot.height, motionPadding, minZ, maxZ)\n return true\n}\n\nexport function createDecorationGeometry(\n snapshot: DomLayoutSnapshot,\n textGeometry: InstancedBufferGeometry,\n drawable: (key: string) => boolean,\n motionPadding: number,\n): InstancedBufferGeometry | null {\n const records = decorationRecords(snapshot, drawable)\n const count = records.length\n if (!count) return null\n const rects = new Float32Array(count * 4)\n const strokes = new Float32Array(count * 4)\n const indices = new Float32Array(count)\n const colors = new Uint8Array(count * 4)\n const clips = new Float32Array(count * 4)\n const metadata = new Float32Array(count * 2)\n const runMotion = records.some((record) => record[10] !== null)\n ? new Float32Array(count * 3)\n : null\n const [minZ, maxZ] = writeDecorationBatch(\n records,\n glyphRectTable(textGeometry),\n rects,\n strokes,\n indices,\n colors,\n clips,\n metadata,\n runMotion,\n )\n const geometry = new InstancedBufferGeometry()\n geometry.name = 'ultra-text instanced solid text decorations'\n setUnitQuad(geometry)\n const attr = (name: string, a: Float32Array | Uint8Array, n: number, norm = false): void => {\n geometry.setAttribute(name, new InstancedBufferAttribute(a, n, norm))\n }\n attr('sdfRect', rects, 4)\n attr('decorationRect', strokes, 4)\n attr('decorationIndex', indices, 1)\n attr('sdfColor', colors, 4, true)\n attr('sdfClip', clips, 4)\n attr('sdfMeta', metadata, 2)\n if (runMotion) attr('sdfRunMotion', runMotion, 3)\n geometry.instanceCount = count\n setBounds(geometry, snapshot.width, snapshot.height, motionPadding, minZ, maxZ)\n return geometry\n}\n"],"mappings":";;;;;AAOA,IAAa,kBAAkB;AAC/B,SAAgB,eAAe,UAAsD;CACnF,OACG,SAA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