PipelineOverrides

Summary: PipelineOverrides - Manage WGSL override constants WGSL override constants allow compile-time specialization: ```wgsl override USE_NORMAL_MAP: bool = false; override ALPHA_CUTOFF: f32 = 0.5; ```


ShaderVariant

Summary: ShaderVariant - A specific configuration of a shader


UberShaderBuilder

Summary: UberShaderBuilder - Build ubershaders with feature toggles


createDefaultRegistry

Summary: Create a default shader chunk registry with standard chunks


Summary: Standard WGSL chunks for voxel rendering


Summary: Std140StructBuilder - Build CPU-side structs that match GPU layout exactly


Summary: Std140StructLayout - Immutable layout definition with write methods


alignOffset

Summary: Calculate aligned offset for a field


createFrameUniformsLayout

Summary: Create a FrameUniforms layout matching the VoxelRenderer


createChunkUniformsLayout

Summary: Create a ChunkUniforms layout


createPBRMaterialLayout

Summary: Create a MaterialUniforms layout for PBR materials


render/materials/TextureManager

Summary: Create a TextureManager instance.


createTextureManager

createTextureManager(device, options = {})

Summary: Create a TextureManager instance.


render/materials/VoxelMaterial

Summary: VoxelMaterial.js - Production Voxel Material Implementation Now powered by vGPU driver Demonstrates the complete material system architecture: - Frequency-based bind groups (Frame/Material/Chunk) - std140-compliant uniform layouts - Pipeline specialization with override constants - Modular shader composition


VoxelMaterial

Summary: VoxelMaterial - Complete material implementation for voxel rendering


createVoxelFrameLayout

Summary: Create the Frame uniforms layout (Group 0)


createVoxelMaterialLayout

Summary: Create the Material uniforms layout (Group 1)


createVoxelChunkLayout

Summary: Create the Chunk uniforms layout (Group 2)


Summary: Standard voxel vertex buffer layout


render/materials/VoxelMaterialIntegration

Summary: VoxelMaterialManager - Manages voxel materials with the new system


createVoxelFrameUniformsLayout

Summary: Create validated Frame uniforms layout matching VoxelRenderer shader


createVoxelChunkUniformsLayout

Summary: Create validated Chunk uniforms layout


createDefaultVoxelOverrides

Summary: Create default voxel pipeline overrides


createLowQualityOverrides

Summary: Create low-quality overrides for performance


integrateWithVoxelRenderer

Summary: Integrate material system with existing VoxelRenderer


createValidatedFrameUniformsBuffer

Summary: Create frame uniforms buffer with validated layout


createValidatedChunkUniformsBuffer

Summary: Create chunk uniforms buffer with validated layout


Summary: Voxel shader features that can be toggled via overrides


render/materials/index

Summary: Create a complete material system for voxel rendering


render/mesh/ClothMeshRenderer

Summary: ClothMeshRenderer.js - GPU Cloth Mesh Rendering Renders cloth simulations as triangle meshes with proper shading. Reads particle positions from GPU buffer and generates mesh on the fly.


render/mesh/CustomMeshRegistry

Summary: ============================================================================ CustomMeshRegistry.js - Store imported mesh geometry for custom models ============================================================================


registerCustomMesh

Summary: Register a custom mesh geometry.


unregisterCustomMesh

Summary: Unregister a custom mesh.


getCustomMesh

Summary: Get geometry data for a custom mesh.


isCustomMesh

Summary: Check if a meshType is a custom (imported) mesh.


getRegisteredMeshTypes

Summary: Get all registered custom mesh keys.


onMeshRegistered

Summary: Subscribe to mesh registration events. Callback: (meshKey, geo) => void


getCustomMeshCount

Summary: Get count of registered custom meshes.


render/mesh/EntityMeshRenderer


render/mesh/GPUSkinning

Summary: ============================================================================ GPUSkinning.js — Compute-shader skeletal skinning  Moves vertex skinning from CPU to GPU. Per skinned mesh: Static buffers (uploaded once):  bind-pose positions+normals+tangents, UVs, joint indices, joint weights Dynamic buffer (per frame):       skin matrices (jointCount × mat4x4) Output:                           interleaved vertex buffer (pos3+norm3+uv2+tangent4) with STORAGE|VERTEX usage so the existing render pipeline reads it directly.  The compute shader skins all vertices in parallel (workgroup_size=64). ============================================================================


render/mesh/ProceduralSkeleton

Summary: ============================================================================ ProceduralSkeleton.js — Auto-generate skeleton + skin weights for arbitrary meshes  Uses PCA to find principal axes, places bones along them, and computes smooth distance-based vertex weights (4 influences per vertex). Output format matches glTF import so it plugs directly into registerSkinnedMesh() / SkeletalAnimation.js. ============================================================================


generateProceduralSkeleton

generateProceduralSkeleton(positions, normals, options = {})

Summary: Generate a procedural skeleton for an arbitrary mesh. Algorithm: 1. Compute mesh centroid + covariance matrix 2. PCA via Jacobi iteration → 3 principal axes sorted by extent 3. Place bones along principal axis (chain), with optional branches along secondary axis if mesh is wide enough 4. Compute per-vertex weights: 4 nearest bones, inverse-distance 5. Build inverse bind matrices (identity rotation, translation only)


augmentGeoWithSkeleton

Summary: Convenience: generate skeleton AND augment geo object in-place. Returns the skeleton object for passing to registerSkinnedMesh.


render/mesh/RopeMeshRenderer

Summary: RopeMeshRenderer.js - GPU Rope Mesh Rendering with Anisotropic Fiber Shading Renders rope simulations as smooth tube meshes with Marschner hair shading model. Supports twist, color blending, and material properties for realistic fiber appearance.


render/mesh/SkeletalAnimation

Summary: ============================================================================ SkeletalAnimation.js - CPU skeletal animation + skinning for imported models  Evaluates glTF animations per-frame, computes joint world matrices, and skins vertex positions/normals/tangents on CPU. Updates the GPU vertex buffer via EntityMeshRenderer. ============================================================================


registerSkinnedMesh

registerSkinnedMesh(meshKey, geo, skeleton, animations)

Summary: Register a skinned mesh for animation playback.


unregisterSkinnedMesh

Summary: Unregister a skinned mesh.


getSkinnedMesh

Summary: Get a skinned mesh instance.


tickSkeletalAnimations

Summary: Tick all active skinned meshes. Call once per frame before rendering.


registerModelNodeAnimation

registerModelNodeAnimation(modelInstanceId, graph, animations, playbackState = null)

Summary: Register ordinary glTF node animation once per model entity instance.


isSkinnedMesh

Summary: Check if a meshKey has skeletal animation.


getSkinnedGeometry

Summary: Get the current skinned positions/normals/tangents for a mesh. Returns null if not a skinned mesh.


getSkinnedBounds

Summary: Compute current local-space skinned bounds from bind vertices and live skin matrices. This remains authoritative when GPU skinning intentionally leaves CPU outputs stale.


getCachedSkinnedBounds

Summary: Get the current bounds already refreshed by the animation/ragdoll tick.


getSkinnedMeshKeys

Summary: Get all registered skinned mesh keys.


getBoneCapsules

Summary: Get per-bone capsule dimensions computed from vertex weights. Returns cached data computed once at registration time.


getAnimatedBoneShapes

Summary: Get ANIMATED bone shapes for visual overlay rendering. Returns current-frame bone positions/rotations with mesh-measured capsule sizes. Uses the CURRENT animated worldMatrices so capsules track the animation exactly. This is the PRIMARY API for the visual bone overlay in Viewport.js. Each bone returns: - pos: world position (midpoint between bone and first child) - rot: quaternion aligning Y-axis with bone direction - radius: mesh-measured perpendicular distance (90th percentile) - halfHeight: half the bone length minus radius - name: bone name for debug/classification - parentIndex: parent bone index (-1 for roots) - isTerminal: true for end/nub bones (skip rendering)


getBindPoseBones

Summary: Get bind-pose bone data WITHOUT modifying state (no ragdoll, no animation stop). Used for edit-mode SDF collider visualization preview.


enableRagdoll

Summary: Enable ragdoll mode for a skinned mesh. Stops animation and returns bind-pose bone world positions + hierarchy for creating physics bodies.


setRagdollBoneTransforms

Summary: Update bone world matrices from ragdoll physics transforms, then reskin.


disableRagdoll

Summary: Disable ragdoll mode, resuming animation.


render/mesh/VirtualGeometrySystem


render/mesh/index

Summary: Mesh Renderers - GPU mesh rendering utilities


render/morphfield/assets/MorphAssetCodec


encodeMorphAsset

async encodeMorphAsset(sceneInput, options = {})


decodeMorphAsset

async decodeMorphAsset(input, options = {})


loadMorphAsset

async loadMorphAsset(source, options = {})


render/morphfield/assets/MorphAssetFormat


render/morphfield/assets/index


render/morphfield/assets/selfTest


render/morphfield/core/AabbBvh


render/morphfield/core/FieldletAbi


createOutwardF32Bounds(bounds, expansion = 0)


packFieldletMeta

packFieldletMeta({ subtype = 0, family = 0, queryMask = 0, flags = 0 } = {})


createFieldletHeader

createFieldletHeader({ boundsRef, payloadRef, meta, certificateRef = INVALID_REF })


readFieldletHeader

readFieldletHeader(view, byteOffset = 0)


createCertificateBundle

createCertificateBundle({ surfaceRef = INVALID_REF, mediumRef = INVALID_REF, motionRef = INVALID_REF, collisionRef = INVALID_REF, } = {})


createSurfaceCertificate

createSurfaceCertificate({ fieldValueErrorMax = 0, lipschitzMax, fallbackBand = 0, motionRadiusMax = 0, })


createMediumCertificate

createMediumCertificate({ densityMax = 0, extinctionMax = 0, emissionLuminanceMax = 0, motionRadiusMax = 0, } = {})


createMotionCertificate

createMotionCertificate({ displacementMax = 0, speedMax = 0, accelerationMax = 0, validDuration = 0, } = {})


createCollisionCertificate

createCollisionCertificate({ fieldValueErrorMax = 0, lipschitzMax, contactOffset, contactSlop = 0, motionRadiusMax = 0, })


render/morphfield/core/MeshTopologyValidation

Summary: Validate finite indexed triangle geometry and, when requested, prove an oriented closed 2-manifold index topology. This is shared by authored indexed Nexels and extracted surface-cache publication.


validateIndexedTriangleMesh

validateIndexedTriangleMesh(mesh, options = {})


render/morphfield/core/MorphFieldCompiler

Summary: Qualify a structured-cloned/worker result by deterministically recompiling its authoritative semantic snapshot and comparing every executable ABI byte. This is the cross-realm path; normal same-realm compiler output uses the private registry above and does not pay for a second compilation.


inspectNexelCompilerFeasibility

Summary: Run the compiler's exact isolated-descriptor admission gates synchronously. Capability inspection uses this probe so it cannot claim a direct GPU path for a descriptor that compilation would later reject.


render/morphfield/core/NexelScene


render/morphfield/core/ReferenceQueries


render/morphfield/core/Transform


normalizeVector3(value, path = 'vector', fallback = [0, 0, 0])


normalizeQuaternion

normalizeQuaternion(value, path = 'rotation')


normalizeTransform

normalizeTransform(input = undefined, path = 'transform')


render/morphfield/core/constants


render/morphfield/core/errors


failMorphField

failMorphField(code, message, details = undefined)


invariant

invariant(condition, code, message, details = undefined)


asMorphFieldError

asMorphFieldError(error, code, message, details = undefined)


render/morphfield/core/index


render/morphfield/core/selfTest


render/morphfield/core/serialization

Summary: Compare identifiers by ECMAScript UTF-16 code-unit order. Unlike localeCompare(), this ordering is independent of the host locale and ICU version, so packed Fieldlet indices remain reproducible across machines.


canonicalize

canonicalize(value, path = '$', options = {})


deepFreeze

