@needle-tools/three-mesh-effects 0.3.7 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +14 -1
- package/build/box-impostor-runtime.js +321 -195
- package/build/box-impostor-runtime.js.map +4 -4
- package/build/impostor-runtime.js +944 -202
- package/build/impostor-runtime.js.map +4 -4
- package/build/index.js +7 -7
- package/build/index.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-display.js +319 -193
- package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
- package/build/internal/box-impostor/box-impostor-faces.js +8 -6
- package/build/internal/box-impostor/box-impostor-faces.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-material.js +319 -193
- package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
- package/build/internal/box-impostor/box-impostor-projection.js +8 -5
- package/build/internal/box-impostor/box-impostor-projection.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-runtime.js +321 -195
- package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
- package/build/internal/impostor/adaptive-impostor-renderer.js +434 -0
- package/build/internal/impostor/adaptive-impostor-renderer.js.map +7 -0
- package/build/internal/impostor/impostor-node-material.js +944 -202
- package/build/internal/impostor/impostor-node-material.js.map +4 -4
- package/build/internal/impostor/impostor-performance.js +136 -0
- package/build/internal/impostor/impostor-performance.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js +6 -1
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +2 -2
- package/build/internal/rendering/instance-space.js +110 -0
- package/build/internal/rendering/instance-space.js.map +7 -0
- package/build/internal/rendering/renderer-support.js +6 -1
- package/build/internal/rendering/renderer-support.js.map +2 -2
- package/build/pixel-impostor-runtime.js +6 -1
- package/build/pixel-impostor-runtime.js.map +2 -2
- package/build/types/box-impostor/box-impostor-faces.d.ts +3 -1
- package/build/types/box-impostor/box-impostor-projection.d.ts +3 -1
- package/build/types/impostor/adaptive-impostor-renderer.d.ts +74 -0
- package/build/types/impostor/adaptive-impostor-renderer.js +1 -0
- package/build/types/impostor/impostor-node-material.d.ts +5 -1
- package/build/types/impostor/impostor-performance.d.ts +90 -0
- package/build/types/impostor/impostor-performance.js +1 -0
- package/build/types/public/impostor-runtime.d.ts +2 -0
- package/build/types/public/index.d.ts +3 -0
- package/build/types/rendering/instance-space.d.ts +26 -0
- package/build/types/rendering/instance-space.js +1 -0
- package/build/types/rendering/renderer-support.d.ts +13 -0
- package/package.json +2 -2
- package/src/box-impostor/box-impostor-faces.js +7 -5
- package/src/box-impostor/box-impostor-material.js +34 -19
- package/src/box-impostor/box-impostor-projection.js +7 -4
- package/src/impostor/adaptive-impostor-renderer.js +423 -0
- package/src/impostor/impostor-node-material.js +347 -157
- package/src/impostor/impostor-performance.js +152 -0
- package/src/public/impostor-runtime.js +2 -0
- package/src/public/index.js +12 -9
- package/src/rendering/instance-space.js +121 -0
- package/src/rendering/renderer-support.js +9 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/rendering/renderer-support.js", "../src/rendering/classic-webgl-support.js", "../src/rendering/captured-surface-material.js", "../src/rendering/captured-surface-depth.js", "../src/impostor/impostor-node-material.js", "../src/impostor/impostor-metadata.js", "../src/rendering/texture-slot.js", "../src/impostor/octahedral.js", "../src/impostor/impostor-runtime-support.js"],
|
|
4
|
-
"sourcesContent": ["// @ts-check\nimport {REVISION} from 'three';\nimport * as TSL from 'three/tsl';\nimport {classicWebGLSupportsNodeMaterials} from './classic-webgl-support.js';\n\n/**\n * @typedef {object} ImpostorRenderer\n * @property {boolean=} isWebGPURenderer\n * @property {boolean=} isWebGLRenderer\n * @property {(object & {supportsNodeMaterials?: boolean})=} capabilities\n * @property {((handler: import('three/addons/tsl/WebGLNodesHandler.js').WebGLNodesHandler) => void)=} setNodesHandler\n */\n\n/**\n * Reports whether a renderer can compile TSL impostor materials.\n * WebGPURenderer supports node materials directly. Classic WebGLRenderer\n * integrations must advertise that they installed a compatible nodes handler.\n *\n * @param {ImpostorRenderer | undefined} renderer\n */\nexport function rendererSupportsImpostorNodeMaterials(renderer) {\n\tif (typeof Reflect.get(TSL, 'struct') !== 'function') return false;\n\treturn renderer?.isWebGPURenderer === true\n\t\t|| renderer?.capabilities?.supportsNodeMaterials === true;\n}\n\n/** @type {WeakMap<ImpostorRenderer, Promise<void>>} */\nconst pending = new WeakMap();\n\n/** Enable Three's existing TSL handler only when an enabled asset needs it.\n * Hosts with their own compiler advertise supportsNodeMaterials to retain it.\n * @param {ImpostorRenderer | undefined} renderer */\nexport async function enableRendererNodeMaterials(renderer) {\n\tif (rendererSupportsImpostorNodeMaterials(renderer) ||\n\t\t!renderer?.isWebGLRenderer || !renderer.setNodesHandler ||\n\t\ttypeof Reflect.get(TSL, 'struct') !== 'function') return;\n\tlet setup = pending.get(renderer);\n\tif (!setup) {\n\t\tsetup = import('three/addons/tsl/WebGLNodesHandler.js').then(({WebGLNodesHandler}) => {\n\t\t\tif (rendererSupportsImpostorNodeMaterials(renderer)) return;\n\t\t\tif (!classicWebGLSupportsNodeMaterials(REVISION)) {\n\t\t\t\tconsole.warn(`Mesh Effects: WebGLRenderer from three r${REVISION} stops drawing node materials after about a dozen are in use. Use three r187 or later, or WebGPURenderer.`);\n\t\t\t}\n\t\t\trenderer.setNodesHandler?.(new WebGLNodesHandler());\n\t\t\trenderer.capabilities ??= {};\n\t\t\trenderer.capabilities.supportsNodeMaterials = true;\n\t\t}).catch(error => {\n\t\t\tpending.delete(renderer);\n\t\t\tthrow error;\n\t\t});\n\t\tpending.set(renderer, setup);\n\t}\n\tawait setup;\n}\n\n", "// @ts-check\n\n/**\n * Reports whether WebGLRenderer from a three revision can keep many node\n * materials alive. Before r187 every uniform block holds one of a few binding\n * points until its material is disposed, so node materials stop drawing after\n * about a dozen. The Needle fork backports the fix from 0.186.2-alpha.2.\n *\n * @param {string} revision three's `REVISION`, such as `'187'` or `'186.2-alpha.2'`\n */\nexport function classicWebGLSupportsNodeMaterials(revision) {\n\tconst fork = /^186\\.2-alpha\\.(\\d+)$/.exec(revision);\n\tif (fork) return Number(fork[1]) >= 2;\n\treturn Number.parseInt(revision, 10) >= 187;\n}\n", "// @ts-check\nimport { MeshStandardNodeMaterial } from 'three/webgpu';\nimport { context, modelViewMatrix, modelWorldMatrix, vec4 } from 'three/tsl';\n\n/** Light reconstructed surfaces at their hit position, not the carrier face.\n * View directions stay on the same ray; local lights also need the hit distance.\n */\nexport class CapturedSurfaceMaterial extends MeshStandardNodeMaterial {\n /** @type {import('three/webgpu').Node<'vec3'> | null} */\n capturedPositionNode = null;\n\n /**\n * @override\n * @param {import('three/webgpu').NodeBuilder} builder\n */\n setupLighting(builder) {\n const lighting = super.setupLighting(builder);\n if (!this.capturedPositionNode) return lighting;\n const world = modelWorldMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;\n const view = modelViewMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;\n return context(lighting, {\n positionView: view,\n positionWorld: world,\n shadowPositionWorld: world,\n });\n }\n}\n", "// @ts-check\nimport {\n Fn,\n cameraFar,\n cameraNear,\n cameraProjectionMatrix,\n modelViewMatrix,\n vec4,\n viewZToLogarithmicDepth,\n viewZToOrthographicDepth,\n viewZToPerspectiveDepth,\n viewZToReversedOrthographicDepth,\n viewZToReversedPerspectiveDepth,\n} from 'three/tsl';\n\n/** Match the renderer's depth convention after reconstructing a local hit.\n * @param {import('three/webgpu').Node<'vec3'>} position\n * @param {number} [shadowBias]\n */\nexport function capturedSurfaceDepth(position, shadowBias = 0) {\n return Fn(\n (\n /** @type {unknown} */ _,\n /** @type {import('three/webgpu').NodeBuilder} */ builder,\n ) => {\n // Resolve the shared hit before either projection branch consumes it.\n const z = modelViewMatrix\n .mul(vec4(position, 1))\n .z.toVar('capturedSurfaceViewZ');\n const reversed = builder.renderer.reversedDepthBuffer === true;\n // One material can alternate between a perspective view and orthographic\n // shadow cameras without a new pipeline; select using the active projection.\n const perspective = cameraProjectionMatrix\n .mul(vec4(0, 0, 0, 1))\n .w.equal(0);\n const perspectiveDepth =\n builder.renderer.logarithmicDepthBuffer === true\n ? viewZToLogarithmicDepth(z, cameraNear, cameraFar)\n : (reversed\n ? viewZToReversedPerspectiveDepth\n : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);\n const result = perspective.select(\n perspectiveDepth,\n (reversed\n ? viewZToReversedOrthographicDepth\n : viewZToOrthographicDepth)(z, cameraNear, cameraFar),\n );\n return shadowBias &&\n 'isShadowPassMaterial' in builder.material &&\n builder.material.isShadowPassMaterial\n ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1)\n : result;\n },\n )();\n}\n", "// TSL's current declarations erase custom struct member types to `Node`, which\n// makes a checked JS implementation impossible without casting every operator.\n// Keep this backend module runtime-tested until Three's StructNode types retain\n// their declared member layout.\n// @ts-nocheck\n\nimport { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';\nexport { rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';\n\nimport { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';\nimport { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';\nimport {\n ClampToEdgeWrapping,\n DoubleSide,\n GLSL3,\n LinearFilter,\n LinearMipmapLinearFilter,\n MeshStandardNodeMaterial,\n NoColorSpace,\n SRGBColorSpace,\n ShaderMaterial,\n Vector3,\n Vector4,\n} from 'three/webgpu';\nimport * as TSL from 'three/tsl';\nimport {\n Fn,\n If,\n Loop,\n Break,\n abs,\n any,\n bool,\n cameraPosition,\n cameraWorldMatrix,\n cross,\n dot,\n exp,\n float,\n floor,\n fract,\n fwidth,\n int,\n ivec2,\n max,\n min,\n mix,\n modelWorldMatrix,\n modelWorldMatrixInverse,\n positionGeometry,\n smoothstep,\n texture,\n textureLoad,\n textureSize,\n transformNormalToView,\n uniformArray,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl';\nimport { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';\nimport { bindTextureSlot } from '../rendering/texture-slot.js';\nimport { PERSPECTIVE_RAY_PLANE_SIGN } from './octahedral.js';\nimport {\n REPROJECTION_CONFIDENCE_INNER_TEXELS,\n REPROJECTION_CONFIDENCE_OUTER_TEXELS,\n createImpostorViewBoundsTexture,\n impostorContourUnionSharpness,\n parseImpostorDescriptor,\n} from './impostor-runtime-support.js';\n\nconst NAMED_STRUCT_FACTORY = Reflect.get(TSL, 'struct');\n\n/** @import { ImpostorDescriptor } from './impostor-metadata.js' */\n\n/** @typedef {import('../rendering/renderer-support.js').ImpostorRenderer} ImpostorRenderer */\n/**\n * @typedef {object} ImpostorRuntimeFeatures\n * @property {boolean} interpolation\n * @property {boolean} reprojection\n * @property {boolean} depthWeights\n * @property {boolean} perspectiveCorrection\n * @property {boolean} cellCorrection\n * @property {boolean} boundedReprojection\n * @property {number} raySamples\n * @property {number} depthSamples\n * @property {number} blendZone\n */\n\n/**\n * @typedef {object} ResolvedImpostorRuntimeFeatures\n * @property {ImpostorRuntimeFeatures} requested\n * @property {Pick<ImpostorRuntimeFeatures, 'interpolation' | 'reprojection' | 'depthWeights' | 'perspectiveCorrection' | 'cellCorrection' | 'boundedReprojection'>} effective\n * @property {Pick<ImpostorRuntimeFeatures, 'interpolation' | 'reprojection' | 'depthWeights' | 'perspectiveCorrection' | 'cellCorrection' | 'boundedReprojection' | 'raySamples' | 'depthSamples'> & {frameSamples: number, blendZone: number}} profile\n */\n\nconst RUNTIME_FEATURE_NAMES = /** @type {const} */ ([\n 'interpolation',\n 'reprojection',\n 'depthWeights',\n 'perspectiveCorrection',\n 'cellCorrection',\n 'boundedReprojection',\n]);\n\nexport const DEFAULT_IMPOSTOR_RUNTIME_FEATURES = Object.freeze({\n interpolation: true,\n reprojection: true,\n depthWeights: true,\n perspectiveCorrection: true,\n cellCorrection: false,\n boundedReprojection: true,\n});\n\nexport const IMPOSTOR_RUNTIME_SAMPLE_LIMITS = Object.freeze({\n raySamples: 32,\n depthSamples: 8,\n});\n\nconst IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS = 0.002;\nconst HEMISPHERE_HORIZON_TRANSITION_SINE = Math.sin(Math.PI / 180);\n\n\n/**\n * @param {ImpostorDescriptor} descriptor\n * @param {Partial<ImpostorRuntimeFeatures>=} input\n * @returns {ResolvedImpostorRuntimeFeatures}\n */\nexport function resolveImpostorRuntimeFeatures(descriptor, input = {}) {\n const requested = {\n ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,\n raySamples: descriptor.parallaxSteps * 4,\n depthSamples: descriptor.parallaxSteps,\n blendZone: descriptor.blendZone,\n ...input,\n };\n for (const name of RUNTIME_FEATURE_NAMES) requested[name] = requested[name] !== false;\n requested.raySamples = clampRuntimeSamples(\n requested.raySamples,\n IMPOSTOR_RUNTIME_SAMPLE_LIMITS.raySamples,\n );\n requested.depthSamples = clampRuntimeSamples(\n requested.depthSamples,\n IMPOSTOR_RUNTIME_SAMPLE_LIMITS.depthSamples,\n );\n requested.blendZone = Math.min(1, Math.max(0.35, Number(requested.blendZone) || descriptor.blendZone));\n const interpolation = requested.interpolation;\n const reprojection = interpolation && requested.reprojection && requested.raySamples > 0;\n const depthWeights = interpolation && requested.depthWeights && descriptor.depthDerivedWeights;\n const perspectiveCorrection = requested.perspectiveCorrection;\n const cellCorrection = interpolation && perspectiveCorrection && requested.cellCorrection;\n const boundedReprojection = reprojection && requested.boundedReprojection;\n return {\n requested,\n effective: {\n interpolation,\n reprojection,\n depthWeights,\n perspectiveCorrection,\n cellCorrection,\n boundedReprojection,\n },\n profile: {\n interpolation,\n reprojection,\n depthWeights,\n perspectiveCorrection,\n cellCorrection,\n boundedReprojection,\n frameSamples: interpolation ? 3 : 1,\n raySamples: reprojection ? requested.raySamples : 0,\n depthSamples: reprojection ? requested.depthSamples : 0,\n blendZone: requested.blendZone,\n },\n };\n}\n\nfunction clampRuntimeSamples(value, maximum) {\n const numeric = Number(value);\n if (!Number.isFinite(numeric)) return 0;\n return Math.min(maximum, Math.max(0, Math.round(numeric)));\n}\n\n/**\n * Installs a backend-neutral TSL material. WebGPURenderer compiles this graph\n * to WGSL on WebGPU and GLSL on its WebGL2 compatibility backend.\n *\n * @param {import('three').Object3D} root\n * @param {Map<import('three').Object3D, {descriptor: unknown, maps: {\n * baseColor: import('three').Texture,\n * normalDepth: import('three').Texture,\n * material?: import('three').Texture | null,\n * emissive?: import('three').Texture | null,\n * geometry?: import('three').Texture | null,\n * }}>} bindings\n * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures\n * @param {ImpostorRenderer=} renderer\n */\nexport function upgradeImpostorScene(root, bindings = new Map(), inputFeatures = {}, renderer) {\n let upgraded = 0;\n root.traverse((object) => {\n const binding = bindings.get(object);\n const metadata = binding?.descriptor\n ?? object.userData?.gltfExtensions?.[NEEDLE_MESH_IMPOSTOR];\n if (metadata === undefined) return;\n if (!('isMesh' in object) || object.isMesh !== true) {\n throw new Error('Impostor metadata must belong to a mesh.');\n }\n const descriptor = parseImpostorDescriptor(metadata);\n if (!descriptor) {\n throw new Error('Unsupported NEEDLE_mesh_impostor descriptor.');\n }\n if (!binding) {\n throw new Error('NEEDLE_mesh_impostor textures require the registered GLTFLoader plugin.');\n }\n const fallback = Array.isArray(object.material) ? object.material[0] : object.material;\n if (!fallback) return;\n const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';\n if (!binding.maps.baseColor || !binding.maps.normalDepth) {\n throw new Error('Impostor GLB is missing a required base-color or normal-depth atlas.');\n }\n const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';\n if (compressedGeometry && !binding.maps.geometry) {\n throw new Error('Compressed impostor GLB is missing its geometry atlas.');\n }\n // Extension texture semantics are authoritative. Do not depend on a\n // fallback PBR slot having happened to request the same glTF texture first:\n // loader order and host integrations may otherwise leave a base-color atlas\n // in linear space, which turns bright authored colors nearly white. Packed\n // normals, depth, ORM, and coverage are data and must never be decoded.\n binding.maps.baseColor.colorSpace = SRGBColorSpace;\n binding.maps.normalDepth.colorSpace = NoColorSpace;\n if (binding.maps.material) binding.maps.material.colorSpace = NoColorSpace;\n if (binding.maps.geometry) binding.maps.geometry.colorSpace = NoColorSpace;\n if (binding.maps.emissive) binding.maps.emissive.colorSpace = SRGBColorSpace;\n for (const atlas of [\n binding.maps.baseColor,\n binding.maps.normalDepth,\n binding.maps.material,\n binding.maps.geometry,\n binding.maps.emissive,\n ]) {\n if (!atlas) continue;\n // glTF declares CLAMP_TO_EDGE for every impostor atlas. Reassert it on\n // the runtime textures as well: these are packed view grids, never\n // repeatable images, and one repeated edge texel can become a visible\n // line around the billboard.\n atlas.wrapS = ClampToEdgeWrapping;\n atlas.wrapT = ClampToEdgeWrapping;\n atlas.minFilter = LinearMipmapLinearFilter;\n atlas.magFilter = LinearFilter;\n atlas.generateMipmaps = !atlas.isCompressedTexture;\n atlas.needsUpdate = true;\n }\n if (compressedGeometry && binding.maps.geometry) {\n binding.maps.geometry.minFilter = LinearFilter;\n binding.maps.geometry.generateMipmaps = false;\n binding.maps.geometry.needsUpdate = true;\n }\n const viewBoundsTexture = createImpostorViewBoundsTexture(descriptor);\n const maps = {\n baseColor: binding.maps.baseColor,\n normalDepth: binding.maps.normalDepth,\n orm: compactLayout ? binding.maps.normalDepth : binding.maps.material,\n emissive: compactLayout\n ? descriptor.compression?.emissive ? binding.maps.baseColor : null\n : binding.maps.emissive,\n geometry: compressedGeometry ? binding.maps.geometry : null,\n viewBounds: viewBoundsTexture,\n };\n const nodeMaterials = rendererSupportsImpostorNodeMaterials(renderer);\n const runtime = {\n backend: nodeMaterials ? 'three-tsl' : 'three-webgl-compat',\n descriptor,\n viewBoundsTexture,\n atlases: {\n baseColor: binding.maps.baseColor,\n normalDepth: binding.maps.normalDepth,\n orm: compactLayout ? binding.maps.normalDepth : binding.maps.material,\n emissive: compactLayout\n ? descriptor.compression?.emissive ? binding.maps.baseColor : null\n : binding.maps.emissive,\n geometry: compressedGeometry ? binding.maps.geometry : null,\n },\n };\n const requestedFeatures = {\n ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,\n raySamples: descriptor.parallaxSteps * 4,\n depthSamples: descriptor.parallaxSteps,\n blendZone: descriptor.blendZone,\n ...inputFeatures,\n };\n const debugControls = Object.fromEntries(RUNTIME_FEATURE_NAMES.map((name) => [\n name,\n { value: requestedFeatures[name] ? 1 : 0 },\n ]));\n debugControls.raySamples = { value: descriptor.parallaxSteps * 4 };\n debugControls.depthSamples = { value: descriptor.parallaxSteps };\n debugControls.blendZone = { value: descriptor.blendZone };\n debugControls.setFeatures = (features) => {\n const next = resolveImpostorRuntimeFeatures(descriptor, features);\n if (JSON.stringify(next.requested) === JSON.stringify(requestedFeatures)) return false;\n Object.assign(requestedFeatures, next.requested);\n for (const name of RUNTIME_FEATURE_NAMES) {\n debugControls[name].value = requestedFeatures[name] ? 1 : 0;\n }\n debugControls.raySamples.value = requestedFeatures.raySamples;\n debugControls.depthSamples.value = requestedFeatures.depthSamples;\n debugControls.blendZone.value = requestedFeatures.blendZone;\n const previous = object.material;\n const replacement = createPbrImpostorNodeMaterial(\n descriptor,\n maps,\n requestedFeatures,\n renderer,\n );\n replacement.userData.impostor = runtime;\n replacement.userData.impostorDebug = debugControls;\n debugControls.profile = replacement.userData.impostorShaderProfile;\n object.material = replacement;\n if (previous !== fallback) previous.dispose();\n return true;\n };\n const material = createPbrImpostorNodeMaterial(descriptor, maps, requestedFeatures, renderer);\n material.userData.impostor = runtime;\n material.userData.impostorDebug = debugControls;\n debugControls.profile = material.userData.impostorShaderProfile;\n object.material = material;\n object.castShadow = descriptor.castShadow;\n object.receiveShadow = descriptor.receiveShadow;\n object.frustumCulled = false;\n fallback.dispose();\n upgraded++;\n });\n return upgraded;\n}\n\n/**\n * Three.js GLTFLoader plugin that upgrades Needle impostor nodes after their\n * atlas textures have loaded. Register KTX2Loader on GLTFLoader as usual when\n * loading compressed impostors; uncompressed GLBs need no extra texture setup.\n */\nexport class NeedleImpostorLoaderPlugin {\n /**\n * @param {unknown} parser GLTFLoader parser supplied by `loader.register()`.\n * @param {{\n * onUpgrade?: (count: number, result: import('three/addons/loaders/GLTFLoader.js').GLTF) => void,\n * features?: Partial<ImpostorRuntimeFeatures>,\n * renderer?: ImpostorRenderer,\n * }=} options\n */\n constructor(parser, options = {}) {\n this.name = NEEDLE_MESH_IMPOSTOR;\n this.parser = parser;\n this.options = options;\n }\n\n /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */\n async afterRoot(result) {\n await enableRendererNodeMaterials(this.options.renderer);\n const parser = /** @type {{\n * json: {meshes?: Array<{primitives: Array<{extensions?: Record<string, unknown>}>}>},\n * associations: Map<import('three').Object3D, {meshes?: number, primitives?: number}>,\n * getDependency(type: 'texture', index: number): Promise<import('three').Texture>,\n * }} */ (this.parser);\n const bindings = new Map();\n const roots = result.scenes?.length ? result.scenes : [result.scene];\n const visited = new Set();\n let upgraded = 0;\n for (const root of roots) {\n if (!root || visited.has(root)) continue;\n visited.add(root);\n const pending = [];\n root.traverse((object) => {\n if (!('isMesh' in object) || object.isMesh !== true) return;\n const association = parser.associations.get(object);\n if (association?.meshes === undefined || association.primitives === undefined) return;\n const raw = parser.json.meshes?.[association.meshes]\n ?.primitives[association.primitives]?.extensions?.[NEEDLE_MESH_IMPOSTOR];\n if (!raw || typeof raw !== 'object') return;\n const definition = /** @type {Record<string, unknown>} */ (raw);\n const descriptor = parseImpostorDescriptor(definition);\n if (!descriptor) {\n throw new Error('Unsupported NEEDLE_mesh_impostor descriptor.');\n }\n const rawTextures = definition.textures;\n if (!rawTextures || typeof rawTextures !== 'object') {\n throw new Error('NEEDLE_mesh_impostor has no texture bindings.');\n }\n pending.push((async () => {\n const maps = /** @type {Record<string, import('three').Texture>} */ ({});\n for (const role of ['baseColor', 'normalDepth', 'material', 'emissive', 'geometry']) {\n const info = Reflect.get(rawTextures, role);\n const index = info && typeof info === 'object' ? Reflect.get(info, 'index') : undefined;\n if (!Number.isInteger(index)) continue;\n maps[role] = await parser.getDependency('texture', index);\n }\n if (!maps.baseColor || !maps.normalDepth) {\n throw new Error('NEEDLE_mesh_impostor is missing a required atlas binding.');\n }\n bindings.set(object, {\n descriptor,\n maps: /** @type {any} */ (maps),\n });\n })());\n });\n await Promise.all(pending);\n upgraded += upgradeImpostorScene(\n root,\n bindings,\n this.options.features,\n this.options.renderer,\n );\n }\n this.options.onUpgrade?.(upgraded, result);\n }\n}\n\n/**\n * Registers the Needle impostor material plugin on a Three.js GLTFLoader.\n *\n * @template {import('three/addons/loaders/GLTFLoader.js').GLTFLoader} T\n * @param {T} loader\n * @param {ConstructorParameters<typeof NeedleImpostorLoaderPlugin>[1]=} options\n * @returns {T}\n */\nexport function registerNeedleImpostorLoader(loader, options = {}) {\n loader.register((parser) => new NeedleImpostorLoaderPlugin(parser, options));\n return loader;\n}\n\n/**\n * Compact GLSL runtime for Three versions before named TSL structs. It uses\n * the closest authored capture and reconstructs fragment depth without asking\n * the older node compiler to expand the modern structured graph.\n *\n * @param {ImpostorDescriptor} descriptor\n * @param {Parameters<typeof createPbrImpostorNodeMaterial>[1]} maps\n */\nfunction createCompatibleImpostorNodeMaterial(descriptor, maps) {\n const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';\n const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';\n const compactEmissive = descriptor.compression?.emissive === true;\n const boundsCount = descriptor.frames * descriptor.frames;\n const material = new ShaderMaterial({\n name: 'Needle PBR impostor WebGL compatibility',\n side: DoubleSide,\n transparent: false,\n depthTest: true,\n depthWrite: true,\n glslVersion: GLSL3,\n uniforms: {\n baseColorAtlas: { value: maps.baseColor },\n geometryAtlas: { value: maps.geometry ?? maps.normalDepth },\n viewBounds: {\n value: Array.from({ length: boundsCount }, (_, index) => new Vector4(\n descriptor.viewBounds[index * 4],\n descriptor.viewBounds[index * 4 + 1],\n descriptor.viewBounds[index * 4 + 2],\n descriptor.viewBounds[index * 4 + 3],\n )),\n },\n frames: { value: descriptor.frames },\n frameResolution: { value: descriptor.frameResolution },\n padding: { value: descriptor.padding },\n radius: { value: descriptor.radius },\n captureDirection: { value: new Vector3(...(descriptor.captureDirection ?? [0, 1, 0])) },\n },\n defines: {\n VIEW_BOUNDS_COUNT: boundsCount,\n FULL_SPHERE: descriptor.mapping === 'full' ? 1 : 0,\n SINGLE_VIEW: descriptor.mapping === 'single' ? 1 : 0,\n COMPACT_COLOR: compactLayout ? 1 : 0,\n COMPACT_EMISSIVE: compactEmissive ? 1 : 0,\n COMPRESSED_GEOMETRY: compressedGeometry ? 1 : 0,\n },\n vertexShader: /* glsl */ `\n out vec3 vPlaneLocal;\n void main() {\n mat4 inverseModel = inverse(modelMatrix);\n mat4 cameraWorld = inverse(viewMatrix);\n vec3 rightLocal = normalize((inverseModel * vec4(cameraWorld[0].xyz, 0.0)).xyz);\n vec3 upLocal = normalize((inverseModel * vec4(cameraWorld[1].xyz, 0.0)).xyz);\n vPlaneLocal = rightLocal * position.x + upLocal * position.y;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(vPlaneLocal, 1.0);\n }\n `,\n fragmentShader: /* glsl */ `\n uniform sampler2D baseColorAtlas;\n uniform sampler2D geometryAtlas;\n uniform vec4 viewBounds[VIEW_BOUNDS_COUNT];\n uniform float frames;\n uniform float frameResolution;\n uniform float padding;\n uniform float radius;\n uniform vec3 captureDirection;\n uniform mat4 modelMatrix;\n uniform mat4 modelViewMatrix;\n uniform mat4 projectionMatrix;\n in vec3 vPlaneLocal;\n out vec4 fragColor;\n\n float nonZeroSign(float value) { return value < 0.0 ? -1.0 : 1.0; }\n vec2 directionToGrid(vec3 direction) {\n direction = normalize(direction);\n #if !FULL_SPHERE\n direction.y = max(direction.y, 0.000001);\n #endif\n direction /= abs(direction.x) + abs(direction.y) + abs(direction.z);\n #if FULL_SPHERE\n vec2 folded = vec2(\n nonZeroSign(direction.x) * (1.0 - abs(direction.z)),\n nonZeroSign(direction.z) * (1.0 - abs(direction.x))\n );\n return (direction.y < 0.0 ? folded : direction.xz) * 0.5 + 0.5;\n #else\n return vec2(direction.x + direction.z, direction.z - direction.x) * 0.5 + 0.5;\n #endif\n }\n vec3 gridToDirection(vec2 coordinate) {\n #if FULL_SPHERE\n float x = coordinate.x * 2.0 - 1.0;\n float z = coordinate.y * 2.0 - 1.0;\n float y = 1.0 - abs(x) - abs(z);\n if (y < 0.0) {\n float foldedX = nonZeroSign(x) * (1.0 - abs(z));\n float foldedZ = nonZeroSign(z) * (1.0 - abs(x));\n x = foldedX;\n z = foldedZ;\n }\n return normalize(vec3(x, y, z));\n #else\n return normalize(vec3(\n coordinate.x - coordinate.y,\n 1.0 - abs(coordinate.x - coordinate.y) - abs(-1.0 + coordinate.x + coordinate.y),\n -1.0 + coordinate.x + coordinate.y\n ));\n #endif\n }\n vec2 atlasUv(vec2 frame, vec2 frameUv) {\n float interiorPixels = max(frameResolution - padding * 2.0, 1.0);\n float interiorScale = interiorPixels / frameResolution;\n float gutterUv = padding / interiorPixels;\n vec2 insideCell = padding / frameResolution\n + clamp(frameUv, vec2(-gutterUv), vec2(1.0 + gutterUv)) * interiorScale;\n float halfTexel = 0.5001 / frameResolution;\n return (frame + clamp(insideCell, vec2(halfTexel), vec2(1.0 - halfTexel))) / frames;\n }\n vec4 sampleColorAtlas(vec2 coordinates) {\n vec2 size = vec2(textureSize(baseColorAtlas, 0));\n vec2 grid = vec2(frames);\n #if COMPACT_COLOR && COMPACT_EMISSIVE\n grid.x *= 2.0;\n #endif\n vec2 pixels = coordinates * size;\n float footprint = max(length(dFdx(pixels)), length(dFdy(pixels)));\n float gutter = padding * size.y / (frames * frameResolution);\n float lod = clamp(log2(max(footprint, 1.0)), 0.0, floor(log2(max(gutter, 1.0))));\n vec2 cell = floor(clamp(coordinates * grid, vec2(0.0), grid - 0.00001));\n vec2 guard = vec2(0.5001 * exp2(lod)) / size;\n vec2 safe = clamp(coordinates, cell / grid + guard, (cell + 1.0) / grid - guard);\n return textureLod(baseColorAtlas, safe, lod);\n }\n void main() {\n vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;\n vec3 cameraDirection = normalize(cameraLocal);\n #if SINGLE_VIEW\n vec2 frame = vec2(0.0);\n vec3 frameDirection = normalize(captureDirection);\n #else\n vec2 frame = clamp(\n floor(directionToGrid(cameraDirection) * (frames - 1.0) + 0.5),\n vec2(0.0),\n vec2(frames - 1.0)\n );\n vec3 frameDirection = gridToDirection(frame / (frames - 1.0));\n #endif\n vec3 referenceUp = abs(frameDirection.y) > 0.999 ? vec3(0.0, 0.0, -1.0) : vec3(0.0, 1.0, 0.0);\n vec3 right = normalize(cross(referenceUp, frameDirection));\n vec3 up = normalize(cross(frameDirection, right));\n int frameIndex = int(frame.y * frames + frame.x);\n vec4 bounds = viewBounds[frameIndex];\n float denominator = dot(cameraDirection, frameDirection);\n float safeDenominator = nonZeroSign(denominator) * max(abs(denominator), 0.05);\n vec3 framePlanePosition = vPlaneLocal - cameraDirection\n * (dot(vPlaneLocal, frameDirection) / safeDenominator);\n vec2 frameUv = (vec2(dot(framePlanePosition, right), dot(framePlanePosition, up))\n - bounds.xy) / (bounds.zw - bounds.xy);\n float interiorPixels = max(frameResolution - padding * 2.0, 1.0);\n float gutterUv = padding / interiorPixels;\n if (any(lessThan(frameUv, vec2(-gutterUv)))\n || any(greaterThan(frameUv, vec2(1.0 + gutterUv)))) discard;\n vec2 atlas = atlasUv(frame, frameUv);\n vec2 colorUv = atlas;\n #if COMPACT_COLOR\n colorUv.x *= COMPACT_EMISSIVE == 1 ? 0.5 : 1.0;\n #endif\n vec4 base = sampleColorAtlas(colorUv);\n vec4 geometry = texture(geometryAtlas, atlas);\n float contour = base.a;\n float depthValue;\n #if COMPRESSED_GEOMETRY\n vec2 packed = floor(geometry.rg * 255.0 + 0.5);\n depthValue = (packed.x * 4.0 + floor(packed.y / 85.0 + 0.5)) / 1023.0;\n contour = geometry.a;\n #else\n vec2 packed = floor(geometry.ba * 255.0 + 0.5);\n depthValue = (packed.x * 256.0 + packed.y) / 65535.0;\n #endif\n float width = max(fwidth(contour), 1.0 / 255.0);\n float coverage = smoothstep(0.5 - width, 0.5 + width, contour);\n if (coverage < 0.25) discard;\n vec2 plane = mix(bounds.xy, bounds.zw, frameUv);\n vec3 reconstructedLocal = right * plane.x + up * plane.y\n + frameDirection * (radius - depthValue * radius * 2.0);\n vec4 clip = projectionMatrix * modelViewMatrix * vec4(reconstructedLocal, 1.0);\n gl_FragDepth = clip.z / clip.w * 0.5 + 0.5;\n fragColor = vec4(base.rgb, coverage);\n #if defined(TONE_MAPPING)\n fragColor.rgb = toneMapping(fragColor.rgb);\n #endif\n fragColor = linearToOutputTexel(fragColor);\n }\n `,\n });\n material.alphaToCoverage = true;\n material.toneMapped = true;\n material.userData.impostorShaderProfile = {\n interpolation: false,\n reprojection: false,\n depthWeights: false,\n perspectiveCorrection: false,\n cellCorrection: false,\n boundedReprojection: false,\n frameSamples: 1,\n raySamples: 0,\n depthSamples: 0,\n blendZone: descriptor.blendZone,\n };\n return material;\n}\n\n/**\n * @param {ImpostorDescriptor} descriptor\n * @param {{\n * baseColor: import('three').Texture,\n * normalDepth: import('three').Texture,\n * orm?: import('three').Texture | null,\n * emissive: import('three').Texture | null,\n * geometry?: import('three').Texture | null,\n * viewBounds: import('three').DataTexture,\n * }} maps\n * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures\n * @param {ImpostorRenderer=} renderer\n * @returns {MeshStandardNodeMaterial | ShaderMaterial}\n */\nexport function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, renderer) {\n if (!rendererSupportsImpostorNodeMaterials(renderer)) {\n return createCompatibleImpostorNodeMaterial(descriptor, maps);\n }\n const { effective: features, profile } = resolveImpostorRuntimeFeatures(descriptor, inputFeatures);\n const frames = float(descriptor.frames);\n const frameResolution = float(descriptor.frameResolution);\n const padding = float(descriptor.padding);\n const radius = float(descriptor.radius);\n const captureAlphaCutoff = float(descriptor.captureAlphaCutoff);\n // Source MASK/OPAQUE alpha has already been resolved during capture. At\n // multisampled silhouette edges, one covered sample is valid geometry even\n // though its resolved alpha is below the authored 0.5 contour. Reprojection\n // must retain that depth candidate; the SDF and final alpha-to-coverage pass\n // still decide whether the pixel contributes to the visible silhouette.\n // A literal, not a node expression: Three r186 caches a shared expression in\n // the first branch that reads it, so other branches compared against 0.\n const reprojectionSurfaceCutoff = descriptor.coverageEncoding === 'sdf-base-alpha'\n ? float(0.5)\n : float(Math.min(Number(descriptor.captureAlphaCutoff), 0.25));\n const blendCutoff = float((1 - profile.blendZone) * 0.5);\n const coarseSearchSteps = profile.raySamples;\n const fullSphere = descriptor.mapping === 'full';\n const singleView = descriptor.mapping === 'single';\n const singleCaptureDirection = vec3(...(descriptor.captureDirection ?? [0, 1, 0])).normalize();\n const baseColorAtlas = texture(maps.baseColor);\n const normalDepthAtlas = texture(maps.normalDepth);\n const geometryAtlas = texture(maps.geometry ?? maps.normalDepth);\n const ormAtlas = maps.orm ? texture(maps.orm) : null;\n const emissiveAtlas = maps.emissive ? texture(maps.emissive) : null;\n const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';\n const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';\n const compactEmissive = descriptor.compression?.emissive === true;\n const colorAtlasUv = (uvNode, emissive = false) => compactLayout\n ? vec2(\n uvNode.x.mul(compactEmissive ? 0.5 : 1).add(emissive && compactEmissive ? 0.5 : 0),\n uvNode.y,\n )\n : uvNode;\n const mapLod = (atlas, coordinates) => {\n const size = vec2(textureSize(atlas));\n const pixels = coordinates.mul(size);\n const footprint = max(pixels.dFdx().length(), pixels.dFdy().length());\n const gutter = padding.mul(size.y).div(frames.mul(frameResolution));\n return max(footprint, 1).log2().clamp(0, max(gutter, 1).log2().floor());\n };\n const sampleAtlas = (atlas, coordinates, lod = float(0), columns = frames) => {\n const size = vec2(textureSize(atlas));\n const grid = vec2(columns, frames);\n const cell = coordinates.mul(grid).clamp(0, grid.sub(0.00001)).floor();\n const guard = float(0.5001).mul(float(2).pow(lod)).div(size);\n const safe = coordinates.clamp(cell.div(grid).add(guard), cell.add(1).div(grid).sub(guard));\n return texture(atlas, safe).level(lod);\n };\n const colorColumns = frames.mul(compactLayout && compactEmissive ? 2 : 1);\n const sampleCapturedAlpha = (uvNode) => compressedGeometry\n ? sampleAtlas(baseColorAtlas, colorAtlasUv(uvNode), float(0), colorColumns).a\n : sampleAtlas(baseColorAtlas, uvNode).a;\n const sampleContour = (uvNode) => compressedGeometry\n ? texture(geometryAtlas, uvNode).level(0).a\n : descriptor.coverageEncoding === 'sdf-base-alpha'\n ? sampleAtlas(baseColorAtlas, uvNode).a\n : sampleAtlas(ormAtlas, uvNode).a;\n const viewBounds = uniformArray(\n Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new Vector4(\n descriptor.viewBounds[index * 4],\n descriptor.viewBounds[index * 4 + 1],\n descriptor.viewBounds[index * 4 + 2],\n descriptor.viewBounds[index * 4 + 3],\n )),\n 'vec4',\n );\n const atlasResolution = float(descriptor.frames * descriptor.frameResolution);\n\n const FrameBasis = NAMED_STRUCT_FACTORY(\n { right: 'vec3', up: 'vec3' },\n 'ImpostorFrameBasis',\n );\n const FrameSample = NAMED_STRUCT_FACTORY({\n base: 'vec4',\n surfaceAlpha: 'float',\n normalLocal: 'vec3',\n positionLocal: 'vec3',\n orm: 'vec3',\n emissive: 'vec3',\n contour: 'float',\n validity: 'float',\n strictValidity: 'float',\n rayError: 'float',\n footprint: 'float',\n }, 'ImpostorFrameSample');\n const BlendedSample = NAMED_STRUCT_FACTORY({\n base: 'vec4',\n normalLocal: 'vec3',\n positionLocal: 'vec3',\n orm: 'vec3',\n emissive: 'vec3',\n capturedCoverage: 'float',\n distanceCoverage: 'float',\n cropSupport: 'float',\n coverageWidth: 'float',\n transition: 'float',\n }, 'ImpostorBlendedSample');\n const basisMember = (value, name) => value.get(name);\n const frameMember = (value, name) => value.get(name);\n const blendedMember = (value, name) => value.get(name);\n\n const nonZeroSign = Fn(([value]) => value.lessThan(0).select(float(-1), float(1)), 'float');\n const buildFrameBasis = ([direction]) => {\n const referenceUp = abs(direction.y).greaterThan(0.999)\n .select(vec3(0, 0, -1), vec3(0, 1, 0));\n const right = referenceUp.cross(direction).normalize();\n return FrameBasis(right, direction.cross(right).normalize());\n };\n const frameBasis = Fn(buildFrameBasis);\n const gridToDirection = Fn(([coordinate]) => {\n const hemisphere = vec3(\n coordinate.x.sub(coordinate.y),\n float(1).sub(abs(coordinate.x.sub(coordinate.y))).sub(abs(float(-1).add(coordinate.x).add(coordinate.y))),\n float(-1).add(coordinate.x).add(coordinate.y),\n ).normalize();\n const fullX = coordinate.x.mul(2).sub(1).toVar();\n const fullZ = coordinate.y.mul(2).sub(1).toVar();\n const fullY = float(1).sub(abs(fullX)).sub(abs(fullZ)).toVar();\n const foldedX = nonZeroSign(fullX).mul(float(1).sub(abs(fullZ)));\n const foldedZ = nonZeroSign(fullZ).mul(float(1).sub(abs(fullX)));\n const full = fullY.lessThan(0)\n .select(vec3(foldedX, fullY, foldedZ), vec3(fullX, fullY, fullZ))\n .normalize();\n return fullSphere ? full : hemisphere;\n }, 'vec3');\n const directionToGrid = Fn(([inputDirection]) => {\n const direction = inputDirection.normalize().toVar();\n if (!fullSphere) {\n direction.y.assign(max(direction.y, 0.000001));\n }\n direction.divAssign(abs(direction.x).add(abs(direction.y)).add(abs(direction.z)));\n const hemisphere = vec2(direction.x.add(direction.z), direction.z.sub(direction.x));\n const folded = vec2(\n nonZeroSign(direction.x).mul(float(1).sub(abs(direction.z))),\n nonZeroSign(direction.z).mul(float(1).sub(abs(direction.x))),\n );\n const full = direction.y.lessThan(0).select(folded, direction.xz);\n return (fullSphere ? full : hemisphere).mul(0.5).add(0.5).clamp(0, 1);\n }, 'vec2');\n const atlasUv = Fn(([frame, frameUv]) => {\n const interiorPixels = max(frameResolution.sub(padding.mul(2)), 1);\n const interiorScale = interiorPixels.div(frameResolution);\n const gutterUv = padding.div(interiorPixels);\n const insideCell = padding.div(frameResolution).add(\n frameUv.clamp(gutterUv.negate(), float(1).add(gutterUv)).mul(interiorScale),\n );\n // Clamp to texel centers, not the mathematical cell edge. Clamp-to-edge\n // only protects the outside of the complete texture; it cannot protect\n // internal atlas cells. Sampling exactly on an internal boundary linearly\n // mixes two unrelated captured views and exposes the neighboring cell as\n // a faint rectangular card outline.\n const halfTexel = float(0.5001).div(frameResolution);\n return frame.add(insideCell.clamp(halfTexel, float(1).sub(halfTexel))).div(frames);\n }, 'vec2');\n const decodeDepth16 = Fn(([packed]) => {\n if (descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba') {\n const bytes = floor(packed.rg.mul(255).add(0.5));\n return bytes.x.mul(4).add(floor(bytes.y.div(85).add(0.5))).div(1023);\n }\n const bytes = floor(packed.ba.mul(255).add(0.5));\n return bytes.x.mul(256).add(bytes.y).div(65535);\n }, 'float');\n const loadDepth16 = Fn(([texel]) => decodeDepth16(textureLoad(\n geometryAtlas,\n ivec2(texel).clamp(ivec2(0), ivec2(atlasResolution.sub(1))),\n )), 'float');\n // Packed 16-bit depth cannot use hardware linear filtering: interpolating\n // the high/low bytes independently produces carry artifacts. Decode four\n // integer texels first and then bilinearly filter their scalar depths. The\n // previous nearest-depth lookup made a sub-pixel UV crossing alter the\n // reprojection root abruptly, which showed up as half-degree silhouette\n // flicker even though view weights were continuous.\n const sampleDepth16 = Fn(([uvNode]) => {\n const pixel = uvNode.mul(atlasResolution).sub(0.5);\n const base = floor(pixel);\n const fraction = fract(pixel);\n const lower = mix(\n loadDepth16(base),\n loadDepth16(base.add(vec2(1, 0))),\n fraction.x,\n );\n const upper = mix(\n loadDepth16(base.add(vec2(0, 1))),\n loadDepth16(base.add(1)),\n fraction.x,\n );\n return mix(lower, upper, fraction.y);\n }, 'float');\n const decodeOctahedral = Fn(([encoded]) => {\n const f = encoded.mul(2).sub(1).toVar();\n const value = vec3(f, float(1).sub(abs(f.x)).sub(abs(f.y))).toVar();\n const folded = vec2(\n float(1).sub(abs(value.y)).mul(nonZeroSign(value.x)),\n float(1).sub(abs(value.x)).mul(nonZeroSign(value.y)),\n );\n If(value.z.lessThan(0), () => {\n value.xy.assign(folded);\n });\n return value.normalize();\n }, 'vec3');\n const reconstructPosition = Fn(([frameUv, bounds, frameDirection, right, up, depthValue]) => {\n const plane = mix(bounds.xy, bounds.zw, frameUv);\n return right.mul(plane.x)\n .add(up.mul(plane.y))\n .add(frameDirection.mul(radius.sub(depthValue.mul(radius).mul(2))));\n }, 'vec3');\n const cameraLocal = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;\n // Match the physical card basis produced by Three's billboard helper. A\n // direction-derived world-up frame is equivalent away from the poles, but\n // becomes undefined at zenith/nadir and falls back to a fixed orientation.\n // The camera still has a valid screen-space roll there, so using its actual\n // right/up axes keeps sampling coordinates rotating with the source view.\n const cameraRightLocal = modelWorldMatrixInverse\n .mul(vec4(cameraWorldMatrix[0].xyz, 0)).xyz.normalize();\n const cameraUpLocal = modelWorldMatrixInverse\n .mul(vec4(cameraWorldMatrix[1].xyz, 0)).xyz.normalize();\n const cameraOutLocal = modelWorldMatrixInverse\n .mul(vec4(cameraWorldMatrix[2].xyz, 0)).xyz.normalize();\n const projectionCameraDirection = Fn(([], builder) => (\n builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal\n ), 'vec3')();\n // An upper-hemisphere atlas has no authored camera below the horizon. Keep\n // its sampling camera and sampling plane on that horizon. The display card\n // remains camera-facing: below the authored range it therefore shows the\n // last representable horizon view at a stable size instead of stretching\n // reprojection rays into a solid rectangle. It only fades at exact nadir.\n const horizontalCamera = vec3(\n projectionCameraDirection.x,\n 0,\n projectionCameraDirection.z,\n );\n const horizontalUp = vec3(cameraUpLocal.x, 0, cameraUpLocal.z);\n const horizonFromPosition = horizontalCamera.div(max(horizontalCamera.length(), 0.000001));\n const horizonFromCameraUp = horizontalUp.div(max(horizontalUp.length(), 0.000001));\n const horizonDirection = horizontalCamera.length().greaterThan(0.0001)\n .select(horizonFromPosition, horizonFromCameraUp);\n const cameraDirection = projectionCameraDirection;\n // There is no well-defined horizon azimuth at exact nadir. Preserve the\n // clamped horizon reconstruction through almost the entire lower hemisphere,\n // then remove the card within the final ~1.8 degrees instead of exposing an\n // arbitrary pole orientation as an opaque rectangle.\n const mappingVisibility = (fullSphere || singleView)\n ? float(1)\n : smoothstep(-1, -0.9995, cameraDirection.y);\n // Ease into the authored hemisphere over its first degree. Although the\n // directions on either side of zero are mathematically close, switching the\n // billboard basis exactly at zero moves rasterized edges by a pixel and\n // exposes a visible horizon seam.\n const horizonTransition = smoothstep(\n 0,\n HEMISPHERE_HORIZON_TRANSITION_SINE,\n max(cameraDirection.y, 0),\n );\n const clampedCameraDirection = (fullSphere || singleView)\n ? cameraDirection\n : mix(horizonDirection, cameraDirection, horizonTransition).normalize();\n const horizonBillboardUp = cross(horizonDirection, cameraRightLocal).normalize();\n const billboardUpLocal = (fullSphere || singleView)\n ? cameraUpLocal\n : mix(horizonBillboardUp, cameraUpLocal, horizonTransition).normalize();\n const samplingCamera = clampedCameraDirection.mul(cameraLocal.length());\n const samplingBillboardPosition = cameraRightLocal.mul(positionGeometry.x)\n .add(billboardUpLocal.mul(positionGeometry.y));\n const displayBillboardPosition = cameraRightLocal.mul(positionGeometry.x)\n .add(cameraUpLocal.mul(positionGeometry.y));\n const planeLocal = samplingBillboardPosition.toVarying('vImpostorPlaneLocal');\n const createFrameSampler = (withReprojection) => {\n const buildFrameSample = ([frame, planePosition, rayDirection, bounds]) => {\n const frameDirection = singleView\n ? singleCaptureDirection\n : gridToDirection(frame.div(frames.sub(1)));\n const basis = frameBasis(frameDirection);\n const right = basisMember(basis, 'right');\n const up = basisMember(basis, 'up');\n // Every atlas frame is an orthographic capture whose image plane passes\n // through the object center. Start from the intersection of the current\n // perspective camera ray and that frame plane. Projecting `planePosition`\n // directly only works when the selected capture matches the current view;\n // with sparse view grids it starts neighboring frames on different source\n // features and no finite depth iteration can put them back in register.\n const rayPlaneDenominator = dot(rayDirection, frameDirection);\n const safeRayPlaneDenominator = nonZeroSign(rayPlaneDenominator)\n .mul(max(abs(rayPlaneDenominator), 0.05));\n const framePlanePosition = planePosition.sub(rayDirection.mul(\n dot(planePosition, frameDirection).div(safeRayPlaneDenominator),\n ));\n const projectedFrameUv = vec2(\n dot(framePlanePosition, right),\n dot(framePlanePosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const interiorResolution = max(frameResolution.sub(padding.mul(2)), 1);\n const gutterUv = padding.div(interiorResolution);\n const minimumFrameUv = gutterUv.negate();\n const maximumFrameUv = float(1).add(gutterUv);\n const frameUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();\n const reconstructed = planePosition.toVar();\n const rootSolved = bool(!withReprojection).toVar();\n const strictRootSolved = bool(!withReprojection).toVar();\n if (withReprojection) {\n // A capture is a height field D(u). Parameterize the physical runtime\n // ray by the same normalized capture depth `s`: at a surface root,\n // `s == D(u(s))`. March from the capture camera toward the back, bracket\n // the first sign change, then refine that scalar equation. This is\n // standard relief mapping applied to an orthographic depth capture. The\n // previous soft closest-point average could blend two unrelated roots\n // and then jump between them as the camera moved.\n const rootFound = bool(false).toVar();\n const rootLower = float(0).toVar();\n const rootUpper = float(1).toVar();\n // Empty billboard pixels must not traverse the whole capture volume.\n // The source AABB is conservative, with one texel for filtered edges.\n const safeRay = vec3(\n nonZeroSign(rayDirection.x),\n nonZeroSign(rayDirection.y),\n nonZeroSign(rayDirection.z),\n ).mul(max(abs(rayDirection), vec3(1e-7)));\n const boundsGuard = radius.mul(2).div(interiorResolution);\n const boxT0 = vec3(...descriptor.boundsMin).sub(boundsGuard)\n .sub(planePosition).div(safeRay);\n const boxT1 = vec3(...descriptor.boundsMax).add(boundsGuard)\n .sub(planePosition).div(safeRay);\n const boxLow = min(boxT0, boxT1), boxHigh = max(boxT0, boxT1);\n const boxStart = max(boxLow.x, max(boxLow.y, boxLow.z));\n const boxEnd = min(boxHigh.x, min(boxHigh.y, boxHigh.z));\n const intersectsBounds = boxStart.lessThanEqual(boxEnd);\n const captureDepthAt = (t) => radius.sub(\n dot(planePosition.add(rayDirection.mul(t)), frameDirection),\n ).div(radius.mul(2));\n const depth0 = captureDepthAt(boxStart), depth1 = captureDepthAt(boxEnd);\n // UV is affine in capture depth. Clipping to the capture crop spends\n // the existing march budget on possible surfaces instead of empty space.\n const uvDepthSlope = vec2(dot(rayDirection, right), dot(rayDirection, up))\n .mul(radius.mul(-2).div(safeRayPlaneDenominator))\n .div(bounds.zw.sub(bounds.xy));\n const safeSlope = vec2(\n nonZeroSign(uvDepthSlope.x), nonZeroSign(uvDepthSlope.y),\n ).mul(max(abs(uvDepthSlope), vec2(1e-7)));\n const uvStart = projectedFrameUv.sub(uvDepthSlope.mul(0.5));\n const t0 = vec2(minimumFrameUv).sub(uvStart).div(safeSlope);\n const t1 = vec2(maximumFrameUv).sub(uvStart).div(safeSlope);\n const lower = min(t0, t1), upper = max(t0, t1);\n const searchStart = max(min(depth0, depth1), max(0, max(lower.x, lower.y)));\n const searchEnd = min(max(depth0, depth1), min(1, min(upper.x, upper.y)));\n const searchRange = max(searchEnd.sub(searchStart), 1e-6);\n const coarseStep = searchRange.div(coarseSearchSteps);\n const validateRoot = () => {\n If(rootSolved, () => {\n const at = atlasUv(frame, frameUv);\n const surface = reconstructPosition(frameUv, bounds, frameDirection, right, up, sampleDepth16(at));\n const closest = planePosition.add(rayDirection.mul(dot(surface.sub(planePosition), rayDirection)));\n const footprint = max(bounds.z.sub(bounds.x), bounds.w.sub(bounds.y)).div(interiorResolution);\n const nearestPixel = floor(at.mul(atlasResolution));\n const nearestDepth = loadDepth16(nearestPixel);\n const depthJump = abs(sampleDepth16(at).sub(nearestDepth)).mul(radius).mul(2);\n const discontinuity = bool(false).toVar();\n If(depthJump.greaterThan(footprint.mul(4)), () => {\n const neighbor = (offset) => loadDepth16(nearestPixel.add(offset).clamp(\n frame.mul(frameResolution), frame.add(1).mul(frameResolution).sub(1),\n ));\n // A steep plane can change depth arbitrarily fast. Unlike a slope\n // cap, second differences reject interpolated depth steps without\n // rejecting a continuous plane merely because it is steep.\n const curvature = max(\n abs(neighbor(vec2(-1, 0)).add(neighbor(vec2(1, 0))).sub(nearestDepth.mul(2))),\n abs(neighbor(vec2(0, -1)).add(neighbor(vec2(0, 1))).sub(nearestDepth.mul(2))),\n ).mul(radius).mul(2);\n discontinuity.assign(curvature.greaterThan(footprint.mul(4)));\n });\n If(surface.sub(closest).length().greaterThan(footprint.mul(4))\n .or(discontinuity)\n .or(sampleCapturedAlpha(at).lessThan(reprojectionSurfaceCutoff)), () => {\n rootFound.assign(false);\n rootSolved.assign(false);\n strictRootSolved.assign(false);\n });\n });\n };\n const refineRoot = () => {\n If(rootFound, () => {\n Loop(profile.depthSamples, () => {\n const searchDepth = rootLower.add(rootUpper).mul(0.5);\n const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));\n const searchRayPosition = planePosition.add(rayDirection.mul(\n searchPlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n const searchUv = vec2(\n dot(searchRayPosition, right),\n dot(searchRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))\n .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));\n const midpointIsUpper = bool(false).toVar();\n If(searchOutOfBounds.not(), () => {\n const searchAtlasUv = atlasUv(frame, searchUv);\n const searchCoverage = sampleCapturedAlpha(searchAtlasUv);\n const searchSurfaceDepth = sampleDepth16(searchAtlasUv);\n midpointIsUpper.assign(\n searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)\n .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),\n );\n });\n If(midpointIsUpper, () => {\n rootUpper.assign(searchDepth);\n });\n If(midpointIsUpper.not(), () => {\n rootLower.assign(searchDepth);\n });\n });\n const residualAt = (depth) => {\n const planeDepth = radius.sub(depth.mul(radius).mul(2));\n const position = planePosition.add(rayDirection.mul(\n planeDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator),\n ));\n const address = vec2(dot(position, right), dot(position, up))\n .sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n return depth.sub(sampleDepth16(atlasUv(frame,address)));\n };\n // A midpoint leaves large physical errors on a steep height field.\n // Secant interpolation is exact for a plane and stays in the bracket.\n const lowResidual = residualAt(rootLower), highResidual = residualAt(rootUpper);\n const difference = lowResidual.sub(highResidual);\n const fraction = lowResidual.div(\n nonZeroSign(difference).mul(max(abs(difference), 1e-8)),\n ).clamp(0, 1);\n const rootDepth = mix(rootLower,rootUpper,fraction);\n\n const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));\n const rootRayPosition = planePosition.add(rayDirection.mul(\n rootPlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n frameUv.assign(vec2(\n dot(rootRayPosition, right),\n dot(rootRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(\n minimumFrameUv,\n maximumFrameUv,\n ));\n });\n };\n const traceInterval = (steps, start = searchStart, end = searchEnd) => {\n const coarseStep = max(end.sub(start), 1e-6).div(float(steps));\n Loop({ start: 0, end: steps, type: 'int' }, ({ i }) => {\n If(rootFound.or(intersectsBounds.not()).or(end.lessThan(start)), () => { Break(); });\n const searchDepth = start.add(float(i).add(1).mul(coarseStep));\n const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));\n const searchRayPosition = planePosition.add(rayDirection.mul(\n searchPlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n const searchUv = vec2(\n dot(searchRayPosition, right),\n dot(searchRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))\n .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));\n If(searchOutOfBounds.not(), () => {\n const searchAtlasUv = atlasUv(frame, searchUv);\n const searchCoverage = sampleCapturedAlpha(searchAtlasUv);\n const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);\n If(hasSurface, () => {\n const searchSurfaceDepth = sampleDepth16(searchAtlasUv);\n const depthDelta = searchDepth.sub(searchSurfaceDepth);\n If(\n rootFound.not()\n .and(hasSurface)\n .and(depthDelta.greaterThanEqual(0)),\n () => {\n rootLower.assign(max(searchDepth.sub(coarseStep), 0));\n rootUpper.assign(searchDepth);\n rootFound.assign(true);\n rootSolved.assign(true);\n strictRootSolved.assign(true);\n refineRoot();\n if (features.boundedReprojection) validateRoot();\n },\n );\n });\n });\n });\n };\n traceInterval(int(coarseSearchSteps));\n // A fixed-point solution can recover a grazing ray with no sign bracket.\n // Retain it only after convergence inside captured coverage; blend-time\n // seed suppression still prevents an unrelated background layer.\n If(rootFound.not().and(intersectsBounds), () => {\n // A rejected march root must not seed itself back into validity.\n const iterativeUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();\n const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();\n const iterationResidual = float(1).toVar();\n const iterationValid = bool(true).toVar();\n Loop(profile.depthSamples * 2, () => {\n If(iterationValid, () => {\n const iterativePlaneDepth = radius.sub(iterativeDepth.mul(radius).mul(2));\n const iterativeRayPosition = planePosition.add(rayDirection.mul(\n iterativePlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n const nextUv = vec2(\n dot(iterativeRayPosition, right),\n dot(iterativeRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const nextOutOfBounds = any(nextUv.lessThan(vec2(minimumFrameUv)))\n .or(any(nextUv.greaterThan(vec2(maximumFrameUv))));\n If(nextOutOfBounds, () => {\n iterationValid.assign(false);\n });\n If(nextOutOfBounds.not(), () => {\n const nextAtlasUv = atlasUv(frame, nextUv);\n const nextCoverage = sampleCapturedAlpha(nextAtlasUv);\n const nextDepth = sampleDepth16(nextAtlasUv);\n iterationResidual.assign(abs(nextDepth.sub(iterativeDepth)));\n iterativeUv.assign(nextUv);\n iterativeDepth.assign(nextDepth);\n If(nextCoverage.lessThan(reprojectionSurfaceCutoff), () => {\n iterationValid.assign(false);\n });\n });\n });\n });\n If(\n iterationValid.and(iterationResidual.lessThanEqual(coarseStep)),\n () => {\n frameUv.assign(iterativeUv);\n rootSolved.assign(true);\n if (features.boundedReprojection) validateRoot();\n },\n );\n });\n }\n const uvNode = atlasUv(frame, frameUv);\n reconstructed.assign(reconstructPosition(\n frameUv,\n bounds,\n frameDirection,\n right,\n up,\n sampleDepth16(uvNode),\n ));\n const shadingSample = sampleAtlas(normalDepthAtlas, uvNode, mapLod(normalDepthAtlas, uvNode));\n const geometrySample = compressedGeometry\n ? texture(geometryAtlas, uvNode).level(0)\n : null;\n const viewNormal = decodeOctahedral(shadingSample.rg);\n const normal = right.mul(viewNormal.x)\n .add(up.mul(viewNormal.y))\n .add(frameDirection.mul(viewNormal.z))\n .normalize();\n // Captures face-forward double-sided source normals. Neighboring views of\n // a thin card can therefore encode opposite local directions; averaging\n // those vectors collapses toward zero and creates dark foliage splotches.\n // Reorient every contributing normal into the runtime view hemisphere\n // before interpolation. Exact capture views are unchanged.\n const faceForwardNormal = dot(normal, rayDirection).lessThan(0)\n .select(normal.negate(), normal);\n const closestRayPoint = planePosition.add(\n rayDirection.mul(dot(reconstructed.sub(planePosition), rayDirection)),\n );\n const footprint = max(\n bounds.z.sub(bounds.x),\n bounds.w.sub(bounds.y),\n ).div(interiorResolution);\n const rayError = reconstructed.sub(closestRayPoint).length();\n const finalFrameEdgeDistance = min(\n min(frameUv.x.sub(minimumFrameUv), frameUv.y.sub(minimumFrameUv)),\n min(maximumFrameUv.sub(frameUv.x), maximumFrameUv.sub(frameUv.y)),\n );\n // Validate the address that actually supplies the reconstructed surface.\n // Using the pre-reprojection center-plane address here erased precisely the\n // deep features that the ray solve had recovered near a tight crop edge.\n const boundsConfidence = smoothstep(\n 0,\n float(1).div(interiorResolution),\n finalFrameEdgeDistance,\n );\n // Reprojection confidence fades across a bounded texel interval instead\n // of switching at one residual. The outer bound still rejects a different\n // depth layer, while the continuous interval prevents thin features from\n // changing reconstruction paths after a sub-degree camera move.\n const alignedConfidence = float(1).sub(smoothstep(\n REPROJECTION_CONFIDENCE_INNER_TEXELS,\n REPROJECTION_CONFIDENCE_OUTER_TEXELS,\n rayError.div(max(footprint, 0.000001)),\n ));\n const validFloat = boundsConfidence.mul(\n withReprojection\n ? alignedConfidence.mul(rootSolved)\n : float(1),\n );\n const strictValidFloat = boundsConfidence.mul(\n withReprojection\n ? alignedConfidence.mul(strictRootSolved)\n : float(1),\n );\n const colorUv = colorAtlasUv(uvNode);\n const baseColor = sampleAtlas(baseColorAtlas, colorUv, mapLod(baseColorAtlas, colorUv), colorColumns);\n const capturedAlpha = sampleCapturedAlpha(uvNode);\n const orm = compactLayout\n ? vec4(geometrySample.b, shadingSample.b, shadingSample.a, 1)\n : ormAtlas\n ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode))\n : vec4(\n descriptor.material.occlusion,\n descriptor.material.roughness,\n descriptor.material.metalness,\n 1,\n );\n // The signed-distance contour must not shift with minification. Only the\n // material channels use mip LOD; coverage keeps its authored level-zero\n // values and performs screen-space antialiasing after view interpolation.\n const coverage = sampleContour(uvNode);\n const resolvedValidity = validFloat;\n return FrameSample(\n // Validity is a blend weight, not an attribute. Premultiplying both the\n // sampled color/alpha here and the frame weight below applied crop\n // confidence twice; low-confidence crop-edge samples consequently\n // rendered as black outlines instead of fading away.\n vec4(baseColor.rgb, coverage),\n capturedAlpha,\n faceForwardNormal,\n reconstructed,\n orm.rgb,\n emissiveAtlas\n ? sampleAtlas(emissiveAtlas, colorAtlasUv(uvNode, true), mapLod(emissiveAtlas, colorAtlasUv(uvNode, true)), colorColumns).rgb\n : vec3(0),\n coverage,\n resolvedValidity,\n strictValidFloat,\n rayError,\n footprint,\n );\n };\n // Share the expensive frame search across the three selected captures.\n // Resolve uniform-array bounds at the call site for both TSL backends.\n // Three reuses a layout function's generated code for every builder of a\n // backend, but this one reads the atlases from its closure: a second\n // builder, such as the shadow pass, would get code naming texture bindings\n // it never declared. One function per builder still shares it per shader.\n /** @type {WeakMap<object, ReturnType<typeof Fn>>} */\n const functions = new WeakMap();\n return (/** @type {object} */ builder) => {\n let sampleFrame = functions.get(builder);\n if (!sampleFrame) {\n sampleFrame = Fn(buildFrameSample).setLayout({\n name: withReprojection ? 'sampleReprojectedImpostorFrame' : 'samplePlanarImpostorFrame',\n type: 'ImpostorFrameSample',\n inputs: [\n { name: 'frame', type: 'vec2' },\n { name: 'planePosition', type: 'vec3' },\n { name: 'rayDirection', type: 'vec3' },\n { name: 'bounds', type: 'vec4' },\n ],\n });\n functions.set(builder, sampleFrame);\n }\n return (frame, planePosition, rayDirection) => sampleFrame(frame, planePosition, rayDirection,\n viewBounds.element(int(frame.y.mul(frames).add(frame.x))));\n };\n };\n const planarFrameSamplers = createFrameSampler(false);\n const reprojectedFrameSamplers = features.reprojection ? createFrameSampler(true) : null;\n const buildBlendedSample = ([], builder) => {\n const samplePlanarFrame = planarFrameSamplers(builder);\n const sampleReprojectedFrame = reprojectedFrameSamplers ? reprojectedFrameSamplers(builder) : null;\n // An upper-hemisphere atlas has no authored views below the horizon.\n // Project both frame selection and depth rays onto that horizon together;\n // clamping selection alone while retaining a below-ground ray makes the\n // reprojection solver pull samples out of their frames.\n const samplingCameraLocal = samplingCamera;\n const centerViewDirection = samplingCameraLocal.normalize();\n const usePerspectiveCorrection = features.perspectiveCorrection\n && builder.camera.isPerspectiveCamera;\n const rayDirection = usePerspectiveCorrection\n ? samplingCameraLocal.sub(planeLocal).normalize()\n : centerViewDirection;\n if (singleView) {\n const singleFrame = vec2(0, 0);\n const raw = features.reprojection\n ? sampleReprojectedFrame(singleFrame, planeLocal, rayDirection)\n : samplePlanarFrame(singleFrame, planeLocal, rayDirection);\n // A one-view impostor has no neighboring capture that can fill a ray\n // which leaves the authored crop or fails to intersect its depth field.\n // `sampleReprojectedFrame` applies the same optional capture-domain\n // constraint used by every frame count; this branch only reduces the\n // already-resolved sample to the common blended representation.\n const validity = frameMember(raw, 'validity');\n const capturedCoverage = frameMember(raw, 'surfaceAlpha').mul(validity);\n const distanceCoverage = min(\n frameMember(raw, 'contour'),\n capturedCoverage,\n );\n return BlendedSample(\n frameMember(raw, 'base'),\n frameMember(raw, 'normalLocal'),\n frameMember(raw, 'positionLocal'),\n frameMember(raw, 'orm'),\n frameMember(raw, 'emissive'),\n capturedCoverage,\n distanceCoverage,\n validity,\n float(0),\n float(0),\n );\n }\n const centerGrid = directionToGrid(centerViewDirection).mul(frames.sub(1));\n // Match every card point to a capture along its physical point-to-camera\n // ray. Adding the card offset instead mirrors this correction: a shallow\n // box makes that inversion visible immediately on its near/far corners.\n const perspectiveGrid = usePerspectiveCorrection\n ? directionToGrid(\n samplingCameraLocal.add(planeLocal.mul(PERSPECTIVE_RAY_PLANE_SIGN)).normalize(),\n ).mul(frames.sub(1))\n : centerGrid;\n const maximumBase = vec2(frames.sub(2));\n const centerBase = min(floor(centerGrid), maximumBase);\n // Keep one frame triangle for the whole card. Switching discrete atlas\n // cells per fragment creates visible vertical bands even with perfectly\n // valid source frames. Perspective correction instead adjusts the three\n // weights inside the center-selected triangle and clamps to its simplex.\n const weightGrid = features.cellCorrection\n ? perspectiveGrid\n : centerGrid;\n const base = centerBase;\n const centerFraction = centerGrid.sub(base);\n const fraction = weightGrid.sub(base);\n const horizontal = centerFraction.x.greaterThan(centerFraction.y);\n const ordinaryFrame1 = base.add(horizontal.select(vec2(1, 0), vec2(0, 1)));\n const ordinaryWeights = horizontal.select(\n vec3(float(1).sub(fraction.x), fraction.x.sub(fraction.y), fraction.y),\n vec3(float(1).sub(fraction.y), fraction.y.sub(fraction.x), fraction.x),\n );\n const foldCell = fullSphere\n ? bool(false)\n : base.x.add(base.y).equal(frames.sub(2));\n const baseDirection = gridToDirection(base.div(frames.sub(1)));\n const rightDirection = gridToDirection(base.add(vec2(1, 0)).div(frames.sub(1)));\n const upDirection = gridToDirection(base.add(vec2(0, 1)).div(frames.sub(1)));\n const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));\n const antiDiagonal = foldCell.or(\n dot(rightDirection, upDirection).greaterThan(dot(baseDirection, diagonalDirection)),\n );\n const antiLower = centerFraction.x.add(centerFraction.y).lessThanEqual(1);\n const antiFrame0 = antiLower.select(base, base.add(1));\n const antiFrame1 = antiLower.select(base.add(vec2(1, 0)), base.add(vec2(0, 1)));\n const antiFrame2 = antiLower.select(base.add(vec2(0, 1)), base.add(vec2(1, 0)));\n const antiWeights = antiLower.select(\n vec3(float(1).sub(fraction.x).sub(fraction.y), fraction.x, fraction.y),\n vec3(fraction.x.add(fraction.y).sub(1), float(1).sub(fraction.x), float(1).sub(fraction.y)),\n );\n const frame0 = antiDiagonal.select(antiFrame0, base);\n const frame1 = antiDiagonal.select(antiFrame1, ordinaryFrame1);\n const frame2 = antiDiagonal.select(antiFrame2, base.add(1));\n const weights = max(antiDiagonal.select(antiWeights, ordinaryWeights), vec3(0)).toVar();\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n // Compact angular support: on each triangle edge, `blendZone` is the\n // fraction over which both endpoint captures contribute. Unlike exponent\n // sharpening, this gives capture vertices a real single-view neighborhood\n // instead of letting tiny contributors affect virtually the whole cell.\n weights.assign(max(weights.sub(blendCutoff), vec3(0)));\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n const frame0Nearest = weights.x.greaterThanEqual(weights.y)\n .and(weights.x.greaterThanEqual(weights.z));\n // TSL expressions are lazy. Snapshot the winner before raw mode mutates\n // `weights` to [1, 0, 0], otherwise the expression is re-evaluated later\n // and silently falls back to frame0 instead of the reported nearest frame.\n const nearestFrame = frame0Nearest.select(\n frame0,\n weights.y.greaterThanEqual(weights.z).select(frame1, frame2),\n ).toVar('impostorNearestFrame');\n if (!features.interpolation) {\n const raw = samplePlanarFrame(nearestFrame, planeLocal, rayDirection);\n return BlendedSample(\n frameMember(raw, 'base'),\n frameMember(raw, 'normalLocal'),\n frameMember(raw, 'positionLocal'),\n frameMember(raw, 'orm'),\n frameMember(raw, 'emissive'),\n frameMember(raw, 'surfaceAlpha'),\n frameMember(raw, 'surfaceAlpha'),\n frameMember(raw, 'validity'),\n float(0),\n float(0),\n );\n }\n const a = features.reprojection\n ? sampleReprojectedFrame(frame0, planeLocal, rayDirection)\n : samplePlanarFrame(frame0, planeLocal, rayDirection);\n const b = features.reprojection\n ? sampleReprojectedFrame(frame1, planeLocal, rayDirection)\n : samplePlanarFrame(frame1, planeLocal, rayDirection);\n const c = features.reprojection\n ? sampleReprojectedFrame(frame2, planeLocal, rayDirection)\n : samplePlanarFrame(frame2, planeLocal, rayDirection);\n const angularWeights = weights.toVar('impostorAngularWeights');\n if (features.depthWeights) {\n // A reprojected frame sample only represents this camera ray while its\n // residual lies inside the source texel's physical footprint. A\n // half-texel Gaussian retains subpixel agreement while decisively\n // rejecting a neighboring frame whose reconstructed surface belongs\n // to another depth layer. Wider kernels visibly duplicate sparse-view\n // silhouettes even though their barycentric weights are correct.\n const residual = vec3(\n frameMember(a, 'rayError').div(frameMember(a, 'footprint')),\n frameMember(b, 'rayError').div(frameMember(b, 'footprint')),\n frameMember(c, 'rayError').div(frameMember(c, 'footprint')),\n ).div(0.5);\n // Never let residual weighting amplify an almost-zero barycentric\n // contributor into the sole visible frame. A small factor floor keeps\n // the view-space prior authoritative and removes isolated fold-cell\n // fragments without introducing a hard angular cutoff.\n weights.mulAssign(max(exp(residual.mul(residual).mul(-0.5)), vec3(0.05)));\n }\n // Residual weighting chooses among frames; it is not transparency. Keep\n // the attribute weights normalized so a uniform residual cannot darken\n // otherwise opaque material channels.\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n // Snapshot the depth-aware visibility distribution before alpha and crop\n // confidence mutate the attribute weights below.\n const visibilityWeights = weights.toVar('impostorVisibilityWeights');\n const resolvedSampleValidity = vec3(\n frameMember(a, 'validity'),\n frameMember(b, 'validity'),\n frameMember(c, 'validity'),\n );\n const strictSampleValidity = vec3(\n frameMember(a, 'strictValidity'),\n frameMember(b, 'strictValidity'),\n frameMember(c, 'strictValidity'),\n );\n // A converged seed is only a disocclusion fill. Fade every seed out over\n // the first 1% of bounded-root support so a background fixed point cannot\n // appear as a second layer behind valid geometry.\n const strictSupport = dot(angularWeights, strictSampleValidity);\n const seedValidity = max(resolvedSampleValidity.sub(strictSampleValidity), vec3(0));\n const seedWeight = float(1).sub(smoothstep(0, 0.01, strictSupport));\n const sampleValidity = strictSampleValidity.add(seedValidity.mul(seedWeight));\n const surfaceAlpha = vec3(\n frameMember(a, 'surfaceAlpha'),\n frameMember(b, 'surfaceAlpha'),\n frameMember(c, 'surfaceAlpha'),\n );\n const largestAngularWeight = max(\n angularWeights.x,\n max(angularWeights.y, angularWeights.z),\n );\n const transition = smoothstep(\n 0,\n 0.5,\n float(1).sub(largestAngularWeight),\n ).toVar('impostorCoverageTransition');\n weights.mulAssign(surfaceAlpha).mulAssign(sampleValidity);\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n const weighted3 = (field) => frameMember(a, field).mul(weights.x)\n .add(frameMember(b, field).mul(weights.y))\n .add(frameMember(c, field).mul(weights.z));\n const weighted4 = (field) => frameMember(a, field).mul(weights.x)\n .add(frameMember(b, field).mul(weights.y))\n .add(frameMember(c, field).mul(weights.z));\n // A weighted average of inside/outside SDFs makes whole features cross the\n // 0.5 contour together near a frame bisector. Normalized log-sum-exp acts\n // as a smooth union: it preserves thin features and equals the authored\n // SDF when one view has unit weight.\n // Keep the angular width of an unmatched contour contribution roughly\n // constant as view density changes. Sparse grids need a stronger union to\n // retain disoccluded thin parts; dense grids can use a near-linear blend,\n // preventing a tiny-weight frame from popping in a whole feature. This is\n // derived only from sampling density, never from asset classification.\n const contourSharpness = impostorContourUnionSharpness(descriptor.frames);\n // A contour from a newly entering capture must begin as an ordinary\n // weighted SDF contribution. Applying the full smooth-union temperature\n // at an infinitesimal angular weight makes an entire disoccluded feature\n // cross the alpha mask in one sub-degree step. Ramp to the preserving\n // union only near a balanced transition; exact capture neighborhoods stay\n // exact and the blend-zone boundary remains visually continuous.\n const effectiveContourSharpness = mix(\n float(0.01),\n float(contourSharpness),\n transition,\n );\n const coverageContributions = visibilityWeights.mul(sampleValidity)\n .toVar('impostorCoverageContributions');\n const coverageSupport = dot(coverageContributions, vec3(1))\n .toVar('impostorCoverageSupport');\n const coverageWeights = coverageContributions\n .div(max(coverageSupport, 0.0001))\n .toVar('impostorCoverageWeights');\n // Do not normalize occupancy. If only a low-weight capture claims a pixel,\n // that claim remains low confidence instead of becoming a second opaque\n // silhouette. Normalization is retained solely for blending attributes of\n // samples that have already passed this coverage test.\n const perspectiveCapturedCoverage = dot(\n coverageContributions,\n surfaceAlpha,\n );\n const coverageDistanceSamples = vec3(\n frameMember(a, 'contour'),\n frameMember(b, 'contour'),\n frameMember(c, 'contour'),\n );\n const unionDistanceCoverage = max(\n dot(coverageWeights, exp(coverageDistanceSamples.mul(effectiveContourSharpness))),\n 0.0001,\n ).log().div(effectiveContourSharpness);\n // The SDF provides a stable subpixel contour, but it may not expand beyond\n // actual captured occupancy. This cap removes disjoint depth layers that a\n // smooth union would otherwise preserve from multiple camera frames.\n const perspectiveDistanceCoverage = min(\n unionDistanceCoverage,\n perspectiveCapturedCoverage,\n );\n const coverageDistanceMean = dot(coverageWeights, coverageDistanceSamples);\n const coverageDistanceDeviation = dot(\n coverageWeights,\n abs(coverageDistanceSamples.sub(coverageDistanceMean)),\n );\n return BlendedSample(\n weighted4('base'),\n weighted3('normalLocal').normalize(),\n weighted3('positionLocal'),\n weighted3('orm'),\n weighted3('emissive'),\n perspectiveCapturedCoverage,\n perspectiveDistanceCoverage,\n coverageSupport,\n // View-domain antialiasing complements screen-space fwidth. It widens\n // only where the contributing captures disagree about occupancy, so a\n // moving contour crosses pixels over an angular interval rather than in\n // one frame while stable interiors remain sharp.\n coverageDistanceDeviation.mul(0.2).mul(transition),\n transition,\n );\n };\n const blendImpostor = Fn(buildBlendedSample);\n\n const sample = blendImpostor().toVar('impostorSample');\n const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(blendedMember(sample, 'positionLocal'), 1)).xyz;\n const material = new CapturedSurfaceMaterial({\n name: 'Needle PBR impostor TSL',\n side: DoubleSide,\n transparent: false,\n depthTest: true,\n depthWrite: true,\n });\n const distanceCoverage = blendedMember(sample, 'distanceCoverage');\n const coverageWidth = max(\n max(fwidth(distanceCoverage), blendedMember(sample, 'coverageWidth')),\n 1 / 255,\n );\n const screenDistanceCoverage = smoothstep(\n float(0.5).sub(coverageWidth),\n float(0.5).add(coverageWidth),\n distanceCoverage,\n );\n const screenCoverage = screenDistanceCoverage.mul(mappingVisibility);\n // Use a local-space billboard position instead of a clip-space vertex node.\n // Three's shadow override copies `positionNode`/`castShadowPositionNode`, but\n // not `vertexNode`; the latter therefore made the shadow pass rasterize an\n // unrotated card while writing reconstructed fragment depth. Keeping the\n // card position in local space makes color, depth, and shadow passes share\n // the same camera-facing geometry (the shadow camera during a shadow pass).\n material.positionNode = displayBillboardPosition;\n material.castShadowPositionNode = displayBillboardPosition;\n material.colorNode = vec4(blendedMember(sample, 'base').rgb, screenCoverage);\n material.normalNode = transformNormalToView(blendedMember(sample, 'normalLocal'));\n material.aoNode = blendedMember(sample, 'orm').r;\n material.roughnessNode = blendedMember(sample, 'orm').g;\n material.metalnessNode = blendedMember(sample, 'orm').b;\n material.emissiveNode = blendedMember(sample, 'emissive');\n // Values below one four-sample alpha-to-coverage quantum cannot contribute\n // stable spatial coverage. In the soft 0.25\u20130.5 transition, also require\n // meaningful pre-normalization crop support: otherwise a nearly rejected\n // frame is promoted to a faint rectangular card outline. Opaque contour\n // samples bypass that gate so real thin features retain silhouette quality.\n const cropSupported = blendedMember(sample, 'cropSupport').greaterThanEqual(0.25);\n material.maskNode = screenCoverage.greaterThanEqual(0.25).and(\n screenCoverage.greaterThanEqual(0.5).or(cropSupported),\n );\n material.maskShadowNode = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);\n material.alphaToCoverage = true;\n material.capturedPositionNode = blendedMember(sample, 'positionLocal');\n // Offset only the shadow writer: different capture views can disagree slightly.\n material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);\n material.receivedShadowPositionNode = reconstructedWorldPosition;\n material.toneMapped = true;\n material.userData.impostorShaderProfile = profile;\n bindTextureSlot(material, 'baseColorAtlas', maps.baseColor, [baseColorAtlas, ...(compactLayout && compactEmissive && emissiveAtlas ? [emissiveAtlas] : [])], value => {\n maps.baseColor = value;\n if (compactLayout && compactEmissive) maps.emissive = value;\n if (material.userData.impostor) {\n material.userData.impostor.atlases.baseColor = value;\n if (compactLayout && compactEmissive) material.userData.impostor.atlases.emissive = value;\n }\n });\n bindTextureSlot(material, 'normalDepthAtlas', maps.normalDepth, [normalDepthAtlas, ...(compactLayout && ormAtlas ? [ormAtlas] : []), ...(!compressedGeometry ? [geometryAtlas] : [])], value => {\n maps.normalDepth = value;\n if (compactLayout) maps.orm = value;\n if (material.userData.impostor) {\n material.userData.impostor.atlases.normalDepth = value;\n if (compactLayout) material.userData.impostor.atlases.orm = value;\n }\n });\n if (!compactLayout && maps.orm && ormAtlas) bindTextureSlot(material, 'ormAtlas', maps.orm, [ormAtlas], value => { maps.orm = value; });\n if (!compactLayout && maps.emissive && emissiveAtlas) bindTextureSlot(material, 'emissiveAtlas', maps.emissive, [emissiveAtlas], value => { maps.emissive = value; });\n return material;\n}\n", "// @ts-check\n\n/** Primitive extension declaring an explicitly-bound Needle mesh impostor. */\nexport const NEEDLE_MESH_IMPOSTOR = 'NEEDLE_mesh_impostor';\n\n/**\n * @typedef {object} ImpostorDescriptor\n * @property {1} version\n * @property {'hemisphere' | 'full' | 'single'} mapping\n * @property {number} frames\n * @property {readonly [number, number, number]=} captureDirection\n * @property {number} frameResolution\n * @property {number} padding\n * @property {number} radius\n * @property {readonly [number, number, number]} boundsMin\n * @property {readonly [number, number, number]} boundsMax\n * @property {readonly [number, number, number]} center\n * @property {readonly number[]} viewBounds\n * @property {'captured-alpha+sdf-material' | 'sdf-base-alpha'} coverageEncoding\n * @property {number} captureAlphaCutoff\n * @property {number} alphaCutoff\n * @property {number} blendZone\n * @property {number} parallaxSteps\n * @property {boolean} depthDerivedWeights\n * @property {boolean} castShadow\n * @property {boolean} receiveShadow\n * @property {{occlusion: number, roughness: number, metalness: number}} material\n * @property {{version: 4, layout: 'compact-atlas-v4', depthEncoding: 'lossless-geometry10-rgba', materialFrameResolution: number, emissive: boolean}=} compression\n */\n\n/** @param {unknown} value @returns {ImpostorDescriptor | null} */\nexport function parseImpostorDescriptor(value) {\n if (!value || typeof value !== 'object') return null;\n const descriptor = /** @type {Partial<ImpostorDescriptor>} */ (value);\n if (\n descriptor.version !== 1\n || (descriptor.mapping !== 'hemisphere' && descriptor.mapping !== 'full' && descriptor.mapping !== 'single')\n || !isPositiveInteger(descriptor.frames)\n || (descriptor.mapping === 'single'\n ? (descriptor.frames !== 1 || !isUnitVec3(descriptor.captureDirection))\n : false)\n || !isPositiveInteger(descriptor.frameResolution)\n || !isNonNegativeInteger(descriptor.padding)\n || !isPositiveFinite(descriptor.radius)\n || (descriptor.compression !== undefined && (\n descriptor.compression.version !== 4\n || descriptor.compression.layout !== 'compact-atlas-v4'\n || descriptor.compression.depthEncoding !== 'lossless-geometry10-rgba'\n || !isPositiveInteger(descriptor.compression.materialFrameResolution)\n || typeof descriptor.compression.emissive !== 'boolean'\n ))\n || !isFiniteVec3(descriptor.boundsMin)\n || !isFiniteVec3(descriptor.boundsMax)\n || !isFiniteVec3(descriptor.center)\n || !Array.isArray(descriptor.viewBounds)\n || descriptor.viewBounds.length !== (descriptor.frames ?? 0) * (descriptor.frames ?? 0) * 4\n || !descriptor.viewBounds.every(Number.isFinite)\n || (descriptor.coverageEncoding !== 'captured-alpha+sdf-material'\n && descriptor.coverageEncoding !== 'sdf-base-alpha')\n || !isUnitInterval(descriptor.captureAlphaCutoff)\n || !isUnitInterval(descriptor.alphaCutoff)\n || !isBlendZone(descriptor.blendZone)\n || !isNonNegativeInteger(descriptor.parallaxSteps)\n || typeof descriptor.depthDerivedWeights !== 'boolean'\n || typeof descriptor.castShadow !== 'boolean'\n || typeof descriptor.receiveShadow !== 'boolean'\n || !descriptor.material\n || !isUnitInterval(descriptor.material.occlusion)\n || !isUnitInterval(descriptor.material.roughness)\n || !isUnitInterval(descriptor.material.metalness)\n ) return null;\n const valid = /** @type {ImpostorDescriptor} */ (descriptor);\n return {\n version: 1,\n mapping: valid.mapping,\n frames: valid.frames,\n ...(valid.mapping === 'single' ? { captureDirection: valid.captureDirection } : {}),\n frameResolution: valid.frameResolution,\n padding: valid.padding,\n radius: valid.radius,\n boundsMin: valid.boundsMin,\n boundsMax: valid.boundsMax,\n center: valid.center,\n viewBounds: valid.viewBounds,\n coverageEncoding: valid.coverageEncoding,\n captureAlphaCutoff: valid.captureAlphaCutoff,\n alphaCutoff: valid.alphaCutoff,\n blendZone: valid.blendZone,\n parallaxSteps: valid.parallaxSteps,\n depthDerivedWeights: valid.depthDerivedWeights,\n castShadow: valid.castShadow,\n receiveShadow: valid.receiveShadow,\n material: valid.material,\n ...(valid.compression ? { compression: valid.compression } : {}),\n };\n}\n\n/** @param {unknown} value */\nfunction isFiniteVec3(value) {\n return Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);\n}\n\n/** @param {unknown} value */\nfunction isUnitVec3(value) {\n if (!isFiniteVec3(value)) return false;\n const vector = /** @type {number[]} */ (value);\n return Math.abs(Math.hypot(vector[0], vector[1], vector[2]) - 1) < 1e-4;\n}\n\n/** @param {unknown} value */\nfunction isPositiveInteger(value) {\n return Number.isInteger(value) && /** @type {number} */ (value) > 0;\n}\n\n/** @param {unknown} value */\nfunction isNonNegativeInteger(value) {\n return Number.isInteger(value) && /** @type {number} */ (value) >= 0;\n}\n\n/** @param {unknown} value */\nfunction isPositiveFinite(value) {\n return Number.isFinite(value) && /** @type {number} */ (value) > 0;\n}\n\n/** @param {unknown} value */\nfunction isUnitInterval(value) {\n return Number.isFinite(value)\n && /** @type {number} */ (value) >= 0\n && /** @type {number} */ (value) <= 1;\n}\n\n/** @param {unknown} value */\nfunction isBlendZone(value) {\n return Number.isFinite(value)\n && /** @type {number} */ (value) >= 0.35\n && /** @type {number} */ (value) <= 1;\n}\n", "// @ts-check\n\n/** Keep material-slot texture replacement connected to the shader nodes.\n * @param {import('three').Material} material\n * @param {string} slot\n * @param {import('three').Texture} initial\n * @param {{value: import('three').Texture}[]} nodes\n * @param {((value: import('three').Texture) => void)=} onChange\n */\nexport function bindTextureSlot(material, slot, initial, nodes, onChange) {\n let current = initial;\n Object.defineProperty(material, slot, {\n configurable: true, enumerable: true,\n get: () => current,\n set: (/** @type {import('three').Texture} */ value) => {\n value.channel = current.channel;\n value.offset = current.offset;\n value.repeat = current.repeat;\n value.center = current.center;\n value.rotation = current.rotation;\n current = value;\n for (const node of nodes) node.value = value;\n onChange?.(value);\n material.needsUpdate = true;\n },\n });\n}\n", "// @ts-check\n\n// A billboard point samples the capture camera along point -> camera, so its\n// local plane offset is subtracted from the object-center camera vector.\nexport const PERSPECTIVE_RAY_PLANE_SIGN = -1;\n\n/**\n * Encodes a local-space point into the orthographic capture depth used by the\n * normal/depth atlas. Capture cameras sit at `direction * 2r` and cover the\n * interval from +r to -r along their forward axis.\n *\n * @param {[number, number, number]} point\n * @param {[number, number, number]} direction Unit capture direction.\n * @param {number} radius\n */\nexport function captureDepthFromPoint(point, direction, radius) {\n if (!(radius > 0) || !Number.isFinite(radius)) {\n throw new RangeError('Capture radius must be positive and finite.');\n }\n const normalizedDirection = normalize3(direction);\n return (radius - dot3(point, normalizedDirection)) / (2 * radius);\n}\n\n/**\n * Intersects a runtime point-to-camera ray with the capture-depth plane\n * `dot(P, captureDirection) = radius - 2 * radius * depth`.\n *\n * This is the fixed-point step solved by the runtime parallax shader. It is\n * deliberately expressed independently here so sign and scale regressions are\n * caught by browserless tests.\n *\n * @param {[number, number, number]} rayOrigin\n * @param {[number, number, number]} rayDirection Unit point-to-camera ray.\n * @param {[number, number, number]} captureDirection Unit capture direction.\n * @param {number} depth\n * @param {number} radius\n * @returns {[number, number, number]}\n */\nexport function intersectRayWithCaptureDepth(\n rayOrigin,\n rayDirection,\n captureDirection,\n depth,\n radius,\n) {\n if (!(radius > 0) || !Number.isFinite(radius) || !Number.isFinite(depth)) {\n throw new RangeError('Capture depth and radius must be finite, with a positive radius.');\n }\n const ray = normalize3(rayDirection);\n const capture = normalize3(captureDirection);\n const denominator = dot3(ray, capture);\n if (Math.abs(denominator) < 1e-8) {\n throw new RangeError('Runtime ray is parallel to the capture-depth plane.');\n }\n const planeDepth = radius - 2 * radius * depth;\n const distance = (planeDepth - dot3(rayOrigin, capture)) / denominator;\n return /** @type {[number, number, number]} */ (rayOrigin.map((value, index) => (\n value + ray[index] * distance\n )));\n}\n\n/**\n * Decodes a regular or upper-hemisphere octahedral grid coordinate.\n * Uses Y as the up axis.\n *\n * @param {[number, number]} coordinate normalized 0..1 grid coordinate\n * @param {'hemisphere' | 'full'} mapping\n * @returns {[number, number, number]}\n */\nexport function gridToDirection(coordinate, mapping) {\n const [u, v] = coordinate;\n let x;\n let y;\n let z;\n if (mapping === 'hemisphere') {\n x = u - v;\n z = -1 + u + v;\n y = 1 - Math.abs(x) - Math.abs(z);\n } else {\n x = u * 2 - 1;\n z = v * 2 - 1;\n y = 1 - Math.abs(x) - Math.abs(z);\n if (y < 0) {\n const oldX = x;\n x = nonZeroSign(x) * (1 - Math.abs(z));\n z = nonZeroSign(z) * (1 - Math.abs(oldX));\n }\n }\n return normalize3([x, y, z]);\n}\n\n/**\n * @param {[number, number, number]} input\n * @param {'hemisphere' | 'full'} mapping\n * @returns {[number, number]}\n */\nexport function directionToGrid(input, mapping) {\n let [x, y, z] = normalize3(input);\n if (mapping === 'hemisphere') y = Math.max(y, 1e-6);\n const inverseL1 = 1 / Math.max(1e-12, Math.abs(x) + Math.abs(y) + Math.abs(z));\n x *= inverseL1;\n y *= inverseL1;\n z *= inverseL1;\n if (mapping === 'hemisphere') {\n return clamp2([(x + z) * 0.5 + 0.5, (z - x) * 0.5 + 0.5]);\n }\n if (y < 0) {\n const oldX = x;\n x = nonZeroSign(x) * (1 - Math.abs(z));\n z = nonZeroSign(z) * (1 - Math.abs(oldX));\n }\n return clamp2([x * 0.5 + 0.5, z * 0.5 + 0.5]);\n}\n\n/**\n * Finds the authored grid direction with the smallest spherical angle to an\n * arbitrary view. Octahedral coordinates are not equal-area, so independently\n * rounding U/V is not guaranteed to choose the closest capture near folds.\n * The production grids contain at most 24\u00B2 views; an exact dot-product search\n * is both cheap and unambiguous for an interaction that runs on orbit release.\n *\n * @param {[number, number, number]} inputDirection\n * @param {'hemisphere' | 'full'} mapping\n * @param {number} frames\n */\nexport function nearestOctahedralCapture(inputDirection, mapping, frames) {\n if (mapping !== 'hemisphere' && mapping !== 'full') {\n throw new RangeError('Impostor mapping must be hemisphere or full.');\n }\n if (!Number.isInteger(frames) || frames < 2) {\n throw new RangeError('Impostor capture search requires at least two frames per axis.');\n }\n const direction = normalize3(inputDirection);\n let bestFrame = /** @type {[number, number]} */ ([0, 0]);\n let bestDirection = gridToDirection([0, 0], mapping);\n let bestDot = -Number.POSITIVE_INFINITY;\n for (let y = 0; y < frames; y++) {\n for (let x = 0; x < frames; x++) {\n const candidate = gridToDirection([x / (frames - 1), y / (frames - 1)], mapping);\n const similarity = dot3(direction, candidate);\n if (similarity <= bestDot) continue;\n bestDot = similarity;\n bestFrame = [x, y];\n bestDirection = candidate;\n }\n }\n return {\n frame: bestFrame,\n direction: bestDirection,\n dot: Math.max(-1, Math.min(1, bestDot)),\n angleDegrees: Math.acos(Math.max(-1, Math.min(1, bestDot))) * 180 / Math.PI,\n };\n}\n\n/**\n * Projects a spherical direction beyond the latest sample. OrbitControls'\n * residual release motion supplies the two samples; values above one look\n * ahead in the same direction, so a fast release cannot select the capture\n * behind its visible trajectory.\n *\n * @param {[number, number, number]} startDirection\n * @param {[number, number, number]} endDirection\n * @param {number} multiplier 1 returns the end sample, 1.5 projects half of\n * the sampled angular motion beyond it.\n * @returns {[number, number, number]}\n */\nexport function extrapolateSphericalDirection(startDirection, endDirection, multiplier) {\n if (!Number.isFinite(multiplier) || multiplier < 0) {\n throw new RangeError('Spherical extrapolation multiplier must be finite and non-negative.');\n }\n const start = normalize3(startDirection);\n const end = normalize3(endDirection);\n const similarity = Math.max(-1, Math.min(1, dot3(start, end)));\n const angle = Math.acos(similarity);\n const axis = cross3(start, end);\n const axisLength = Math.hypot(...axis);\n if (angle < 1e-8 || axisLength < 1e-8) return end;\n const unitAxis = /** @type {[number, number, number]} */ (\n axis.map((component) => component / axisLength)\n );\n const projectedAngle = angle * multiplier;\n const cosine = Math.cos(projectedAngle);\n const sine = Math.sin(projectedAngle);\n const axisCrossStart = cross3(unitAxis, start);\n const axisDotStart = dot3(unitAxis, start);\n return normalize3(/** @type {[number, number, number]} */ (start.map((component, index) => (\n component * cosine\n + axisCrossStart[index] * sine\n + unitAxis[index] * axisDotStart * (1 - cosine)\n ))));\n}\n\n/**\n * Returns the three vertices and barycentric weights of the grid triangle\n * containing a direction. The diagonal is chosen consistently on CPU and GPU.\n *\n * @param {[number, number, number]} direction\n * @param {'hemisphere' | 'full'} mapping\n * @param {number} frames\n */\nexport function selectOctahedralFrames(direction, mapping, frames) {\n const scale = frames - 1;\n const grid = directionToGrid(direction, mapping);\n const gx = grid[0] * scale;\n const gy = grid[1] * scale;\n const x = Math.min(scale - 1, Math.floor(gx));\n const y = Math.min(scale - 1, Math.floor(gy));\n const fx = gx - x;\n const fy = gy - y;\n const base = gridToDirection([x / scale, y / scale], mapping);\n const right = gridToDirection([(x + 1) / scale, y / scale], mapping);\n const up = gridToDirection([x / scale, (y + 1) / scale], mapping);\n const diagonal = gridToDirection([(x + 1) / scale, (y + 1) / scale], mapping);\n // Octahedral grid quads are strongly warped on the sphere, especially at\n // low view counts. Use the shorter of their two spherical diagonals instead\n // of always connecting base -> diagonal. Fold cells still necessarily use\n // the anti-diagonal because it is the captured z=0 view edge.\n const antiDiagonal = mapping === 'hemisphere' && x + y === scale - 1\n || dot3(right, up) > dot3(base, diagonal);\n if (antiDiagonal) {\n if (fx + fy <= 1) {\n return {\n frames: /** @type {[[number, number], [number, number], [number, number]]} */ ([\n [x, y], [x + 1, y], [x, y + 1],\n ]),\n weights: /** @type {[number, number, number]} */ ([1 - fx - fy, fx, fy]),\n };\n }\n return {\n frames: /** @type {[[number, number], [number, number], [number, number]]} */ ([\n [x + 1, y + 1], [x, y + 1], [x + 1, y],\n ]),\n weights: /** @type {[number, number, number]} */ ([fx + fy - 1, 1 - fx, 1 - fy]),\n };\n }\n const horizontal = fx > fy;\n return {\n frames: /** @type {[[number, number], [number, number], [number, number]]} */ ([\n [x, y],\n horizontal ? [x + 1, y] : [x, y + 1],\n [x + 1, y + 1],\n ]),\n weights: /** @type {[number, number, number]} */ ([\n Math.min(1 - fx, 1 - fy),\n Math.abs(fx - fy),\n Math.min(fx, fy),\n ]),\n };\n}\n\n/** @param {[number, number, number]} a @param {[number, number, number]} b */\nfunction dot3(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/** @param {[number, number, number]} a @param {[number, number, number]} b */\nfunction cross3(a, b) {\n return /** @type {[number, number, number]} */ ([\n a[1] * b[2] - a[2] * b[1],\n a[2] * b[0] - a[0] * b[2],\n a[0] * b[1] - a[1] * b[0],\n ]);\n}\n\n/** @param {[number, number, number]} value */\nfunction normalize3(value) {\n const length = Math.hypot(...value);\n if (length < 1e-12) return /** @type {[number, number, number]} */ ([0, 1, 0]);\n return /** @type {[number, number, number]} */ (value.map((component) => component / length));\n}\n\n/** @param {[number, number]} value */\nfunction clamp2(value) {\n return /** @type {[number, number]} */ (value.map((component) => Math.max(0, Math.min(1, component))));\n}\n\n/** @param {number} value */\nfunction nonZeroSign(value) {\n return value < 0 ? -1 : 1;\n}\n", "// @ts-check\n\nimport {\n DataTexture,\n FloatType,\n NearestFilter,\n RGBAFormat,\n} from 'three';\n\nimport { parseImpostorDescriptor } from './impostor-metadata.js';\n/** @import { ImpostorDescriptor } from './impostor-metadata.js' */\n\nexport { parseImpostorDescriptor } from './impostor-metadata.js';\n\nexport const REPROJECTION_CONFIDENCE_INNER_TEXELS = 0.25;\nexport const REPROJECTION_CONFIDENCE_OUTER_TEXELS = 16;\n\n/**\n * Restricts barycentric interpolation to a compact fraction of each angular\n * transition. A value of one preserves ordinary linear barycentrics. Smaller\n * values create an exact single-view region around each capture while the\n * active transition remains continuous and normalized.\n *\n * Along a triangle edge, `blendZone` is exactly the fraction of that edge over\n * which both endpoint captures contribute.\n *\n * @param {readonly [number, number, number]} inputWeights\n * @param {number} blendZone\n * @returns {[number, number, number]}\n */\nexport function applyImpostorBlendZone(inputWeights, blendZone) {\n if (!isBlendZone(blendZone)) {\n throw new RangeError('Impostor blend zone must be from 0.35 to 1.');\n }\n if (inputWeights.some((weight) => !Number.isFinite(weight) || weight < 0)) {\n throw new RangeError('Impostor barycentric weights must be finite and non-negative.');\n }\n const cutoff = (1 - blendZone) * 0.5;\n const weights = /** @type {[number, number, number]} */ (\n inputWeights.map((weight) => Math.max(0, weight - cutoff))\n );\n const sum = weights[0] + weights[1] + weights[2];\n if (!(sum > 0)) return [1, 0, 0];\n return /** @type {[number, number, number]} */ (\n weights.map((weight) => weight / sum)\n );\n}\n\n/**\n * Keeps the angular onset of a previously occluded contour approximately\n * stable as the atlas grid gets denser. The returned value is the temperature\n * used by the normalized log-sum-exp union in the runtime shader.\n *\n * @param {number} frames\n */\nexport function impostorContourUnionSharpness(frames) {\n if (!Number.isInteger(frames) || frames < 2) {\n throw new RangeError('Impostor contour union requires at least two frames per atlas axis.');\n }\n return Math.max(1, 16 / frames);\n}\n\n/**\n * CPU mirror of the runtime's continuous geometric confidence. A binary\n * half-texel cutoff made individual pixels (and sometimes entire thin\n * features) switch reconstruction paths at one camera angle. The fade keeps\n * the same bounded rejection while making angular motion continuous.\n *\n * @param {boolean} startedOutOfBounds\n * @param {number} rayError\n * @param {number} footprint\n * @param {boolean=} reprojectionActive\n */\nexport function reprojectedSampleConfidence(\n startedOutOfBounds,\n rayError,\n footprint,\n reprojectionActive = true,\n) {\n if (startedOutOfBounds) return 0;\n if (!reprojectionActive) return 1;\n if (!(footprint > 0)) return 0;\n const residual = rayError / footprint;\n const interval = REPROJECTION_CONFIDENCE_OUTER_TEXELS\n - REPROJECTION_CONFIDENCE_INNER_TEXELS;\n const t = Math.min(1, Math.max(\n 0,\n (residual - REPROJECTION_CONFIDENCE_INNER_TEXELS) / interval,\n ));\n const eased = t * t * (3 - 2 * t);\n return 1 - eased;\n}\n\n/**\n * Mirrors the runtime coverage contribution used after depth reprojection.\n * Validity can remove a frame from a pixel, but it must never renormalize the\n * remaining frame to full opacity. Preserving angular support prevents a\n * surface visible in only one capture from appearing as a second opaque layer.\n *\n * @param {readonly [number, number, number]} visibilityWeights\n * @param {readonly [number, number, number]} correctedValidity\n * @returns {[number, number, number]}\n */\nexport function resolveImpostorCoverageWeights(\n visibilityWeights,\n correctedValidity,\n) {\n const values = [...visibilityWeights, ...correctedValidity];\n if (values.some((value) => !Number.isFinite(value) || value < 0)) {\n throw new RangeError('Coverage weights and validity must be finite and non-negative.');\n }\n return /** @type {[number, number, number]} */ (\n visibilityWeights.map((weight, index) => weight * correctedValidity[index])\n );\n}\n\n/** @param {ImpostorDescriptor} descriptor */\nexport function createImpostorViewBoundsTexture(descriptor) {\n const texture = new DataTexture(\n new Float32Array(descriptor.viewBounds),\n descriptor.frames,\n descriptor.frames,\n RGBAFormat,\n FloatType,\n );\n texture.name = 'impostor view bounds';\n texture.minFilter = NearestFilter;\n texture.magFilter = NearestFilter;\n texture.generateMipmaps = false;\n texture.needsUpdate = true;\n return texture;\n}\n\n/** @param {unknown} value */\nfunction isBlendZone(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nB,QAAI,cAAe,MAAK,MAAM;AAC9B,QAAI,SAAS,SAAS,UAAU;AAC9B,eAAS,SAAS,SAAS,QAAQ,cAAc;AACjD,UAAI,cAAe,UAAS,SAAS,SAAS,QAAQ,MAAM;AAAA,IAC9D;AAAA,EACF,CAAC;AACD,MAAI,CAAC,iBAAiB,KAAK,OAAO,SAAU,iBAAgB,UAAU,YAAY,KAAK,KAAK,CAAC,QAAQ,GAAG,WAAS;AAAE,SAAK,MAAM;AAAA,EAAO,CAAC;AACtI,MAAI,CAAC,iBAAiB,KAAK,YAAY,cAAe,iBAAgB,UAAU,iBAAiB,KAAK,UAAU,CAAC,aAAa,GAAG,WAAS;AAAE,SAAK,WAAW;AAAA,EAAO,CAAC;AACpK,SAAO;AACT;",
|
|
6
|
-
"names": ["modelViewMatrix", "vec4", "MeshStandardNodeMaterial", "TSL", "Fn", "modelWorldMatrix", "vec4", "texture", "TSL", "pending", "Fn", "bytes", "vec4", "footprint", "coarseStep", "distanceCoverage", "modelWorldMatrix"]
|
|
3
|
+
"sources": ["../src/rendering/renderer-support.js", "../src/rendering/classic-webgl-support.js", "../src/rendering/captured-surface-material.js", "../src/rendering/captured-surface-depth.js", "../src/impostor/impostor-node-material.js", "../src/impostor/impostor-metadata.js", "../src/impostor/adaptive-impostor-renderer.js", "../src/impostor/impostor-performance.js", "../src/rendering/texture-slot.js", "../src/rendering/instance-space.js", "../src/impostor/octahedral.js", "../src/impostor/impostor-runtime-support.js"],
|
|
4
|
+
"sourcesContent": ["// @ts-check\nimport {REVISION} from 'three';\nimport * as TSL from 'three/tsl';\nimport {classicWebGLSupportsNodeMaterials} from './classic-webgl-support.js';\n\n/**\n * @typedef {object} ImpostorRenderer\n * @property {boolean=} isWebGPURenderer\n * @property {boolean=} isWebGLRenderer\n * @property {(object & {supportsNodeMaterials?: boolean})=} capabilities\n * @property {((handler: import('three/addons/tsl/WebGLNodesHandler.js').WebGLNodesHandler) => void)=} setNodesHandler\n */\n\n/**\n * Reports whether a renderer can compile TSL impostor materials.\n * WebGPURenderer supports node materials directly. Classic WebGLRenderer\n * integrations must advertise that they installed a compatible nodes handler.\n *\n * @param {ImpostorRenderer | undefined} renderer\n */\nexport function rendererSupportsImpostorNodeMaterials(renderer) {\n\tif (typeof Reflect.get(TSL, 'struct') !== 'function') return false;\n\treturn renderer?.isWebGPURenderer === true\n\t\t|| renderer?.capabilities?.supportsNodeMaterials === true;\n}\n\n/** Classic WebGL exposes MSAA on the target or the canvas context.\n * @param {{currentSamples?: number, getRenderTarget?: () => {samples: number} | null,\n * getContextAttributes?: () => {antialias?: boolean} | null}} renderer\n */\nexport function rendererUsesMultisampleCoverage(renderer) {\n\tconst samples = renderer.currentSamples ?? renderer.getRenderTarget?.()?.samples;\n\treturn samples === undefined ? renderer.getContextAttributes?.()?.antialias === true : samples > 1;\n}\n\n/** @type {WeakMap<ImpostorRenderer, Promise<void>>} */\nconst pending = new WeakMap();\n\n/** Enable Three's existing TSL handler only when an enabled asset needs it.\n * Hosts with their own compiler advertise supportsNodeMaterials to retain it.\n * @param {ImpostorRenderer | undefined} renderer */\nexport async function enableRendererNodeMaterials(renderer) {\n\tif (rendererSupportsImpostorNodeMaterials(renderer) ||\n\t\t!renderer?.isWebGLRenderer || !renderer.setNodesHandler ||\n\t\ttypeof Reflect.get(TSL, 'struct') !== 'function') return;\n\tlet setup = pending.get(renderer);\n\tif (!setup) {\n\t\tsetup = import('three/addons/tsl/WebGLNodesHandler.js').then(({WebGLNodesHandler}) => {\n\t\t\tif (rendererSupportsImpostorNodeMaterials(renderer)) return;\n\t\t\tif (!classicWebGLSupportsNodeMaterials(REVISION)) {\n\t\t\t\tconsole.warn(`Mesh Effects: WebGLRenderer from three r${REVISION} stops drawing node materials after about a dozen are in use. Use three r187 or later, or WebGPURenderer.`);\n\t\t\t}\n\t\t\trenderer.setNodesHandler?.(new WebGLNodesHandler());\n\t\t\trenderer.capabilities ??= {};\n\t\t\trenderer.capabilities.supportsNodeMaterials = true;\n\t\t}).catch(error => {\n\t\t\tpending.delete(renderer);\n\t\t\tthrow error;\n\t\t});\n\t\tpending.set(renderer, setup);\n\t}\n\tawait setup;\n}\n\n", "// @ts-check\n\n/**\n * Reports whether WebGLRenderer from a three revision can keep many node\n * materials alive. Before r187 every uniform block holds one of a few binding\n * points until its material is disposed, so node materials stop drawing after\n * about a dozen. The Needle fork backports the fix from 0.186.2-alpha.2.\n *\n * @param {string} revision three's `REVISION`, such as `'187'` or `'186.2-alpha.2'`\n */\nexport function classicWebGLSupportsNodeMaterials(revision) {\n\tconst fork = /^186\\.2-alpha\\.(\\d+)$/.exec(revision);\n\tif (fork) return Number(fork[1]) >= 2;\n\treturn Number.parseInt(revision, 10) >= 187;\n}\n", "// @ts-check\nimport { MeshStandardNodeMaterial } from 'three/webgpu';\nimport { context, modelViewMatrix, modelWorldMatrix, vec4 } from 'three/tsl';\n\n/** Light reconstructed surfaces at their hit position, not the carrier face.\n * View directions stay on the same ray; local lights also need the hit distance.\n */\nexport class CapturedSurfaceMaterial extends MeshStandardNodeMaterial {\n /** @type {import('three/webgpu').Node<'vec3'> | null} */\n capturedPositionNode = null;\n\n /**\n * @override\n * @param {import('three/webgpu').NodeBuilder} builder\n */\n setupLighting(builder) {\n const lighting = super.setupLighting(builder);\n if (!this.capturedPositionNode) return lighting;\n const world = modelWorldMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;\n const view = modelViewMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;\n return context(lighting, {\n positionView: view,\n positionWorld: world,\n shadowPositionWorld: world,\n });\n }\n}\n", "// @ts-check\nimport {\n Fn,\n cameraFar,\n cameraNear,\n cameraProjectionMatrix,\n modelViewMatrix,\n vec4,\n viewZToLogarithmicDepth,\n viewZToOrthographicDepth,\n viewZToPerspectiveDepth,\n viewZToReversedOrthographicDepth,\n viewZToReversedPerspectiveDepth,\n} from 'three/tsl';\n\n/** Match the renderer's depth convention after reconstructing a local hit.\n * @param {import('three/webgpu').Node<'vec3'>} position\n * @param {number} [shadowBias]\n */\nexport function capturedSurfaceDepth(position, shadowBias = 0) {\n return Fn(\n (\n /** @type {unknown} */ _,\n /** @type {import('three/webgpu').NodeBuilder} */ builder,\n ) => {\n // Resolve the shared hit before either projection branch consumes it.\n const z = modelViewMatrix\n .mul(vec4(position, 1))\n .z.toVar('capturedSurfaceViewZ');\n const reversed = builder.renderer.reversedDepthBuffer === true;\n // One material can alternate between a perspective view and orthographic\n // shadow cameras without a new pipeline; select using the active projection.\n const perspective = cameraProjectionMatrix\n .mul(vec4(0, 0, 0, 1))\n .w.equal(0);\n const perspectiveDepth =\n builder.renderer.logarithmicDepthBuffer === true\n ? viewZToLogarithmicDepth(z, cameraNear, cameraFar)\n : (reversed\n ? viewZToReversedPerspectiveDepth\n : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);\n const result = perspective.select(\n perspectiveDepth,\n (reversed\n ? viewZToReversedOrthographicDepth\n : viewZToOrthographicDepth)(z, cameraNear, cameraFar),\n );\n return shadowBias &&\n 'isShadowPassMaterial' in builder.material &&\n builder.material.isShadowPassMaterial\n ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1)\n : result;\n },\n )();\n}\n", "// TSL's current declarations erase custom struct member types to `Node`, which\n// makes a checked JS implementation impossible without casting every operator.\n// Keep this backend module runtime-tested until Three's StructNode types retain\n// their declared member layout.\n// @ts-nocheck\n\nimport { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials, rendererUsesMultisampleCoverage } from '../rendering/renderer-support.js';\nexport { rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';\n\nimport { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';\nimport { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';\nimport {\n Box3,\n ClampToEdgeWrapping,\n DoubleSide,\n GLSL3,\n LinearFilter,\n LinearMipmapLinearFilter,\n MeshStandardNodeMaterial,\n NoColorSpace,\n SRGBColorSpace,\n ShaderMaterial,\n Sphere,\n Vector3,\n Vector4,\n} from 'three/webgpu';\nimport * as TSL from 'three/tsl';\nimport {\n Fn,\n If,\n Loop,\n Break,\n abs,\n any,\n bool,\n cameraPosition,\n cameraWorldMatrix,\n cross,\n dot,\n exp,\n float,\n floor,\n fract,\n fwidth,\n int,\n ivec2,\n max,\n min,\n mix,\n modelWorldMatrix,\n modelWorldMatrixInverse,\n positionGeometry,\n smoothstep,\n texture,\n textureLoad,\n textureSize,\n transformNormalToView,\n uniformArray,\n varying,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl';\nimport { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';\nimport { registerAdaptiveImpostorMaterial } from './adaptive-impostor-renderer.js';\nimport { IMPOSTOR_PERFORMANCE_PRESETS, resolveImpostorFrameBudget } from './impostor-performance.js';\nimport { bindTextureSlot } from '../rendering/texture-slot.js';\nimport { instanceSpace } from '../rendering/instance-space.js';\nimport { PERSPECTIVE_RAY_PLANE_SIGN } from './octahedral.js';\nimport {\n REPROJECTION_CONFIDENCE_INNER_TEXELS,\n REPROJECTION_CONFIDENCE_OUTER_TEXELS,\n createImpostorViewBoundsTexture,\n impostorContourUnionSharpness,\n parseImpostorDescriptor,\n} from './impostor-runtime-support.js';\n\nconst NAMED_STRUCT_FACTORY = Reflect.get(TSL, 'struct');\n\n/** @import { ImpostorDescriptor } from './impostor-metadata.js' */\n\n/** @typedef {import('../rendering/renderer-support.js').ImpostorRenderer} ImpostorRenderer */\n/**\n * @typedef {object} ImpostorRuntimeFeatures\n * @property {boolean} interpolation\n * @property {boolean} reprojection\n * @property {boolean} depthWeights\n * @property {boolean} perspectiveCorrection\n * @property {boolean} cellCorrection\n * @property {boolean} boundedReprojection\n * @property {number} raySamples\n * @property {number} depthSamples\n * @property {number} blendZone\n */\n\n/**\n * @typedef {object} ResolvedImpostorRuntimeFeatures\n * @property {ImpostorRuntimeFeatures} requested\n * @property {Pick<ImpostorRuntimeFeatures, 'interpolation' | 'reprojection' | 'depthWeights' | 'perspectiveCorrection' | 'cellCorrection' | 'boundedReprojection'>} effective\n * @property {Pick<ImpostorRuntimeFeatures, 'interpolation' | 'reprojection' | 'depthWeights' | 'perspectiveCorrection' | 'cellCorrection' | 'boundedReprojection' | 'raySamples' | 'depthSamples'> & {frameSamples: number, blendZone: number}} profile\n */\n\nconst RUNTIME_FEATURE_NAMES = /** @type {const} */ ([\n 'interpolation',\n 'reprojection',\n 'depthWeights',\n 'perspectiveCorrection',\n 'cellCorrection',\n 'boundedReprojection',\n]);\n\nexport const DEFAULT_IMPOSTOR_RUNTIME_FEATURES = Object.freeze({\n interpolation: true,\n reprojection: true,\n depthWeights: true,\n perspectiveCorrection: true,\n cellCorrection: false,\n boundedReprojection: true,\n});\n\nexport const IMPOSTOR_RUNTIME_SAMPLE_LIMITS = Object.freeze({\n raySamples: 32,\n depthSamples: 8,\n});\n\nconst IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS = 0.002;\nconst HEMISPHERE_HORIZON_TRANSITION_SINE = Math.sin(Math.PI / 180);\n\n\n/**\n * @param {ImpostorDescriptor} descriptor\n * @param {Partial<ImpostorRuntimeFeatures>=} input\n * @returns {ResolvedImpostorRuntimeFeatures}\n */\nexport function resolveImpostorRuntimeFeatures(descriptor, input = {}) {\n const requested = {\n ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,\n raySamples: descriptor.parallaxSteps * 4,\n depthSamples: descriptor.parallaxSteps,\n blendZone: descriptor.blendZone,\n ...input,\n };\n for (const name of RUNTIME_FEATURE_NAMES) requested[name] = requested[name] !== false;\n requested.raySamples = clampRuntimeSamples(\n requested.raySamples,\n IMPOSTOR_RUNTIME_SAMPLE_LIMITS.raySamples,\n );\n requested.depthSamples = clampRuntimeSamples(\n requested.depthSamples,\n IMPOSTOR_RUNTIME_SAMPLE_LIMITS.depthSamples,\n );\n requested.blendZone = Math.min(1, Math.max(0.35, Number(requested.blendZone) || descriptor.blendZone));\n const interpolation = requested.interpolation;\n const reprojection = interpolation && requested.reprojection && requested.raySamples > 0;\n const depthWeights = interpolation && requested.depthWeights && descriptor.depthDerivedWeights;\n const perspectiveCorrection = requested.perspectiveCorrection;\n const cellCorrection = interpolation && perspectiveCorrection && requested.cellCorrection;\n const boundedReprojection = reprojection && requested.boundedReprojection;\n return {\n requested,\n effective: {\n interpolation,\n reprojection,\n depthWeights,\n perspectiveCorrection,\n cellCorrection,\n boundedReprojection,\n },\n profile: {\n interpolation,\n reprojection,\n depthWeights,\n perspectiveCorrection,\n cellCorrection,\n boundedReprojection,\n frameSamples: interpolation ? 3 : 1,\n raySamples: reprojection ? requested.raySamples : 0,\n depthSamples: reprojection ? requested.depthSamples : 0,\n blendZone: requested.blendZone,\n },\n };\n}\n\nfunction clampRuntimeSamples(value, maximum) {\n const numeric = Number(value);\n if (!Number.isFinite(numeric)) return 0;\n return Math.min(maximum, Math.max(0, Math.round(numeric)));\n}\n\n/**\n * Installs a backend-neutral TSL material. WebGPURenderer compiles this graph\n * to WGSL on WebGPU and GLSL on its WebGL2 compatibility backend.\n *\n * @param {import('three').Object3D} root\n * @param {Map<import('three').Object3D, {descriptor: unknown, maps: {\n * baseColor: import('three').Texture,\n * normalDepth: import('three').Texture,\n * material?: import('three').Texture | null,\n * emissive?: import('three').Texture | null,\n * geometry?: import('three').Texture | null,\n * }}>} bindings\n * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures\n * @param {ImpostorRenderer=} renderer\n * @param {import('./impostor-performance.js').ImpostorPerformance=} performance\n */\nexport function upgradeImpostorScene(root, bindings = new Map(), inputFeatures = {}, renderer, performance = 'fixed') {\n const frameBudgetMs = resolveImpostorFrameBudget(performance);\n let upgraded = 0;\n root.traverse((object) => {\n const binding = bindings.get(object);\n const metadata = binding?.descriptor\n ?? object.userData?.gltfExtensions?.[NEEDLE_MESH_IMPOSTOR];\n if (metadata === undefined) return;\n if (!('isMesh' in object) || object.isMesh !== true) {\n throw new Error('Impostor metadata must belong to a mesh.');\n }\n const descriptor = parseImpostorDescriptor(metadata);\n if (!descriptor) {\n throw new Error('Unsupported NEEDLE_mesh_impostor descriptor.');\n }\n if (!binding) {\n throw new Error('NEEDLE_mesh_impostor textures require the registered GLTFLoader plugin.');\n }\n const fallback = Array.isArray(object.material) ? object.material[0] : object.material;\n if (!fallback) return;\n const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';\n if (!binding.maps.baseColor || !binding.maps.normalDepth) {\n throw new Error('Impostor GLB is missing a required base-color or normal-depth atlas.');\n }\n const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';\n if (compressedGeometry && !binding.maps.geometry) {\n throw new Error('Compressed impostor GLB is missing its geometry atlas.');\n }\n // Extension texture semantics are authoritative. Do not depend on a\n // fallback PBR slot having happened to request the same glTF texture first:\n // loader order and host integrations may otherwise leave a base-color atlas\n // in linear space, which turns bright authored colors nearly white. Packed\n // normals, depth, ORM, and coverage are data and must never be decoded.\n binding.maps.baseColor.colorSpace = SRGBColorSpace;\n binding.maps.normalDepth.colorSpace = NoColorSpace;\n if (binding.maps.material) binding.maps.material.colorSpace = NoColorSpace;\n if (binding.maps.geometry) binding.maps.geometry.colorSpace = NoColorSpace;\n if (binding.maps.emissive) binding.maps.emissive.colorSpace = SRGBColorSpace;\n for (const atlas of [\n binding.maps.baseColor,\n binding.maps.normalDepth,\n binding.maps.material,\n binding.maps.geometry,\n binding.maps.emissive,\n ]) {\n if (!atlas) continue;\n // glTF declares CLAMP_TO_EDGE for every impostor atlas. Reassert it on\n // the runtime textures as well: these are packed view grids, never\n // repeatable images, and one repeated edge texel can become a visible\n // line around the billboard.\n atlas.wrapS = ClampToEdgeWrapping;\n atlas.wrapT = ClampToEdgeWrapping;\n atlas.minFilter = LinearMipmapLinearFilter;\n atlas.magFilter = LinearFilter;\n atlas.generateMipmaps = !atlas.isCompressedTexture;\n atlas.needsUpdate = true;\n }\n if (compressedGeometry && binding.maps.geometry) {\n binding.maps.geometry.minFilter = LinearFilter;\n binding.maps.geometry.generateMipmaps = false;\n binding.maps.geometry.needsUpdate = true;\n }\n const viewBoundsTexture = createImpostorViewBoundsTexture(descriptor);\n const maps = {\n baseColor: binding.maps.baseColor,\n normalDepth: binding.maps.normalDepth,\n orm: compactLayout ? binding.maps.normalDepth : binding.maps.material,\n emissive: compactLayout\n ? descriptor.compression?.emissive ? binding.maps.baseColor : null\n : binding.maps.emissive,\n geometry: compressedGeometry ? binding.maps.geometry : null,\n viewBounds: viewBoundsTexture,\n };\n const nodeMaterials = rendererSupportsImpostorNodeMaterials(renderer);\n const runtime = {\n backend: nodeMaterials ? 'three-tsl' : 'three-webgl-compat',\n descriptor,\n viewBoundsTexture,\n atlases: {\n baseColor: binding.maps.baseColor,\n normalDepth: binding.maps.normalDepth,\n orm: compactLayout ? binding.maps.normalDepth : binding.maps.material,\n emissive: compactLayout\n ? descriptor.compression?.emissive ? binding.maps.baseColor : null\n : binding.maps.emissive,\n geometry: compressedGeometry ? binding.maps.geometry : null,\n },\n };\n const requestedFeatures = {\n ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,\n raySamples: descriptor.parallaxSteps * 4,\n depthSamples: descriptor.parallaxSteps,\n blendZone: descriptor.blendZone,\n ...inputFeatures,\n };\n const debugControls = Object.fromEntries(RUNTIME_FEATURE_NAMES.map((name) => [\n name,\n { value: requestedFeatures[name] ? 1 : 0 },\n ]));\n debugControls.raySamples = { value: descriptor.parallaxSteps * 4 };\n debugControls.depthSamples = { value: descriptor.parallaxSteps };\n debugControls.blendZone = { value: descriptor.blendZone };\n // Auto cycles through three profiles. Retain their programs while the\n // preview owns them, and release the variants when its active material is\n // disposed. Manual edits keep the normal replace-and-dispose lifecycle.\n const variants = new Map();\n let cachedAtlases = '';\n let adaptive;\n function stopAdaptivePerformance() {\n adaptive?.dispose();\n adaptive = undefined;\n }\n const releaseVariants = (keep) => {\n const retained = [...variants.values()];\n variants.clear();\n for (const material of retained) {\n material.removeEventListener('dispose', onVariantDisposed);\n if (material !== keep) material.dispose();\n }\n };\n const onVariantDisposed = (event) => releaseVariants(event.target);\n debugControls.setFeatures = (features, cacheVariants = false) => {\n const next = resolveImpostorRuntimeFeatures(descriptor, features);\n const previous = object.material;\n // An atlas can be replaced on the active material after loading.\n const atlasKey = cacheVariants ? Object.values(maps).map(texture => texture?.uuid).join('/') : '';\n if (!cacheVariants || next.requested.blendZone !== requestedFeatures.blendZone || atlasKey !== cachedAtlases) {\n releaseVariants(previous);\n cachedAtlases = atlasKey;\n }\n const key = JSON.stringify(next.requested);\n const unchanged = key === JSON.stringify(requestedFeatures);\n if (unchanged && (!cacheVariants || variants.has(key))) return false;\n const wasRetained = [...variants.values()].includes(previous);\n const material = unchanged ? previous : variants.get(key) ?? createPbrImpostorNodeMaterial(\n descriptor, maps, next.requested, renderer,\n );\n if (cacheVariants) {\n variants.delete(key);\n variants.set(key, material);\n material.addEventListener('dispose', onVariantDisposed);\n if (variants.size > 3) {\n const [oldKey, oldest] = variants.entries().next().value;\n variants.delete(oldKey);\n oldest.removeEventListener('dispose', onVariantDisposed);\n oldest.dispose();\n }\n }\n if (unchanged) return false;\n stopAdaptivePerformance();\n Object.assign(requestedFeatures, next.requested);\n for (const name of RUNTIME_FEATURE_NAMES) {\n debugControls[name].value = requestedFeatures[name] ? 1 : 0;\n }\n debugControls.raySamples.value = requestedFeatures.raySamples;\n debugControls.depthSamples.value = requestedFeatures.depthSamples;\n debugControls.blendZone.value = requestedFeatures.blendZone;\n material.userData.impostor = runtime;\n material.userData.impostorDebug = debugControls;\n debugControls.profile = material.userData.impostorShaderProfile;\n object.material = material;\n if (!wasRetained && previous !== fallback) previous.dispose();\n return true;\n };\n const material = createPbrImpostorNodeMaterial(descriptor, maps, requestedFeatures, renderer);\n material.userData.impostor = runtime;\n material.userData.impostorDebug = debugControls;\n debugControls.profile = material.userData.impostorShaderProfile;\n debugControls.getAdaptivePerformance = () => adaptive?.read() ?? null;\n debugControls.setPerformance = (mode) => {\n if (mode === 'fixed') {\n stopAdaptivePerformance();\n return;\n }\n if (adaptive || !nodeMaterials || descriptor.mapping === 'single') return;\n const bounds = new Box3(new Vector3(...descriptor.boundsMin), new Vector3(...descriptor.boundsMax))\n .getBoundingSphere(new Sphere());\n const limits = { ...requestedFeatures };\n adaptive = registerAdaptiveImpostorMaterial(renderer, object.material, bounds, tier => {\n const preset = tier === 0 ? IMPOSTOR_PERFORMANCE_PRESETS.fast\n : tier === 1 ? IMPOSTOR_PERFORMANCE_PRESETS.medium : limits;\n const variant = createPbrImpostorNodeMaterial(descriptor, maps, {\n ...limits,\n raySamples: Math.min(limits.raySamples, preset.raySamples),\n depthSamples: Math.min(limits.depthSamples, preset.depthSamples),\n reprojection: limits.reprojection && preset.reprojection,\n depthWeights: limits.depthWeights && preset.depthWeights,\n }, renderer);\n variant.userData.impostor = runtime;\n return variant;\n }, frameBudgetMs);\n };\n object.material = material;\n debugControls.setPerformance(typeof performance === 'object' ? 'auto' : performance);\n object.castShadow = descriptor.castShadow;\n object.receiveShadow = descriptor.receiveShadow;\n object.frustumCulled = false;\n fallback.dispose();\n upgraded++;\n });\n return upgraded;\n}\n\n/**\n * Three.js GLTFLoader plugin that upgrades Needle impostor nodes after their\n * atlas textures have loaded. Register KTX2Loader on GLTFLoader as usual when\n * loading compressed impostors; uncompressed GLBs need no extra texture setup.\n */\nexport class NeedleImpostorLoaderPlugin {\n /**\n * @param {unknown} parser GLTFLoader parser supplied by `loader.register()`.\n * @param {{\n * onUpgrade?: (count: number, result: import('three/addons/loaders/GLTFLoader.js').GLTF) => void,\n * features?: Partial<ImpostorRuntimeFeatures>,\n * renderer?: ImpostorRenderer,\n * performance?: import('./impostor-performance.js').ImpostorPerformance,\n * }=} options\n */\n constructor(parser, options = {}) {\n this.name = NEEDLE_MESH_IMPOSTOR;\n this.parser = parser;\n this.options = options;\n }\n\n /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */\n async afterRoot(result) {\n await enableRendererNodeMaterials(this.options.renderer);\n const parser = /** @type {{\n * json: {meshes?: Array<{primitives: Array<{extensions?: Record<string, unknown>}>}>},\n * associations: Map<import('three').Object3D, {meshes?: number, primitives?: number}>,\n * getDependency(type: 'texture', index: number): Promise<import('three').Texture>,\n * }} */ (this.parser);\n const bindings = new Map();\n const roots = result.scenes?.length ? result.scenes : [result.scene];\n const visited = new Set();\n let upgraded = 0;\n for (const root of roots) {\n if (!root || visited.has(root)) continue;\n visited.add(root);\n const pending = [];\n root.traverse((object) => {\n if (!('isMesh' in object) || object.isMesh !== true) return;\n const association = parser.associations.get(object);\n if (association?.meshes === undefined || association.primitives === undefined) return;\n const raw = parser.json.meshes?.[association.meshes]\n ?.primitives[association.primitives]?.extensions?.[NEEDLE_MESH_IMPOSTOR];\n if (!raw || typeof raw !== 'object') return;\n const definition = /** @type {Record<string, unknown>} */ (raw);\n const descriptor = parseImpostorDescriptor(definition);\n if (!descriptor) {\n throw new Error('Unsupported NEEDLE_mesh_impostor descriptor.');\n }\n const rawTextures = definition.textures;\n if (!rawTextures || typeof rawTextures !== 'object') {\n throw new Error('NEEDLE_mesh_impostor has no texture bindings.');\n }\n pending.push((async () => {\n const maps = /** @type {Record<string, import('three').Texture>} */ ({});\n for (const role of ['baseColor', 'normalDepth', 'material', 'emissive', 'geometry']) {\n const info = Reflect.get(rawTextures, role);\n const index = info && typeof info === 'object' ? Reflect.get(info, 'index') : undefined;\n if (!Number.isInteger(index)) continue;\n maps[role] = await parser.getDependency('texture', index);\n }\n if (!maps.baseColor || !maps.normalDepth) {\n throw new Error('NEEDLE_mesh_impostor is missing a required atlas binding.');\n }\n bindings.set(object, {\n descriptor,\n maps: /** @type {any} */ (maps),\n });\n })());\n });\n await Promise.all(pending);\n upgraded += upgradeImpostorScene(\n root,\n bindings,\n this.options.features,\n this.options.renderer,\n this.options.performance ?? (this.options.features ? 'fixed' : 'auto'),\n );\n }\n this.options.onUpgrade?.(upgraded, result);\n }\n}\n\n/**\n * Registers the Needle impostor material plugin on a Three.js GLTFLoader.\n *\n * @template {import('three/addons/loaders/GLTFLoader.js').GLTFLoader} T\n * @param {T} loader\n * @param {ConstructorParameters<typeof NeedleImpostorLoaderPlugin>[1]=} options\n * @returns {T}\n */\nexport function registerNeedleImpostorLoader(loader, options = {}) {\n loader.register((parser) => new NeedleImpostorLoaderPlugin(parser, options));\n return loader;\n}\n\n/**\n * Compact GLSL runtime for Three versions before named TSL structs. It uses\n * the closest authored capture and reconstructs fragment depth without asking\n * the older node compiler to expand the modern structured graph.\n *\n * @param {ImpostorDescriptor} descriptor\n * @param {Parameters<typeof createPbrImpostorNodeMaterial>[1]} maps\n */\nfunction createCompatibleImpostorNodeMaterial(descriptor, maps) {\n const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';\n const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';\n const compactEmissive = descriptor.compression?.emissive === true;\n const boundsCount = descriptor.frames * descriptor.frames;\n const material = new ShaderMaterial({\n name: 'Needle PBR impostor WebGL compatibility',\n side: DoubleSide,\n transparent: false,\n depthTest: true,\n depthWrite: true,\n glslVersion: GLSL3,\n uniforms: {\n baseColorAtlas: { value: maps.baseColor },\n geometryAtlas: { value: maps.geometry ?? maps.normalDepth },\n viewBounds: {\n value: Array.from({ length: boundsCount }, (_, index) => new Vector4(\n descriptor.viewBounds[index * 4],\n descriptor.viewBounds[index * 4 + 1],\n descriptor.viewBounds[index * 4 + 2],\n descriptor.viewBounds[index * 4 + 3],\n )),\n },\n frames: { value: descriptor.frames },\n frameResolution: { value: descriptor.frameResolution },\n padding: { value: descriptor.padding },\n radius: { value: descriptor.radius },\n captureDirection: { value: new Vector3(...(descriptor.captureDirection ?? [0, 1, 0])) },\n },\n defines: {\n VIEW_BOUNDS_COUNT: boundsCount,\n FULL_SPHERE: descriptor.mapping === 'full' ? 1 : 0,\n SINGLE_VIEW: descriptor.mapping === 'single' ? 1 : 0,\n COMPACT_COLOR: compactLayout ? 1 : 0,\n COMPACT_EMISSIVE: compactEmissive ? 1 : 0,\n COMPRESSED_GEOMETRY: compressedGeometry ? 1 : 0,\n },\n vertexShader: /* glsl */ `\n out vec3 vPlaneLocal;\n #ifdef USE_INSTANCING\n flat out vec3 vCameraLocal;\n flat out mat4 vInstanceMatrix;\n #endif\n void main() {\n #ifdef USE_INSTANCING\n mat4 inverseModel = inverse(modelMatrix * instanceMatrix);\n vCameraLocal = (inverseModel * vec4(cameraPosition, 1.0)).xyz;\n vInstanceMatrix = instanceMatrix;\n #else\n mat4 inverseModel = inverse(modelMatrix);\n #endif\n mat4 cameraWorld = inverse(viewMatrix);\n vec3 rightLocal = normalize((inverseModel * vec4(cameraWorld[0].xyz, 0.0)).xyz);\n vec3 upLocal = normalize((inverseModel * vec4(cameraWorld[1].xyz, 0.0)).xyz);\n vPlaneLocal = rightLocal * position.x + upLocal * position.y;\n #ifdef USE_INSTANCING\n gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(vPlaneLocal, 1.0);\n #else\n gl_Position = projectionMatrix * modelViewMatrix * vec4(vPlaneLocal, 1.0);\n #endif\n }\n `,\n fragmentShader: /* glsl */ `\n uniform sampler2D baseColorAtlas;\n uniform sampler2D geometryAtlas;\n uniform vec4 viewBounds[VIEW_BOUNDS_COUNT];\n uniform float frames;\n uniform float frameResolution;\n uniform float padding;\n uniform float radius;\n uniform vec3 captureDirection;\n uniform mat4 modelMatrix;\n uniform mat4 modelViewMatrix;\n uniform mat4 projectionMatrix;\n in vec3 vPlaneLocal;\n #ifdef USE_INSTANCING\n flat in vec3 vCameraLocal;\n flat in mat4 vInstanceMatrix;\n #endif\n out vec4 fragColor;\n\n float nonZeroSign(float value) { return value < 0.0 ? -1.0 : 1.0; }\n vec2 directionToGrid(vec3 direction) {\n direction = normalize(direction);\n #if !FULL_SPHERE\n direction.y = max(direction.y, 0.000001);\n #endif\n direction /= abs(direction.x) + abs(direction.y) + abs(direction.z);\n #if FULL_SPHERE\n vec2 folded = vec2(\n nonZeroSign(direction.x) * (1.0 - abs(direction.z)),\n nonZeroSign(direction.z) * (1.0 - abs(direction.x))\n );\n return (direction.y < 0.0 ? folded : direction.xz) * 0.5 + 0.5;\n #else\n return vec2(direction.x + direction.z, direction.z - direction.x) * 0.5 + 0.5;\n #endif\n }\n vec3 gridToDirection(vec2 coordinate) {\n #if FULL_SPHERE\n float x = coordinate.x * 2.0 - 1.0;\n float z = coordinate.y * 2.0 - 1.0;\n float y = 1.0 - abs(x) - abs(z);\n if (y < 0.0) {\n float foldedX = nonZeroSign(x) * (1.0 - abs(z));\n float foldedZ = nonZeroSign(z) * (1.0 - abs(x));\n x = foldedX;\n z = foldedZ;\n }\n return normalize(vec3(x, y, z));\n #else\n return normalize(vec3(\n coordinate.x - coordinate.y,\n 1.0 - abs(coordinate.x - coordinate.y) - abs(-1.0 + coordinate.x + coordinate.y),\n -1.0 + coordinate.x + coordinate.y\n ));\n #endif\n }\n vec2 atlasUv(vec2 frame, vec2 frameUv) {\n float interiorPixels = max(frameResolution - padding * 2.0, 1.0);\n float interiorScale = interiorPixels / frameResolution;\n float gutterUv = padding / interiorPixels;\n vec2 insideCell = padding / frameResolution\n + clamp(frameUv, vec2(-gutterUv), vec2(1.0 + gutterUv)) * interiorScale;\n float halfTexel = 0.5001 / frameResolution;\n return (frame + clamp(insideCell, vec2(halfTexel), vec2(1.0 - halfTexel))) / frames;\n }\n vec4 sampleColorAtlas(vec2 coordinates) {\n vec2 size = vec2(textureSize(baseColorAtlas, 0));\n vec2 grid = vec2(frames);\n #if COMPACT_COLOR && COMPACT_EMISSIVE\n grid.x *= 2.0;\n #endif\n vec2 pixels = coordinates * size;\n float footprint = max(length(dFdx(pixels)), length(dFdy(pixels)));\n float gutter = padding * size.y / (frames * frameResolution);\n float lod = clamp(log2(max(footprint, 1.0)), 0.0, floor(log2(max(gutter, 1.0))));\n vec2 cell = floor(clamp(coordinates * grid, vec2(0.0), grid - 0.00001));\n vec2 guard = vec2(0.5001 * exp2(lod)) / size;\n vec2 safe = clamp(coordinates, cell / grid + guard, (cell + 1.0) / grid - guard);\n return textureLod(baseColorAtlas, safe, lod);\n }\n void main() {\n #ifdef USE_INSTANCING\n vec3 cameraLocal = vCameraLocal;\n #else\n vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;\n #endif\n vec3 cameraDirection = normalize(cameraLocal);\n #if SINGLE_VIEW\n vec2 frame = vec2(0.0);\n vec3 frameDirection = normalize(captureDirection);\n #else\n vec2 frame = clamp(\n floor(directionToGrid(cameraDirection) * (frames - 1.0) + 0.5),\n vec2(0.0),\n vec2(frames - 1.0)\n );\n vec3 frameDirection = gridToDirection(frame / (frames - 1.0));\n #endif\n vec3 referenceUp = abs(frameDirection.y) > 0.999 ? vec3(0.0, 0.0, -1.0) : vec3(0.0, 1.0, 0.0);\n vec3 right = normalize(cross(referenceUp, frameDirection));\n vec3 up = normalize(cross(frameDirection, right));\n int frameIndex = int(frame.y * frames + frame.x);\n vec4 bounds = viewBounds[frameIndex];\n float denominator = dot(cameraDirection, frameDirection);\n float safeDenominator = nonZeroSign(denominator) * max(abs(denominator), 0.05);\n vec3 framePlanePosition = vPlaneLocal - cameraDirection\n * (dot(vPlaneLocal, frameDirection) / safeDenominator);\n vec2 frameUv = (vec2(dot(framePlanePosition, right), dot(framePlanePosition, up))\n - bounds.xy) / (bounds.zw - bounds.xy);\n float interiorPixels = max(frameResolution - padding * 2.0, 1.0);\n float gutterUv = padding / interiorPixels;\n if (any(lessThan(frameUv, vec2(-gutterUv)))\n || any(greaterThan(frameUv, vec2(1.0 + gutterUv)))) discard;\n vec2 atlas = atlasUv(frame, frameUv);\n vec2 colorUv = atlas;\n #if COMPACT_COLOR\n colorUv.x *= COMPACT_EMISSIVE == 1 ? 0.5 : 1.0;\n #endif\n vec4 base = sampleColorAtlas(colorUv);\n vec4 geometry = texture(geometryAtlas, atlas);\n float contour = base.a;\n float depthValue;\n #if COMPRESSED_GEOMETRY\n vec2 packed = floor(geometry.rg * 255.0 + 0.5);\n depthValue = (packed.x * 4.0 + floor(packed.y / 85.0 + 0.5)) / 1023.0;\n contour = geometry.a;\n #else\n vec2 packed = floor(geometry.ba * 255.0 + 0.5);\n depthValue = (packed.x * 256.0 + packed.y) / 65535.0;\n #endif\n float width = max(fwidth(contour), 1.0 / 255.0);\n float coverage = smoothstep(0.5 - width, 0.5 + width, contour);\n if (coverage < 0.25) discard;\n vec2 plane = mix(bounds.xy, bounds.zw, frameUv);\n vec3 reconstructedLocal = right * plane.x + up * plane.y\n + frameDirection * (radius - depthValue * radius * 2.0);\n #ifdef USE_INSTANCING\n vec4 clip = projectionMatrix * modelViewMatrix * vInstanceMatrix * vec4(reconstructedLocal, 1.0);\n #else\n vec4 clip = projectionMatrix * modelViewMatrix * vec4(reconstructedLocal, 1.0);\n #endif\n gl_FragDepth = clip.z / clip.w * 0.5 + 0.5;\n fragColor = vec4(base.rgb, coverage);\n #if defined(TONE_MAPPING)\n fragColor.rgb = toneMapping(fragColor.rgb);\n #endif\n fragColor = linearToOutputTexel(fragColor);\n }\n `,\n });\n // Three defines USE_INSTANCING for the vertex stage only.\n material.onBeforeCompile = (shader) => {\n if (shader.instancing) shader.fragmentShader = `#define USE_INSTANCING\\n${shader.fragmentShader}`;\n };\n material.alphaToCoverage = true;\n material.toneMapped = true;\n material.userData.impostorShaderProfile = {\n interpolation: false,\n reprojection: false,\n depthWeights: false,\n perspectiveCorrection: false,\n cellCorrection: false,\n boundedReprojection: false,\n frameSamples: 1,\n raySamples: 0,\n depthSamples: 0,\n blendZone: descriptor.blendZone,\n };\n return material;\n}\n\n/**\n * @param {ImpostorDescriptor} descriptor\n * @param {{\n * baseColor: import('three').Texture,\n * normalDepth: import('three').Texture,\n * orm?: import('three').Texture | null,\n * emissive: import('three').Texture | null,\n * geometry?: import('three').Texture | null,\n * viewBounds: import('three').DataTexture,\n * }} maps\n * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures\n * @param {ImpostorRenderer=} renderer\n * @returns {MeshStandardNodeMaterial | ShaderMaterial}\n */\nexport function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, renderer) {\n if (!rendererSupportsImpostorNodeMaterials(renderer)) {\n return createCompatibleImpostorNodeMaterial(descriptor, maps);\n }\n const { effective: features, profile } = resolveImpostorRuntimeFeatures(descriptor, inputFeatures);\n const frames = float(descriptor.frames);\n const frameResolution = float(descriptor.frameResolution);\n const padding = float(descriptor.padding);\n const radius = float(descriptor.radius);\n const captureAlphaCutoff = float(descriptor.captureAlphaCutoff);\n // Source MASK/OPAQUE alpha has already been resolved during capture. At\n // multisampled silhouette edges, one covered sample is valid geometry even\n // though its resolved alpha is below the authored 0.5 contour. Reprojection\n // must retain that depth candidate; the SDF and final alpha-to-coverage pass\n // still decide whether the pixel contributes to the visible silhouette.\n // A literal, not a node expression: Three r186 caches a shared expression in\n // the first branch that reads it, so other branches compared against 0.\n const reprojectionSurfaceCutoff = descriptor.coverageEncoding === 'sdf-base-alpha'\n ? float(0.5)\n : float(Math.min(Number(descriptor.captureAlphaCutoff), 0.25));\n const blendCutoff = float((1 - profile.blendZone) * 0.5);\n const coarseSearchSteps = profile.raySamples;\n const fullSphere = descriptor.mapping === 'full';\n const singleView = descriptor.mapping === 'single';\n const singleCaptureDirection = vec3(...(descriptor.captureDirection ?? [0, 1, 0])).normalize();\n const baseColorAtlas = texture(maps.baseColor);\n const normalDepthAtlas = texture(maps.normalDepth);\n const geometryAtlas = texture(maps.geometry ?? maps.normalDepth);\n const ormAtlas = maps.orm ? texture(maps.orm) : null;\n const emissiveAtlas = maps.emissive ? texture(maps.emissive) : null;\n const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';\n const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';\n const compactEmissive = descriptor.compression?.emissive === true;\n const colorAtlasUv = (uvNode, emissive = false) => compactLayout\n ? vec2(\n uvNode.x.mul(compactEmissive ? 0.5 : 1).add(emissive && compactEmissive ? 0.5 : 0),\n uvNode.y,\n )\n : uvNode;\n const mapLod = (atlas, coordinates) => {\n const size = vec2(textureSize(atlas));\n const pixels = coordinates.mul(size);\n const footprint = max(pixels.dFdx().length(), pixels.dFdy().length());\n const gutter = padding.mul(size.y).div(frames.mul(frameResolution));\n return max(footprint, 1).log2().clamp(0, max(gutter, 1).log2().floor());\n };\n const sampleAtlas = (atlas, coordinates, lod = float(0), columns = frames) => {\n const size = vec2(textureSize(atlas));\n const grid = vec2(columns, frames);\n const cell = coordinates.mul(grid).clamp(0, grid.sub(0.00001)).floor();\n const guard = float(0.5001).mul(float(2).pow(lod)).div(size);\n const safe = coordinates.clamp(cell.div(grid).add(guard), cell.add(1).div(grid).sub(guard));\n return texture(atlas, safe).level(lod);\n };\n const colorColumns = frames.mul(compactLayout && compactEmissive ? 2 : 1);\n const sampleCapturedAlpha = (uvNode) => compressedGeometry\n ? sampleAtlas(baseColorAtlas, colorAtlasUv(uvNode), float(0), colorColumns).a\n : sampleAtlas(baseColorAtlas, uvNode).a;\n const sampleContour = (uvNode) => compressedGeometry\n ? texture(geometryAtlas, uvNode).level(0).a\n : descriptor.coverageEncoding === 'sdf-base-alpha'\n ? sampleAtlas(baseColorAtlas, uvNode).a\n : sampleAtlas(ormAtlas, uvNode).a;\n const viewBounds = uniformArray(\n Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new Vector4(\n descriptor.viewBounds[index * 4],\n descriptor.viewBounds[index * 4 + 1],\n descriptor.viewBounds[index * 4 + 2],\n descriptor.viewBounds[index * 4 + 3],\n )),\n 'vec4',\n );\n const atlasResolution = float(descriptor.frames * descriptor.frameResolution);\n\n const FrameBasis = NAMED_STRUCT_FACTORY(\n { right: 'vec3', up: 'vec3' },\n 'ImpostorFrameBasis',\n );\n const FrameSample = NAMED_STRUCT_FACTORY({\n base: 'vec4',\n surfaceAlpha: 'float',\n normalLocal: 'vec3',\n positionLocal: 'vec3',\n orm: 'vec3',\n emissive: 'vec3',\n contour: 'float',\n validity: 'float',\n strictValidity: 'float',\n rayError: 'float',\n footprint: 'float',\n }, 'ImpostorFrameSample');\n const BlendedSample = NAMED_STRUCT_FACTORY({\n base: 'vec4',\n normalLocal: 'vec3',\n positionLocal: 'vec3',\n orm: 'vec3',\n emissive: 'vec3',\n capturedCoverage: 'float',\n distanceCoverage: 'float',\n cropSupport: 'float',\n }, 'ImpostorBlendedSample');\n const basisMember = (value, name) => value.get(name);\n const frameMember = (value, name) => value.get(name);\n const blendedMember = (value, name) => value.get(name);\n\n const nonZeroSign = Fn(([value]) => value.lessThan(0).select(float(-1), float(1)), 'float');\n const buildFrameBasis = ([direction]) => {\n const referenceUp = abs(direction.y).greaterThan(0.999)\n .select(vec3(0, 0, -1), vec3(0, 1, 0));\n const right = referenceUp.cross(direction).normalize();\n return FrameBasis(right, direction.cross(right).normalize());\n };\n const frameBasis = Fn(buildFrameBasis);\n const gridToDirection = Fn(([coordinate]) => {\n const hemisphere = vec3(\n coordinate.x.sub(coordinate.y),\n float(1).sub(abs(coordinate.x.sub(coordinate.y))).sub(abs(float(-1).add(coordinate.x).add(coordinate.y))),\n float(-1).add(coordinate.x).add(coordinate.y),\n ).normalize();\n const fullX = coordinate.x.mul(2).sub(1).toVar();\n const fullZ = coordinate.y.mul(2).sub(1).toVar();\n const fullY = float(1).sub(abs(fullX)).sub(abs(fullZ)).toVar();\n const foldedX = nonZeroSign(fullX).mul(float(1).sub(abs(fullZ)));\n const foldedZ = nonZeroSign(fullZ).mul(float(1).sub(abs(fullX)));\n const full = fullY.lessThan(0)\n .select(vec3(foldedX, fullY, foldedZ), vec3(fullX, fullY, fullZ))\n .normalize();\n return fullSphere ? full : hemisphere;\n }, 'vec3');\n const directionToGrid = Fn(([inputDirection]) => {\n const direction = inputDirection.normalize().toVar();\n if (!fullSphere) {\n direction.y.assign(max(direction.y, 0.000001));\n }\n direction.divAssign(abs(direction.x).add(abs(direction.y)).add(abs(direction.z)));\n const hemisphere = vec2(direction.x.add(direction.z), direction.z.sub(direction.x));\n const folded = vec2(\n nonZeroSign(direction.x).mul(float(1).sub(abs(direction.z))),\n nonZeroSign(direction.z).mul(float(1).sub(abs(direction.x))),\n );\n const full = direction.y.lessThan(0).select(folded, direction.xz);\n return (fullSphere ? full : hemisphere).mul(0.5).add(0.5).clamp(0, 1);\n }, 'vec2');\n const atlasUv = Fn(([frame, frameUv]) => {\n const interiorPixels = max(frameResolution.sub(padding.mul(2)), 1);\n const interiorScale = interiorPixels.div(frameResolution);\n const gutterUv = padding.div(interiorPixels);\n const insideCell = padding.div(frameResolution).add(\n frameUv.clamp(gutterUv.negate(), float(1).add(gutterUv)).mul(interiorScale),\n );\n // Clamp to texel centers, not the mathematical cell edge. Clamp-to-edge\n // only protects the outside of the complete texture; it cannot protect\n // internal atlas cells. Sampling exactly on an internal boundary linearly\n // mixes two unrelated captured views and exposes the neighboring cell as\n // a faint rectangular card outline.\n const halfTexel = float(0.5001).div(frameResolution);\n return frame.add(insideCell.clamp(halfTexel, float(1).sub(halfTexel))).div(frames);\n }, 'vec2');\n const decodeDepth16 = Fn(([packed]) => {\n if (descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba') {\n const bytes = floor(packed.rg.mul(255).add(0.5));\n return bytes.x.mul(4).add(floor(bytes.y.div(85).add(0.5))).div(1023);\n }\n const bytes = floor(packed.ba.mul(255).add(0.5));\n return bytes.x.mul(256).add(bytes.y).div(65535);\n }, 'float');\n const loadDepth16 = Fn(([texel]) => decodeDepth16(textureLoad(\n geometryAtlas,\n ivec2(texel).clamp(ivec2(0), ivec2(atlasResolution.sub(1))),\n )), 'float');\n // Packed 16-bit depth cannot use hardware linear filtering: interpolating\n // the high/low bytes independently produces carry artifacts. Decode four\n // integer texels first and then bilinearly filter their scalar depths. The\n // previous nearest-depth lookup made a sub-pixel UV crossing alter the\n // reprojection root abruptly, which showed up as half-degree silhouette\n // flicker even though view weights were continuous.\n const sampleDepth16 = Fn(([uvNode]) => {\n const pixel = uvNode.mul(atlasResolution).sub(0.5);\n const base = floor(pixel);\n const fraction = fract(pixel);\n const lower = mix(\n loadDepth16(base),\n loadDepth16(base.add(vec2(1, 0))),\n fraction.x,\n );\n const upper = mix(\n loadDepth16(base.add(vec2(0, 1))),\n loadDepth16(base.add(1)),\n fraction.x,\n );\n return mix(lower, upper, fraction.y);\n }, 'float');\n const decodeOctahedral = Fn(([encoded]) => {\n const f = encoded.mul(2).sub(1).toVar();\n const value = vec3(f, float(1).sub(abs(f.x)).sub(abs(f.y))).toVar();\n const folded = vec2(\n float(1).sub(abs(value.y)).mul(nonZeroSign(value.x)),\n float(1).sub(abs(value.x)).mul(nonZeroSign(value.y)),\n );\n If(value.z.lessThan(0), () => {\n value.xy.assign(folded);\n });\n return value.normalize();\n }, 'vec3');\n const reconstructPosition = Fn(([frameUv, bounds, frameDirection, right, up, depthValue]) => {\n const plane = mix(bounds.xy, bounds.zw, frameUv);\n return right.mul(plane.x)\n .add(up.mul(plane.y))\n .add(frameDirection.mul(radius.sub(depthValue.mul(radius).mul(2))));\n }, 'vec3');\n // Each instance of an InstancedMesh holds the capture in its own space, so\n // the camera is brought there per instance, in the vertex stage.\n const local = (value, direction) => Fn((_, builder) => {\n const space = instanceSpace(builder);\n if (!space) return value;\n return direction ? space.toLocalDirection(value) : space.toLocalPoint(value);\n })();\n const perInstance = (name, value) => Fn((_, builder) => (\n instanceSpace(builder) ? varying(value, name) : value\n ))();\n const cameraLocal = local(modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz, false);\n // Match the physical card basis produced by Three's billboard helper. A\n // direction-derived world-up frame is equivalent away from the poles, but\n // becomes undefined at zenith/nadir and falls back to a fixed orientation.\n // The camera still has a valid screen-space roll there, so using its actual\n // right/up axes keeps sampling coordinates rotating with the source view.\n const cameraRightLocal = local(modelWorldMatrixInverse\n .mul(vec4(cameraWorldMatrix[0].xyz, 0)).xyz, true).normalize();\n const cameraUpLocal = local(modelWorldMatrixInverse\n .mul(vec4(cameraWorldMatrix[1].xyz, 0)).xyz, true).normalize();\n const cameraOutLocal = local(modelWorldMatrixInverse\n .mul(vec4(cameraWorldMatrix[2].xyz, 0)).xyz, true).normalize();\n const projectionCameraDirection = Fn(([], builder) => (\n builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal\n ), 'vec3')();\n // An upper-hemisphere atlas has no authored camera below the horizon. Keep\n // its sampling camera and sampling plane on that horizon. The display card\n // remains camera-facing: below the authored range it therefore shows the\n // last representable horizon view at a stable size instead of stretching\n // reprojection rays into a solid rectangle. It only fades at exact nadir.\n const horizontalCamera = vec3(\n projectionCameraDirection.x,\n 0,\n projectionCameraDirection.z,\n );\n const horizontalUp = vec3(cameraUpLocal.x, 0, cameraUpLocal.z);\n const horizonFromPosition = horizontalCamera.div(max(horizontalCamera.length(), 0.000001));\n const horizonFromCameraUp = horizontalUp.div(max(horizontalUp.length(), 0.000001));\n const horizonDirection = horizontalCamera.length().greaterThan(0.0001)\n .select(horizonFromPosition, horizonFromCameraUp);\n const cameraDirection = projectionCameraDirection;\n // There is no well-defined horizon azimuth at exact nadir. Preserve the\n // clamped horizon reconstruction through almost the entire lower hemisphere,\n // then remove the card within the final ~1.8 degrees instead of exposing an\n // arbitrary pole orientation as an opaque rectangle.\n const mappingVisibility = (fullSphere || singleView)\n ? float(1)\n : perInstance('vImpostorMappingVisibility', smoothstep(-1, -0.9995, cameraDirection.y));\n // Ease into the authored hemisphere over its first degree. Although the\n // directions on either side of zero are mathematically close, switching the\n // billboard basis exactly at zero moves rasterized edges by a pixel and\n // exposes a visible horizon seam.\n const horizonTransition = smoothstep(\n 0,\n HEMISPHERE_HORIZON_TRANSITION_SINE,\n max(cameraDirection.y, 0),\n );\n const clampedCameraDirection = (fullSphere || singleView)\n ? cameraDirection\n : mix(horizonDirection, cameraDirection, horizonTransition).normalize();\n const horizonBillboardUp = cross(horizonDirection, cameraRightLocal).normalize();\n const billboardUpLocal = (fullSphere || singleView)\n ? cameraUpLocal\n : mix(horizonBillboardUp, cameraUpLocal, horizonTransition).normalize();\n const samplingCameraPosition = clampedCameraDirection.mul(cameraLocal.length());\n const samplingCamera = perInstance('vImpostorSamplingCamera', samplingCameraPosition);\n const samplingBillboardPosition = cameraRightLocal.mul(positionGeometry.x)\n .add(billboardUpLocal.mul(positionGeometry.y));\n // A position node replaces the instanced position, so place the card here.\n const displayBillboardPosition = Fn((_, builder) => {\n const card = cameraRightLocal.mul(positionGeometry.x)\n .add(cameraUpLocal.mul(positionGeometry.y));\n return instanceSpace(builder)?.toMeshPoint(card) ?? card;\n })();\n const planeLocal = samplingBillboardPosition.toVarying('vImpostorPlaneLocal');\n // Use the same triangle in both shader stages. Per-pixel perspective\n // correction may change its weights, never which captures it addresses.\n const selectFrameTriangle = (centerGrid, orientation = null) => {\n const base = min(floor(centerGrid), vec2(frames.sub(2)));\n const centerFraction = centerGrid.sub(base);\n if (!orientation) {\n const foldCell = fullSphere\n ? bool(false)\n : base.x.add(base.y).equal(frames.sub(2));\n const baseDirection = gridToDirection(base.div(frames.sub(1)));\n const rightDirection = gridToDirection(base.add(vec2(1, 0)).div(frames.sub(1)));\n const upDirection = gridToDirection(base.add(vec2(0, 1)).div(frames.sub(1)));\n const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));\n const splitOnAntiDiagonal = foldCell.or(\n dot(rightDirection, upDirection).greaterThan(dot(baseDirection, diagonalDirection)),\n );\n orientation = splitOnAntiDiagonal.select(\n centerFraction.x.add(centerFraction.y).lessThanEqual(1).select(float(2), float(3)),\n centerFraction.x.greaterThan(centerFraction.y).select(float(0), float(1)),\n );\n }\n const horizontal = orientation.equal(0);\n const antiDiagonal = orientation.greaterThanEqual(2);\n const antiLower = orientation.equal(2);\n const right = base.add(vec2(1, 0));\n const up = base.add(vec2(0, 1));\n const diagonal = base.add(1);\n const frame0 = orientation.equal(3).select(diagonal, base);\n const frame1 = horizontal.or(antiLower).select(right, up);\n const frame2 = antiDiagonal.select(antiLower.select(up, right), diagonal);\n return { base, orientation, horizontal, antiDiagonal, antiLower, frame0, frame1, frame2 };\n };\n const vertexGrid = directionToGrid(samplingCameraPosition.normalize()).mul(frames.sub(1));\n const vertexTriangle = selectFrameTriangle(vertexGrid);\n // Carry the selected triangle across intact. Re-selecting it in the\n // fragment could pair a corner projection with the wrong atlas cell at a tie.\n const cardTriangle = varying(\n vec3(vertexGrid, vertexTriangle.orientation),\n 'vImpostorCardTriangle',\n ).setInterpolation('flat');\n // For steep views of an upper-hemisphere capture, align the sampled\n // planes nearer the bottom of the object. A center-plane rotation can\n // project the base of a tall asset to different places in adjacent views.\n const elevationSine = clampedCameraDirection.y;\n const cardAnchorHeight = fullSphere\n ? float(0)\n : elevationSine.mul(elevationSine)\n .mul(smoothstep(0.35, 0.8, elevationSine))\n .mul(descriptor.boundsMin[1] * 0.8);\n const cardAnchor = vec3(0, cardAnchorHeight, 0);\n const anchoredCardCorner = fullSphere ? samplingBillboardPosition : Fn(() => {\n const planeNormal = cross(cameraRightLocal, billboardUpLocal);\n // Move along the live camera ray so the rasterized card stays unchanged.\n const shift = cardAnchorHeight.mul(planeNormal.y)\n .div(max(dot(samplingCameraPosition, planeNormal), 0.000001));\n return mix(samplingBillboardPosition, samplingCameraPosition, shift);\n })();\n const projectCardCorner = Fn(([frame, corner, eye, anchor]) => {\n const normal = gridToDirection(frame.div(frames.sub(1))).toVar();\n const basis = frameBasis(normal).toVar();\n // Aim between the live and captured views. In the orthographic limit,\n // this rotates the card into the capture plane without stretching it.\n // Projecting directly along the live view makes oblique captures stretch\n // as they come into the blend.\n const projectionEye = eye.add(normal.mul(eye.length())).toVar();\n const eyeDepth = dot(projectionEye.sub(anchor), normal).toVar();\n const cornerDepth = dot(corner.sub(anchor), normal).toVar();\n const projected = corner.mul(eyeDepth).sub(projectionEye.mul(cornerDepth)).toVar();\n // Interpolate the homogeneous position, then divide in the fragment.\n // Dividing at the corners would skew the projective mapping diagonally.\n return vec3(dot(projected, basisMember(basis, 'right')),\n dot(projected, basisMember(basis, 'up')), eyeDepth.sub(cornerDepth));\n }).setLayout({\n name: 'projectImpostorCardCorner',\n type: 'vec3',\n inputs: [\n { name: 'frame', type: 'vec2' },\n { name: 'corner', type: 'vec3' },\n { name: 'eye', type: 'vec3' },\n { name: 'anchor', type: 'vec3' },\n ],\n });\n const createFrameSampler = (withReprojection, withCardProjection = false) => {\n const buildFrameSample = ([frame, planePosition, rayDirection, bounds, cardProjection]) => {\n const frameDirection = singleView\n ? singleCaptureDirection\n : gridToDirection(frame.div(frames.sub(1)));\n const basis = frameBasis(frameDirection);\n const right = basisMember(basis, 'right');\n const up = basisMember(basis, 'up');\n // Every atlas frame is an orthographic capture whose image plane passes\n // through the object center. Start from the intersection of the current\n // perspective camera ray and that frame plane. Projecting `planePosition`\n // directly only works when the selected capture matches the current view;\n // with sparse view grids it starts neighboring frames on different source\n // features and no finite depth iteration can put them back in register.\n const rayPlaneDenominator = dot(rayDirection, frameDirection);\n const safeRayPlaneDenominator = nonZeroSign(rayPlaneDenominator)\n .mul(max(abs(rayPlaneDenominator), 0.05));\n const framePlanePosition = planePosition.sub(rayDirection.mul(\n dot(planePosition, frameDirection).div(safeRayPlaneDenominator),\n ));\n const projectedPlane = withCardProjection\n ? cardProjection.xy.div(max(cardProjection.z, 0.000001))\n : vec2(dot(framePlanePosition, right), dot(framePlanePosition, up));\n const projectedFrameUv = projectedPlane.sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const interiorResolution = max(frameResolution.sub(padding.mul(2)), 1);\n const gutterUv = padding.div(interiorResolution);\n const minimumFrameUv = gutterUv.negate();\n const maximumFrameUv = float(1).add(gutterUv);\n const frameUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();\n const reconstructed = planePosition.toVar();\n const rootSolved = bool(!withReprojection).toVar();\n const strictRootSolved = bool(!withReprojection).toVar();\n if (withReprojection) {\n // A capture is a height field D(u). Parameterize the physical runtime\n // ray by the same normalized capture depth `s`: at a surface root,\n // `s == D(u(s))`. March from the capture camera toward the back, bracket\n // the first sign change, then refine that scalar equation. This is\n // standard relief mapping applied to an orthographic depth capture. The\n // previous soft closest-point average could blend two unrelated roots\n // and then jump between them as the camera moved.\n const rootFound = bool(false).toVar();\n const rootLower = float(0).toVar();\n const rootUpper = float(1).toVar();\n // Empty billboard pixels must not traverse the whole capture volume.\n // The source AABB is conservative, with one texel for filtered edges.\n const safeRay = vec3(\n nonZeroSign(rayDirection.x),\n nonZeroSign(rayDirection.y),\n nonZeroSign(rayDirection.z),\n ).mul(max(abs(rayDirection), vec3(1e-7)));\n const boundsGuard = radius.mul(2).div(interiorResolution);\n const boxT0 = vec3(...descriptor.boundsMin).sub(boundsGuard)\n .sub(planePosition).div(safeRay);\n const boxT1 = vec3(...descriptor.boundsMax).add(boundsGuard)\n .sub(planePosition).div(safeRay);\n const boxLow = min(boxT0, boxT1), boxHigh = max(boxT0, boxT1);\n const boxStart = max(boxLow.x, max(boxLow.y, boxLow.z));\n const boxEnd = min(boxHigh.x, min(boxHigh.y, boxHigh.z));\n const intersectsBounds = boxStart.lessThanEqual(boxEnd);\n const captureDepthAt = (t) => radius.sub(\n dot(planePosition.add(rayDirection.mul(t)), frameDirection),\n ).div(radius.mul(2));\n const depth0 = captureDepthAt(boxStart), depth1 = captureDepthAt(boxEnd);\n // UV is affine in capture depth. Clipping to the capture crop spends\n // the existing march budget on possible surfaces instead of empty space.\n const uvDepthSlope = vec2(dot(rayDirection, right), dot(rayDirection, up))\n .mul(radius.mul(-2).div(safeRayPlaneDenominator))\n .div(bounds.zw.sub(bounds.xy));\n const safeSlope = vec2(\n nonZeroSign(uvDepthSlope.x), nonZeroSign(uvDepthSlope.y),\n ).mul(max(abs(uvDepthSlope), vec2(1e-7)));\n const uvStart = projectedFrameUv.sub(uvDepthSlope.mul(0.5));\n const t0 = vec2(minimumFrameUv).sub(uvStart).div(safeSlope);\n const t1 = vec2(maximumFrameUv).sub(uvStart).div(safeSlope);\n const lower = min(t0, t1), upper = max(t0, t1);\n const searchStart = max(min(depth0, depth1), max(0, max(lower.x, lower.y)));\n const searchEnd = min(max(depth0, depth1), min(1, min(upper.x, upper.y)));\n const searchRange = max(searchEnd.sub(searchStart), 1e-6);\n const coarseStep = searchRange.div(coarseSearchSteps);\n const validateRoot = () => {\n If(rootSolved, () => {\n const at = atlasUv(frame, frameUv);\n const surface = reconstructPosition(frameUv, bounds, frameDirection, right, up, sampleDepth16(at));\n const closest = planePosition.add(rayDirection.mul(dot(surface.sub(planePosition), rayDirection)));\n const footprint = max(bounds.z.sub(bounds.x), bounds.w.sub(bounds.y)).div(interiorResolution);\n const nearestPixel = floor(at.mul(atlasResolution));\n const nearestDepth = loadDepth16(nearestPixel);\n const depthJump = abs(sampleDepth16(at).sub(nearestDepth)).mul(radius).mul(2);\n const discontinuity = bool(false).toVar();\n If(depthJump.greaterThan(footprint.mul(4)), () => {\n const neighbor = (offset) => loadDepth16(nearestPixel.add(offset).clamp(\n frame.mul(frameResolution), frame.add(1).mul(frameResolution).sub(1),\n ));\n // A steep plane can change depth arbitrarily fast. Unlike a slope\n // cap, second differences reject interpolated depth steps without\n // rejecting a continuous plane merely because it is steep.\n const curvature = max(\n abs(neighbor(vec2(-1, 0)).add(neighbor(vec2(1, 0))).sub(nearestDepth.mul(2))),\n abs(neighbor(vec2(0, -1)).add(neighbor(vec2(0, 1))).sub(nearestDepth.mul(2))),\n ).mul(radius).mul(2);\n discontinuity.assign(curvature.greaterThan(footprint.mul(4)));\n });\n If(surface.sub(closest).length().greaterThan(footprint.mul(4))\n .or(discontinuity)\n .or(sampleCapturedAlpha(at).lessThan(reprojectionSurfaceCutoff)), () => {\n rootFound.assign(false);\n rootSolved.assign(false);\n strictRootSolved.assign(false);\n });\n });\n };\n const refineRoot = () => {\n If(rootFound, () => {\n Loop(profile.depthSamples, () => {\n const searchDepth = rootLower.add(rootUpper).mul(0.5);\n const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));\n const searchRayPosition = planePosition.add(rayDirection.mul(\n searchPlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n const searchUv = vec2(\n dot(searchRayPosition, right),\n dot(searchRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))\n .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));\n const midpointIsUpper = bool(false).toVar();\n If(searchOutOfBounds.not(), () => {\n const searchAtlasUv = atlasUv(frame, searchUv);\n const searchCoverage = sampleCapturedAlpha(searchAtlasUv);\n const searchSurfaceDepth = sampleDepth16(searchAtlasUv);\n midpointIsUpper.assign(\n searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)\n .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),\n );\n });\n If(midpointIsUpper, () => {\n rootUpper.assign(searchDepth);\n });\n If(midpointIsUpper.not(), () => {\n rootLower.assign(searchDepth);\n });\n });\n const residualAt = (depth) => {\n const planeDepth = radius.sub(depth.mul(radius).mul(2));\n const position = planePosition.add(rayDirection.mul(\n planeDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator),\n ));\n const address = vec2(dot(position, right), dot(position, up))\n .sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n return depth.sub(sampleDepth16(atlasUv(frame,address)));\n };\n // A midpoint leaves large physical errors on a steep height field.\n // Secant interpolation is exact for a plane and stays in the bracket.\n const lowResidual = residualAt(rootLower), highResidual = residualAt(rootUpper);\n const difference = lowResidual.sub(highResidual);\n const fraction = lowResidual.div(\n nonZeroSign(difference).mul(max(abs(difference), 1e-8)),\n ).clamp(0, 1);\n const rootDepth = mix(rootLower,rootUpper,fraction);\n\n const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));\n const rootRayPosition = planePosition.add(rayDirection.mul(\n rootPlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n frameUv.assign(vec2(\n dot(rootRayPosition, right),\n dot(rootRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(\n minimumFrameUv,\n maximumFrameUv,\n ));\n });\n };\n const traceInterval = (steps, start = searchStart, end = searchEnd) => {\n const coarseStep = max(end.sub(start), 1e-6).div(float(steps));\n Loop({ start: 0, end: steps, type: 'int' }, ({ i }) => {\n If(rootFound.or(intersectsBounds.not()).or(end.lessThan(start)), () => { Break(); });\n const searchDepth = start.add(float(i).add(1).mul(coarseStep));\n const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));\n const searchRayPosition = planePosition.add(rayDirection.mul(\n searchPlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n const searchUv = vec2(\n dot(searchRayPosition, right),\n dot(searchRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))\n .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));\n If(searchOutOfBounds.not(), () => {\n const searchAtlasUv = atlasUv(frame, searchUv);\n const searchCoverage = sampleCapturedAlpha(searchAtlasUv);\n const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);\n If(hasSurface, () => {\n const searchSurfaceDepth = sampleDepth16(searchAtlasUv);\n const depthDelta = searchDepth.sub(searchSurfaceDepth);\n If(\n rootFound.not()\n .and(hasSurface)\n .and(depthDelta.greaterThanEqual(0)),\n () => {\n rootLower.assign(max(searchDepth.sub(coarseStep), 0));\n rootUpper.assign(searchDepth);\n rootFound.assign(true);\n rootSolved.assign(true);\n strictRootSolved.assign(true);\n refineRoot();\n if (features.boundedReprojection) validateRoot();\n },\n );\n });\n });\n });\n };\n traceInterval(int(coarseSearchSteps));\n // A fixed-point solution can recover a grazing ray with no sign bracket.\n // Retain it only after convergence inside captured coverage; blend-time\n // seed suppression still prevents an unrelated background layer.\n If(rootFound.not().and(intersectsBounds), () => {\n // A rejected march root must not seed itself back into validity.\n const iterativeUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();\n const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();\n const iterationResidual = float(1).toVar();\n const iterationValid = bool(true).toVar();\n Loop(profile.depthSamples * 2, () => {\n If(iterationValid, () => {\n const iterativePlaneDepth = radius.sub(iterativeDepth.mul(radius).mul(2));\n const iterativeRayPosition = planePosition.add(rayDirection.mul(\n iterativePlaneDepth.sub(dot(planePosition, frameDirection))\n .div(safeRayPlaneDenominator),\n ));\n const nextUv = vec2(\n dot(iterativeRayPosition, right),\n dot(iterativeRayPosition, up),\n ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));\n const nextOutOfBounds = any(nextUv.lessThan(vec2(minimumFrameUv)))\n .or(any(nextUv.greaterThan(vec2(maximumFrameUv))));\n If(nextOutOfBounds, () => {\n iterationValid.assign(false);\n });\n If(nextOutOfBounds.not(), () => {\n const nextAtlasUv = atlasUv(frame, nextUv);\n const nextCoverage = sampleCapturedAlpha(nextAtlasUv);\n const nextDepth = sampleDepth16(nextAtlasUv);\n iterationResidual.assign(abs(nextDepth.sub(iterativeDepth)));\n iterativeUv.assign(nextUv);\n iterativeDepth.assign(nextDepth);\n If(nextCoverage.lessThan(reprojectionSurfaceCutoff), () => {\n iterationValid.assign(false);\n });\n });\n });\n });\n If(\n iterationValid.and(iterationResidual.lessThanEqual(coarseStep)),\n () => {\n frameUv.assign(iterativeUv);\n rootSolved.assign(true);\n if (features.boundedReprojection) validateRoot();\n },\n );\n });\n }\n const uvNode = atlasUv(frame, frameUv);\n reconstructed.assign(reconstructPosition(\n frameUv,\n bounds,\n frameDirection,\n right,\n up,\n sampleDepth16(uvNode),\n ));\n const shadingSample = sampleAtlas(normalDepthAtlas, uvNode, mapLod(normalDepthAtlas, uvNode));\n const geometrySample = compressedGeometry\n ? texture(geometryAtlas, uvNode).level(0)\n : null;\n const viewNormal = decodeOctahedral(shadingSample.rg);\n const normal = right.mul(viewNormal.x)\n .add(up.mul(viewNormal.y))\n .add(frameDirection.mul(viewNormal.z))\n .normalize();\n // Captures face-forward double-sided source normals. Neighboring views of\n // a thin card can therefore encode opposite local directions; averaging\n // those vectors collapses toward zero and creates dark foliage splotches.\n // Reorient every contributing normal into the runtime view hemisphere\n // before interpolation. Exact capture views are unchanged.\n const faceForwardNormal = dot(normal, rayDirection).lessThan(0)\n .select(normal.negate(), normal);\n const closestRayPoint = planePosition.add(\n rayDirection.mul(dot(reconstructed.sub(planePosition), rayDirection)),\n );\n const footprint = max(\n bounds.z.sub(bounds.x),\n bounds.w.sub(bounds.y),\n ).div(interiorResolution);\n const rayError = reconstructed.sub(closestRayPoint).length();\n const finalFrameEdgeDistance = min(\n min(frameUv.x.sub(minimumFrameUv), frameUv.y.sub(minimumFrameUv)),\n min(maximumFrameUv.sub(frameUv.x), maximumFrameUv.sub(frameUv.y)),\n );\n // Validate the address that actually supplies the reconstructed surface.\n // Using the pre-reprojection center-plane address here erased precisely the\n // deep features that the ray solve had recovered near a tight crop edge.\n const boundsConfidence = smoothstep(\n 0,\n float(1).div(interiorResolution),\n finalFrameEdgeDistance,\n );\n // Reprojection confidence fades across a bounded texel interval instead\n // of switching at one residual. The outer bound still rejects a different\n // depth layer, while the continuous interval prevents thin features from\n // changing reconstruction paths after a sub-degree camera move.\n const alignedConfidence = float(1).sub(smoothstep(\n REPROJECTION_CONFIDENCE_INNER_TEXELS,\n REPROJECTION_CONFIDENCE_OUTER_TEXELS,\n rayError.div(max(footprint, 0.000001)),\n ));\n const validFloat = boundsConfidence.mul(\n withReprojection\n ? alignedConfidence.mul(rootSolved)\n : float(1),\n );\n const strictValidFloat = boundsConfidence.mul(\n withReprojection\n ? alignedConfidence.mul(strictRootSolved)\n : float(1),\n );\n const colorUv = colorAtlasUv(uvNode);\n const baseColor = sampleAtlas(baseColorAtlas, colorUv, mapLod(baseColorAtlas, colorUv), colorColumns);\n const capturedAlpha = sampleCapturedAlpha(uvNode);\n const orm = compactLayout\n ? vec4(geometrySample.b, shadingSample.b, shadingSample.a, 1)\n : ormAtlas\n ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode))\n : vec4(\n descriptor.material.occlusion,\n descriptor.material.roughness,\n descriptor.material.metalness,\n 1,\n );\n // The signed-distance contour must not shift with minification. Only the\n // material channels use mip LOD; coverage keeps its authored level-zero\n // values and performs screen-space antialiasing after view interpolation.\n const coverage = sampleContour(uvNode);\n const resolvedValidity = validFloat;\n return FrameSample(\n // Validity is a blend weight, not an attribute. Premultiplying both the\n // sampled color/alpha here and the frame weight below applied crop\n // confidence twice; low-confidence crop-edge samples consequently\n // rendered as black outlines instead of fading away.\n vec4(baseColor.rgb, coverage),\n capturedAlpha,\n faceForwardNormal,\n reconstructed,\n orm.rgb,\n emissiveAtlas\n ? sampleAtlas(emissiveAtlas, colorAtlasUv(uvNode, true), mapLod(emissiveAtlas, colorAtlasUv(uvNode, true)), colorColumns).rgb\n : vec3(0),\n coverage,\n resolvedValidity,\n strictValidFloat,\n rayError,\n footprint,\n );\n };\n // Share the expensive frame search across the three selected captures.\n // Resolve uniform-array bounds at the call site for both TSL backends.\n // Three reuses a layout function's generated code for every builder of a\n // backend, but this one reads the atlases from its closure: a second\n // builder, such as the shadow pass, would get code naming texture bindings\n // it never declared. One function per builder still shares it per shader.\n /** @type {WeakMap<object, ReturnType<typeof Fn>>} */\n const functions = new WeakMap();\n return (/** @type {object} */ builder) => {\n let sampleFrame = functions.get(builder);\n if (!sampleFrame) {\n sampleFrame = Fn(buildFrameSample).setLayout({\n name: withReprojection ? 'sampleReprojectedImpostorFrame' : withCardProjection\n ? 'sampleProjectedImpostorCard' : 'samplePlanarImpostorFrame',\n type: 'ImpostorFrameSample',\n inputs: [\n { name: 'frame', type: 'vec2' },\n { name: 'planePosition', type: 'vec3' },\n { name: 'rayDirection', type: 'vec3' },\n { name: 'bounds', type: 'vec4' },\n ...(withCardProjection ? [{ name: 'cardProjection', type: 'vec3' }] : []),\n ],\n });\n functions.set(builder, sampleFrame);\n }\n return (frame, planePosition, rayDirection, cardProjection) => sampleFrame(\n frame, planePosition, rayDirection,\n viewBounds.element(int(frame.y.mul(frames).add(frame.x))),\n ...(withCardProjection ? [cardProjection] : []),\n );\n };\n };\n const planarFrameSamplers = createFrameSampler(false);\n const reprojectedFrameSamplers = features.reprojection ? createFrameSampler(true) : null;\n const cardFrameSamplers = features.interpolation && features.perspectiveCorrection && !features.reprojection\n ? createFrameSampler(false, true)\n : null;\n const buildBlendedSample = ([], builder) => {\n const samplePlanarFrame = planarFrameSamplers(builder);\n const sampleReprojectedFrame = reprojectedFrameSamplers ? reprojectedFrameSamplers(builder) : null;\n // An upper-hemisphere atlas has no authored views below the horizon.\n // Project both frame selection and depth rays onto that horizon together;\n // clamping selection alone while retaining a below-ground ray makes the\n // reprojection solver pull samples out of their frames.\n const samplingCameraLocal = samplingCamera;\n const centerViewDirection = samplingCameraLocal.normalize();\n const usePerspectiveCorrection = features.perspectiveCorrection\n && builder.camera.isPerspectiveCamera;\n const rayDirection = usePerspectiveCorrection\n ? samplingCameraLocal.sub(planeLocal).normalize()\n : centerViewDirection;\n const sampleCardFrame = usePerspectiveCorrection && cardFrameSamplers\n ? cardFrameSamplers(builder)\n : null;\n if (singleView) {\n const singleFrame = vec2(0, 0);\n const raw = features.reprojection\n ? sampleReprojectedFrame(singleFrame, planeLocal, rayDirection)\n : samplePlanarFrame(singleFrame, planeLocal, rayDirection);\n // A one-view impostor has no neighboring capture that can fill a ray\n // which leaves the authored crop or fails to intersect its depth field.\n // `sampleReprojectedFrame` applies the same optional capture-domain\n // constraint used by every frame count; this branch only reduces the\n // already-resolved sample to the common blended representation.\n const validity = frameMember(raw, 'validity');\n const capturedCoverage = frameMember(raw, 'surfaceAlpha').mul(validity);\n const distanceCoverage = min(\n frameMember(raw, 'contour'),\n capturedCoverage,\n );\n return BlendedSample(\n frameMember(raw, 'base'),\n frameMember(raw, 'normalLocal'),\n frameMember(raw, 'positionLocal'),\n frameMember(raw, 'orm'),\n frameMember(raw, 'emissive'),\n capturedCoverage,\n distanceCoverage,\n validity,\n );\n }\n const centerGrid = sampleCardFrame\n ? cardTriangle.xy\n : directionToGrid(centerViewDirection).mul(frames.sub(1));\n // Match every card point to a capture along its physical point-to-camera\n // ray. Adding the card offset instead mirrors this correction: a shallow\n // box makes that inversion visible immediately on its near/far corners.\n const perspectiveGrid = usePerspectiveCorrection\n ? directionToGrid(\n samplingCameraLocal.add(planeLocal.mul(PERSPECTIVE_RAY_PLANE_SIGN)).normalize(),\n ).mul(frames.sub(1))\n : centerGrid;\n const { base, horizontal, antiDiagonal, antiLower, frame0, frame1, frame2 } = selectFrameTriangle(\n centerGrid, sampleCardFrame ? cardTriangle.z : null,\n );\n const fraction = (features.cellCorrection ? perspectiveGrid : centerGrid).sub(base);\n const ordinaryWeights = horizontal.select(\n vec3(float(1).sub(fraction.x), fraction.x.sub(fraction.y), fraction.y),\n vec3(float(1).sub(fraction.y), fraction.y.sub(fraction.x), fraction.x),\n );\n const antiWeights = antiLower.select(\n vec3(float(1).sub(fraction.x).sub(fraction.y), fraction.x, fraction.y),\n vec3(fraction.x.add(fraction.y).sub(1), float(1).sub(fraction.x), float(1).sub(fraction.y)),\n );\n const weights = max(antiDiagonal.select(antiWeights, ordinaryWeights), vec3(0)).toVar();\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n // Compact angular support: on each triangle edge, `blendZone` is the\n // fraction over which both endpoint captures contribute. Unlike exponent\n // sharpening, this gives capture vertices a real single-view neighborhood\n // instead of letting tiny contributors affect virtually the whole cell.\n // Planar captures need more overlap to move between offset contours.\n const angularCutoff = features.reprojection ? blendCutoff : blendCutoff.mul(0.35);\n weights.assign(max(weights.sub(angularCutoff), vec3(0)));\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n if (!features.interpolation) {\n const frame0Nearest = weights.x.greaterThanEqual(weights.y)\n .and(weights.x.greaterThanEqual(weights.z));\n const nearestFrame = frame0Nearest.select(\n frame0,\n weights.y.greaterThanEqual(weights.z).select(frame1, frame2),\n );\n const raw = samplePlanarFrame(nearestFrame, planeLocal, rayDirection);\n return BlendedSample(\n frameMember(raw, 'base'),\n frameMember(raw, 'normalLocal'),\n frameMember(raw, 'positionLocal'),\n frameMember(raw, 'orm'),\n frameMember(raw, 'emissive'),\n frameMember(raw, 'surfaceAlpha'),\n frameMember(raw, 'surfaceAlpha'),\n frameMember(raw, 'validity'),\n );\n }\n const resolveFrame = (frame, key) => {\n if (sampleCardFrame) {\n const corner = projectCardCorner(\n vertexTriangle[key], anchoredCardCorner, samplingCameraPosition, cardAnchor,\n );\n return sampleCardFrame(frame, planeLocal, rayDirection, varying(corner, 'vImpostorCard_' + key));\n }\n return (sampleReprojectedFrame ?? samplePlanarFrame)(frame, planeLocal, rayDirection);\n };\n const a = resolveFrame(frame0, 'frame0');\n const b = resolveFrame(frame1, 'frame1');\n const c = resolveFrame(frame2, 'frame2');\n const angularWeights = weights.toVar('impostorAngularWeights');\n if (features.depthWeights) {\n // A reprojected frame sample only represents this camera ray while its\n // residual lies inside the source texel's physical footprint. A\n // half-texel Gaussian retains subpixel agreement while decisively\n // rejecting a neighboring frame whose reconstructed surface belongs\n // to another depth layer. Wider kernels visibly duplicate sparse-view\n // silhouettes even though their barycentric weights are correct.\n const residual = vec3(\n frameMember(a, 'rayError').div(frameMember(a, 'footprint')),\n frameMember(b, 'rayError').div(frameMember(b, 'footprint')),\n frameMember(c, 'rayError').div(frameMember(c, 'footprint')),\n ).div(0.5);\n // Never let residual weighting amplify an almost-zero barycentric\n // contributor into the sole visible frame. A small factor floor keeps\n // the view-space prior authoritative and removes isolated fold-cell\n // fragments without introducing a hard angular cutoff.\n weights.mulAssign(max(exp(residual.mul(residual).mul(-0.5)), vec3(0.05)));\n }\n // Residual weighting chooses among frames; it is not transparency. Keep\n // the attribute weights normalized so a uniform residual cannot darken\n // otherwise opaque material channels.\n weights.divAssign(max(dot(weights, vec3(1)), 0.0001));\n // Snapshot the depth-aware visibility distribution before alpha and crop\n // confidence mutate the attribute weights below.\n const visibilityWeights = weights.toVar('impostorVisibilityWeights');\n const resolvedSampleValidity = vec3(\n frameMember(a, 'validity'),\n frameMember(b, 'validity'),\n frameMember(c, 'validity'),\n );\n const strictSampleValidity = vec3(\n frameMember(a, 'strictValidity'),\n frameMember(b, 'strictValidity'),\n frameMember(c, 'strictValidity'),\n );\n // A converged seed is only a disocclusion fill. Fade every seed out over\n // the first 1% of bounded-root support so a background fixed point cannot\n // appear as a second layer behind valid geometry.\n const strictSupport = dot(angularWeights, strictSampleValidity);\n const seedValidity = max(resolvedSampleValidity.sub(strictSampleValidity), vec3(0));\n const seedWeight = float(1).sub(smoothstep(0, 0.01, strictSupport));\n const sampleValidity = strictSampleValidity.add(seedValidity.mul(seedWeight));\n const surfaceAlpha = vec3(\n frameMember(a, 'surfaceAlpha'),\n frameMember(b, 'surfaceAlpha'),\n frameMember(c, 'surfaceAlpha'),\n );\n const largestAngularWeight = max(\n angularWeights.x,\n max(angularWeights.y, angularWeights.z),\n );\n const transition = smoothstep(\n 0,\n 0.5,\n float(1).sub(largestAngularWeight),\n ).toVar('impostorCoverageTransition');\n weights.mulAssign(surfaceAlpha).mulAssign(sampleValidity);\n const capturedCoverage = dot(weights, vec3(1)).toVar();\n // Prefer the better-aligned texture sooner. Keeping these weights out of\n // the contour, lighting normals and depth lets those transition smoothly.\n const textureWeights = weights.mul(weights).toVar();\n textureWeights.divAssign(max(dot(textureWeights, vec3(1)), 0.00000001));\n weights.divAssign(max(capturedCoverage, 0.0001));\n const weighted = (field, blend = weights) => frameMember(a, field).mul(blend.x)\n .add(frameMember(b, field).mul(blend.y))\n .add(frameMember(c, field).mul(blend.z));\n // A weighted average of inside/outside SDFs makes whole features cross the\n // 0.5 contour together near a frame bisector. Normalized log-sum-exp acts\n // as a smooth union: it preserves thin features and equals the authored\n // SDF when one view has unit weight.\n // Keep the angular width of an unmatched contour contribution roughly\n // constant as view density changes. Sparse grids need a stronger union to\n // retain disoccluded thin parts; dense grids can use a near-linear blend,\n // preventing a tiny-weight frame from popping in a whole feature. This is\n // derived only from sampling density, never from asset classification.\n // The planar warp can leave nearby features slightly misaligned. A\n // gentler union keeps those contours from briefly reproducing both views.\n const contourSharpness = impostorContourUnionSharpness(descriptor.frames)\n * (features.reprojection ? 1 : 0.5);\n // A contour from a newly entering capture must begin as an ordinary\n // weighted SDF contribution. Applying the full smooth-union temperature\n // at an infinitesimal angular weight makes an entire disoccluded feature\n // cross the alpha mask in one sub-degree step. Ramp to the preserving\n // union only near a balanced transition; exact capture neighborhoods stay\n // exact and the blend-zone boundary remains visually continuous.\n const effectiveContourSharpness = mix(\n float(0.01),\n float(contourSharpness),\n transition,\n );\n const coverageContributions = visibilityWeights.mul(sampleValidity)\n .toVar('impostorCoverageContributions');\n const coverageSupport = dot(coverageContributions, vec3(1))\n .toVar('impostorCoverageSupport');\n const coverageDistanceSamples = vec3(\n frameMember(a, 'contour'),\n frameMember(b, 'contour'),\n frameMember(c, 'contour'),\n );\n const signedDistances = coverageDistanceSamples.sub(0.5);\n let edgeDistance;\n if (features.reprojection) {\n // Fold the threshold into the smooth union so it has the same zero\n // crossing as log-sum-exp without taking a logarithm.\n edgeDistance = dot(\n coverageContributions, exp(signedDistances.mul(effectiveContourSharpness)).sub(1),\n ).div(max(coverageSupport, 0.0001).mul(effectiveContourSharpness));\n } else {\n // Missing planar crops vote outside. Renormalizing their weights away\n // lets a barely active view reveal a whole disconnected silhouette.\n const cropDistances = mix(vec3(-0.5), signedDistances, sampleValidity).toVar();\n // A mild quadratic bias retains fine silhouettes without bringing\n // whole regions across the threshold together in sparse view blends.\n const unionBias = min(effectiveContourSharpness.mul(0.4), 1);\n edgeDistance = dot(visibilityWeights, cropDistances.add(cropDistances.mul(cropDistances).mul(unionBias)));\n }\n return BlendedSample(\n weighted('base', textureWeights),\n weighted('normalLocal').normalize(),\n weighted('positionLocal'),\n weighted('orm'),\n weighted('emissive', textureWeights),\n capturedCoverage,\n edgeDistance.add(0.5),\n coverageSupport,\n );\n };\n const blendImpostor = Fn(buildBlendedSample);\n\n const sample = blendImpostor().toVar('impostorSample');\n // Lighting, depth and shadows work in the mesh's space.\n const capturedPosition = Fn((_, builder) => {\n const position = blendedMember(sample, 'positionLocal');\n return instanceSpace(builder)?.fragment.toMeshPoint(position) ?? position;\n })().toVar('impostorCapturedPosition');\n const capturedNormal = Fn((_, builder) => {\n const normal = blendedMember(sample, 'normalLocal');\n return instanceSpace(builder)?.fragment.toMeshNormal(normal) ?? normal;\n })();\n const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(capturedPosition, 1)).xyz;\n const material = new CapturedSurfaceMaterial({\n name: 'Needle PBR impostor TSL',\n side: DoubleSide,\n transparent: false,\n depthTest: true,\n depthWrite: true,\n });\n const distanceCoverage = blendedMember(sample, 'distanceCoverage');\n const coverageWidth = max(fwidth(distanceCoverage), 1 / 255);\n const screenDistanceCoverage = smoothstep(\n float(0.5).sub(coverageWidth),\n float(0.5).add(coverageWidth),\n distanceCoverage,\n );\n const screenCoverage = screenDistanceCoverage.mul(mappingVisibility);\n // Use a local-space billboard position instead of a clip-space vertex node.\n // Three's shadow override copies `positionNode`/`castShadowPositionNode`, but\n // not `vertexNode`; the latter therefore made the shadow pass rasterize an\n // unrotated card while writing reconstructed fragment depth. Keeping the\n // card position in local space makes color, depth, and shadow passes share\n // the same camera-facing geometry (the shadow camera during a shadow pass).\n material.positionNode = displayBillboardPosition;\n material.castShadowPositionNode = displayBillboardPosition;\n const multisampleCoverage = Fn(([], builder) => (\n rendererUsesMultisampleCoverage(builder.renderer) ? screenCoverage : float(1)\n ))();\n material.colorNode = vec4(blendedMember(sample, 'base').rgb, multisampleCoverage);\n material.normalNode = transformNormalToView(capturedNormal);\n material.aoNode = blendedMember(sample, 'orm').r;\n material.roughnessNode = blendedMember(sample, 'orm').g;\n material.metalnessNode = blendedMember(sample, 'orm').b;\n material.emissiveNode = blendedMember(sample, 'emissive');\n // Values below one four-sample alpha-to-coverage quantum cannot contribute\n // stable spatial coverage. In the soft 0.25\u20130.5 transition, also require\n // meaningful pre-normalization crop support: otherwise a nearly rejected\n // frame is promoted to a faint rectangular card outline. Opaque contour\n // samples bypass that gate so real thin features retain silhouette quality.\n const cropSupported = blendedMember(sample, 'cropSupport').greaterThanEqual(0.25);\n // A filter footprint can reach past every contributing capture. Such\n // fragments have no captured color and would leave a dark outline.\n // Depth reconstruction also needs enough occupancy to reject a stray root\n // from a low-weight capture. Make that a mask so it cannot fade solid pixels.\n const captured = blendedMember(sample, 'capturedCoverage')\n .greaterThanEqual(features.reprojection ? 0.25 : 0.0001);\n const solidContour = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);\n material.maskNode = Fn(([], builder) => {\n if (!rendererUsesMultisampleCoverage(builder.renderer)) return solidContour.and(captured);\n return screenCoverage.greaterThanEqual(0.25).and(\n screenCoverage.greaterThanEqual(0.5).or(cropSupported),\n ).and(captured);\n })();\n material.maskShadowNode = solidContour.and(captured);\n material.alphaToCoverage = true;\n material.capturedPositionNode = capturedPosition;\n // Offset only the shadow writer: different capture views can disagree slightly.\n material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);\n material.receivedShadowPositionNode = reconstructedWorldPosition;\n material.toneMapped = true;\n material.userData.impostorShaderProfile = profile;\n bindTextureSlot(material, 'baseColorAtlas', maps.baseColor, [baseColorAtlas, ...(compactLayout && compactEmissive && emissiveAtlas ? [emissiveAtlas] : [])], value => {\n maps.baseColor = value;\n if (compactLayout && compactEmissive) maps.emissive = value;\n if (material.userData.impostor) {\n material.userData.impostor.atlases.baseColor = value;\n if (compactLayout && compactEmissive) material.userData.impostor.atlases.emissive = value;\n }\n });\n bindTextureSlot(material, 'normalDepthAtlas', maps.normalDepth, [normalDepthAtlas, ...(compactLayout && ormAtlas ? [ormAtlas] : []), ...(!compressedGeometry ? [geometryAtlas] : [])], value => {\n maps.normalDepth = value;\n if (compactLayout) maps.orm = value;\n if (material.userData.impostor) {\n material.userData.impostor.atlases.normalDepth = value;\n if (compactLayout) material.userData.impostor.atlases.orm = value;\n }\n });\n if (!compactLayout && maps.orm && ormAtlas) bindTextureSlot(material, 'ormAtlas', maps.orm, [ormAtlas], value => { maps.orm = value; });\n if (!compactLayout && maps.emissive && emissiveAtlas) bindTextureSlot(material, 'emissiveAtlas', maps.emissive, [emissiveAtlas], value => { maps.emissive = value; });\n return material;\n}\n", "// @ts-check\n\n/** Primitive extension declaring an explicitly-bound Needle mesh impostor. */\nexport const NEEDLE_MESH_IMPOSTOR = 'NEEDLE_mesh_impostor';\n\n/**\n * @typedef {object} ImpostorDescriptor\n * @property {1} version\n * @property {'hemisphere' | 'full' | 'single'} mapping\n * @property {number} frames\n * @property {readonly [number, number, number]=} captureDirection\n * @property {number} frameResolution\n * @property {number} padding\n * @property {number} radius\n * @property {readonly [number, number, number]} boundsMin\n * @property {readonly [number, number, number]} boundsMax\n * @property {readonly [number, number, number]} center\n * @property {readonly number[]} viewBounds\n * @property {'captured-alpha+sdf-material' | 'sdf-base-alpha'} coverageEncoding\n * @property {number} captureAlphaCutoff\n * @property {number} alphaCutoff\n * @property {number} blendZone\n * @property {number} parallaxSteps\n * @property {boolean} depthDerivedWeights\n * @property {boolean} castShadow\n * @property {boolean} receiveShadow\n * @property {{occlusion: number, roughness: number, metalness: number}} material\n * @property {{version: 4, layout: 'compact-atlas-v4', depthEncoding: 'lossless-geometry10-rgba', materialFrameResolution: number, emissive: boolean}=} compression\n */\n\n/** @param {unknown} value @returns {ImpostorDescriptor | null} */\nexport function parseImpostorDescriptor(value) {\n if (!value || typeof value !== 'object') return null;\n const descriptor = /** @type {Partial<ImpostorDescriptor>} */ (value);\n if (\n descriptor.version !== 1\n || (descriptor.mapping !== 'hemisphere' && descriptor.mapping !== 'full' && descriptor.mapping !== 'single')\n || !isPositiveInteger(descriptor.frames)\n || (descriptor.mapping === 'single'\n ? (descriptor.frames !== 1 || !isUnitVec3(descriptor.captureDirection))\n : false)\n || !isPositiveInteger(descriptor.frameResolution)\n || !isNonNegativeInteger(descriptor.padding)\n || !isPositiveFinite(descriptor.radius)\n || (descriptor.compression !== undefined && (\n descriptor.compression.version !== 4\n || descriptor.compression.layout !== 'compact-atlas-v4'\n || descriptor.compression.depthEncoding !== 'lossless-geometry10-rgba'\n || !isPositiveInteger(descriptor.compression.materialFrameResolution)\n || typeof descriptor.compression.emissive !== 'boolean'\n ))\n || !isFiniteVec3(descriptor.boundsMin)\n || !isFiniteVec3(descriptor.boundsMax)\n || !isFiniteVec3(descriptor.center)\n || !Array.isArray(descriptor.viewBounds)\n || descriptor.viewBounds.length !== (descriptor.frames ?? 0) * (descriptor.frames ?? 0) * 4\n || !descriptor.viewBounds.every(Number.isFinite)\n || (descriptor.coverageEncoding !== 'captured-alpha+sdf-material'\n && descriptor.coverageEncoding !== 'sdf-base-alpha')\n || !isUnitInterval(descriptor.captureAlphaCutoff)\n || !isUnitInterval(descriptor.alphaCutoff)\n || !isBlendZone(descriptor.blendZone)\n || !isNonNegativeInteger(descriptor.parallaxSteps)\n || typeof descriptor.depthDerivedWeights !== 'boolean'\n || typeof descriptor.castShadow !== 'boolean'\n || typeof descriptor.receiveShadow !== 'boolean'\n || !descriptor.material\n || !isUnitInterval(descriptor.material.occlusion)\n || !isUnitInterval(descriptor.material.roughness)\n || !isUnitInterval(descriptor.material.metalness)\n ) return null;\n const valid = /** @type {ImpostorDescriptor} */ (descriptor);\n return {\n version: 1,\n mapping: valid.mapping,\n frames: valid.frames,\n ...(valid.mapping === 'single' ? { captureDirection: valid.captureDirection } : {}),\n frameResolution: valid.frameResolution,\n padding: valid.padding,\n radius: valid.radius,\n boundsMin: valid.boundsMin,\n boundsMax: valid.boundsMax,\n center: valid.center,\n viewBounds: valid.viewBounds,\n coverageEncoding: valid.coverageEncoding,\n captureAlphaCutoff: valid.captureAlphaCutoff,\n alphaCutoff: valid.alphaCutoff,\n blendZone: valid.blendZone,\n parallaxSteps: valid.parallaxSteps,\n depthDerivedWeights: valid.depthDerivedWeights,\n castShadow: valid.castShadow,\n receiveShadow: valid.receiveShadow,\n material: valid.material,\n ...(valid.compression ? { compression: valid.compression } : {}),\n };\n}\n\n/** @param {unknown} value */\nfunction isFiniteVec3(value) {\n return Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);\n}\n\n/** @param {unknown} value */\nfunction isUnitVec3(value) {\n if (!isFiniteVec3(value)) return false;\n const vector = /** @type {number[]} */ (value);\n return Math.abs(Math.hypot(vector[0], vector[1], vector[2]) - 1) < 1e-4;\n}\n\n/** @param {unknown} value */\nfunction isPositiveInteger(value) {\n return Number.isInteger(value) && /** @type {number} */ (value) > 0;\n}\n\n/** @param {unknown} value */\nfunction isNonNegativeInteger(value) {\n return Number.isInteger(value) && /** @type {number} */ (value) >= 0;\n}\n\n/** @param {unknown} value */\nfunction isPositiveFinite(value) {\n return Number.isFinite(value) && /** @type {number} */ (value) > 0;\n}\n\n/** @param {unknown} value */\nfunction isUnitInterval(value) {\n return Number.isFinite(value)\n && /** @type {number} */ (value) >= 0\n && /** @type {number} */ (value) <= 1;\n}\n\n/** @param {unknown} value */\nfunction isBlendZone(value) {\n return Number.isFinite(value)\n && /** @type {number} */ (value) >= 0.35\n && /** @type {number} */ (value) <= 1;\n}\n", "// @ts-check\n\nimport {\n DynamicDrawUsage, InstancedBufferAttribute, InstancedMesh, Matrix4,\n OrthographicCamera, Sphere, Vector2, Vector4,\n} from 'three';\nimport { IMPOSTOR_PERFORMANCE_TIERS, createImpostorFrameBudget, impostorPixelDiameter, selectImpostorTier } from './impostor-performance.js';\n\n/** @import {Camera, Material, Mesh, Object3D, RenderTarget} from 'three' */\n/** @import {ImpostorRenderer} from '../rendering/renderer-support.js' */\n/** @import {FixedPerformancePreset} from './impostor-performance.js' */\n/** @import {ResolvedImpostorRuntimeFeatures} from './impostor-node-material.js' */\n/** @typedef {{fast: number, medium: number, high: number}} ImpostorTierCounts */\n/** @typedef {ReturnType<typeof createImpostorFrameBudget>} FrameBudget */\n/** @typedef {{binding: ReturnType<typeof createBinding>, frameBudget?: FrameBudget}} AdaptiveBinding */\n/**\n * @typedef {{active: FixedPerformancePreset | 'mixed', instances: ImpostorTierCounts | null,\n * profile: ResolvedImpostorRuntimeFeatures['profile'] | null}} AdaptiveImpostorPerformance\n */\n/**\n * @typedef {ImpostorRenderer & {\n * render?: (scene: Object3D, camera: Camera) => unknown,\n * getDrawingBufferSize?: (target: Vector2) => Vector2,\n * getViewport?: (target: Vector4) => Vector4,\n * getPixelRatio?: () => number,\n * getRenderTarget?: () => RenderTarget | null,\n * info?: { frame?: number, render?: { timestamp?: number } },\n * backend?: { device?: { queue?: { onSubmittedWorkDone?: () => Promise<void> } } },\n * }} AdaptiveRenderer\n */\n/** @type {WeakMap<ImpostorRenderer, NonNullable<ReturnType<typeof wrapRenderer>>>} */\nconst renderers = new WeakMap();\n\n/** @param {AdaptiveRenderer} renderer */\nfunction wrapRenderer(renderer) {\n const original = renderer.render;\n if (typeof original !== 'function') return null;\n /** @type {WeakMap<Material, AdaptiveBinding>} */\n const bindings = new WeakMap();\n // Sample the renderer once and share pressure among assets with equal budgets.\n /** @type {Map<number, {state: FrameBudget, references: number}>} */\n const frameBudgets = new Map();\n const drawingSize = new Vector2(), viewport = new Vector4();\n let rendering = false, active = 0, lastGpuTime = 0, lastFrame = -1;\n let submittedAt = -1, lastProbe = -Infinity, queueLag = 0, completedAt = -Infinity;\n\n /** @param {number} time */\n function probeQueue(time) {\n if (submittedAt >= 0 || time - lastProbe < 120) return;\n const queue = renderer.backend?.device?.queue;\n if (!queue?.onSubmittedWorkDone) return;\n lastProbe = submittedAt = time;\n void queue.onSubmittedWorkDone().then(() => {\n completedAt = performance.now();\n queueLag = completedAt - submittedAt;\n submittedAt = -1;\n }, () => { submittedAt = -1; });\n }\n\n const render = (/** @type {Object3D} */ scene, /** @type {Camera} */ camera) => {\n if (rendering || !active) return original.call(renderer, scene, camera);\n /** @type {Array<{mesh: Mesh} & AdaptiveBinding>} */\n const objects = [];\n scene.traverseVisible(object => {\n const mesh = /** @type {Mesh} */ (object);\n if (!mesh.isMesh || Array.isArray(mesh.material) || !camera.layers.test(mesh.layers)) return;\n const entry = bindings.get(mesh.material);\n if (entry) objects.push({ mesh, ...entry });\n });\n if (!objects.length) return original.call(renderer, scene, camera);\n\n const target = renderer.getRenderTarget?.();\n const height = target?.viewport.w ?? (renderer.getViewport\n ? renderer.getViewport(viewport).w * (renderer.getPixelRatio?.() ?? 1)\n : renderer.getDrawingBufferSize?.(drawingSize).y ?? 0);\n if (height <= 0) return original.call(renderer, scene, camera);\n\n // WebGPURenderer exposes the animation-frame counter during postprocessing.\n // Classic WebGL uses canvas pacing. Headless renders have no display cadence.\n const frame = renderer.info?.frame ?? 0;\n const page = /** @type {typeof globalThis & { document?: { hidden: boolean } }} */ (globalThis).document;\n const sampleFrame = frameBudgets.size > 0 && (frame > 0 ? frame !== lastFrame : !target)\n && page?.hidden === false;\n if (sampleFrame) {\n const time = performance.now();\n const gpuTime = renderer.info?.render?.timestamp ?? 0;\n const backlog = submittedAt >= 0 ? time - submittedAt : time - completedAt < 120 ? queueLag : 0;\n // Time waiting for the submitted queue to drain indicates backlog. It\n // covers the whole queue and does not require waiting on the GPU here.\n for (const { state } of frameBudgets.values()) {\n state.observe(time, gpuTime === lastGpuTime ? 0 : gpuTime, backlog);\n }\n lastGpuTime = gpuTime;\n lastFrame = frame;\n }\n const scale = height * Math.abs(camera.projectionMatrix.elements[5]);\n camera.updateWorldMatrix(true, false);\n /** @type {Array<() => void>} */\n const restore = [];\n rendering = true;\n try {\n for (const binding of new Set(objects.map(entry => entry.binding))) binding.beginFrame();\n for (const { mesh, binding, frameBudget } of objects) {\n mesh.updateWorldMatrix(true, false);\n const reset = binding.prepare(mesh, camera, scale, frameBudget?.pressure ?? 1, frameBudget?.ceiling ?? 2);\n if (reset) restore.push(reset);\n }\n const result = original.call(renderer, scene, camera);\n if (sampleFrame) probeQueue(performance.now());\n return result;\n } finally {\n for (let index = restore.length - 1; index >= 0; index--) restore[index]();\n rendering = false;\n }\n };\n\n renderer.render = render;\n return {\n /** @param {Material} material @param {ReturnType<typeof createBinding>} binding @param {number | false} frameBudgetMs */\n add(material, binding, frameBudgetMs) {\n const budget = frameBudgetMs === false ? undefined\n : frameBudgets.get(frameBudgetMs) ?? { state: createImpostorFrameBudget(frameBudgetMs), references: 0 };\n if (frameBudgetMs !== false && budget) {\n budget.references++;\n frameBudgets.set(frameBudgetMs, budget);\n }\n const entry = { binding, frameBudget: budget?.state };\n bindings.set(material, entry);\n active++;\n const dispose = () => {\n if (bindings.get(material) !== entry) return;\n material.removeEventListener('dispose', dispose);\n bindings.delete(material);\n binding.dispose();\n if (frameBudgetMs !== false && budget && --budget.references === 0) frameBudgets.delete(frameBudgetMs);\n if (--active === 0 && renderer.render === render) {\n renderer.render = original;\n renderers.delete(renderer);\n }\n };\n material.addEventListener('dispose', dispose);\n return dispose;\n },\n };\n}\n\n/**\n * Install once per renderer, when an opted-in octahedral material is loaded.\n * Preparing before Three builds its render list lets every tier keep its own\n * compiled program. Temporary changes are unwound even if rendering throws.\n * @param {ImpostorRenderer} renderer\n * @param {Material} material\n * @param {Sphere} bounds\n * @param {(tier: number) => Material} createVariant\n * @param {number | false} frameBudgetMs\n */\nexport function registerAdaptiveImpostorMaterial(renderer, material, bounds, createVariant, frameBudgetMs) {\n let hook = renderers.get(renderer);\n if (!hook) {\n const installed = wrapRenderer(renderer);\n if (!installed) return;\n hook = installed;\n renderers.set(renderer, hook);\n }\n const binding = createBinding(material, bounds, createVariant, renderer.isWebGLRenderer === true);\n const dispose = hook.add(material, binding, frameBudgetMs);\n return { dispose, read: binding.read };\n}\n\n/**\n * @param {Material} material @param {Sphere} bounds\n * @param {(tier: number) => Material} createVariant @param {boolean} classicWebGL\n */\nfunction createBinding(material, bounds, createVariant, classicWebGL) {\n /** @type {WeakMap<Mesh, number>} */\n const single = new WeakMap();\n /** @type {WeakMap<InstancedMesh, ReturnType<typeof createInstanceBins>>} */\n const instanced = new WeakMap();\n /** @type {Set<ReturnType<typeof createInstanceBins>>} */\n const ownedBins = new Set();\n /** @type {Array<Material | undefined>} */\n const variants = [undefined, undefined, material];\n // The classic TSL renderer keeps different attribute bindings for an\n // instanced draw. A material that was used on a plain mesh may not share them.\n /** @type {Array<Material | undefined>} */\n const instanceVariants = [];\n const sphere = new Sphere();\n const viewFromMesh = new Matrix4();\n const frameCounts = [0, 0, 0];\n let frameInstanced = false;\n let version = material.version;\n\n function clearVariants() {\n for (const variant of [...variants, ...instanceVariants]) {\n if (variant && variant !== material) variant.dispose();\n }\n variants[0] = variants[1] = undefined;\n instanceVariants.length = 0;\n }\n\n /** @param {number} tier */\n const variant = tier => variants[tier] ??= createVariant(tier);\n /** @param {number} tier */\n const instanceVariant = tier => classicWebGL ? instanceVariants[tier] ??= createVariant(tier) : variant(tier);\n\n return {\n beginFrame() {\n frameCounts.fill(0);\n frameInstanced = false;\n },\n /** @returns {AdaptiveImpostorPerformance | null} */\n read() {\n const [fast, medium, high] = frameCounts;\n const active = [fast, medium, high].filter(count => count > 0).length;\n if (!active) return null;\n const tier = fast ? 0 : medium ? 1 : 2;\n return {\n active: active > 1 ? 'mixed' : IMPOSTOR_PERFORMANCE_TIERS[tier],\n instances: frameInstanced ? { fast, medium, high } : null,\n profile: active === 1 ? (frameInstanced ? instanceVariant(tier) : variant(tier)).userData.impostorShaderProfile : null,\n };\n },\n /** @param {Mesh} mesh @param {Camera} camera @param {number} scale @param {number} pressure @param {number} ceiling */\n prepare(mesh, camera, scale, pressure, ceiling) {\n if (version !== material.version) {\n version = material.version;\n clearVariants();\n }\n const ortho = camera instanceof OrthographicCamera;\n viewFromMesh.multiplyMatrices(camera.matrixWorldInverse, mesh.matrixWorld);\n const worldScale = mesh.matrixWorld.getMaxScaleOnAxis();\n if (/** @type {InstancedMesh} */ (mesh).isInstancedMesh) {\n const source = /** @type {InstancedMesh} */ (mesh);\n if (!source.count || source.morphTexture) return;\n let bins = instanced.get(source);\n if (!bins) {\n bins = createInstanceBins(bounds);\n instanced.set(source, bins);\n ownedBins.add(bins);\n const owned = bins;\n source.addEventListener('dispose', () => {\n if (ownedBins.delete(owned)) owned.dispose();\n instanced.delete(source);\n });\n }\n const reset = bins.prepare(source, instanceVariant, viewFromMesh, worldScale, scale, ortho, pressure, ceiling);\n frameInstanced = true;\n for (let tier = 0; tier < 3; tier++) frameCounts[tier] += bins.counts[tier];\n return reset;\n }\n sphere.copy(bounds).applyMatrix4(viewFromMesh);\n const pixels = impostorPixelDiameter(sphere.radius, -sphere.center.z, scale, ortho);\n const tier = selectImpostorTier(pixels, single.get(mesh) ?? -1, pressure, ceiling);\n single.set(mesh, tier);\n frameCounts[tier]++;\n return applyTier(mesh, variant(tier));\n },\n dispose() {\n clearVariants();\n for (const bins of ownedBins) bins.dispose();\n ownedBins.clear();\n },\n };\n}\n\n/** @param {Mesh} mesh @param {Material} material */\nfunction applyTier(mesh, material) {\n const original = mesh.material;\n if (material === original) return;\n mesh.material = material;\n return () => { if (mesh.material === material) mesh.material = original; };\n}\n\n/** @param {Sphere} bounds */\nfunction createInstanceBins(bounds) {\n /** @type {Array<InstancedMesh | undefined>} */\n const meshes = [];\n const matrix = new Matrix4(), previousView = new Matrix4();\n const sphere = new Sphere();\n const counts = [0, 0, 0];\n let dirty = 0, count = -1, capacity = 0;\n let assignments = new Uint8Array(), centers = new Float32Array();\n /** @type {InstancedMesh['instanceMatrix'] | null} */ let matrixAttribute = null;\n /** @type {InstancedMesh['instanceColor']} */ let colorAttribute = null;\n let matrixVersion = -1, colorVersion = -1, lastScale = 0, lastPressure = 0, lastCeiling = 2, lastOrtho = false;\n\n function dispose() {\n for (const mesh of meshes) mesh?.dispose();\n meshes.length = 0;\n }\n\n return {\n counts,\n /**\n * @param {InstancedMesh} source @param {(tier: number) => Material} variant\n * @param {Matrix4} view @param {number} worldScale @param {number} scale\n * @param {boolean} ortho @param {number} pressure @param {number} ceiling\n */\n prepare(source, variant, view, worldScale, scale, ortho, pressure, ceiling) {\n const sourceMatrices = source.instanceMatrix, colors = source.instanceColor;\n if (capacity !== sourceMatrices.count) {\n dispose();\n capacity = sourceMatrices.count;\n assignments = new Uint8Array(capacity).fill(3);\n centers = new Float32Array(capacity * 4);\n count = -1;\n }\n const transformed = count !== source.count || matrixAttribute !== sourceMatrices || matrixVersion !== sourceMatrices.version;\n const recolored = colorAttribute !== colors || colorVersion !== (colors?.version ?? -1);\n if (transformed) {\n count = source.count;\n matrixAttribute = sourceMatrices;\n matrixVersion = sourceMatrices.version;\n for (let index = 0; index < count; index++) {\n source.getMatrixAt(index, matrix);\n sphere.copy(bounds).applyMatrix4(matrix);\n const offset = index * 4;\n centers[offset] = sphere.center.x;\n centers[offset + 1] = sphere.center.y;\n centers[offset + 2] = sphere.center.z;\n centers[offset + 3] = sphere.radius;\n }\n }\n if (recolored) {\n colorAttribute = colors;\n colorVersion = colors?.version ?? -1;\n }\n if (transformed || lastScale !== scale || lastPressure !== pressure || lastCeiling !== ceiling || lastOrtho !== ortho || !previousView.equals(view)) {\n previousView.copy(view);\n lastScale = scale;\n lastPressure = pressure;\n lastCeiling = ceiling;\n lastOrtho = ortho;\n counts.fill(0);\n const e = view.elements;\n for (let index = 0; index < count; index++) {\n const offset = index * 4;\n const depth = -(e[2] * centers[offset] + e[6] * centers[offset + 1] + e[10] * centers[offset + 2] + e[14]);\n const pixels = impostorPixelDiameter(centers[offset + 3] * worldScale, depth, scale, ortho);\n const previous = assignments[index];\n const tier = selectImpostorTier(pixels, previous, pressure, ceiling);\n counts[tier]++;\n if (tier === previous) continue;\n dirty |= (1 << previous) | (1 << tier);\n assignments[index] = tier;\n }\n }\n const wholeTier = counts.indexOf(count);\n if (wholeTier >= 0) return applyTier(source, variant(wholeTier));\n /** @type {InstancedMesh[]} */\n const active = [];\n for (let tier = 0; tier < counts.length; tier++) {\n if (!counts[tier]) continue;\n let mesh = meshes[tier];\n if (!mesh) {\n meshes[tier] = mesh = new InstancedMesh(source.geometry, variant(tier), capacity);\n mesh.instanceMatrix.setUsage(DynamicDrawUsage);\n dirty |= 1 << tier;\n }\n mesh.geometry = source.geometry;\n mesh.material = variant(tier);\n mesh.count = counts[tier];\n mesh.castShadow = source.castShadow;\n mesh.receiveShadow = source.receiveShadow;\n mesh.renderOrder = source.renderOrder;\n mesh.layers.mask = source.layers.mask;\n mesh.frustumCulled = false;\n mesh.customDepthMaterial = source.customDepthMaterial;\n mesh.customDistanceMaterial = source.customDistanceMaterial;\n if (colors && (!mesh.instanceColor || recolored && mesh.instanceColor.array.constructor !== colors.array.constructor)) {\n mesh.instanceColor = new InstancedBufferAttribute(colors.array.slice(), colors.itemSize, colors.normalized);\n mesh.instanceColor.setUsage(DynamicDrawUsage);\n } else if (!colors) {\n mesh.instanceColor = null;\n }\n if (transformed || recolored || (dirty & (1 << tier))) {\n packInstances(source, mesh, assignments, tier);\n }\n mesh.onBeforeRender = (...args) => source.onBeforeRender(...args);\n mesh.onAfterRender = (...args) => source.onAfterRender(...args);\n active.push(mesh);\n }\n dirty = 0;\n const mask = source.layers.mask;\n source.add(...active);\n source.layers.mask = 0;\n return () => {\n if (source.layers.mask === 0) source.layers.mask = mask;\n source.remove(...active);\n for (const mesh of active) {\n mesh.onBeforeRender = Object3DPrototype.onBeforeRender;\n mesh.onAfterRender = Object3DPrototype.onAfterRender;\n }\n };\n },\n dispose,\n };\n}\n\nconst Object3DPrototype = InstancedMesh.prototype;\n\n/** @param {InstancedMesh} source @param {InstancedMesh} destination @param {Uint8Array} assignments @param {number} tier */\nfunction packInstances(source, destination, assignments, tier) {\n const matrices = source.instanceMatrix.array, packed = destination.instanceMatrix.array;\n const sourceColors = source.instanceColor, targetColors = destination.instanceColor;\n let next = 0;\n for (let index = 0; index < source.count; index++) {\n if (assignments[index] !== tier) continue;\n for (let lane = 0; lane < 16; lane++) packed[next * 16 + lane] = matrices[index * 16 + lane];\n if (sourceColors && targetColors) {\n for (let lane = 0; lane < sourceColors.itemSize; lane++) {\n targetColors.array[next * sourceColors.itemSize + lane] = sourceColors.array[index * sourceColors.itemSize + lane];\n }\n }\n next++;\n }\n for (const attribute of [destination.instanceMatrix, destination.instanceColor]) {\n if (!attribute) continue;\n attribute.clearUpdateRanges();\n attribute.addUpdateRange(0, next * attribute.itemSize);\n attribute.needsUpdate = true;\n }\n}\n", "// @ts-check\n\nimport { OrthographicCamera } from 'three';\n\n/** @import {Camera, Sphere} from 'three' */\nexport const IMPOSTOR_PERFORMANCE_PRESETS = /** @type {const} */ ({\n fast: {\n interpolation: true,\n reprojection: false,\n depthWeights: false,\n perspectiveCorrection: true,\n cellCorrection: false,\n boundedReprojection: true,\n raySamples: 0,\n depthSamples: 0,\n },\n medium: {\n interpolation: true,\n reprojection: true,\n depthWeights: true,\n perspectiveCorrection: true,\n cellCorrection: false,\n boundedReprojection: true,\n raySamples: 8,\n depthSamples: 2,\n },\n high: {\n interpolation: true,\n reprojection: true,\n depthWeights: true,\n perspectiveCorrection: true,\n cellCorrection: false,\n boundedReprojection: true,\n raySamples: 16,\n depthSamples: 4,\n },\n});\n\nexport const IMPOSTOR_PERFORMANCE_TIERS = /** @type {const} */ (['fast', 'medium', 'high']);\n/** @typedef {typeof IMPOSTOR_PERFORMANCE_TIERS[number]} FixedPerformancePreset */\n/**\n * @typedef {object} ImpostorAutoOptions\n * @property {number | false} [frameBudgetMs] Whole-renderer frame budget in milliseconds. Use false for size-based selection alone.\n */\n/** @typedef {'auto' | 'fixed' | ImpostorAutoOptions} ImpostorPerformance */\nconst DEFAULT_FRAME_BUDGET_MS = 1000 / 60;\n\n/** @param {ImpostorPerformance} performance */\nexport function resolveImpostorFrameBudget(performance) {\n const budget = typeof performance === 'object'\n ? performance.frameBudgetMs ?? DEFAULT_FRAME_BUDGET_MS\n : DEFAULT_FRAME_BUDGET_MS;\n if (budget !== false && (!Number.isFinite(budget) || budget <= 0)) {\n throw new RangeError('Impostor frameBudgetMs must be a positive finite number or false.');\n }\n return budget;\n}\n\n/**\n * The same diameter can keep either adjacent tier near a boundary. Zooming\n * back and forth inside that interval keeps the compiled program stable.\n * @param {number} pixels\n * @param {FixedPerformancePreset | 'custom' | null} previous\n * @param {number=} pressure\n * @param {number=} ceiling\n * @returns {FixedPerformancePreset}\n */\nexport function selectImpostorPerformance(pixels, previous, pressure = 1, ceiling = 2) {\n return IMPOSTOR_PERFORMANCE_TIERS[selectImpostorTier(\n pixels, previous === 'high' ? 2 : previous === 'fast' ? 0 : 1, pressure, ceiling,\n )];\n}\n\n/** @param {number} pixels @param {number} previous @param {number=} pressure @param {number=} ceiling */\nexport function selectImpostorTier(pixels, previous, pressure = 1, ceiling = 2) {\n if (ceiling >= 2 && pixels >= pressure * (previous === 2 ? 160 : 208)) return 2;\n return ceiling >= 1 && pixels >= pressure * (previous === 0 ? 96 : 72) ? 1 : 0;\n}\n\n/**\n * @param {number} radius @param {number} depth\n * @param {number} scale @param {boolean} orthographic\n */\nexport function impostorPixelDiameter(radius, depth, scale, orthographic) {\n if (orthographic) return radius * scale;\n return depth <= -radius ? 0 : radius * scale / Math.max(radius, depth, 0.0001);\n}\n\n/** @param {Sphere} sphere @param {Camera} camera @param {number} viewportHeight */\nexport function projectedImpostorDiameter(sphere, camera, viewportHeight) {\n const scale = viewportHeight * Math.abs(camera.projectionMatrix.elements[5]);\n const { x, y, z } = sphere.center;\n const view = camera.matrixWorldInverse.elements;\n const depth = -(view[2] * x + view[6] * y + view[10] * z + view[14]);\n return impostorPixelDiameter(sphere.radius, depth, scale, camera instanceof OrthographicCamera);\n}\n\n\n/** Smooth frame pressure across the renderer's display frames. GPU timing is\n * optional and owned by the host profiler. Reading it never adds a query.\n * @param {number} [budget]\n */\nexport function createImpostorFrameBudget(budget = DEFAULT_FRAME_BUDGET_MS) {\n const minimumInterval = Math.min(6, budget / 2);\n const backlogThreshold = budget * (32 / DEFAULT_FRAME_BUDGET_MS);\n let previous = -1, average = budget, pressure = 1;\n let slow = 0, headroom = 0, ceiling = 2;\n return {\n get pressure() { return pressure; },\n get ceiling() { return ceiling; },\n /** @param {number} time @param {number=} gpuMilliseconds @param {number=} queueLag */\n observe(time, gpuMilliseconds = 0, queueLag = 0) {\n if (previous < 0) {\n previous = time;\n return pressure;\n }\n const elapsed = time - previous;\n if (elapsed >= 0 && elapsed < minimumInterval) return pressure;\n previous = time;\n // A suspended tab or a pause between renders is not sustained load.\n if (elapsed > 250 || elapsed <= 0) {\n average = budget;\n slow = headroom = 0;\n return pressure;\n }\n average += (elapsed - average) * 0.14;\n if (queueLag > backlogThreshold) gpuMilliseconds = Math.max(gpuMilliseconds, queueLag);\n const slowFrame = elapsed > budget * 1.13 && average > budget * 1.13;\n if (slowFrame || gpuMilliseconds > budget * 0.95) {\n headroom = 0;\n slow += Math.min(elapsed, 100);\n if (slow >= 160) {\n // At very low FPS, respond in a fraction of a second. If even the\n // widest thresholds can't help, cap the tier for close-up cards.\n if (pressure >= 8) ceiling = Math.max(0, ceiling - 1);\n else pressure = Math.min(8, pressure * Math.max(1.3, Math.min(2.5, average / budget)));\n slow = 0;\n }\n } else if (average < budget * 1.06 && gpuMilliseconds < budget * 0.8) {\n slow = 0;\n if (++headroom >= 60) {\n if (ceiling < 2) ceiling++;\n else pressure = Math.max(1, pressure / 1.18);\n headroom = 0;\n }\n } else {\n slow = headroom = 0;\n }\n return pressure;\n },\n };\n}\n", "// @ts-check\n\n/** Keep material-slot texture replacement connected to the shader nodes.\n * @param {import('three').Material} material\n * @param {string} slot\n * @param {import('three').Texture} initial\n * @param {{value: import('three').Texture}[]} nodes\n * @param {((value: import('three').Texture) => void)=} onChange\n */\nexport function bindTextureSlot(material, slot, initial, nodes, onChange) {\n let current = initial;\n Object.defineProperty(material, slot, {\n configurable: true, enumerable: true,\n get: () => current,\n set: (/** @type {import('three').Texture} */ value) => {\n value.channel = current.channel;\n value.offset = current.offset;\n value.repeat = current.repeat;\n value.center = current.center;\n value.rotation = current.rotation;\n current = value;\n for (const node of nodes) node.value = value;\n onChange?.(value);\n material.needsUpdate = true;\n },\n });\n}\n", "// @ts-check\nimport { DataTexture, DynamicDrawUsage, FloatType, InstancedInterleavedBuffer, InterpolationSamplingType, NodeUpdateType, RGBAFormat } from 'three/webgpu';\nimport { cross, dot, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, ivec2, textureLoad, varying, vec3, vec4 } from 'three/tsl';\n\n/** @import {InstancedBufferAttribute, InstancedMesh, Node, NodeBuilder} from 'three/webgpu' */\n/** @typedef {Node<'vec3'>} Vec3Node */\n/** @typedef {(value: Vec3Node) => Vec3Node} Transform */\n/** @typedef {{toLocalPoint: Transform, toLocalDirection: Transform, toMeshPoint: Transform, toMeshDirection: Transform}} CoordinateSpace */\n/** @typedef {CoordinateSpace & {fragment: CoordinateSpace & {toMeshNormal: Transform}}} InstanceSpace */\n\n/** @type {WeakMap<InstancedBufferAttribute, InstanceSpace>} */\nconst spaces = new WeakMap();\n/** @type {WeakMap<InstancedBufferAttribute, InstanceSpace>} */\nconst webglSpaces = new WeakMap();\n\n/** @param {InstancedMesh} object @param {InstancedBufferAttribute} matrix @param {boolean} useTexture */\nfunction instanceColumns(object, matrix, useTexture) {\n const columns = [0, 1, 2, 3];\n if (useTexture) {\n // Once Three's instance transforms move from uniforms into attributes, a\n // second set of matrix attributes can exceed WebGL2's vertex-slot limit.\n const rowSize = Math.ceil(Math.sqrt(matrix.count) / 2);\n const rows = Math.ceil(matrix.count / rowSize);\n const data = new Float32Array(rowSize * rows * 16);\n const texture = new DataTexture(data, rowSize * 4, rows, RGBAFormat, FloatType);\n const upload = () => {\n data.set(matrix.array);\n texture.needsUpdate = true;\n };\n upload();\n const release = () => {\n object.removeEventListener('dispose', release);\n texture.dispose();\n webglSpaces.delete(matrix);\n };\n object.addEventListener('dispose', release);\n const x = instanceIndex.mod(rowSize).mul(4);\n const y = instanceIndex.div(rowSize);\n return { nodes: columns.map(column => textureLoad(texture, ivec2(int(x.add(column)), int(y)))), upload };\n }\n const interleaved = new InstancedInterleavedBuffer(matrix.array, 16, 1);\n const read = matrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;\n return {\n nodes: columns.map(column => read(interleaved, /** @type {const} */ ('vec4'), 16, column * 4)),\n upload: () => { interleaved.needsUpdate = true; },\n };\n}\n\n/** Nodes that move between an InstancedMesh's own space and the space of one\n * instance, so a material can trace in its captured coordinates and still\n * light, depth-test and shadow in the mesh's. Returns null for other objects.\n *\n * `toLocal*` and `toMesh*` run in the vertex stage; wrap their result in\n * `varying()` to use it in the fragment stage. `fragment` holds the same\n * conversions for values that only exist per fragment.\n * @param {NodeBuilder & {getUniformBufferLimit?: () => number}} builder */\nexport function instanceSpace(builder) {\n const object = /** @type {InstancedMesh} */ (builder.object);\n const matrix = object?.isInstancedMesh ? object.instanceMatrix : null;\n if (!matrix) return null;\n const backend = /** @type {{isWebGPUBackend?: boolean} | undefined} */ (builder.renderer.backend);\n const useTexture = !backend?.isWebGPUBackend\n && matrix.count * 64 > (builder.getUniformBufferLimit?.() ?? 16_384);\n const cache = useTexture ? webglSpaces : spaces;\n const cached = cache.get(matrix);\n if (cached) return cached;\n const { nodes, upload } = instanceColumns(object, matrix, useTexture);\n let version = matrix.version;\n nodes[0].updateBeforeType = NodeUpdateType.OBJECT;\n nodes[0].updateBefore = () => {\n if (matrix.version !== version) {\n version = matrix.version;\n upload();\n }\n return undefined;\n };\n const [a, b, c, d] = nodes.map((node) => node.xyz);\n const determinant = dot(a, cross(b, c));\n const rows = [cross(b, c), cross(c, a), cross(a, b)].map((row) => row.div(determinant));\n /** @type {Transform} */\n const toLocalDirection = (v) => vec3(dot(rows[0], v), dot(rows[1], v), dot(rows[2], v));\n /** @type {Transform} */\n const toMeshDirection = (v) => a.mul(v.x).add(b.mul(v.y)).add(c.mul(v.z));\n // Three outputs carry the whole transform; shaders with many per-box\n // attributes have few to spare.\n // Flat: the transform is one value per instance, and interpolating equal\n // values still perturbs them enough to move a traced hit.\n const translation = [d.x, d.y, d.z];\n const packed = [a, b, c].map((column, k) =>\n varying(vec4(column, translation[k]), `instanceSpace${k}`).setInterpolation(InterpolationSamplingType.FLAT),\n );\n const [fa, fb, fc] = packed.map((column) => column.xyz);\n const cofactors = () => [cross(fb, fc), cross(fc, fa), cross(fa, fb)];\n /** @type {InstanceSpace} */\n const space = {\n toLocalPoint: (p) => toLocalDirection(p.sub(d)),\n toLocalDirection,\n toMeshPoint: (p) => toMeshDirection(p).add(d),\n toMeshDirection,\n fragment: {\n toMeshPoint: (p) =>\n fa.mul(p.x).add(fb.mul(p.y)).add(fc.mul(p.z)).add(vec3(packed[0].w, packed[1].w, packed[2].w)),\n toMeshDirection: (v) => fa.mul(v.x).add(fb.mul(v.y)).add(fc.mul(v.z)),\n toMeshNormal: (n) => {\n const [x, y, z] = cofactors();\n return x.mul(n.x).add(y.mul(n.y)).add(z.mul(n.z)).mul(dot(fa, x).sign()).normalize();\n },\n toLocalDirection: (v) => {\n const [x, y, z] = cofactors();\n return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));\n },\n toLocalPoint: (p) => {\n const [x, y, z] = cofactors();\n const v = p.sub(vec3(packed[0].w, packed[1].w, packed[2].w));\n return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));\n },\n },\n };\n cache.set(matrix, space);\n return space;\n}\n", "// @ts-check\n\n// A billboard point samples the capture camera along point -> camera, so its\n// local plane offset is subtracted from the object-center camera vector.\nexport const PERSPECTIVE_RAY_PLANE_SIGN = -1;\n\n/**\n * Encodes a local-space point into the orthographic capture depth used by the\n * normal/depth atlas. Capture cameras sit at `direction * 2r` and cover the\n * interval from +r to -r along their forward axis.\n *\n * @param {[number, number, number]} point\n * @param {[number, number, number]} direction Unit capture direction.\n * @param {number} radius\n */\nexport function captureDepthFromPoint(point, direction, radius) {\n if (!(radius > 0) || !Number.isFinite(radius)) {\n throw new RangeError('Capture radius must be positive and finite.');\n }\n const normalizedDirection = normalize3(direction);\n return (radius - dot3(point, normalizedDirection)) / (2 * radius);\n}\n\n/**\n * Intersects a runtime point-to-camera ray with the capture-depth plane\n * `dot(P, captureDirection) = radius - 2 * radius * depth`.\n *\n * This is the fixed-point step solved by the runtime parallax shader. It is\n * deliberately expressed independently here so sign and scale regressions are\n * caught by browserless tests.\n *\n * @param {[number, number, number]} rayOrigin\n * @param {[number, number, number]} rayDirection Unit point-to-camera ray.\n * @param {[number, number, number]} captureDirection Unit capture direction.\n * @param {number} depth\n * @param {number} radius\n * @returns {[number, number, number]}\n */\nexport function intersectRayWithCaptureDepth(\n rayOrigin,\n rayDirection,\n captureDirection,\n depth,\n radius,\n) {\n if (!(radius > 0) || !Number.isFinite(radius) || !Number.isFinite(depth)) {\n throw new RangeError('Capture depth and radius must be finite, with a positive radius.');\n }\n const ray = normalize3(rayDirection);\n const capture = normalize3(captureDirection);\n const denominator = dot3(ray, capture);\n if (Math.abs(denominator) < 1e-8) {\n throw new RangeError('Runtime ray is parallel to the capture-depth plane.');\n }\n const planeDepth = radius - 2 * radius * depth;\n const distance = (planeDepth - dot3(rayOrigin, capture)) / denominator;\n return /** @type {[number, number, number]} */ (rayOrigin.map((value, index) => (\n value + ray[index] * distance\n )));\n}\n\n/**\n * Decodes a regular or upper-hemisphere octahedral grid coordinate.\n * Uses Y as the up axis.\n *\n * @param {[number, number]} coordinate normalized 0..1 grid coordinate\n * @param {'hemisphere' | 'full'} mapping\n * @returns {[number, number, number]}\n */\nexport function gridToDirection(coordinate, mapping) {\n const [u, v] = coordinate;\n let x;\n let y;\n let z;\n if (mapping === 'hemisphere') {\n x = u - v;\n z = -1 + u + v;\n y = 1 - Math.abs(x) - Math.abs(z);\n } else {\n x = u * 2 - 1;\n z = v * 2 - 1;\n y = 1 - Math.abs(x) - Math.abs(z);\n if (y < 0) {\n const oldX = x;\n x = nonZeroSign(x) * (1 - Math.abs(z));\n z = nonZeroSign(z) * (1 - Math.abs(oldX));\n }\n }\n return normalize3([x, y, z]);\n}\n\n/**\n * @param {[number, number, number]} input\n * @param {'hemisphere' | 'full'} mapping\n * @returns {[number, number]}\n */\nexport function directionToGrid(input, mapping) {\n let [x, y, z] = normalize3(input);\n if (mapping === 'hemisphere') y = Math.max(y, 1e-6);\n const inverseL1 = 1 / Math.max(1e-12, Math.abs(x) + Math.abs(y) + Math.abs(z));\n x *= inverseL1;\n y *= inverseL1;\n z *= inverseL1;\n if (mapping === 'hemisphere') {\n return clamp2([(x + z) * 0.5 + 0.5, (z - x) * 0.5 + 0.5]);\n }\n if (y < 0) {\n const oldX = x;\n x = nonZeroSign(x) * (1 - Math.abs(z));\n z = nonZeroSign(z) * (1 - Math.abs(oldX));\n }\n return clamp2([x * 0.5 + 0.5, z * 0.5 + 0.5]);\n}\n\n/**\n * Finds the authored grid direction with the smallest spherical angle to an\n * arbitrary view. Octahedral coordinates are not equal-area, so independently\n * rounding U/V is not guaranteed to choose the closest capture near folds.\n * The production grids contain at most 24\u00B2 views; an exact dot-product search\n * is both cheap and unambiguous for an interaction that runs on orbit release.\n *\n * @param {[number, number, number]} inputDirection\n * @param {'hemisphere' | 'full'} mapping\n * @param {number} frames\n */\nexport function nearestOctahedralCapture(inputDirection, mapping, frames) {\n if (mapping !== 'hemisphere' && mapping !== 'full') {\n throw new RangeError('Impostor mapping must be hemisphere or full.');\n }\n if (!Number.isInteger(frames) || frames < 2) {\n throw new RangeError('Impostor capture search requires at least two frames per axis.');\n }\n const direction = normalize3(inputDirection);\n let bestFrame = /** @type {[number, number]} */ ([0, 0]);\n let bestDirection = gridToDirection([0, 0], mapping);\n let bestDot = -Number.POSITIVE_INFINITY;\n for (let y = 0; y < frames; y++) {\n for (let x = 0; x < frames; x++) {\n const candidate = gridToDirection([x / (frames - 1), y / (frames - 1)], mapping);\n const similarity = dot3(direction, candidate);\n if (similarity <= bestDot) continue;\n bestDot = similarity;\n bestFrame = [x, y];\n bestDirection = candidate;\n }\n }\n return {\n frame: bestFrame,\n direction: bestDirection,\n dot: Math.max(-1, Math.min(1, bestDot)),\n angleDegrees: Math.acos(Math.max(-1, Math.min(1, bestDot))) * 180 / Math.PI,\n };\n}\n\n/**\n * Projects a spherical direction beyond the latest sample. OrbitControls'\n * residual release motion supplies the two samples; values above one look\n * ahead in the same direction, so a fast release cannot select the capture\n * behind its visible trajectory.\n *\n * @param {[number, number, number]} startDirection\n * @param {[number, number, number]} endDirection\n * @param {number} multiplier 1 returns the end sample, 1.5 projects half of\n * the sampled angular motion beyond it.\n * @returns {[number, number, number]}\n */\nexport function extrapolateSphericalDirection(startDirection, endDirection, multiplier) {\n if (!Number.isFinite(multiplier) || multiplier < 0) {\n throw new RangeError('Spherical extrapolation multiplier must be finite and non-negative.');\n }\n const start = normalize3(startDirection);\n const end = normalize3(endDirection);\n const similarity = Math.max(-1, Math.min(1, dot3(start, end)));\n const angle = Math.acos(similarity);\n const axis = cross3(start, end);\n const axisLength = Math.hypot(...axis);\n if (angle < 1e-8 || axisLength < 1e-8) return end;\n const unitAxis = /** @type {[number, number, number]} */ (\n axis.map((component) => component / axisLength)\n );\n const projectedAngle = angle * multiplier;\n const cosine = Math.cos(projectedAngle);\n const sine = Math.sin(projectedAngle);\n const axisCrossStart = cross3(unitAxis, start);\n const axisDotStart = dot3(unitAxis, start);\n return normalize3(/** @type {[number, number, number]} */ (start.map((component, index) => (\n component * cosine\n + axisCrossStart[index] * sine\n + unitAxis[index] * axisDotStart * (1 - cosine)\n ))));\n}\n\n/**\n * Returns the three vertices and barycentric weights of the grid triangle\n * containing a direction. The diagonal is chosen consistently on CPU and GPU.\n *\n * @param {[number, number, number]} direction\n * @param {'hemisphere' | 'full'} mapping\n * @param {number} frames\n */\nexport function selectOctahedralFrames(direction, mapping, frames) {\n const scale = frames - 1;\n const grid = directionToGrid(direction, mapping);\n const gx = grid[0] * scale;\n const gy = grid[1] * scale;\n const x = Math.min(scale - 1, Math.floor(gx));\n const y = Math.min(scale - 1, Math.floor(gy));\n const fx = gx - x;\n const fy = gy - y;\n const base = gridToDirection([x / scale, y / scale], mapping);\n const right = gridToDirection([(x + 1) / scale, y / scale], mapping);\n const up = gridToDirection([x / scale, (y + 1) / scale], mapping);\n const diagonal = gridToDirection([(x + 1) / scale, (y + 1) / scale], mapping);\n // Octahedral grid quads are strongly warped on the sphere, especially at\n // low view counts. Use the shorter of their two spherical diagonals instead\n // of always connecting base -> diagonal. Fold cells still necessarily use\n // the anti-diagonal because it is the captured z=0 view edge.\n const antiDiagonal = mapping === 'hemisphere' && x + y === scale - 1\n || dot3(right, up) > dot3(base, diagonal);\n if (antiDiagonal) {\n if (fx + fy <= 1) {\n return {\n frames: /** @type {[[number, number], [number, number], [number, number]]} */ ([\n [x, y], [x + 1, y], [x, y + 1],\n ]),\n weights: /** @type {[number, number, number]} */ ([1 - fx - fy, fx, fy]),\n };\n }\n return {\n frames: /** @type {[[number, number], [number, number], [number, number]]} */ ([\n [x + 1, y + 1], [x, y + 1], [x + 1, y],\n ]),\n weights: /** @type {[number, number, number]} */ ([fx + fy - 1, 1 - fx, 1 - fy]),\n };\n }\n const horizontal = fx > fy;\n return {\n frames: /** @type {[[number, number], [number, number], [number, number]]} */ ([\n [x, y],\n horizontal ? [x + 1, y] : [x, y + 1],\n [x + 1, y + 1],\n ]),\n weights: /** @type {[number, number, number]} */ ([\n Math.min(1 - fx, 1 - fy),\n Math.abs(fx - fy),\n Math.min(fx, fy),\n ]),\n };\n}\n\n/** @param {[number, number, number]} a @param {[number, number, number]} b */\nfunction dot3(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/** @param {[number, number, number]} a @param {[number, number, number]} b */\nfunction cross3(a, b) {\n return /** @type {[number, number, number]} */ ([\n a[1] * b[2] - a[2] * b[1],\n a[2] * b[0] - a[0] * b[2],\n a[0] * b[1] - a[1] * b[0],\n ]);\n}\n\n/** @param {[number, number, number]} value */\nfunction normalize3(value) {\n const length = Math.hypot(...value);\n if (length < 1e-12) return /** @type {[number, number, number]} */ ([0, 1, 0]);\n return /** @type {[number, number, number]} */ (value.map((component) => component / length));\n}\n\n/** @param {[number, number]} value */\nfunction clamp2(value) {\n return /** @type {[number, number]} */ (value.map((component) => Math.max(0, Math.min(1, component))));\n}\n\n/** @param {number} value */\nfunction nonZeroSign(value) {\n return value < 0 ? -1 : 1;\n}\n", "// @ts-check\n\nimport {\n DataTexture,\n FloatType,\n NearestFilter,\n RGBAFormat,\n} from 'three';\n\nimport { parseImpostorDescriptor } from './impostor-metadata.js';\n/** @import { ImpostorDescriptor } from './impostor-metadata.js' */\n\nexport { parseImpostorDescriptor } from './impostor-metadata.js';\n\nexport const REPROJECTION_CONFIDENCE_INNER_TEXELS = 0.25;\nexport const REPROJECTION_CONFIDENCE_OUTER_TEXELS = 16;\n\n/**\n * Restricts barycentric interpolation to a compact fraction of each angular\n * transition. A value of one preserves ordinary linear barycentrics. Smaller\n * values create an exact single-view region around each capture while the\n * active transition remains continuous and normalized.\n *\n * Along a triangle edge, `blendZone` is exactly the fraction of that edge over\n * which both endpoint captures contribute.\n *\n * @param {readonly [number, number, number]} inputWeights\n * @param {number} blendZone\n * @returns {[number, number, number]}\n */\nexport function applyImpostorBlendZone(inputWeights, blendZone) {\n if (!isBlendZone(blendZone)) {\n throw new RangeError('Impostor blend zone must be from 0.35 to 1.');\n }\n if (inputWeights.some((weight) => !Number.isFinite(weight) || weight < 0)) {\n throw new RangeError('Impostor barycentric weights must be finite and non-negative.');\n }\n const cutoff = (1 - blendZone) * 0.5;\n const weights = /** @type {[number, number, number]} */ (\n inputWeights.map((weight) => Math.max(0, weight - cutoff))\n );\n const sum = weights[0] + weights[1] + weights[2];\n if (!(sum > 0)) return [1, 0, 0];\n return /** @type {[number, number, number]} */ (\n weights.map((weight) => weight / sum)\n );\n}\n\n/**\n * Keeps the angular onset of a previously occluded contour approximately\n * stable as the atlas grid gets denser. The returned value is the temperature\n * used by the normalized log-sum-exp union in the runtime shader.\n *\n * @param {number} frames\n */\nexport function impostorContourUnionSharpness(frames) {\n if (!Number.isInteger(frames) || frames < 2) {\n throw new RangeError('Impostor contour union requires at least two frames per atlas axis.');\n }\n return Math.max(1, 16 / frames);\n}\n\n/**\n * CPU mirror of the runtime's continuous geometric confidence. A binary\n * half-texel cutoff made individual pixels (and sometimes entire thin\n * features) switch reconstruction paths at one camera angle. The fade keeps\n * the same bounded rejection while making angular motion continuous.\n *\n * @param {boolean} startedOutOfBounds\n * @param {number} rayError\n * @param {number} footprint\n * @param {boolean=} reprojectionActive\n */\nexport function reprojectedSampleConfidence(\n startedOutOfBounds,\n rayError,\n footprint,\n reprojectionActive = true,\n) {\n if (startedOutOfBounds) return 0;\n if (!reprojectionActive) return 1;\n if (!(footprint > 0)) return 0;\n const residual = rayError / footprint;\n const interval = REPROJECTION_CONFIDENCE_OUTER_TEXELS\n - REPROJECTION_CONFIDENCE_INNER_TEXELS;\n const t = Math.min(1, Math.max(\n 0,\n (residual - REPROJECTION_CONFIDENCE_INNER_TEXELS) / interval,\n ));\n const eased = t * t * (3 - 2 * t);\n return 1 - eased;\n}\n\n/**\n * Mirrors the runtime coverage contribution used after depth reprojection.\n * Validity can remove a frame from a pixel, but it must never renormalize the\n * remaining frame to full opacity. Preserving angular support prevents a\n * surface visible in only one capture from appearing as a second opaque layer.\n *\n * @param {readonly [number, number, number]} visibilityWeights\n * @param {readonly [number, number, number]} correctedValidity\n * @returns {[number, number, number]}\n */\nexport function resolveImpostorCoverageWeights(\n visibilityWeights,\n correctedValidity,\n) {\n const values = [...visibilityWeights, ...correctedValidity];\n if (values.some((value) => !Number.isFinite(value) || value < 0)) {\n throw new RangeError('Coverage weights and validity must be finite and non-negative.');\n }\n return /** @type {[number, number, number]} */ (\n visibilityWeights.map((weight, index) => weight * correctedValidity[index])\n );\n}\n\n/** @param {ImpostorDescriptor} descriptor */\nexport function createImpostorViewBoundsTexture(descriptor) {\n const texture = new DataTexture(\n new Float32Array(descriptor.viewBounds),\n descriptor.frames,\n descriptor.frames,\n RGBAFormat,\n FloatType,\n );\n texture.name = 'impostor view bounds';\n texture.minFilter = NearestFilter;\n texture.magFilter = NearestFilter;\n texture.generateMipmaps = false;\n texture.needsUpdate = true;\n return texture;\n}\n\n/** @param {unknown} value */\nfunction isBlendZone(value) {\n return Number.isFinite(value)\n && /** @type {number} */ (value) >= 0.35\n && /** @type {number} */ (value) <= 1;\n}\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AAS,SAAS,SAAS,QAAQ,MAAM;AAAA,IAC9D;AAAA,EACF,CAAC;AACD,MAAI,CAAC,iBAAiB,KAAK,OAAO,SAAU,iBAAgB,UAAU,YAAY,KAAK,KAAK,CAAC,QAAQ,GAAG,WAAS;AAAE,SAAK,MAAM;AAAA,EAAO,CAAC;AACtI,MAAI,CAAC,iBAAiB,KAAK,YAAY,cAAe,iBAAgB,UAAU,iBAAiB,KAAK,UAAU,CAAC,aAAa,GAAG,WAAS;AAAE,SAAK,WAAW;AAAA,EAAO,CAAC;AACpK,SAAO;AACT;",
|
|
6
|
+
"names": ["modelViewMatrix", "vec4", "MeshStandardNodeMaterial", "Sphere", "Vector4", "TSL", "Fn", "cross", "dot", "int", "ivec2", "modelWorldMatrix", "textureLoad", "varying", "vec3", "vec4", "OrthographicCamera", "performance", "variant", "OrthographicCamera", "tier", "DynamicDrawUsage", "vec4", "texture", "DataTexture", "FloatType", "RGBAFormat", "texture", "DataTexture", "RGBAFormat", "FloatType", "TSL", "performance", "material", "texture", "Sphere", "pending", "Vector4", "vec3", "Fn", "bytes", "textureLoad", "ivec2", "varying", "vec4", "cross", "dot", "footprint", "coarseStep", "int", "capturedCoverage", "distanceCoverage", "modelWorldMatrix"]
|
|
7
7
|
}
|