/** * Stable signed-distance-field generation, rendering, and particle * constraint facades. * * These exports retain the backing constructor and prototype identities while * keeping generated nodes, uniforms, BVH buffers, compute passes, temporary * textures, workgroup controls, and cache state private to the implementation. * * @module three-blocks/sdf-raymarching */ import type * as THREE from 'three/webgpu'; import type { GeometryBVH } from 'three-mesh-bvh'; /** GPU-owned three-dimensional texture produced by an SDF generator. */ export type SDFTextureOutput = THREE.Storage3DTexture; /** Construction configuration for {@link ComputeSDFGenerator}. */ export interface SDFGeneratorOptions { /** Cubic voxel dimension; memory and generation work grow with its cube. */ resolution?: number | undefined; /** World-space padding added around automatically calculated mesh bounds. */ margin?: number | undefined; /** Signed-distance bias written into every generated voxel. */ threshold?: number | undefined; /** Optional caller-owned fixed volume bounds, read during each generation. */ bounds?: THREE.Box3 | null | undefined; } /** * GPU signed-distance-field generator backed by a mesh BVH. * * Generation is asynchronous at the API boundary but submits work through the * supplied renderer before its promise resolves. The returned texture remains * owned by the generator and is invalid after `dispose()` or replacement by a * later generation at another resolution. Geometry and BVH inputs remain * caller-owned. Missing positions, bounds, BVH data, or WebGPU support can make * generation reject. Cost is proportional to `resolution ** 3` BVH queries. */ export interface ComputeSDFGenerator { /** Cubic voxel dimension used by subsequent generations. */ resolution: number; /** World-space padding used when bounds are inferred from the geometry. */ margin: number; /** Signed-distance bias used by subsequent generations. */ threshold: number; /** Current generator-owned texture, or `null` before generation and after disposal. */ readonly sdfTexture: SDFTextureOutput | null; /** Mutable local-to-world transform for the current normalized SDF volume. */ readonly boundsMatrix: THREE.Matrix4; /** Mutable world-to-local inverse of {@link boundsMatrix}. */ readonly inverseBoundsMatrix: THREE.Matrix4; /** Mutable tight source-local geometry bounds consumed by stable volume samplers. */ readonly geometryBounds: THREE.Box3; /** Mutable source-local to world transform consumed by stable volume samplers. */ readonly meshMatrixWorld: THREE.Matrix4; /** Mutable world-space volume bounds including configured padding. */ readonly bounds: THREE.Box3; /** Generate or replace the owned texture and submit its complete compute workload. */ generate(geometry: THREE.BufferGeometry, bvh: GeometryBVH, renderer: THREE.Renderer): Promise; /** Refresh a generated field after caller-owned geometry or BVH data changes. */ update(geometry: THREE.BufferGeometry, bvh: GeometryBVH, renderer: THREE.Renderer): Promise; /** Dispose the owned texture, BVH bindings, and compute graph; repeated calls are safe. */ dispose(): void; } interface ComputeSDFGeneratorConstructor { /** Construct a lazy generator; no GPU resources are allocated until generation. */ new (options?: SDFGeneratorOptions): ComputeSDFGenerator; /** Runtime prototype shared with the backing implementation. */ readonly prototype: ComputeSDFGenerator; } /** Runtime SDF-generator constructor with workgroup and graph state hidden. */ export declare const ComputeSDFGenerator: ComputeSDFGeneratorConstructor; /** Construction configuration for {@link SkinnedMeshSDF}. */ export interface SkinnedMeshSDFOptions { /** Cubic voxel dimension of the field; work and memory grow with its cube. */ resolution?: number | undefined; /** World-space size of the axis-aligned field domain. */ domain?: THREE.Vector3 | undefined; /** Exact-distance band half-width around the surface, in voxels. */ bandVoxels?: number | undefined; /** Signed distance written where no surface information exists. */ far?: number | undefined; /** Upper clamp applied to per-vertex surface velocity, in world units per second. */ maxSurfaceSpeed?: number | undefined; /** Ping-pong distance-propagation passes; each extends coverage by one voxel. */ propagationPasses?: number | undefined; } /** World-space position accepted by the {@link SkinnedMeshSDF} sampling helpers. */ export type SkinnedMeshSDFSamplePosition = THREE.Node<'vec3'> | THREE.Vector3; /** Scalar response parameter: a plain number or any float-producing TSL node. */ export type SkinnedMeshSDFScalar = THREE.Node<'float'> | number; /** Per-particle configuration for {@link SkinnedMeshSDF.collide}. */ export interface SkinnedMeshSDFCollideOptions { /** World-space particle position. */ position: SkinnedMeshSDFSamplePosition; /** World-space particle velocity entering the response. */ velocity: SkinnedMeshSDFSamplePosition; /** Particle radius; the response triggers when signed distance drops below it. */ radius?: SkinnedMeshSDFScalar | undefined; /** Fraction of tangential velocity removed on contact; zero slides freely. */ friction?: SkinnedMeshSDFScalar | undefined; /** Fraction of approach speed reflected on contact; zero absorbs the impact. */ restitution?: SkinnedMeshSDFScalar | undefined; /** Separation speed gained per meter of penetration. */ pushOutRate?: SkinnedMeshSDFScalar | undefined; /** Cap on the push-out separation speed, in world units per second. */ maxPushOutSpeed?: SkinnedMeshSDFScalar | undefined; /** Maximum blend toward a domain-radial escape normal for deep penetrations; zero keeps the raw gradient. */ deepEscape?: SkinnedMeshSDFScalar | undefined; } /** TSL uniform nodes owned and refreshed by a {@link SkinnedMeshSDF} instance. */ export interface SkinnedMeshSDFUniforms { /** Normalized-field to world transform. */ readonly sdfToWorld: THREE.UniformNode<'mat4', THREE.Matrix4>; /** World to normalized-field transform. */ readonly worldToSdf: THREE.UniformNode<'mat4', THREE.Matrix4>; /** Timestep used for surface-velocity estimation. */ readonly dt: THREE.UniformNode<'float', number>; /** World-space size of one voxel per axis. */ readonly voxelSize: THREE.UniformNode<'vec3', THREE.Vector3>; /** Exact-distance band half-width in world units. */ readonly band: THREE.UniformNode<'float', number>; /** Signed distance reported where no surface information exists. */ readonly far: THREE.UniformNode<'float', number>; } /** * Live signed-distance and surface-velocity field rebuilt from a skinned * mesh's actual triangles, entirely on the GPU, every frame. * * Each {@link SkinnedMeshSDF.dispatch} skins every vertex on the GPU, splats * exact triangle distances into a narrow atomic band, propagates them across * the grid, and resolves a pseudonormal sign — producing an rgba16float * texture holding surface velocity (xyz) and signed distance (w). The * skeleton is the provider seam: an `AnimationMixer`, MediaPipe or Kinect * retargeting, WebXR joints, or any other bone driver feeds the field with * no extra configuration. Sample it from TSL with the built-in helpers, or * bind the texture and uniforms directly in custom node graphs and * simulation hooks. */ export interface SkinnedMeshSDF { /** Cubic voxel dimension of the field. */ readonly resolution: number; /** World-space size of the field domain. */ readonly domain: THREE.Vector3; /** Owned rgba16float collider texture: surface velocity xyz, signed distance w. */ readonly texture: SDFTextureOutput; /** Owned uniform nodes shared by every pass and external sampler. */ readonly uniforms: SkinnedMeshSDFUniforms; /** World-space size of one voxel per axis. */ readonly voxelSize: THREE.Vector3; /** Smallest voxel edge; the distance step used during propagation. */ readonly voxelStep: number; /** Mutable normalized-field to world transform, refreshed by {@link setDomainCenter}. */ readonly sdfToWorldMatrix: THREE.Matrix4; /** Mutable world to normalized-field transform, refreshed by {@link setDomainCenter}. */ readonly worldToSdfMatrix: THREE.Matrix4; /** Skinned world-space vertex positions, one vec4 per vertex. */ readonly positionBuffer: THREE.StorageBufferNode<'vec4'>; /** Clamped world-space vertex velocities, one vec4 per vertex. */ readonly velocityBuffer: THREE.StorageBufferNode<'vec4'>; /** Sample the field at a world position: surface velocity xyz, signed distance w. */ sample(worldPosition: SkinnedMeshSDFSamplePosition): THREE.Node<'vec4'>; /** Signed distance from a world position to the tracked surface. */ distance(worldPosition: SkinnedMeshSDFSamplePosition): THREE.Node<'float'>; /** Tetrahedral field gradient at a world position; normalize it for a contact normal. */ gradient(worldPosition: SkinnedMeshSDFSamplePosition): THREE.Node<'vec3'>; /** Interpolated surface velocity of the nearest tracked surface point. */ surfaceVelocity(worldPosition: SkinnedMeshSDFSamplePosition): THREE.Node<'vec3'>; /** * Complete collision response for simulation hooks: sample, tetrahedral * contact normal, friction and restitution against the surface's own * velocity, and penetration push-out. Returns the corrected world-space * velocity. */ collide(options: SkinnedMeshSDFCollideOptions): THREE.Node<'vec3'>; /** Recenter the axis-aligned field domain around a world-space point. */ setDomainCenter(center: THREE.Vector3): void; /** Refresh skeleton, transform, and timestep state before a dispatch. */ update(dt: number, center?: THREE.Vector3): void; /** Submit the complete field rebuild to the renderer. */ dispatch(renderer: THREE.Renderer): void; /** Release the owned texture, storage buffers, and compute passes. */ dispose(): void; } interface SkinnedMeshSDFConstructor { /** Build the complete compute graph for one indexed, skinned mesh. */ new (skinnedMesh: THREE.SkinnedMesh, options?: SkinnedMeshSDFOptions): SkinnedMeshSDF; /** Runtime prototype shared with the backing implementation. */ readonly prototype: SkinnedMeshSDF; } /** Runtime skinned-mesh SDF constructor with its pass graph and seed buffers hidden. */ export declare const SkinnedMeshSDF: SkinnedMeshSDFConstructor; /** Construction configuration for {@link RayMarchSDFNodeMaterial}. */ export interface RayMarchSDFMaterialOptions { /** Base surface color. */ color?: THREE.ColorRepresentation | undefined; /** Rim and specular highlight color. */ highlightColor?: THREE.ColorRepresentation | undefined; /** Top color of the optional material-generated background. */ backgroundTop?: THREE.ColorRepresentation | undefined; /** Bottom color of the optional material-generated background. */ backgroundBottom?: THREE.ColorRepresentation | undefined; /** Background opacity; use zero when compositing over another render. */ backgroundAlpha?: number | undefined; /** Perceptual surface roughness. */ roughness?: number | undefined; /** Conservative sphere-tracing multiplier balancing speed against missed surfaces. */ stepScale?: number | undefined; /** Subsurface scattering blend; zero preserves the opaque material path. */ translucency?: number | undefined; /** Per-unit-depth body transmission color. */ absorptionColor?: THREE.ColorRepresentation | undefined; /** Tint applied to light scattered through the body. */ scatterColor?: THREE.ColorRepresentation | undefined; /** Optical density applied to measured body paths. */ absorptionDensity?: number | undefined; /** Analytic studio-environment blend; zero preserves legacy reflection and background shading. */ envIntensity?: number | undefined; /** Terminator, phase-skirt, and cone-light softening blend. */ scatterSoftness?: number | undefined; /** Interior index of refraction; one preserves the straight transmission path. */ ior?: number | undefined; /** Exit-only red/green/blue refraction spread. */ dispersion?: number | undefined; /** Low-frequency field-local interior density variation. */ cloudStrength?: number | undefined; /** Ridged field-local vein extinction strength. */ veinStrength?: number | undefined; /** Per-unit-depth transmission color inside veins. */ veinColor?: THREE.ColorRepresentation | undefined; /** Dual-lobe polished-surface reflection blend. */ finishIntensity?: number | undefined; /** Surface-only micro-normal and roughness variation. */ surfaceDetail?: number | undefined; /** AgX output-transform blend. */ filmic?: number | undefined; /** Output exposure in stops. */ exposure?: number | undefined; /** Integer-pixel final-gradient dither strength. */ ditherStrength?: number | undefined; /** Integer-pixel primary-ray offset strength. */ marchJitter?: number | undefined; /** * Performance tier from zero through four. Lower tiers reduce field-noise octaves, * disable dispersion, then reduce cone-light transport taps. */ quality?: number | undefined; } /** * Three.js material that ray-marches a caller-owned SDF texture. * * Construction builds the node graph immediately and may throw when required * WGSL features are unavailable. The input texture is borrowed: disposing the * material releases only material-owned resources. The facade remains * assignable to `THREE.Material` while implementation uniforms and nodes stay * private. */ export interface RayMarchSDFNodeMaterial extends THREE.Material { /** Runtime type guard identifying this specialized material. */ readonly isRayMarchSDFNodeMaterial: boolean; /** Dispatch the standard Three.js material disposal event without disposing the texture. */ dispose(): void; } interface RayMarchSDFNodeMaterialConstructor { /** Construct a material that borrows the supplied three-dimensional texture. */ new (sdfTexture: SDFTextureOutput, options?: RayMarchSDFMaterialOptions): RayMarchSDFNodeMaterial; /** Runtime prototype shared with the backing node material. */ readonly prototype: RayMarchSDFNodeMaterial; } /** Runtime ray-marching material constructor with its uniform graph hidden. */ export declare const RayMarchSDFNodeMaterial: RayMarchSDFNodeMaterialConstructor; /** Direct BVH query strategy used by {@link BVHVolumeConstraint}. */ export type BVHVolumeConstraintMode = 'triangles' | 'points'; /** Construction configuration for {@link BVHVolumeConstraint}. */ export interface BVHVolumeConstraintOptions { /** Caller-owned source geometry referenced until the constraint is updated. */ geometry: THREE.BufferGeometry; /** Caller-owned BVH, or `null` to resolve `geometry.boundsTree`. */ bvh?: GeometryBVH | null | undefined; /** Use signed triangle queries or point-shell range queries. */ mode?: BVHVolumeConstraintMode | undefined; /** Penetration correction strength. */ stiffness?: number | undefined; /** Normal-velocity damping applied during collision response. */ damping?: number | undefined; /** Triangle-surface distance offset. */ threshold?: number | undefined; /** Point-shell radius used only in `points` mode. */ pointRadius?: number | undefined; /** Largest local-space distance searched by a BVH query. */ maxSearchDistance?: number | undefined; /** Keep particles inside triangle geometry when true, or outside when false. */ containment?: boolean | undefined; /** Optional initial local-to-world transform copied during construction. */ worldMatrix?: THREE.Matrix4 | null | undefined; } /** Per-dispatch response configuration shared by BVH and SDF constraints. */ export interface SDFBoundaryApplyOptions { /** Particle-center offset added to the effective boundary distance. */ particleRadius?: number | undefined; /** Correct positions without applying a velocity response. */ positionOnly?: boolean | undefined; /** Apply a velocity response without correcting positions. */ velocityOnly?: boolean | undefined; /** Resolve the full measured penetration in one dispatch. */ hardProjection?: boolean | undefined; } /** * Caller-owned vector storage modified in place by a particle constraint. * * Both positions and velocities must describe at least the supplied particle * count and must retain their identity between calls to reuse the cached pass. */ export type SDFParticleVectorStorage = THREE.StorageBufferAttribute | THREE.StorageBufferNode<'vec3'>; /** * Direct BVH particle-volume constraint. * * Construction validates the geometry and BVH and prepares packed query data; * it can throw when either is absent or malformed. `apply()` modifies both * caller-owned buffers in place and submits one ordered compute dispatch. Passes * are cached by buffer identity and count, so stable inputs avoid graph rebuilds. */ export interface BVHVolumeConstraint { /** Active query strategy fixed at construction. */ readonly mode: BVHVolumeConstraintMode; /** Penetration correction strength used by subsequent dispatches. */ stiffness: number; /** Normal-velocity damping used by subsequent dispatches. */ damping: number; /** Triangle-surface offset used in `triangles` mode. */ threshold: number; /** Point-shell radius used in `points` mode. */ pointRadius: number; /** Largest local-space query distance. */ maxSearchDistance: number; /** Whether triangle mode keeps particles inside the volume. */ containment: boolean; /** Copy a local-to-world transform and refresh its cached inverse. */ setWorldMatrix(matrix: THREE.Matrix4): void; /** Submit one in-place boundary response after all preceding simulation writes. */ apply(renderer: THREE.Renderer, positions: SDFParticleVectorStorage, velocities: SDFParticleVectorStorage, particleCount: number, options?: SDFBoundaryApplyOptions): Promise; /** Replace borrowed geometry/BVH inputs and invalidate cached query passes. */ updateBVH(geometry: THREE.BufferGeometry, bvh?: GeometryBVH | null): void; /** Release packed BVH data and cached passes without disposing borrowed inputs. */ dispose(): void; } interface BVHVolumeConstraintConstructor { /** Construct and validate a direct-query boundary constraint. */ new (options: BVHVolumeConstraintOptions): BVHVolumeConstraint; /** Runtime prototype shared with the backing implementation. */ readonly prototype: BVHVolumeConstraint; } /** Runtime BVH-constraint constructor with buffers, passes, and caches hidden. */ export declare const BVHVolumeConstraint: BVHVolumeConstraintConstructor; /** Borrowed SDF resource surface consumed by {@link SDFVolumeConstraint}. */ export interface SDFVolumeSource { /** Current borrowed SDF texture; a missing value makes `apply()` a no-op. */ readonly sdfTexture?: SDFTextureOutput | null | undefined; /** Cubic texture resolution used to derive gradient sample spacing. */ readonly resolution: number; /** Mutable world-to-normalized-volume transform read before each dispatch. */ readonly inverseBoundsMatrix: THREE.Matrix4; /** Mutable normalized-volume-to-world transform read before each dispatch. */ readonly boundsMatrix: THREE.Matrix4; } /** Persistent response configuration for {@link SDFVolumeConstraint}. */ export interface SDFVolumeConstraintOptions { /** Penetration correction strength. */ stiffness?: number | undefined; /** Normal-velocity damping applied during collision response. */ damping?: number | undefined; /** Signed-distance surface offset. */ threshold?: number | undefined; } /** * Particle-volume constraint sampling a generated SDF. * * The source and particle buffers are borrowed and never disposed. `apply()` is * a no-op while the source has no texture; otherwise it modifies positions and * velocities in place with one compute dispatch. Call it after producers have * written both buffers and before consumers read the constrained values. Cached * passes rebuild when source texture, buffer identity, or particle count changes. */ export interface SDFVolumeConstraint { /** Current borrowed source, or `null` to disable dispatches. */ readonly sdfGenerator: SDFVolumeSource | null; /** Penetration correction strength used by subsequent dispatches. */ stiffness: number; /** Normal-velocity damping used by subsequent dispatches. */ damping: number; /** Signed-distance surface offset used by subsequent dispatches. */ threshold: number; /** Submit one in-place SDF boundary response after preceding simulation writes. */ apply(renderer: THREE.Renderer, positions: SDFParticleVectorStorage, velocities: SDFParticleVectorStorage, particleCount: number, options?: SDFBoundaryApplyOptions): Promise; /** Replace the borrowed source and invalidate all cached compute passes. */ updateSDF(source: SDFVolumeSource | null): void; /** Release cached passes without disposing the source, texture, or particle buffers. */ dispose(): void; } interface SDFVolumeConstraintConstructor { /** Construct a lazy SDF constraint around a borrowed source. */ new (source: SDFVolumeSource | null, options?: SDFVolumeConstraintOptions): SDFVolumeConstraint; /** Runtime prototype shared with the backing implementation. */ readonly prototype: SDFVolumeConstraint; } /** Runtime SDF-constraint constructor with uniforms, passes, and caches hidden. */ export declare const SDFVolumeConstraint: SDFVolumeConstraintConstructor; /** Stable SDF generation, visualization, and raymarching extensions. */ export { ComputePointsSDFGenerator } from './Compute/ComputePointsSDFGenerator.js'; export { sdfFieldNodes } from './TSL/SDFFieldNodes.js'; export type { SDFFieldNodes, SDFFieldNodesOptions, SDFFieldNodesSource, SDFFieldOcclusionOptions, SDFFieldShadowOptions, } from './TSL/SDFFieldNodes.js'; export { RaymarchingBox } from './Addons/Raymarching.js'; export { RenderSDFLayerNodeMaterial } from './Materials/RenderSDFLayerNodeMaterial.js'; export { SDFSliceVolumeNodeMaterial } from './Materials/SDFSliceVolumeNodeMaterial.js'; export { createSDFBoundsHelper, createSDFPointCloudHelper, updateSDFBoundsHelper, } from './Compute/SDFVolumeHelpers.js';