deepFreeze(value, visited = new WeakSet()


render/morphfield/core/validation


normalizeSource

normalizeSource(input, path = 'source', depth = 0, options = {})


validateMaterialF32Channels(material, path = 'material')


normalizeNexelDescriptor

normalizeNexelDescriptor(input, path = 'nexel')


render/morphfield/index

Summary: Create a device-independent semantic Nexel scene.


createCompiler

Summary: Create a deterministic device-independent MorphField compiler.


encodeAsset

Summary: Encode a semantic scene into a bounded, checksummed MOR2 container.


loadAsset

Summary: Load a MOR2 container and return its authoritative semantic Nexel scene. Use inspectAsset() when chunk metadata or provenance is also required.


inspectAsset

Summary: Decode a MOR2 container while retaining provenance and optional chunks.


createRenderer

Summary: Create an external-encoder renderer that borrows its host GPUDevice.


createPathTracer

Summary: Create the bounded-queue progressive compute path tracer.


createMicrostructureRenderer

Summary: Create the portable u32 render-cluster decoder on a borrowed GPU device.


createAffineBrickRenderer

Summary: Create the direct 32-byte AFFINE4 brick decoder on a borrowed GPU device.


MorphField

Summary: Stable public namespace used by Engine.MorphField and bundled window.PE. Internal implementation groups remain inspectable without flattening conflicting ABI aliases into the public method surface.


render/morphfield/runtime/AdaptiveQualityGovernor


normalizeQualityDecision

normalizeQualityDecision(decision, fallback, options = {})


render/morphfield/runtime/MorphFieldRenderer


render/morphfield/runtime/NexelAffineBrickRenderer

Summary: Directly expands 32-byte AFFINE4 morphology payloads into render-only cells. Simulation/collision remains attached to the authoritative MorphField scene.


render/morphfield/runtime/NexelAffineBrickShaders

Summary: Direct GPU expansion of a 32-byte, sixty-four-microcube AFFINE4 payload.


render/morphfield/runtime/NexelMicrostructureRenderer

Summary: A borrowed-device, external-encoder renderer. Each 32-byte parent Nexel is decoded directly in WGSL into at most eight render-only samples.


render/morphfield/runtime/NexelMicrostructureShaders

Summary: Portable u32 direct-decode renderer for RM(1,3) Nexel clusters.


render/morphfield/runtime/NexelPresentationRuntime


writeNexelFrameUniforms

writeNexelFrameUniforms(target, { camera, viewport, time, frameCount, quality, pointGain, projectionScale, opacity, } = {})


render/morphfield/runtime/NexelShaderPlan

Summary: Root-Algebra-style immutable execution plan shared by every Nexel shader.


render/morphfield/runtime/QueryEncoder


render/morphfield/runtime/ResourceOwnershipTracker


render/morphfield/runtime/RuntimeShaders


render/morphfield/runtime/SceneBufferUploader

Summary: Validate the compiler-to-runtime binary contract without granting runtime trust.  This is intentionally useful for diagnostics and fuzzing; renderer activation separately requires the private compiler-origin registry.


packSpatialRecords

Summary: Pack Fieldlet bounds, compiler BVH nodes, per-Fieldlet collision metadata, and one validated scene trailer in a single storage binding. WebGPU guarantees only eight storage buffers per shader stage on the portable baseline, so tracing and queries cannot add separate spatial or collision bindings to the existing scene ABI.


render/morphfield/runtime/capabilities

Summary: Reports optional compute paths separately from the portable u32 baseline. Support is not evidence that a pipeline selected or used a feature; callers must record those two states alongside benchmark results.


inspectNexelComputeCapabilities

inspectNexelComputeCapabilities(device, { wgslLanguageFeatures } = {})


render/morphfield/runtime/index

Summary: Validates and detaches the canonical typed-array ABI published by this realm's MorphFieldCompiler. Authored object Fieldlets and cloned certificate arrays are not a certification boundary and are rejected.


render/morphfield/runtime/wavefront/MorphFieldWavefrontPathTracer

Summary: Buffer-only compute wavefront path tracer for compiled MorphField scenes. It borrows every host object, records only into the supplied encoder, and owns only its pipelines, queue/state buffers, uniforms, and accumulation.


render/morphfield/runtime/wavefront/WavefrontShaders


render/morphfield/runtime/wavefront/constants

Summary: Packs one extension record per material as [transmissionFactor, ior, clearcoatFactor, clearcoatRoughness].


render/morphfield/runtime/wavefront/index


render/morphfield/runtime/wavefront/selfTest


runWavefrontSelfTest

async runWavefrontSelfTest({ realWebGpu = false, device = null } = {})


render/morphfield/schemas/ids


render/morphfield/schemas/index

Summary: Normalize one semantic Nexel and report the execution/query capabilities the current R2 implementation can honestly provide for it.


render/morphfield/systems/EngineSimulationAdapters

Summary: Adapt the existing particle world to the shared host encoder.


createParticleWorldAdapter

createParticleWorldAdapter(world, options = {})


createFluidWorldAdapter

createFluidWorldAdapter(world, options = {})

Summary: Adapt the existing external-encoder fluid grid.


createVolumeSystemAdapter

createVolumeSystemAdapter(volumeSystem, options = {})

Summary: Adapt an existing volume system exposing update(encoder, camera).


createGpuSimulationAdapter

Summary: Generic bridge for a caller-owned GPU simulation. It deliberately does not invent domain-specific solver names or resource ownership.


render/morphfield/systems/KernelMedia

Summary: CPU reference and bin-builder for semantic anisotropic oriented kernels.


LayeredOITAccumulator

Summary: Four exact sorted layers followed by a bounded weighted-blended tail.


integrateMedium

integrateMedium(ray, evaluateMedium, options = {})

Summary: Deterministic reference integrator using a certified extinction majorant.


render/morphfield/systems/NexelMicrostructure

Summary: Portable binary microstructure tools for Nexel render clusters and voxel bricks. These helpers describe local storage and verification only; they do not replace a chunk CRC/authentication tag or an outer error-correcting code.


compileNexelAffineDecodePlan

Summary: Compile the eight affine Boolean equations into one u32 of nibble masks, then exhaustively prove the branch-free parity plan against the reducer. This follows Root Algebra Lab's validated-plan discipline without adopting its deliberately research-only carry/sign multiplier.


compileNexelDictionary

Summary: Compile an immutable exact dictionary and reverse lookup once per codebook.


affineCubeSample

Summary: Evaluate one corner of an RM(1,3) affine microcube.


expandAffineCube

Summary: Expand an affine morphology into its exact eight-bit occupancy mask.


decodeAffineCube

Summary: Return the affine morphology for a pattern, or null for a non-codeword.


affineFaceParitySyndrome

Summary: Six-bit local face-parity syndrome ordered x0,x1,y0,y1,z0,z1. A valid RM(1,3) word has zero syndrome; another valid word can still evade it.


Summary: Interleave three five-bit coordinates into the descriptor's 15-bit Morton field.


encodeNexelMicrocube

encodeNexelMicrocube(pattern, { dictionary } = {})

Summary: Choose the smallest lossless local mode under the supplied dictionary.


decodeNexelMicrocube

decodeNexelMicrocube(encoded, { dictionary } = {})


packNexelDescriptor

packNexelDescriptor({ mortonCoordinate = 0, material = 0, morphology = 0, state = 0, lod = 0, flags = 0, } = {})

Summary: Pack the research descriptor: 15/6/4/3/2/2 exact integer fields.


Summary: Pack sixty-four affine microcubes into eight u32 words (32 bytes).


Summary: Pack already-proven morphology nibbles without expanding and re-decoding.


createAffineNexelBrick

createAffineNexelBrick(patterns, options = {})


createAffineNexelBrickFromMorphologies

createAffineNexelBrickFromMorphologies(morphologies, options = {})

Summary: Build a brick directly from its sixty-four affine morphology nibbles.


verifyAffineNexelBrick

Summary: Recompute every local brick invariant without trusting stored TypedArrays.


nexelClusterCornerOrder

Summary: Return a deterministic, exact permutation of the eight microcube corners.


render/morphfield/systems/NexelPbdCollisionAdapter

Summary: Compile semantic static Nexels into PBDSolver collider inputs. PBDSolver's contactRadius remains a predictive OGC shell, while the solver geometry is inset by contactOffset-restOffset so the rendered and collision surfaces settle at the requested restOffset (zero by default).


compileNexelPbdColliderSet

compileNexelPbdColliderSet(descriptorInput, { contactOffset = 0.002, restOffset = 0, friction = 0.36, } = {})


applyNexelPbdColliderSet

Summary: Apply a compiled collider set without taking ownership of the solver.


render/morphfield/systems/ParticleChainNexelAdapter

Summary: Convert a caller-owned particle-chain snapshot into stable sphere/capsule Nexels. The simulation remains authoritative; this adapter performs no stepping, GPU readback, queue submission, or resource ownership transfer. Editor PhysicsChain component `links`, CPU PBD `particles`, and ordinary `[x,y,z]` arrays intentionally share this one input contract.


createParticleChainNexelDescriptors

createParticleChainNexelDescriptors(snapshot, options = {})


createParticleChainNexelPatch

createParticleChainNexelPatch(scene, snapshot, options = {})

Summary: Build an incremental scene patch while preserving stable chain IDs.


render/morphfield/systems/QefSolver

Summary: Rank-aware QEF solver using a Jacobi eigendecomposition of the local normal covariance and a truncated pseudoinverse. Coordinates are translated to the cell center before solving to preserve f32-compatible numerical scale.


solveQef

solveQef(intersections, normals, bounds, options = {})


render/morphfield/systems/RepresentationPlanner

Summary: Stable top-level MorphField execution families.


RepresentationPlanner

Summary: Deterministic representation planner. Source semantics and certificates are authoritative; performance history can only promote an eligible surface to a disposable cache.


selectSurfaceExtractor

selectSurfaceExtractor(intent = {}, capabilities = {})

Summary: Selects a single extractor for an entire connected seam domain. The selector intentionally returns direct rendering when a requested topology guarantee cannot be supported by certified Hermite data.


render/morphfield/systems/ResidualHierarchy

Summary: Certified scalar residual brick with deterministic trilinear sampling.


ResidualHierarchy

Summary: Revisioned, fixed-budget residual residency manager. The coarsest level is pinned, so every accepted source always has a certified fallback.


composeResidualCertificate

Summary: Compose analytic and residual surface certificates conservatively.


render/morphfield/systems/SimulationScheduler

Summary: Fixed-step scheduler for external-encoder simulation domains.


createExternalEncoderAdapter

createExternalEncoderAdapter({ id, authority = 'authoritative', encode, interpolate, updateStride = 1 })

Summary: Wrap an existing external-encoder simulation API without changing its name.


createKinematicAdapter

createKinematicAdapter({ id, sample, apply, authority = 'authoritative' })

Summary: Kinematic adapter that advances a caller-owned transform source.


render/morphfield/systems/SurfaceCacheExtractor

Summary: Device-independent surface cache extractor and validation boundary.


SurfaceCacheManager

Summary: Stages complete connected domains and atomically replaces validated entries.


validateMesh

validateMesh(mesh, topologyRequirement = 'unspecified')


render/morphfield/systems/index


render/morphfield/systems/transitions/TransitionBoundary

Summary: Build canonical signatures from the open edges of a transition mesh. Signatures contain complete sorted segment records as well as a compact hash; comparisons therefore never rely on hash equality alone.  World-space quantization makes opposite local face orientations compare identically.


createTransitionBoundarySignatures

createTransitionBoundarySignatures(mesh, options = {})


compareTransitionBoundaries

compareTransitionBoundaries(left, leftFace, right, rightFace)


assertTransitionBoundaryMatch

assertTransitionBoundaryMatch(left, leftFace, right, rightFace)


render/morphfield/systems/transitions/TransitionCellExtractor

Summary: Extract a deterministic transition slab for one exact-2:1 grid pair.


TransitionExtractionError

class TransitionExtractionError extends Error


render/morphfield/systems/transitions/TransitionValidation

Summary: Validate geometry, local manifoldness, winding, exact-2:1 metadata, and all recorded boundary signatures.  Open edges are valid only on one of the six transition-prism faces.


validateTransitionInterface

validateTransitionInterface(mesh, options = {})


render/morphfield/systems/transitions/index


render/morphfield/systems/transitions/selfTest


render/particles/CustomParticleEffect

Summary: CustomParticleEffect.js - Unified Particle Effect System KEY PRINCIPLE: ONE SDF function defines BOTH: 1. Visual rendering (raymarching in fragment shader) 2. Collision detection (compute shader physics) This ensures particle appearance ALWAYS matches collision shape.


generateVisualShader

generateVisualShader(effect, options = {})

Summary: Generate visual raymarching shader from effect


generateCollisionShader

Summary: Generate collision compute shader from effect


validateEffect

Summary: Validate effect WGSL code


compileEffect

Summary: Compile effect shaders on device (validates WGSL syntax)


createEffect

Summary: Create a new custom effect from template


cloneEffect

Summary: Clone an existing effect


getPresets

Summary: Get all built-in presets as array


getPreset

Summary: Get preset by ID


render/particles/CustomParticleEffectIntegration

Summary: CustomParticleEffectIntegration.js - Integration Layer Wires the custom particle effect system into the engine: - Initializes registry on engine startup - Provides utilities for applying effects to emitters - Connects visual effects to collision system


initCustomParticleEffects

Summary: Initialize the custom particle effect system Call this during engine initialization


getCompiledEffect

Summary: Get compiled effect shaders for an effect ID


getCollisionSDFSystem

Summary: Get the collision SDF system


applyEffectToEmitter

applyEffectToEmitter(emitterComponent, effectId, params = null)

Summary: Apply a custom effect to a particle emitter component


getEffectForRendering

Summary: Get effect data for rendering


createEffectParamsData

Summary: Create effect parameters buffer data for GPU Returns a reusable Float32Array - DO NOT modify after passing to GPU


getParticleSDF

Summary: Get the effective SDF for a particle (for collision queries) Returns a function that evaluates the SDF at a local position


isCustomEffectsInitialized

Summary: Check if custom effects system is initialized


render/particles/ParticleAgeRenderer


createParticleAgeDataBindGroup

createParticleAgeDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)


setParticleAgeParams

setParticleAgeParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })


render/particles/ParticleAlbedoRenderer

Summary: Create particle albedo pass renderer


createParticleAlbedoRenderer

Summary: Create particle albedo pass renderer


createParticleAlbedoDataBindGroup

createParticleAlbedoDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)

Summary: Create data bind group for albedo pass


setParticleAlbedoParams

setParticleAlbedoParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })

Summary: Update albedo pass parameters


render/particles/ParticleBeamRenderer

Summary: ParticleBeamRenderer.js - Beam / Lightning Particle Renderer (GAP 14) Renders connected line segments between sequential particles as thick beams. Supports: - Chain mode: connect particles in sequence (particle 0→1→2→3...) - Source mode: connect all particles to a single source point - Lightning mode: chain + per-segment jitter for electric arcs Each beam segment is a camera-facing quad strip (2 triangles per segment). Width can vary per particle (from meta.w size) and taper at ends. Usage: const beam = await createParticleBeamRenderer(device, { format }); renderBeamParticles(pass, beam, world, { viewProj, instanceCount });


createParticleBeamRenderer

async createParticleBeamRenderer(device, options = {})

Summary: Create a particle beam renderer.


bindBeamParticleData

Summary: Bind particle data from a particle world.


renderBeamParticles

renderBeamParticles(pass, renderer, options = {})

Summary: Render beam particles.


setBeamParams

Summary: Update beam parameters.


destroyParticleBeamRenderer

Summary: Destroy the beam renderer.


render/particles/ParticleBillboardRenderer

Summary: Creates a particle point renderer (spheres instead of flat billboards). This renders particles as actual points with spherical falloff.


createParticleBillboardRenderer

Summary: Creates a particle billboard renderer. This is a pure rendering module - it does not own particle simulation.


createParticleBillboardDataBindGroup

createParticleBillboardDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer, uvBuffer, albedoTextureView, albedoSampler)

Summary: Creates a data bind group for a specific particle world. Call this once per particle world you want to render.


setParticleBillboardParams

setParticleBillboardParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0, rotationRate = 0, useColorGradient = false, stretchFactor = 0, facingMode = 0, })

Summary: Updates particle rendering parameters including quality settings.


setParticleBillboardDepth

Summary: Create or update the scene depth + alive list bind group (GAP 17 + 18). Call this when the depth texture changes (e.g. on resize) or when connecting the alive list from IndirectDispatch for GPU indirect draw.


render/particles/ParticleBlackbodyRenderer

Summary: ParticleBlackbodyRenderer.js - Blackbody Radiation Renderer (GAP 39) Creates and manages the 1D blackbody LUT texture. Provides bind group for particle fragment shaders to sample temperature → color. Integrates with existing billboard and SDF renderers. Usage: const bb = createBlackbodySystem(device); const bindGroup = getBlackbodyBindGroup(bb); // Set as additional bind group in particle render pass


createBlackbodySystem

createBlackbodySystem(device, options = {})

Summary: Create the blackbody rendering system with LUT texture.


createBlackbodyBindGroupLayout

Summary: Create a bind group layout for blackbody resources. Typically bound as an additional group in particle render pipelines.


getBlackbodyBindGroup

Summary: Create the bind group for blackbody resources.


setBlackbodyEmission

Summary: Update emission strength at runtime.


destroyBlackbodySystem

Summary: Destroy.


render/particles/ParticleBondRenderer

Summary: ParticleBondRenderer.js - Bond Line / Stick Renderer (GAP 41) Renders molecular bonds as camera-facing quads between bonded particle pairs. Reads a bond buffer (vec4<u32> per bond: particleA, particleB, bondType, bondOrder). Color blends between element CPK colors at each endpoint. Supports covalent (solid), ionic (dashed), metallic (thick), hydrogen (dotted). Usage: const br = createBondRenderer(device, format); initBondRendererBindGroups(br, device, posBuffer, velBuffer, bondBuffer, colorLutBuffer, elementBuffer); uploadBonds(br, device, bondArray); renderBonds(pass, br, viewProj, cameraPos, viewRight, viewUp, bondCount);


createBondRenderer

Summary: Create the bond renderer.


initBondRendererBindGroups

initBondRendererBindGroups(renderer, device, positionBuffer, velocityBuffer, metaBuffer, thermalBuffer)

Summary: Initialize bind groups.


uploadBonds

uploadBonds(renderer, device, bondData, bondCount)

Summary: Upload bond data from CPU.


renderBonds

renderBonds(pass, renderer, viewProj, cameraPos, viewRight, viewUp)

Summary: Render bonds in the given render pass.


destroyBondRenderer

Summary: Destroy.


render/particles/ParticleCollisionSDF

Summary: ParticleCollisionSDF.js - Custom SDF Collision Integration Integrates custom particle effect SDFs into the collision system. The same SDF code used for visual rendering is used for collision detection. This module: 1. Generates collision compute shaders with custom SDFs 2. Manages effect-to-index mapping for GPU dispatch 3. Provides collision evaluation utilities


registerEffectForCollision

Summary: Register an effect for collision (assigns an index)


getEffectIndex

Summary: Get effect index (0 if not registered)


getEffectByIndex

Summary: Get effect by index


generateMultiEffectCollisionShader

Summary: Generate the multi-effect collision shader This shader supports switching between different SDFs based on effectId


createCollisionPipeline

createCollisionPipeline(device, options = {})

Summary: Create collision compute pipeline with custom SDFs


createParticleCollisionSDFSystem

Summary: Create a particle collision SDF system


render/particles/ParticleDecalRenderer

Summary: ParticleDecalRenderer.js - Render projected decals from particle collisions Renders decal quads at particle impact points (scorch marks, frost patches, wet splats). Reads from ParticleDecalSpawner's CPU-side pool each frame. Pipeline: 1. ParticleDecalSpawner (sim/) creates decal descriptors from collision events 2. This renderer uploads active decals to a GPU storage buffer 3. Instanced draw: each decal = screen-aligned quad projected onto surface 4. Blends onto scene with src-alpha / one-minus-src-alpha Decal data per instance (12 floats): [posX, posY, posZ, size, normX, normY, normZ, age/lifetime, r, g, b, a]


createDecalRenderer

Summary: Create a decal rendering system


uploadDecals

Summary: Upload active decals from the CPU-side spawner pool to GPU


renderDecals

Summary: Render decals into the current render pass


destroyDecalRenderer

Summary: Destroy decal renderer resources


render/particles/ParticleDepthRenderer

Summary: Create particle depth pass renderer


createParticleDepthRenderer

Summary: Create particle depth pass renderer


createParticleDepthDataBindGroup

createParticleDepthDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)

Summary: Create data bind group for depth pass


setParticleDepthParams

setParticleDepthParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })

Summary: Update depth pass parameters


render/particles/ParticleDistortionRenderer

Summary: ParticleDistortionRenderer.js - Heat haze / distortion from particles PopcornFX/Niagara parity: particles can distort the scene behind them. Hot particles, explosions, and magic effects create screen-space UV offsets. Pipeline: 1. Render distortion-emitting particles to an RG16float texture (UV offset) 2. Composite pass samples scene color with distorted UVs The distortion texture stores per-pixel UV offset (R=deltaU, G=deltaV). Particles contribute based on temperature/emissive strength.


createParticleDistortionRenderer

createParticleDistortionRenderer(device, sceneFormat, width, height)

Summary: Create the particle distortion rendering system


initDistortionBindGroups

Summary: Create bind groups for the distortion pass (call once when particle buffers are ready)


setDistortionParams

setDistortionParams(renderer, params = {})

Summary: Update distortion params


renderDistortionPass

renderDistortionPass(encoder, renderer, instanceCount, frameData)

Summary: Render distortion pass: accumulate UV offsets from hot particles


compositeDistortion

Summary: Composite distortion onto scene (fullscreen triangle)


resizeDistortionRenderer

Summary: Resize distortion texture when viewport changes


destroyDistortionRenderer

Summary: Destroy distortion renderer resources


render/particles/ParticleEffectRegistry

Summary: ParticleEffectRegistry.js - Custom Particle Effect Storage & Management Features: - IndexedDB persistence across sessions - Import/export as JSON files - Built-in presets always available - Version tracking for effect updates - Event-based notifications for changes


prepareParticleEffectRecord

Summary: Validate one exact v1/v2 record; no lossy upcasts are attempted.


getParticleEffectRegistry

Summary: Get the global registry instance


initParticleEffectRegistry

Summary: Initialize the global registry


render/particles/ParticleEmissiveRenderer


createParticleEmissiveDataBindGroup

createParticleEmissiveDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)


setParticleEmissiveParams

setParticleEmissiveParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })


render/particles/ParticleFieldRenderer

Summary: ParticleFieldRenderer.js - Electromagnetic Field Visualizer (GAP 42) Renders electric/magnetic field lines and force arrows around charged particles. Computes field probe grid on CPU from charged particle positions, uploads to GPU. Supports arrow glyphs showing force direction/magnitude. Color: red=positive/repulsion, blue=negative/attraction, intensity=magnitude. Usage: const fr = createFieldRenderer(device, format); updateFieldProbes(fr, device, chargedParticles, probeGrid); renderFieldArrows(pass, fr, viewProj, cameraPos, viewRight, viewUp);


createFieldRenderer

Summary: Create the field renderer.


initFieldRendererBindGroups

Summary: Initialize bind groups.


updateFieldProbes

updateFieldProbes(renderer, device, chargedParticles, gridConfig)

Summary: Generate field probes from charged particle positions (CPU-side). Creates a 3D grid of probe points and computes the E field at each.


renderFieldArrows

renderFieldArrows(pass, renderer, viewProj, cameraPos, viewRight, viewUp)

Summary: Render field arrows in the given render pass.


destroyFieldRenderer

Summary: Destroy.


render/particles/ParticleHalfResComposite

Summary: ParticleHalfResComposite.js - Half-resolution particle rendering + bilateral composite Renders particles to a half-res RGBA target, then composites onto the main framebuffer with alpha blending. Provides 4× fill-rate reduction for particle rendering. ==================== PIPELINE OVERVIEW (for future AI/developers) ==================== The particle color pipeline works as follows: 1. CPU writes per-particle color to metaBuffer in ParticleEmitterSystem.js: singleMeta[0..2] = emitterColor[0..2] (RGB from elementMixToEmitterConfig) → uploaded via device.queue.writeBuffer to GPU metaBuffer 2. SDF vertex shader (particles_sdf_billboard.js) reads: uMeta[ii].xyz → input.color Uses instance_index (ii) directly — NO alive list indirection in SDF path. The billboard shader (particles_billboard_vertex.js) DOES use uAliveList, but the active renderer is SDF (set in EditorParticles.js: particles.pipeline = sdfRenderer.pipeline). 3. SDF fragment shader applies volumetric lighting + thermal glow to input.color, outputs vec4<f32>(lit, finalAlpha) — NON-premultiplied. 4. SDF pipeline renders INTO this half-res texture with blend mode: color: src-alpha, one-minus-src-alpha  (standard alpha blend) This produces PRE-MULTIPLIED RGB in the texture because: result.rgb = src.rgb * src.a + cleared_black * (1 - src.a) = src.rgb * src.a 5. This composite pass reads the half-res texture and blends onto the scene. MUST use pre-multiplied blend (srcFactor='one') because step 4 already multiplied RGB by alpha. Using srcFactor='src-alpha' would DOUBLE the alpha (lit * alpha²), making low-alpha particles nearly invisible. CRITICAL: If you change the SDF pipeline blend mode, you must update this composite blend mode to match. src-alpha render → 'one' composite. premultiplied render → 'one' composite. Ref: GPU Gems 3 Ch.23 "High-Speed Off-Screen Particles"


createHalfResCompositeSystem

createHalfResCompositeSystem(device, format, fullWidth, fullHeight)

Summary: Create the half-resolution particle rendering + composite system.


resizeHalfResTargets

Summary: Resize half-res render targets. Call when the window/canvas resizes.


getHalfResPassDescriptor

Summary: Get the render pass descriptor for the half-res particle pass. Clear to transparent black (0,0,0,0) so alpha blending composites correctly. After particles render here with src-alpha blend, the texture contains pre-multiplied color: rgb = lit * alpha, a = combined alpha.


executeComposite

Summary: Execute the composite pass: upsample half-res particles onto main framebuffer.


destroyHalfResCompositeSystem

Summary: Destroy half-res composite system resources.


render/particles/ParticleLightingRenderer

Summary: Create particle lighting pass renderer


createParticleLightingRenderer

Summary: Create particle lighting pass renderer


createParticleLightingDataBindGroup

createParticleLightingDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)

Summary: Create data bind group for lighting pass


setParticleLightingParams

setParticleLightingParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })

Summary: Update lighting pass parameters


render/particles/ParticleMeshRenderer

Summary: ParticleMeshRenderer.js - Instanced Mesh Particle Renderer (GAP 9) Renders each particle as a 3D mesh instance instead of a billboard. Supports both regular triangle meshes AND voxel meshes (compact u32 format). Each particle's position/velocity/meta drives a mesh instance: - Position from particle positions buffer - Rotation from velocity direction (velocity-aligned) or billboard - Scale from meta.w packed size - Color tint from meta.rgb - Age-based fade from pos.w / vel.w Usage: const renderer = await createParticleMeshRenderer(device, { format, mesh }); // In render loop: renderMeshParticles(pass, renderer, world, { viewProj, instanceCount });


createParticleMeshRenderer

async createParticleMeshRenderer(device, options = {})

Summary: Create a particle mesh renderer.


setParticleMesh

Summary: Set the mesh to render per particle.


bindParticleData

Summary: Bind particle data buffers from a particle world.


renderMeshParticles

renderMeshParticles(pass, renderer, options = {})

Summary: Render mesh particles into a render pass.


setMeshParticleParams

setMeshParticleParams(renderer, params = {})

Summary: Update mesh particle renderer params.


initShadowPipeline

Summary: Lazily initialize the shadow depth pipeline for particle mesh shadow casting. Call once before the first flushShadowDepth. Requires dataBindGroup to be set.


flushShadowDepth

flushShadowDepth(pass, renderer, lightViewProj, instanceCount)

Summary: Render mesh particles into a shadow depth pass (depth-only, no color). Compatible with ShadowMapPass.renderShadowDepth().


destroyParticleMeshRenderer

Summary: Destroy the renderer.


render/particles/ParticleNormalsRenderer

Summary: Create particle normals pass renderer


createParticleNormalsRenderer

Summary: Create particle normals pass renderer


createParticleNormalsDataBindGroup

createParticleNormalsDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)

Summary: Create data bind group for normals pass


setParticleNormalsParams

setParticleNormalsParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })

Summary: Update normals pass parameters


render/particles/ParticleOrbitalRenderer

Summary: ParticleOrbitalRenderer.js - Electron Cloud / Orbital Renderer (GAP 40) Renders electron probability clouds around atom-particles using raymarched spherical harmonics. Color by element (CPK convention) from element table. LOD: full orbital at close range, simple sphere at distance. Usage: const orb = createOrbitalRenderer(device, format); renderOrbitals(pass, orb, { positionBuffer, elementBuffer, colorLutBuffer, camera });


createOrbitalRenderer

Summary: Create the orbital renderer.


initOrbitalBindGroups

initOrbitalBindGroups(renderer, device, positionBuffer, velocityBuffer, elementBuffer, lutBuffer, colorLutBuffer)

Summary: Initialize bind groups for orbital rendering.


renderOrbitals

renderOrbitals(pass, renderer, viewProj, cameraPos, viewRight, viewUp, instanceCount)

Summary: Render orbital clouds in the given render pass.


destroyOrbitalRenderer

Summary: Destroy.


render/particles/ParticlePhaseVFX

Summary: ParticlePhaseVFX.js - Phase Transition Visual Effects Manager (GAP 43) Manages phase-transition visual effects for particle rendering. Provides WGSL snippet injection for existing billboard/SDF fragment shaders. Controls: frost crystallization, melt sheen, boiling bubbles, ionization arcs. The actual rendering is done by injecting applyPhaseVFX() into existing particle fragment shaders. This module manages the configuration and provides the WGSL code for inclusion. Usage: import { phaseVFXWGSL } from '../shaders/modules/core/particles_phase_vfx.js'; // Include phaseVFXWGSL in particle fragment shader // Call applyPhaseVFX(baseColor, uv, time, phase, temperature, latentProgress)


createPhaseVFXConfig

Summary: Create a phase VFX configuration object.


getPhaseVFXShader

Summary: Get the WGSL snippet for phase VFX. Include this in particle fragment shaders to enable phase transition effects.


Summary: Phase VFX configuration. These values are passed to shaders via existing particle uniform buffers.


render/particles/ParticleQualityManager

Summary: Create a particle quality manager


createParticleQualityManager

Summary: Create a particle quality manager


Summary: Default quality presets


render/particles/ParticleSPHSurfaceRenderer

Summary: ParticleSPHSurfaceRenderer.js - SPH Fluid Surface Renderer (GAP 44) Screen-space rendering of SPH fluid particles as smooth liquid surface. Bridges SPH particle data (GAP 36) into the existing FluidWaterPass pipeline. Pipeline: 1. Render SPH particles as sphere impostors → depth texture 2. Bilateral blur → smooth surface 3. Thickness accumulation → subsurface scattering 4. Composite with refraction + reflection + Fresnel Per-element tint from element table: water=blue, lava=orange, blood=red. Usage: const ssr = createSPHSurfaceRenderer(device, format, width, height); initSPHSurfaceBindGroups(ssr, device, positionBuffer, velocityBuffer, elementBuffer, colorLutBuffer); renderSPHSurface(ssr, encoder, { sceneColor, sceneDepth, camera, particleCount });


createSPHSurfaceRenderer

createSPHSurfaceRenderer(device, format, width, height)

Summary: Create the SPH surface renderer. Full SSFR pipeline: depth → bilateral blur (H+V) → thickness → normals + composite.


initSPHSurfaceBindGroups

initSPHSurfaceBindGroups(renderer, device, positionBuffer, velocityBuffer, thermalBuffer)

Summary: Initialize bind groups for all SSFR passes.


initSPHCompositeBindGroup

Summary: Create composite bind group (needs scene color texture view). Reads smoothed depth (blurTextureB) + thickness for full SSFR composite.


setSPHSurfaceTint

Summary: Set fluid tint color (e.g., from element).


renderSPHSurface

Summary: Render SPH fluid surface (full SSFR pipeline). Pass 1: Depth (sphere impostors) Pass 2: Bilateral blur H Pass 3: Bilateral blur V Pass 4: Thickness (additive)


compositeSPHSurface

Summary: Composite SPH surface onto the scene in a render pass.


destroySPHSurfaceRenderer

Summary: Destroy.


render/particles/ParticleSdfRenderer

Summary: Create volumetric SDF particle renderer


createParticleSdfRenderer

Summary: Create volumetric SDF particle renderer


createParticleSdfDataBindGroup

createParticleSdfDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer, thermalBuffer, sphDensityBuffer, classBuffer)

Summary: Create data bind group for SDF particle world. Binds the shared particle buffers (position, meta, velocity, thermal) to group 1. The metaBuffer contains per-particle color at .rgb — written by ParticleEmitterSystem.js. If thermalBuffer is missing, a fallback with room-temp defaults (293K) is created.


createParticleSdfDepthBindGroup

Summary: Create depth bind group for soft particles (scene depth texture). Must be recreated when the depth texture changes (e.g. on resize). Only binds depth texture (binding 0). Does NOT include alive list buffer — the SDF vertex shader uses instance_index directly, unlike the billboard shader which uses uAliveList for indirection.


createParticleSdfLutSixWayBindGroup

createParticleSdfLutSixWayBindGroup(renderer, colorGradientView, colorGradientSampler, lifetimeCurvesView, lifetimeCurvesSampler, sixWaySystem)

Summary: Create combined LUT + six-way lighting bind group (group 3). Bindings 0-3: color gradient + lifetime curves LUT textures. Bindings 4-11: six directional lightmap textures + sampler + params. Merged into one group to stay within WebGPU maxBindGroups=4.


setParticleSdfParams

setParticleSdfParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })

Summary: Update SDF particle rendering parameters


render/particles/ParticleShadowCaster


flushBillboardShadowDepth

flushBillboardShadowDepth(pass, caster, lightViewProj, sunDir, instanceCount)


flushAllParticleShadows

flushAllParticleShadows(pass, caster, lightViewProj, sunDir, billboardInstanceCount)


render/particles/ParticleSixWayLighting

Summary: ParticleSixWayLighting.js - Six-Way Lightmap Particles (GAP 24) Pre-baked lighting from 6 directions (+X, -X, +Y, -Y, +Z, -Z) sampled based on dominant light direction. Creates a fake 3D volumetric look on flat billboard particles, especially useful for smoke and fog. Matches Unity VFX Graph six-way lighting feature. The system bakes a 6-channel lightmap texture (3 RGBA8 textures for 6 directions, or a single RGBA16float with packed channels). At render time, the fragment shader blends between the 6 maps based on the light direction relative to the billboard. Usage: const sixway = createSixWayLightingSystem(device); loadSixWayTextures(sixway, device, { right, left, top, bottom, front, back }); // Or generate procedural maps: generateProceduralSixWay(sixway, device, 'smoke'); // Bind to particle renderer: bindSixWayToRenderer(sixway, renderer);


createSixWayLightingSystem

createSixWayLightingSystem(device, config = {})

Summary: Create a six-way lighting system.


generateProceduralSixWay

generateProceduralSixWay(system, device, preset = 'smoke')

Summary: Generate procedural six-way lightmaps.


loadSixWayTextures

async loadSixWayTextures(system, device, images)

Summary: Load six-way textures from external image data.


setSixWayLightDirection

setSixWayLightDirection(system, lightDir, intensity = 1.0)

Summary: Update the dominant light direction.


destroySixWayLightingSystem

Summary: Destroy the system.


render/particles/ParticleSizeRenderer


createParticleSizeDataBindGroup

createParticleSizeDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)


setParticleSizeParams

setParticleSizeParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })


render/particles/ParticleThermalRenderer

Summary: Particle Thermal/Blackbody Debug Pass Renderer Renders particle temperature as blackbody radiation color for debug visualization. Requires thermalData buffer (binding 4) in addition to standard particle buffers.


createParticleThermalDataBindGroup

createParticleThermalDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer, thermalBuffer)


setParticleThermalParams

setParticleThermalParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })


render/particles/ParticleTrailHistory

Summary: ParticleTrailHistory.js - Per-Particle Trail Histories (GAP 26) Individual per-particle position history trails. Unlike ribbon trails (which connect sequential particles into a strip), this stores N frames of position history PER particle and renders each as a fading afterimage. Think sparks leaving comet tails, or tracers behind projectiles. Architecture: - Ring buffer: historyBuffer[maxParticles × historyLength × vec4] stores position snapshots - GPU compute shader shifts history and writes current position each frame - Render pass draws each trail point as a small billboard, fading by age Usage: const trails = createTrailHistorySystem(device, maxParticles, { historyLength: 16 }); initTrailHistoryBindGroups(trails, device, positionBuffer, velocityBuffer); // Each frame: updateTrailHistories(trails, device, particleCount); renderTrailHistories(pass, trails, frameBindGroup);


createTrailHistorySystem

createTrailHistorySystem(device, maxParticles, config = {})

Summary: Create a per-particle trail history system.


initTrailHistoryBindGroups

initTrailHistoryBindGroups(system, device, positionBuffer, velocityBuffer, metaBuffer)

Summary: Initialize bind groups.


updateTrailHistories

updateTrailHistories(system, device, particleCount, dt = 1/60)

Summary: Update trail histories (GPU compute pass). Call once per frame before rendering trails.


renderTrailHistories

renderTrailHistories(pass, system, frameBindGroup, particleCount)

Summary: Render trail histories as additive fading billboards.


destroyTrailHistorySystem

Summary: Destroy the system.


render/particles/ParticleVelocityRenderer


createParticleVelocityDataBindGroup

createParticleVelocityDataBindGroup(renderer, positionBuffer, metaBuffer, velocityBuffer)


setParticleVelocityParams

setParticleVelocityParams(renderer, { size = 1, quality = 1.0, lodBias = 1.0, cullThreshold = 0 })


render/particles/RopeGPURenderer

Summary: RopeGPURenderer.js - GPU-driven rope/tube mesh generation Generates tube geometry from rope particle positions entirely on the GPU. Reads particle positions from the simulation buffer and outputs vertex data for rendering as a triangle mesh. Features: - Compute shader generates tube vertices from particle chain - Configurable tube radius and segment count - Automatic tangent/normal/binormal frame calculation - Twist-resistant frame propagation (parallel transport) - Indirect draw support for variable-length ropes


createRopeGPURenderer

createRopeGPURenderer(device, options = {})

Summary: Create a rope GPU renderer instance


render/particles/RopeRenderSystem

Summary: RopeRenderSystem.js - Integration layer for GPU rope rendering Connects the RopeGPURenderer with the particle simulation world's rope chain registry. Manages multiple ropes and batches rendering.


createRopeRenderSystem

createRopeRenderSystem(device, options = {})

Summary: Create a rope render system


render/particles/billboard/index

Summary: billboard/index.js — Re-exports for billboard particle rendering.


render/particles/custom/index

Summary: custom/index.js — Re-exports for custom particle effects.


render/particles/debug/index

Summary: debug/index.js — Re-exports for debug visualization renderers.


render/particles/distortion/index

Summary: distortion/index.js — Re-exports for distortion and phase VFX rendering.


render/particles/index

Summary: Particle System Exports Barrel file for easy importing of all particle-related modules.


render/particles/mesh/index

Summary: mesh/index.js — Re-exports for mesh particle rendering.


render/particles/rope/index

Summary: rope/index.js — Re-exports for rope/wire rendering.


render/particles/sdf/index

Summary: sdf/index.js — Re-exports for SDF volumetric particle rendering.


render/particles/surface/index

Summary: surface/index.js — Re-exports for SSFR surface rendering pipeline.


render/particles/trail/index

Summary: trail/index.js — Re-exports for trail and beam rendering.


render/passes/AbyssalCameraRig

Summary: Applies a restrained floating-camera offset to isolated DOM scenery planes. WebGPU/2D canvases and document-root styles are deliberately excluded so animation cannot invalidate the page or disrupt GPU presentation textures.


render/passes/AbyssalDiveTeam

Summary: Authored three-person dive team for the abyssal landing scene. The team uses a deterministic mission-state controller instead of random action switching: swim, illuminate, inspect, signal, then inspect again. Individual response, phase, depth, and kick timing keep the formation alive without compromising buddy proximity or opaque paint ordering.


startAbyssalDiveTeam

startAbyssalDiveTeam(layers, options = {})


render/passes/AbyssalFaunaField

Summary: Small DOM fauna field for the authored abyssal landing scene. Local flock rules are deliberately limited to fish on the same depth plane.


startAbyssalFaunaField

startAbyssalFaunaField(layers, options = {})


render/passes/AbyssalSmokeAnimator

Summary: Cross-faded cel animator for the authored abyssal mineral plume. Two staggered lifecycles share the registered atlas. Each lifecycle changes drawing, rises, spreads, sheds opacity, and disappears while its successor is already forming at the vent. Adjacent-frame alpha always sums to one, which prevents the bright flashes produced by transition races.


startAbyssalSmokeAnimator

startAbyssalSmokeAnimator(stage, options = {})


render/passes/AreaResamplePass

Summary: AreaResamplePass - GPU-accelerated area-weighted resampling Better quality than bilinear for arbitrary scale factors. Especially useful for upscaling low-res renders.


areaResampleCPU

Summary: CPU area-weighted resample for ImageData (fallback or small images)


render/passes/AutoExposurePass


render/passes/BloomPass


render/passes/CascadeMetrics

Summary: CascadeMetrics - Central metrics collection for cascaded chunk system


getMetrics

Summary: Get global metrics instance


resetMetrics

Summary: Reset global metrics


render/passes/CascadedShadows

Summary: CascadedShadowMap - Multi-cascade shadow mapping system


render/passes/ChromaticAberrationPass


render/passes/ClearPass


addCanvasClearPass

addCanvasClearPass(frameGraph, options = {})


render/passes/ClothDebugController


render/passes/ClothDebugPass


addClothDebugPass

addClothDebugPass(frameGraph, options = {})


render/passes/ColorGradingPass


render/passes/ContactShadowsPass


render/passes/DepthOfFieldPass


render/passes/DepthVisualizerPass

Summary: Execute depth visualizer pass


executeDepthVisualizerPass

executeDepthVisualizerPass(pass, visualizer, depthTexture, params = {})

Summary: Execute depth visualizer pass


render/passes/FSRPass

Summary: FSRPass.js - FidelityFX Super Resolution 1.0 (Spatial Upscaler) Pure WebGPU/WGSL port of AMD's open-source FSR 1.0 algorithm. Two-pass spatial upscaler: EASU (Edge-Adaptive Spatial Upsampling) + RCAS (Sharpening). Use cases: - Fallback when temporal history is invalid (camera cuts, teleports) - Standalone spatial upscaling for non-temporal content - Combined with TSR as the spatial component Pipeline: Low-res input → EASU (directional upscale) → RCAS (adaptive sharpen) → Full-res output EASU: Analyzes local edge direction and applies a directionally-aware 12-tap filter. Detects edges via luminance gradients and stretches the filter kernel along the edge. This preserves edge sharpness while smoothing along edges (not across them). RCAS: Contrast-adaptive sharpening that avoids ringing artifacts. Computes local contrast from a cross-shaped sample pattern and applies sharpening proportional to inverse contrast (sharp where flat, gentle on edges).


render/passes/FXAAPass


render/passes/FilmGrainPass


render/passes/FluidDebugController


render/passes/FluidDebugPass


addFluidDebugPass

addFluidDebugPass(frameGraph, options = {})


render/passes/FluidWaterPass

Summary: Create resources for the fluid water rendering pass


createFluidWaterPass

createFluidWaterPass(device, options = {})


renderFluidWater

renderFluidWater(pass, encoder, options = {})

Summary: Render water/metaball surfaces from particles


resizeFluidWaterPass

Summary: Resize the fluid water pass textures


destroyFluidWaterPass

Summary: Destroy the fluid water pass resources


render/passes/GeometryPass


addMainGeometryPass

addMainGeometryPass(frameGraph, options = {})


render/passes/GodRays

Summary: GodRays - Volumetric light scattering effect WebGPU implementation with fixed 32-sample radial blur


render/passes/GroundShadowPass

Summary: GroundShadowPass.js - Analytical Blob Shadows on Ground Plane Projects entity shadow casters onto the y=0 ground plane along the sun direction and renders soft circular shadows. This is the standard technique used by mobile games (Minecraft, Animal Crossing) and many 3D editors. Advantages over screen-space ray marching: - No depth buffer artifacts (banding, streaking) - Works from any camera angle - Smooth, soft shadow edges with no aliasing - Very fast (one distance check per caster per pixel) Shadow casters are passed via a storage buffer (position + radius per entity). Output: Alpha-blended darkening composited over the scene.


render/passes/HDRPipeline

Summary: HDRPipeline - Complete HDR rendering pipeline


render/passes/HiZPass


render/passes/ImageHeatHazePass

Summary: ImageHeatHazePass.js - Layered water optics for an authored mineral plate. This is the static-image counterpart to ParticleDistortionRenderer. The authored plate owns geology; this pass owns water refraction, attenuation, caustics, texture-broken god rays, heat haze, and color-aware lava emission.


projectImagePointToViewport

projectImagePointToViewport(imageUV, viewportWidth = window.innerWidth, viewportHeight = window.innerHeight, imageAspect = 1.5,)

Summary: Project a point in authored-image UV space into the backdrop viewport. Keep this in sync with the landing page's background-size breakpoints.


startImageHeatHaze

async startImageHeatHaze(canvas, options = {})


render/passes/LensFlarePass


render/passes/LightingPass


addLightingPass

addLightingPass(frameGraph, options = {})


render/passes/MotionBlurPass


render/passes/OutlinePass


render/passes/PaniniProjectionPass

Summary: PaniniProjectionPass.js - Wide FOV Distortion Correction Now powered by vGPU driver Reduces the "fish-eye" distortion that occurs with wide field of view. Based on the Panini projection which maps perspective to a cylinder. Parameters: - strength: How much correction to apply (0 = none, 1 = full panini) - fov: Current field of view in degrees - cropToFit: Scale to avoid black edges (0 = no crop, 1 = full crop)


render/passes/ParticlePass


addParticleBillboardPass

addParticleBillboardPass(frameGraph, options = {})


render/passes/PathTracingPass


render/passes/PostProcessChainPass


addPostProcessChainPass

addPostProcessChainPass(frameGraph, options = {})


render/passes/PostProcessController


render/passes/PurkinjeEffectPass


render/passes/ReSTIRGIPass


render/passes/ReconstructionProvider

Summary: ReconstructionProvider.js - Unified Upscaling & Reconstruction Interface Abstracts over multiple reconstruction backends: - TSR (Temporal Super-Resolution) - best quality, uses temporal history - FSR (FidelityFX Super Resolution) - spatial only, fallback for camera cuts - SVGF (Denoiser) - for path-traced/GI content - Native TAA - no upscaling, just anti-aliasing - None - passthrough Future-proofed for: - WebNN neural upscaling (when browser API matures) - Custom ML models via WebGPU compute Usage: const provider = new ReconstructionProvider(device); await provider.init(displayWidth, displayHeight); provider.setMode('tsr', TSRQuality.QUALITY); // In render loop: const { width, height } = provider.getRenderSize(); const jitteredProj = provider.applyJitter(projMatrix); // ... render scene at width×height ... provider.execute(encoder, colorTex, depthTex, motionTex, outputTex);


render/passes/RenderPassManager

Summary: Render Pass Manager Manages multi-pass rendering pipeline with pass selection and visualization. Handles render target allocation, pass execution, and debug visualization.


render/passes/SSAOPass

Summary: SSAO Pass Manager


SSAOPass

Summary: SSAO Pass Manager


render/passes/SSGIPass


render/passes/SSRPass

Summary: SSRPass - Screen-Space Reflections render pass


render/passes/SVGFDenoise

Summary: SVGFDenoise.js - Spatiotemporal Variance-Guided Filtering Full SVGF denoising pipeline for compute-based path tracing / GI. Converts noisy 1-spp (or low-spp) input into clean output. Based on: - "Spatiotemporal Variance-Guided Filtering" (Schied et al., HPG 2017) - NVIDIA SVGF implementation techniques - À-Trous wavelet decomposition with edge-stopping functions Pipeline (per frame): 1. Temporal Accumulation: Reproject history, blend with current, track variance 2. Variance Estimation: Compute spatial variance from accumulated moments 3. À-Trous Wavelet Filter: 1-5 iterations of edge-preserving spatial blur - Edge-stopping by normal, depth, luminance, and variance - Increasing step size each iteration (1, 2, 4, 8, 16) - Firefly suppression via luminance clamping Inputs Required: - Noisy color (1-spp path trace output) - World-space normals - Linear depth - Motion vectors Outputs: - Denoised color (rgba16float) - Accumulated variance (for adaptive sampling feedback)


render/passes/SceneDebugVisualizerPass

Summary: Scene Debug Visualizer Pass Fullscreen post-process that reads the ACTUAL scene depth buffer (depth24plus) and renders industry-standard debug visualizations: - Depth: linearized grayscale (near=white, far=black) - Normals: world-space normals reconstructed from depth (RGB = XYZ) Unlike the particle-only debug renderers, this shows the FULL scene (entity meshes + particles + everything that wrote to the depth buffer).


createSceneDebugVisualizerPass

Summary: Create the scene debug visualizer pass


executeSceneDebugVisualizerPass

executeSceneDebugVisualizerPass(encoder, outputView, depthView, visualizer, opts)

Summary: Execute the scene debug visualizer pass


render/passes/ShadowAtlas

Summary: ShadowAtlas.js - Unified Shadow Depth Atlas Single shared depth texture that ALL shadow casters render into. Inspired by Wicked Engine's shadow atlas architecture (2024): - One depth texture, one clear, one uninterrupted render pass - All geometry types (voxels, entities, particles, ropes) write sequentially - All fragment shaders sample from the same atlas - Comparison sampler for hardware PCF Replaces the separate shadow systems: - VoxelRenderer.shadowMapTexture  → ShadowAtlas.texture - ShadowMapPass.shadowTexture     → ShadowAtlas.texture Usage: const atlas = createShadowAtlas(device, { size: 2048 }); atlas.beginFrame(); atlas.addCaster(x, y, z, radius);  // for frustum fitting const lightVP = atlas.computeLightMatrix(sunDir); atlas.renderDepth(encoder, casters);  // all casters in one pass atlas.composite(encoder, ...);        // fullscreen darken Caster interface: { flush(pass: GPURenderPassEncoder, lightViewProj: Float32Array): void }


renderAndCompositeAll

renderAndCompositeAll(atlas, encoder, outputView, sceneDepthTexture, invViewProj, screenW, screenH, cameraPos)


composite

composite(atlas, encoder, outputView, sceneDepthTexture, invViewProj, screenW, screenH, cameraPos)


render/passes/ShadowMapPass

Summary: ShadowMapPass.js - Real Geometry Shadow Maps Renders entity depth from the sun's perspective into a shadow map texture, then composites geometry-accurate shadows onto the scene as a fullscreen pass. Architecture: 1. Shadow depth pass: EntityMeshRenderer.flushShadowDepth() draws all instanced entities into a depth32float texture from the light's orthographic projection. This runs AFTER the main flush() so the GPU instance buffer already contains this frame's data. 2. Composite pass: A fullscreen triangle reads the scene depth buffer, reconstructs world positions, projects them into light space, and samples the shadow map with PCF 3×3 filtering. Output is alpha-blended darkening. The light matrix is computed per-frame from the sun direction and a bounding sphere that encompasses all shadow casters (not the camera frustum), so off-screen entities still cast shadows into the visible area.


render/passes/ShadowPass


addDirectionalShadowPass

addDirectionalShadowPass(frameGraph, options = {})


render/passes/SharpeningPass


render/passes/SpellEffectPass

Summary: Create the spell effect rendering pass


createSpellEffectPass

createSpellEffectPass(device, options = {})

Summary: Create the spell effect rendering pass


renderSpellEffects

renderSpellEffects(pass, encoder, targetView, options = {})

Summary: Render active spell effects


spellElementToEffectType

Summary: Map spell element to effect type


spellConfigToInstance

spellConfigToInstance(spellConfig, position, time, phase = 0.5)

Summary: Convert a spell config to a renderable spell instance


render/passes/TAAPass

Summary: TAAPass - Temporal Anti-Aliasing render pass


render/passes/TemporalSuperResolution

Summary: TemporalSuperResolution.js - Temporal Upscaling System Renders at reduced internal resolution and reconstructs full-res output using temporal reprojection, motion vectors, and edge-aware upsampling. Inspired by Unreal Engine TSR, AMD FSR 2, and Intel XeSS. Pure WebGPU/WGSL compute implementation. Pipeline: Render at renderScale (e.g. 50-75%) resolution ↓ Dilate motion vectors (fill gaps from thin geometry) ↓ Reproject history to current frame ↓ Neighborhood clamp in YCoCg (anti-ghosting) ↓ Compute per-pixel confidence (depth, motion, disocclusion) ↓ Adaptive blend current + history ↓ Lanczos-weighted upscale to output resolution ↓ RCAS sharpening pass ↓ Full-resolution output Quality Modes: Ultra Performance: 33% (3x upscale) Performance:       50% (2x upscale) Balanced:          58% (~1.7x upscale) Quality:           67% (1.5x upscale) Ultra Quality:     77% (1.3x upscale) Native AA:        100% (TAA replacement, no upscale)


render/passes/TonemapPass

Summary: TonemapPass.js - Final Post-Processing Pass Applied as the very last pass after bloom. Provides: 1. ACES filmic tonemapping (HDR → LDR, matches playground SDF demo) 2. Vignette (darkened edges for cinematic look) 3. Distance fog (blend toward sky color at far range) Uses a single fullscreen triangle — no vertex buffer, no index buffer.


render/passes/UIHudPass


render/passes/UnderwaterPass


render/passes/UnderwaterSiltField

Summary: UnderwaterSiltField.js - Lightweight interactive particulate atmosphere. A capped Canvas2D pass draws shallow caustic traces, depth-layered volcanic ash/mineral flecks, and upper-left refracted light shafts. Particles follow a slow analytic flow field and receive a local tangential impulse when the pointer disturbs the water. The module has no runtime dependencies so release pages can ship it beside the standalone authored-image backdrop pass.


startUnderwaterSiltField

startUnderwaterSiltField(canvas, options = {})


render/passes/VignettePass


render/passes/VolumetricCloudsPass

Summary: VolumetricCloudsPass.js - 3D Volumetric Clouds Now powered by vGPU driver Renders realistic volumetric clouds using ray marching through 3D noise-based density fields. Includes lighting and shadowing. Algorithm: 1. Ray march from camera through cloud layer 2. Sample 3D noise for cloud density 3. Accumulate light scattering and extinction 4. Apply shadow from sun direction Parameters: - coverage: Cloud coverage (0-1) - altitude: Cloud layer altitude in meters - thickness: Cloud layer thickness - density: Cloud density multiplier


render/passes/index


render/passes/spellpacks/index

Summary: spellpacks/index.js — placeholder for GPU spell effect manifests. The original data lived in an external sibling tree; this local stub lets SpellEffectPass compile until the spellpack manifest pipeline is merged.


render/postprocess/TemporalAA


render/proxy/ProxyBillboardAlign

Summary: ProxyBillboardAlign — GPU Compute Pass for Billboard Instance Rotation Aligns BILLBOARD-mode proxy instances to face the camera each frame. Equivalent to Blender's "Track To" constraint + "Align Euler to Vector" in Geometry Nodes. Input:  instance buffer (read-write) containing worldMat per instance Output: updated rotation portion of worldMat in-place Only processes instances where proxyMode == PROXY_MODE_BILLBOARD (1u). BOX proxies are skipped (their orientation is set by the developer).


render/proxy/ProxyGBufferPass

Summary: ProxyGBufferPass — Rasterize Proxy AABB Cubes into the GBuffer ID Texture Renders invisible proxy bounding boxes (one per instance) to stamp a 1-indexed proxy instance ID into a r32uint GBuffer attachment. The depth buffer ensures correct occlusion against scene geometry. The r32uint texture is then read by ProxyMaskPass, which fires per-pixel rays only for pixels where instanceId > 0. Pipeline: Proxy cube geometry (GPU instanced) → vertex: transform by instance worldMat → fragment: write flat instanceId to r32uint attachment → depth: standard scene depth (proxy boxes occluded correctly) The proxy cubes are invisible in the color attachment — they only tag the ID texture. ProxyShadePass writes final color to the HDR buffer.


render/proxy/ProxyGeometrySystem

Summary: ProxyGeometrySystem — Main Orchestrator Decouples visual complexity from geometric complexity using the Ray Portal proxy technique adapted from Blender Cycles + 8 researched engine approaches. Architecture: 1. registerTarget(assetId, mesh, material) → Builds BLAS (BVH via BVHAccel), bakes SDF, bakes Octahedral atlas 2. addInstance(assetId, worldMatrix, mode) → Adds to instance buffer + TLAS 3. update(fps, cameraPos, encoder) → Billboard align compute, FPS-driven tier selection, TLAS refit 4. render(encoder, gbuffer, hdrTarget) → ProxyMaskPass → ProxyShadePass Quality tiers (auto-selected by FPS): ULTRA  (>55 FPS) — TLAS/BLAS per-pixel ray portal HIGH   (>40 FPS) — SDF cone march MED    (>28 FPS) — True impostor (height field billboard) LOW    (  <28  ) — Octahedral impostor atlas (baked) Public API: registerTarget(assetId, positions, indices, uvs, material) addInstance(assetId, worldMatrix, mode)        → instanceId removeInstance(instanceId) updateInstanceTransform(instanceId, worldMatrix) setQualityMode('auto' | 'ultra' | 'high' | 'med' | 'low') update(fps, cameraPos, commandEncoder) render(commandEncoder, gbufferTargets, hdrTarget) getStats() destroy()


render/proxy/ProxyMaskPass

Summary: ProxyMaskPass — Compute Pass: Per-Pixel Ray → Hit Mask + Hit Data This is the engine equivalent of Blender's Raycast Node. For each screen pixel tagged with a proxy instance ID (written by the GBuffer proxy rasterization pass), fires a ray into the appropriate quality tier: ULTRA (0) — TLAS/BLAS two-level BVH traversal (exact, per-pixel) HIGH  (1) — SDF cone marching (correct topology, slightly cheaper) MED   (2) — True impostor height-field ray march (billboard) LOW   (3) — Octahedral impostor atlas sample (baked, near zero cost) Outputs four textures consumed by ProxyShadePass: hitMask   — r8uint:  0 = miss (transparent), 1 = hit hitPos    — rgba32float: world-space hit position hitNormal — rgba16float: world-space hit normal hitUV     — rg16float:   UV for material sampling "Is Hit" = 0 causes ProxyShadePass to discard that pixel, producing the transparent cutout that hides the proxy box edges (Blender Transparent BSDF).


render/proxy/ProxyOctahedralCache

Summary: ProxyOctahedralCache — Baked Octahedral Impostor Atlas Pre-renders a target asset from N×N octahedral viewpoints and packs the results into a single texture atlas. At runtime, proxy billboards sample the nearest 4 frames (bilinearly blended in octahedral space). Technique from: Emil Poulsen / Unity Pixyz / UE5 Nanite fallback. Atlas layout: - atlasFrames × atlasFrames grid of FRAME_SIZE×FRAME_SIZE RGBA tiles - Each tile stores: RGB = color, A = alpha mask - An additional normal atlas stores XYZ normals (for lighting correction) Pros:  Near-zero runtime cost, excellent at distance. Cons:  Baked offline (re-bake if mesh changes); limited parallax. Fix:   Dirty flag triggers async re-bake; irradiance probe augments lighting.


render/proxy/ProxySDF

Summary: ProxySDF — SDF Proxy Baking + Runtime Cone March (HIGH tier) Wraps MeshSDFGenerator to produce 3D SDF textures for registered proxy assets. At runtime, the GPU cone marches (sphere traces) through the SDF to produce pixel-perfect silhouettes, normals, and depth from any viewing angle. Advantages over octahedral impostor: - Handles ANY topology (torus, rings, handles — not just height fields) - Normals derived from SDF gradient (analytically smooth) - SDF soft shadows / AO available for free via cone angle Known problems + solutions: Problem: O(n³) memory for 3D texture Fix:     Sparse SDF using VoxelCompression; only near-surface voxels stored Problem: UV data absent from SDF Fix:     Parallel volume storing nearest-triangle barycentric → UV lookup Problem: Thin features lose precision at low grid resolution Fix:     2-level SDF: coarse 32³ + fine 64³ near-surface refinement


render/proxy/ProxyShadePass

Summary: ProxyShadePass — Material Evaluation + Composite to HDR Buffer Reads the hit data textures produced by ProxyMaskPass and: 1. Discards pixels where hitMask = 0 (transparent cutout — Blender Transparent BSDF) 2. Samples the target asset's material at hitUV (albedo, roughness, metallic, normal) 3. Evaluates PBR lighting using the engine's LightManager shader functions 4. Alpha-composites into the HDR color buffer before tonemapping This is the deferred equivalent of Blender's Mix Shader: Mix(factor=IsHit, A=RayPortalBSDF, B=TransparentBSDF) → HDR output


render/proxy/TLASBuilder

Summary: TLASBuilder — Two-Level Acceleration Structure for Proxy Geometry Implements the TLAS (Top-Level Acceleration Structure) over proxy instances, each referencing a BLAS (Bottom-Level Acceleration Structure = the per-asset BVH built by BVHAccel.js / BVHBuilder). Key insight (from Jacco Bikker / Interplay of Light research): "Given a mesh with a BVH in object space and a 4x4 matrix, we intersect its BVH in world space by applying the inverse transform to the ray." This means: - BLAS is built ONCE per unique asset, stored in object space - TLAS stores instance bounding boxes (world space) + inverse world matrices - Per-ray: traverse TLAS → at leaf, transform ray into object space → traverse BLAS - Adding 1000 instances of the same mesh = 1 BLAS + 1000 TLAS entries (not 1000 BVHes) GPU buffer layout designed for direct use in ray_portal.js WGSL traversal.


render/proxy/index

Summary: Proxy Geometry System — Public Exports Ray Portal Proxy Topology rendering system: Decouples visual complexity from geometric complexity using 5 quality tiers that switch dynamically based on FPS. Primary entry point: ProxyGeometrySystem Usage: import { ProxyGeometrySystem, PROXY_MODE, PROXY_TIER } from './proxy/index.js'; const proxy = new ProxyGeometrySystem(device, width, height); await proxy.registerTarget(0, positions, indices, uvs, material); proxy.addInstance(0, worldMatrix, PROXY_MODE.BOX); // Per frame: proxy.update(fps, cameraPos, encoder); proxy.render(encoder, gbuffer, hdrTarget, sceneData);


render/scenes/StandardEntityRenderResources


createStandardEntityRenderResources

createStandardEntityRenderResources(device, renderPipeline, lightsBuffer, entityId, uniformByteLength)


render/scenes/StandardRoomRenderer


render/scenes/StandardUniforms


updateStandardLights

updateStandardLights(device, lightsBuffer, lightsData, options = {})


updateStandardUniforms

updateStandardUniforms(device, targetBuffer, uniformData, uniformDataU32, options = {})


render/scenes/VoxelWorldRenderer

Summary: Create a voxel world renderer.


createVoxelWorldRenderer

Summary: Create a voxel world renderer.


updateVoxelWorldFrameUniforms

updateVoxelWorldFrameUniforms(device, frameBuffer, viewProj, view, proj, cameraPos, time,)


render/sdf/MeshSDFGenerator

Summary: Validate and repair mesh data - removes invalid vertices and degenerate triangles


simplifyMesh

simplifyMesh(positions, indices, targetTriangles = 1000)

Summary: Simplify high-poly mesh for faster SDF generation


analyzeMesh

Summary: Analyze mesh and determine best SDF approach


computeBounds

Summary: Compute axis-aligned bounding box


fitPrimitive

Summary: Auto-fit best primitive shape to mesh


fitCapsules

fitCapsules(positions, indices, maxCapsules = 8)

Summary: Fit multiple capsules to a mesh (for ragdoll bodies)


generateTriangleBuffer

Summary: Generate triangle buffer data for GPU SDF sampling


bakeSDF3D(positions, indices, resolution = 32)

Summary: Bake 3D SDF texture from mesh using BVH acceleration


initGPUBaker

Summary: Initialize GPU SDF baker


hasGPUBaker

Summary: Check if GPU baking is available


async bakeSDF3DGPU(positions, indices, resolution = 32)

Summary: Bake 3D SDF texture using GPU compute (~100x faster) Falls back to CPU if GPU not available


generateMeshSDF

generateMeshSDF(positions, indices, options = {})

Summary: Generate hybrid SDF for a mesh - automatically chooses best approach Now with mesh validation, simplification, and voxel acceleration


getCachedMeshSDF

getCachedMeshSDF(meshId, positions, indices, options = {})

Summary: Get or generate cached SDF for a mesh


clearSDFCache

Summary: Clear SDF cache


generateMeshSDFAsync

async generateMeshSDFAsync(positions, indices, options = {})

Summary: Async version of generateMeshSDF with GPU acceleration Use this for high-resolution baking (64³+)


Summary: WGSL shader code for triangle buffer SDF sampling


Summary: WGSL shader code for 3D texture SDF sampling


render/sdf/SDFBakeCompute

Summary: SDFBakeCompute.js - GPU Compute Shader for 3D SDF Baking Now powered by vGPU driver Accelerates SDF texture generation using WebGPU compute shaders. ~100x faster than CPU for high resolution (64³+) SDF textures. Pipeline: 1. Upload triangle data to GPU buffer 2. Dispatch compute shader to calculate SDF for each voxel in parallel 3. Read back SDF texture data


SDFBakeCompute

Summary: GPU-accelerated SDF baker


createSDFBaker

Summary: Create GPU SDF baker instance


render/sdf/index

Summary: SDF Utilities - Signed Distance Field generation and baking


render/shaders/ShaderComposer


render/shaders/ShaderLoader


render/shaders/ShaderLoaderJS


render/shaders/ShaderSchema

Summary: Generate WGSL struct definition from schema


generateBindingsWGSL

Summary: Generate WGSL binding declarations from binding group schema


generateVertexInputWGSL

Summary: Generate WGSL vertex input struct from vertex layout


alignOffset

Summary: Calculate aligned byte offset for a field


calculateBufferSize

Summary: Calculate total buffer size from schema (with alignment)


createUniformBuffer

Summary: Create a typed array buffer matching schema


writeUniformField

writeUniformField(buffer, schema, fieldName, value)

Summary: Write a value to a uniform buffer at the field's offset


readUniformField

Summary: Read a value from a uniform buffer at the field's offset


validateUniformBuffer

Summary: Validate a uniform buffer against schema


validateBindingGroup

Summary: Validate binding group layout


createFrameUniformsBuffer

Summary: Create frame uniforms buffer with defaults


createModelUniformsBuffer

Summary: Create model uniforms buffer with defaults


createMaterialUniformsBuffer

Summary: Create material uniforms buffer with defaults


createParticleParamsBuffer

Summary: Create particle params buffer with defaults


Summary: WGSL type sizes in bytes (aligned to 16-byte boundaries for uniforms)


Summary: Buffer usage types


Summary: Texture types


Summary: Frame uniforms - camera and time data, updated every frame


Summary: Model uniforms - per-object transform data


Summary: Light struct for dynamic lighting


Summary: PBR material uniforms


Summary: Particle render params


Summary: Post-process common params


Summary: Standard binding group layouts


Summary: Standard vertex layouts


Summary: Common WGSL utility functions


Summary: Full-screen triangle vertex shader


render/shaders/ShaderSources


render/shaders/WgslPreprocessor

Summary: Tagged template literal for WGSL preprocessing


wgslIf

Summary: Simple string-based conditionals without tagged template Useful for simpler cases


wgslFor

Summary: Repeat a string N times with index substitution ${i} in the template is replaced with the iteration index


wgslVariant

Summary: Create a shader variant by selecting features


render/shaders/core/clear_color

Summary: Clear Color Shader - Full-screen clear with uniform color


render/shaders/core/global_common


render/shaders/core/lighting


render/shaders/core/monitor_patterns

Summary: Monitor Patterns - Test patterns for display calibration


render/shaders/core/particles_billboard_legacy

Summary: Legacy Particles Billboard - Horizontal quad particles with cloud-like appearance Note: The main particles_billboard shader is in modules/core/particles_billboard.js


render/shaders/core/solid_color

Summary: Solid Color Shader - Simple vertex color passthrough


render/shaders/core/standard

Summary: ============================================================================ STANDARD PBR SHADER WITH MULTI-TYPE LIGHTING ============================================================================ Supports three light types: - Point (type 0): Position-based with quadratic distance falloff - Directional (type 1): Direction-based, no distance falloff (sun-like) - Spot (type 2): Position + direction + cone falloff GPU BUFFER LAYOUT: Group 0 (Uniforms): Binding 0: Uniforms - projection, view, model matrices - color, alpha - lightCount, feature flags, sunDir, sunColor Binding 1: lights array<Light, 64> - position (vec3) + lightType (u32) - color (vec3) + innerCone (f32) - direction (vec3) + outerCone (f32)


render/shaders/core/textured_quad

Summary: Textured Quad Shader - Simple texture sampling


render/shaders/debug/cloth_debug

Summary: Cloth Debug Shader - Visualize cloth mesh with normal-based coloring


render/shaders/debug/debug_views

Summary: Debug Views Shader - Visualize different render targets (color, depth, normals, roughness/metallic)


render/shaders/debug/fluid_debug

Summary: Fluid Debug Shader - Visualize fluid density grid slices or max projection


render/shaders/materials/pbr_brdf

Summary: PBR BRDF - Physically-based rendering BRDF functions (GGX/Schlick) Dependencies: Requires mathCommonWGSL for saturate() and PI. These are provided separately to avoid duplication when composing shaders.


render/shaders/materials/pbr_extensions

Summary: PBR Extensions - Placeholder hooks for subsurface scattering, fog, and post-lighting effects


render/shaders/materials/pbr_ibl

Summary: PBR IBL - Image-based lighting for diffuse irradiance and specular reflections


render/shaders/materials/pbr_material_uniforms

Summary: PBR Material Uniforms - Standard material parameter bindings


render/shaders/materials/shadow_pcf

Summary: Shadow PCF - Percentage-closer filtering for soft shadows


render/shaders/materials/unlit_world

Summary: Unlit World Shader - Simple unlit rendering with checkerboard floor


render/shaders/materials/voxel_world


render/shaders/modules/chunks/anime_explosion

Summary: Anime Explosion Effects Stylized explosion effects inspired by anime/manga aesthetics. Key Features: 1. Spiky burst shapes - Sharp radial spikes 2. Color banding - Discrete anime-style colors 3. Impact rays - Speed lines radiating outward 4. Shockwave rings - Expanding circular waves 5. Debris particles - Flying sparks and chunks 6. Smoke puffs - Stylized cloud shapes Functions: - explosionBurst(uv, time) - Main explosion shape - impactRays(uv, count, time) - Speed lines - shockwaveRing(uv, time, speed) - Expanding ring - animeColorBand(intensity, colors) - Discrete color steps


render/shaders/modules/chunks/anime_toon

Summary: Anime / Toon Shading Stylized rendering techniques for anime/manga aesthetic. Key Concepts: 1. Multi-step shading - Discrete color bands 2. Outline rendering - Edge detection 3. Specular highlights - Sharp anime-style 4. Rim lighting - Edge glow 5. Hatching/cross-hatching - Manga shadows 6. Subsurface scattering - Skin glow Eye/Face Functions: - animeEye() - Full eye with iris, highlights - animeBrow() - Eyebrow curves - animeBlush() - Cheek flush marks - animeMouth() - Lip curves


render/shaders/modules/chunks/area_lighting

Summary: Area Lighting & Soft Shadows Physically-based area light calculations for soft shadows and lighting. Supports spherical lights and occluders. Key Concepts: 1. Sphere occlusion - AO contribution from nearby spheres 2. Area shadows - Soft shadows from spherical lights/occluders 3. Sphere area lights - Proper falloff for spherical emitters 4. Floor occlusion - Ground plane ambient darkening Functions: - sphOcclusion(pos, nor, sph) - AO from single sphere - sphAreaShadow(P, light, occluder) - Soft shadow - sphAreaLight(P, N, light) - Area light contribution - floorOcclusion(P, N, floorY) - Ground plane AO


render/shaders/modules/chunks/blend_math

Summary: Shared alpha compositing, separable blend, coverage, and ordered-dither helpers for WGSL.


render/shaders/modules/chunks/camera_utils

Summary: Camera Utilities for Shaders Common camera operations for ray generation and view transforms. Used by: ray marching, ray tracing, post-processing Functions: - getCameraMatrix(ro, ta, roll) - Look-at camera matrix - getRay(uv, ro, ta) - Generate ray from UV and camera - screenToWorld(uv, invViewProj) - Unproject screen to world


render/shaders/modules/chunks/color_math

Summary: Shared sRGB, luminance, contrast, YUV/YCbCr, and tone-map helpers for WGSL.


render/shaders/modules/chunks/denoise

Summary: Denoising for Path Tracing Edge-aware filtering and temporal accumulation for noisy renders. Key Concepts: 1. À-Trous Wavelet Transform - Multi-scale edge-aware blur 2. Bilateral filtering - Edge-preserving smoothing 3. Temporal AA/Accumulation - Frame blending with clamping 4. YUV color space - Better for temporal clamping 5. SVGF-style weights - Color, normal, depth weighting


render/shaders/modules/chunks/electricity

Summary: Electricity & Plasma Effects Patterns for lightning, plasma, energy beams, and electrical arcs. Key Concepts: 1. Simplex 3D noise - Smooth organic patterns 2. Sharp glow falloff - Electric intensity 3. Color intensification - Plasma color math 4. Animated distortion - Moving energy Functions: - simplex3d(p) - 3D simplex noise - electricNoise(p) - Multi-octave electric noise - plasmaGlow(intensity, falloff) - Sharp glow - electricArc(uv, time) - Lightning bolt pattern - plasmaColor(intensity, baseColor) - Energy coloring


render/shaders/modules/chunks/fire_turbulence

Summary: Fire & Turbulence Effects Reusable patterns for fire, smoke, and turbulent effects. Based on multi-frequency wave accumulation technique. Key Concepts: 1. Turbulence: Sum of cos() waves at increasing frequencies 2. Twist: Rotate XZ based on Y for spiral motion 3. Expansion: Divide by height for spreading flames 4. Hollow cone SDF: Classic flame silhouette shape Functions: - fireTurbulence(pos, time, octaves) - Multi-octave distortion - fireColor(heat, turbulence) - Heat-based color gradient - flameShape(pos) - Hollow cone distance field - twistPosition(pos, rate) - Helical twist transform


render/shaders/modules/chunks/fractal_edges

Summary: Fractal & Edge Detection Effects Raymarching fractals with stylized edge rendering. Key Concepts: 1. Fractal distance functions - Amazing Surface, Mandelbulb, etc. 2. Edge detection via Laplacian - Dark outlines from SDF 3. Normal-based coloring - No lighting, just normal as color 4. Rainbow/color bands - Animated stripes 5. Stylized sky/sun - Radial gradient with rays 6. Camera path animation - Smooth path following


render/shaders/modules/chunks/fullscreen_quad

Summary: Fullscreen Quad Vertex Shader - Reusable for post-processing effects Renders a fullscreen triangle (more efficient than quad) using vertex index. No vertex buffer needed - just draw 3 vertices. Usage: const myPostFx = `${fullscreenQuadVertexWGSL}${myFragmentShader}`;


render/shaders/modules/chunks/lighting_common


render/shaders/modules/chunks/magic_effects


render/shaders/modules/chunks/math_common

Summary: Shared Math Constants & Utilities for WGSL Shaders Usage: Import and concatenate at the beginning of shaders that need these. Example: `${mathCommonWGSL}` + yourShaderCode


Summary: Shared 2D Noise Functions for WGSL Shaders Used by: particles_billboard, volume_smoke, future effects Functions provided: - hash2d(p) - Pseudo-random hash for 2D position - noise2d(p) - Smooth value noise - fbm2d(p) - Fractal Brownian Motion (4 octaves)


Summary: Shared 3D Noise Functions for WGSL Shaders Used by: volume_smoke, future volumetric effects Functions provided: - hash3d(p) - Pseudo-random hash for 3D position - noise3d(p) - Smooth value noise - fbm3d(p, octaves) - Fractal Brownian Motion (variable octaves) - fbm3dRotated(p, octaves) - FBM with rotation between octaves (reduces banding) - fbm3dVec(p) - Returns 3 independent noise values for domain warping - domainWarp(p, scale, intensity) - Warp position for organic turbulence


render/shaders/modules/chunks/packing

Summary: Normalized integer packing helpers mirrored from engine/core/math/MathPacking.js.


render/shaders/modules/chunks/pathtracing_gi


render/shaders/modules/chunks/pbr_materials

Summary: PBR Materials for Path Tracing Physically-based materials with roughness, metallic, and Fresnel. Key Concepts: 1. Fresnel-Schlick - Reflectance at grazing angles 2. GGX/Roughness sampling - Importance sampling for specular 3. Metallic workflow - Dielectric vs conductor 4. Glass/refraction - Transparent materials 5. Energy conservation - Diffuse + specular balance


render/shaders/modules/chunks/quadtree

Summary: Quadtree / Recursive Cell Pattern Helpers (WGSL) Port of a Shadertoy-style quadtree zoom pattern into reusable WGSL. Functions: - quadtreeCellLevel(uv, time, maxLevels, baseRadius, resolutionY) Returns how deep the recursive subdivision went and a mask for the disc. - quadtreeMask(uv, time) Simple convenience wrapper returning a [0,1] mask based on level.


render/shaders/modules/chunks/quaternion

Summary: Quaternion Math for Shader Animation Full quaternion operations for skeletal animation and rotation. Key Concepts: 1. Quaternion multiplication - Compose rotations 2. Quaternion inverse/conjugate - Reverse rotation 3. Slerp interpolation - Smooth rotation blending 4. Point rotation - Apply quaternion to position 5. Matrix conversion - Quaternion to mat4 Functions: - quaternionMul(a, b) - Multiply quaternions - quaternionInverse(q) - Inverse rotation - quaternionSlerp(a, b, t) - Spherical interpolation - rotatePoint(p, center, q) - Rotate point - quaternionToMatrix(q, offset) - Convert to mat4


render/shaders/modules/chunks/ray_intersect

Summary: Ray-Primitive Intersection Library Analytic ray intersection routines for various geometric primitives. Returns intersection distance and surface normal. All functions follow the pattern: fn iShape(ro, rd, ...) -> RayHit Where RayHit contains: - dist: distance along ray (MAX_RAY_DIST if no hit) - normal: surface normal at intersection Primitives: - Plane, Disk - Sphere, Ellipsoid - Box, Rounded Box - Cylinder, Capsule - Cone, Rounded Cone - Torus - Triangle, Quad


render/shaders/modules/chunks/ray_termination


render/shaders/modules/chunks/ray_tracing

Summary: Ray Tracing Utilities Helper functions for path tracing and ray-based rendering. Includes materials, sampling, and lighting utilities. Functions: - Material handling (Lambertian, Metal, Dielectric) - Random sampling (hemisphere, disk, importance sampling) - Fresnel and BRDF calculations - Sky/environment sampling


render/shaders/modules/chunks/raymarching


render/shaders/modules/chunks/restir_guide_policy


render/shaders/modules/chunks/sdf_primitives

Summary: Signed Distance Field Primitives Common SDF shapes for ray marching. Used by: volume rendering, procedural geometry, collision detection Functions: - sdSphere(p, r) - Sphere SDF - sdBox(p, b) - Box SDF - sdPlane(p, n) - Plane SDF (n.xyz = normal, n.w = distance) - sdCapsule(p, a, b, r) - Capsule/cylinder SDF - sdTorus(p, t) - Torus SDF - opUnion(d1, d2) - Union of two SDFs - opSubtract(d1, d2) - Subtraction (d1 - d2) - opIntersect(d1, d2) - Intersection - opSmoothUnion(d1, d2, k) - Smooth blend union


render/shaders/modules/chunks/shadows_ao

Summary: Soft Shadows and Ambient Occlusion for Ray Marching Used by: SDF rendering, volumetric effects, global illumination Functions: - calcSoftShadow(ro, rd, sceneSDF, mint, maxt, k) - Penumbra soft shadows - calcAO(pos, nor, sceneSDF) - Ambient occlusion via ray marching - calcHardShadow(ro, rd, sceneSDF, mint, maxt) - Binary shadow test


render/shaders/modules/chunks/spell_particles

Summary: Spell Particle Effects - WGSL Shader Chunk Particle behaviors for spell effects including projectiles, shields, auras, and various magical effects.


render/shaders/modules/chunks/structs_common


render/shaders/modules/chunks/temporal_aa

Summary: Temporal Anti-Aliasing (TAA) Utilities Functions for implementing high-quality temporal anti-aliasing. Key Concepts: 1. Jittered sampling (Halton sequence) 2. History reprojection 3. Neighborhood clamping (ghosting prevention) 4. YCoCg color space (better clamping) 5. Catmull-Rom history sampling 6. Sharpening filter Functions: - halton23(index) - Halton 2,3 sequence for jitter - rgb2YCoCg / yCoCg2Rgb - Color space conversion - clipToBox - Neighborhood clamping - catmullRomSample - High quality history sampling


render/shaders/modules/chunks/texture_math

Summary: Shared texture coordinate, mip, atlas, and virtual-texture helpers for WGSL.


render/shaders/modules/chunks/volumetric_clouds

Summary: Volumetric Clouds & Fog Rendering Advanced volumetric rendering with dynamic step size and fog integration. Key Concepts: 1. Deformed periodic grid noise - Cheap volume noise 2. Dynamic step size - Adaptive raymarch based on density 3. Fog integral difference - Proper fog accumulation 4. Multi-octave displacement - FBM-like volume noise 5. Saturation-preserving interpolation - Better color blending


render/shaders/modules/chunks/voronoi

Summary: Voronoi & Cellular Noise Patterns Functions for voronoi diagrams, cellular textures, and organic patterns. Key Concepts: 1. Voronoi cells - Animated cellular patterns 2. Smooth voronoi - Blended cell boundaries 3. Polar coordinates - Radial patterns 4. Ring patterns - Concentric ripples 5. FBM with rotation - Reduced axis artifacts Functions: - voronoi2d(p, time) - Basic 2D voronoi - voronoiSmooth(p, w, time) - Smoothed cell edges - toPolar(v) - Cartesian to polar - ringPattern(p, time) - Concentric rings with noise


render/shaders/modules/chunks/voxel_world

Summary: Voxel World Module - shared terrain functions for voxel-style materials. This chunk does NOT declare entry points. It only provides reusable WGSL helpers for triplanar noise, terrain palette, and voxel edge darkening.