createSpellForce(position, direction, power, element)

createSolidCollisionPipeline(device, workgroupSize = 256)

createCrystalBondPipeline(device, workgroupSize = 256)

createBondConstraintPipeline(device, workgroupSize = 256)

stepSolidCollision(device, collisionPipeline, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

stepCrystalBonds(device, bondPipeline, phaseBuffers, particleWorld, options = {})

stepBondConstraints(device, constraintPipeline, phaseBuffers, particleWorld, bondCount, options = {})

stepCrystalSystem(device, systems, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

createCrystalSystemPipelines(device, workgroupSize = 256)

async extractCrystalClusters(device, phaseBuffers, particleWorld, minClusterSize = 5)

createSeedInjectionParams(position, radius, seedStrength, temperature, magicSaturation)

createCrystallizationPipeline(device, workgroupSize = 256)

stepCrystallization(device, crystallization, phaseBuffers, particleWorld, dt, options = {})

injectFreezeSeeds(device, phaseBuffers, particleWorld, seedParams)

injectHeatSeeds(device, phaseBuffers, particleWorld, seedParams)

applyPhaseVisuals(device, phaseBuffers, particleWorld, options = {})

async extractFrozenShape(device, phaseChangeBuffers, gridSize, worldMin, cellSize)

injectMeltedFluid(device, fluidWorld, position, velocity, mass, radius)

async extractFrozenParticles(device, phaseBuffer, positionBuffer, particleCount, minClusterSize = 5)

magic" has accumulated solidPhase: 0=fluid, 1=freezing, 2=frozen seedStrength: If 0, this particle spreads solidification — Crystal bond attributes (per bond) Stores connections between frozen particles forming crystal lattice particleA: index of first particle particleB: index of second particle restDistance: original distance when bond formed (constraint target) stiffness: bond strength (0 1, higher = more rigid) — Default crystallization parameters tuned for fast freeze, slow melt — Default solid collision parameters <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh),


async createFluidSimWorld(gpuDevice, options = {})

stepFluidSimWorld(world, deltaSeconds, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Clear/reset the density and velocity buffers to zero. Use this when bounds change significantly to prevent stale data from appearing at wrong world space locations. Clear the density and color buffers to zero. Used in particle as smoke mode to reset before splatting particle positions/colors. Parameters: (Object) — Fluid sim world Initialize fluid sim world lazily with bind group creation for smoke rendering. This is a convenience function that handles the full setup sequence. Parameters: (Object) — Initialization options (Object) — GPU device wrapper (Object) — Smoke state object to populate (Object) — Particle state (for attaching fluid) (Array) — Grid dimensions [x, y, z] (default: [128, 96, 128]) (number) — Compute workgroup size (default: 64) (number) — Pressure solve iterations (default: 8) (Function) — Function to attach fluid to particles (Function) — Optional logger Returns: Created fluid world <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks


A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/fluids/FluidSimulation.js
Classes
class FluidMetadata
class FluidSimulator
Constants
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Per voxel simulation metadata Stored separately from material ID to avoid expanding chunks Method Signature Summary Mark a voxel as active (needs simulation) Check if a voxel was updated this frame Mark voxel as updated this frame Clear all update flags for new frame Clear dirty rectangles after processing Method Signature Summary Detect monitor refresh rate and set target Set target FPS manually (e.g., from user settings) Auto detect refresh rate from actual frame times Call this after a few frames to refine the target Update FPS tracking and adapt budget Deterministic random based on position and frame Ensures same behavior on all clients for multiplayer Mark a voxel position as needing fluid simulation Only activates actual fluid materials (liquid, powder, gas, fire) Activate fluid materials in a chunk that are at the surface (adjacent to air) Only surface fluids need simulation buried fluids are stable Rebuild dirty rectangles from active voxels (limited for performance) Rotates through active voxels to ensure all get processed eventually Main simulation tick call once per frame Process a dirty rectangle within a chunk Updates from bottom to top for proper gravity Get voxel at world position (handles chunk boundaries) Set voxel at world position (handles chunk boundaries) Swap two voxels (for falling/rising) Check if material A can displace material B (based on density) Update powder (sand, gravel) Falls down, slides diagonally if blocked Update liquid (water, lava) Falls down, spreads horizontally Update gas (steam, smoke) Rises up, spreads horizontally Update fire


slides diagonally if blocked Update liquid (water, lava) Falls down, spreads horizontally Update gas (steam, smoke) Rises up, spreads horizontally Update fire (energy) Spreads to flammable neighbors, has lifetime Update acid (special liquid that corrodes) Check for special chemical reactions between materials Called when materials are adjacent Load configuration from engine.cfg section Constants — Physical properties for each material type Properties: type: 'solid' 'powder' 'liquid' 'gas' 'fire' density: Higher density sinks below lower density (0 100) viscosity: How slowly liquid spreads (0=instant, 1=very slow) flammable: Can catch fire burnTime: Ticks until destroyed by fire spreadRate: How many cells to check for spreading (liquids/gases) <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async splatFluidSources(fluidWorld, gpuDevice, options = {})

splatParticleDensity(fluidWorld, particleWorld, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions PARTICLES AS SMOKE splat density at each particle position. Each particle IS the smoke not a separate effect. Inherits from particle: Position → where density is splatted Size (from meta.a) → splat radius Color (from meta.rgb) → smoke color (sampled by smoke shader) Age/Lifetime → fade behavior When raymarched, overlapping particles merge into smooth fluid blobs. Parameters: (Object) — Fluid simulation world with densityBuffer (Object) — Particle simulation world with position/velocity/meta buffers (Object) — { radiusScale, densityScale, worldMin, worldMax, encoder, logger } <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


buildFluidDomainFromColliders(ecsWorld, options = {})

createWorldFluidDomain(device, ecsWorld, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Build fluid domain from ECS world colliders Parameters: (Object) — ECS world with component storage (Object) — Configuration options Returns: Domain info with bounds and collider list Create a 3D solid mask texture from colliders Each cell is 0 (fluid) or 1 (solid) Create a world fluid domain with solid mask Update world fluid domain params buffer Destroy world fluid domain Rebuild solid mask when scene changes <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Ray with wave properties (phasor representation) Method Signature Summary Advance ray by distance, accumulating phase Get wavelength in current medium Get wave number k Get complex phasor value Get instantaneous E field (for visualization) Clone ray Terminate ray Method Signature Summary Compute Fresnel coefficients for interface Compute time interface coefficients When ε changes: t = (n1+n2)/(2n2), r = (n2 n1)/(2n2) Compute reflected direction Compute refracted direction (Snell's law) Compute time reflected direction (reverses!) Method Signature Summary Add temporal material region Spawn a new ray Trace all active rays for one step Handle time reflection (temporal boundary) Creates backward propagating ray while preserving frequency Get all rays for visualization Get time reflected rays only Clear all rays Functions Convert frequency to visible color (RGB) Parameters: (number) — Frequency in Hz Returns: RGB values [0 1] Convert wavelength to color Parameters: (number) — Wavelength in meters Apply Doppler shift color Parameters: (number) — No description in source JSDoc. (number) — No description in source JSDoc. Returns: } Generate visualization data for rays Parameters: (PhasorRay[]) — No description in source JSDoc. (number) — No description in source JSDoc. Constants — Base visible light frequencies — Ray interaction types — Ray state Re exports <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU


system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/fluids/PhotonicCrystal.js
Classes
class DispersionCalculator
class PhotonicTimeCrystal
class TimeReflectionEvent
class TemporalCloak
class PhotonicCrystalManager
Constants
Re-exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Computes dispersion relation for time varying medium For photonic time crystal: ω(k) has gaps in k space (momentum gaps) Method Signature Summary Get effective permittivity at time t ε(t) = ε₀(1 + Δε/ε₀ · cos(ωₘt)) Check if frequency/momentum is in band gap Temporal band gaps occur at k = n·ωₘ/(2c) Compute Floquet exponent (Bloch theorem in time) For determining band structure Floquet theorem: E(t) = e^(μt) · P(t) where μ is the Floquet exponent and P(t) is periodic Real μ → exponential growth/decay (in band gap) Imaginary μ → oscillatory (propagating wave) Get band gap boundaries for nth gap Compute parametric amplification factor Get transmission/reflection coefficients for time interface When ε₁ → ε₂ suddenly Method Signature Summary Get permittivity at position and time Check if point is inside crystal Activate the crystal (start modulation) Deactivate the crystal Check if wave at given frequency/momentum will be in band gap Get expected effects for incoming wave Create TimeVaryingMaterial for FDTD solver Get visualization data Apply parametric amplification to field amplitude with saturation Prevents numerical explosion (NaN/Inf) from exponential growth Soft clipping saturation to prevent NaN/Inf explosion Uses tanh for smooth limiting: E final = E sat tanh(E / E sat) Saturate a 3D vector field Get stability info for current parameters Get Floquet analysis for debugging Represents a sudden change in ε that creates time reflection Method Signature Summary Get permittivity at time t Check if point is in event region Trigger the time reflection Get expected output waves


time reflection Method Signature Summary Get permittivity at time t Check if point is in event region Trigger the time reflection Get expected output waves from input wave Create TimeVaryingMaterial for FDTD Temporal cloaking using time lens approach Opens and closes a gap in the time domain Method Signature Summary Get permittivity for temporal cloaking Uses time lens approach: slow down light before gap, speed up after Check if event at given time would be cloaked Method Signature Summary Add a photonic time crystal Create and add a new crystal Schedule a time reflection event Create temporal cloak Update all photonic elements Get all active effects at a position Get visualization data for all elements Remove all elements Constants — Photonic crystal types — Modulation waveforms — Time crystal effects Re exports <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/fluids/VolumeFieldSmooth.js
Functions
smoothVolumeField(world, options = {})
disposeVolumeFieldSmooth(device)
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createVolumeFieldWorld(gpuDevice, options = {})


sim/fluids/index.js
Re-exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Re exports , , , , , , , , , , , <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async captureFrameAsync(snapshot, particleState, emitters, currentTimeMs)

captureFrameTripleBuffered(snapshot, particleState, emitters, currentTimeMs)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: AsyncSnapshotManager.js Async wrapper for worker based snapshot capture Coordinates between main thread (GPU readback) and worker (compression). Uses TRIPLE buffering for completely non blocking capture: Buffer A: Being filled from GPU readback Buffer B: Being processed by worker Buffer C: Completed and ready for use This ensures the render loop NEVER waits for GPU or worker. Functions Initialize the async snapshot system Capture a frame asynchronously GPU readback happens on main thread, compression in worker Triple buffered capture completely non blocking Returns immediately, GPU readback and worker processing happen in background Clean up Set capture interval (for quality/performance tradeoff) <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async updateAttachedParticlesIntoWorld(gpuDevice, meshBuffers, particleWorld, attachmentBuffer, options = {})

async updateAttachedParticlesIntoParticlesState(particles, meshBuffers, options = {})


async assignParticlesToBonesIntoWorld(gpuDevice, boneBuffer, particleWorld, attachmentBuffer, options = {})

async updateBoneAttachedParticlesIntoWorld(gpuDevice, boneBuffer, particleWorld, attachmentBuffer, options = {})

async assignParticlesToBonesIntoParticlesState(particles, boneBuffer, options = {})

async updateBoneAttachedParticlesIntoParticlesState(particles, boneBuffer, options = {})


createCustomEffectCollisionSystem(device, registeredEffects = [])

addCustomEffectCollider(system, device, effectId, center, radius, effectParams = [0, 0, 0, 0])

updateCustomEffectCollider(system, device, index, center, radius, effectParams)

initCustomEffectCollisionBindGroup(system, device, positionsBuffer, velocitiesBuffer, metaBuffer = null)

executeCustomEffectCollision(system, device, queue, particleCount, time, dt, bounciness = 0.3, friction = 0.1, fallbackRadius = 0.1)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: CustomSDFCollisionBridge.js Bridge Custom Particle Effects to Physics Collision Ensures visual SDF and collision SDF are IDENTICAL by: 1. Generating collision shaders from the same SDF code as visual effects 2. Providing a unified API for registering custom effects with physics 3. Syncing effect parameters between render and simulation This ensures "what you see is what collides" particles collide exactly with the shape that's being rendered. Functions Generate collision shader that uses the SAME SDF code as visual rendering This is the key to ensuring physics matches visuals exactly Create custom effect collision system Uses the same SDF code as visual rendering for exact physics/visual match Add a custom effect collider Uses the same effect ID as visual rendering for exact match Update collider transform (for moving effects) Initialize bind group with particle buffers Parameters: (object) — Custom effect collision system (GPUDevice) — WebGPU device (GPUBuffer) — Particle positions buffer (GPUBuffer) — Particle velocities buffer (GPUBuffer) — Particle meta buffer (for per particle size) Execute custom effect collision pass Parameters: (object) — Custom effect collision system (GPUDevice) — WebGPU device (GPUQueue) — WebGPU queue (number) — Number of particles (number) — Current simulation time (number) — Time step (number) — Bounce coefficient (0 1) (number) — Friction coefficient (0 1) (number) — Fallback particle radius if no meta buffer Rebuild collision system when effects change Call this after registering new custom effects Clear all colliders Destroy system and release GPU resources <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides


effects Clear all colliders Destroy system and release GPU resources <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/particles/GPUParticleSorter.js
Classes
class GPUParticleSorter
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Sort particles by depth (back to front for transparency) Get sorted indices buffer for use in rendering <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async generateMeshParticlesIntoWorld(gpuDevice, meshBuffers, particleWorld, options = {})

async generateMeshParticlesIntoParticlesState(particles, meshBuffers, options = {})


estimateMaxSpeedCPU(velocityData, particleCount, sampleCount = 256)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleAdaptiveSubstep.js Adaptive Substeps with CFL Condition (GAP 20) Automatically determines the number of simulation substeps per frame based on the maximum particle velocity (CFL condition), preventing tunneling for fast particles without wasting substeps on slow ones. CFL: dt sub = cellSize cflFactor / maxSpeed Substeps = ceil(dt frame / dt sub), clamped to [minSubsteps, maxSubsteps] Uses GPU readback of max velocity (from indirect dispatch counters or a separate reduction pass) when available, falls back to CPU side estimate. Ref: Houdini POP Solver CFL, PhysX particle substeps Functions Create an adaptive substep controller. Parameters: (Object) — No description in source JSDoc. (number) — CFL safety factor (0.5 = particle travels at most 50% of cell per substep) (number) — Spatial cell size (collision grid resolution) (number) — Minimum substeps per frame (default 1) (number) — Maximum substeps per frame (default 8) (number) — Exponential smoothing for substep count changes (0 1, default 0.3) Compute the number of substeps needed for this frame. Parameters: (Object) — Adaptive substep controller (number) — Frame delta time in seconds (number) — Maximum particle speed this frame (from GPU readback or estimate) Returns: } Estimate max particle speed from CPU side velocity data. Use this as fallback when GPU readback is not available. Parameters: (Float32Array) — Particle velocity buffer (vec4 per particle) (number) — Number of active particles (number) — How many particles to sample (default 256 for performance) Returns: Estimated max speed Reset the controller state. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body


Returns: Estimated max speed Reset the controller state. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


executeGPUSort(sortSystem, device, particleCount, cameraPos)

createChunkedBufferSystem(device, maxParticles, bytesPerParticle = 16)

createWireConstraintSystem(device, maxWires = 10000)

addWireConstraint(wireSystem, device, particleA, particleB, restLength, stiffness = 0.5)

initWireBindGroup(wireSystem, device, positionsBuffer, velocitiesBuffer)

solveWireConstraints(wireSystem, device, iterations = 4)

createSDFCollisionSystem(device, initialCapacity = 64)

addSDFCollider(sdfSystem, device, type, center, radius, halfExtents = [1, 1, 1])

initSDFBindGroup(sdfSystem, device, positionsBuffer, velocitiesBuffer, metaBuffer = null)

executeSDFCollision(sdfSystem, device, particleCount, bounciness = 0.3, friction = 0.1, options = {})

initSeedingBindGroup(seedSystem, device, positionsBuffer, velocitiesBuffer)

seedParticlesGPU(seedSystem, device, particleCount, options = {})

initVolumetricBindGroup(volSystem, device, positionsBuffer, thermalBuffer, velocitiesBuffer)

computeVolumetricLighting(volSystem, device, particleCount, lightPos, lightColor, options = {})

initDepthCollisionBindGroup(system, device, positionsBuffer, velocitiesBuffer, depthTextureView)

executeDepthCollision(system, device, particleCount, viewProj, invViewProj, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleAdvanced.js GPU Sorting, Chunked Buffers, Wire Constraints, SDF Collision Advanced particle system features: Bitonic GPU sorting for transparency Chunked buffer management for 100M+ particles Wire/spring constraints between particles SDF mesh collision GPU particle seeding Volumetric lighting integration Functions Create GPU sorting system for transparent particle rendering Initialize sort bind group with position buffer Execute GPU sort pass Create chunked particle buffer system for 100M+ particles Get chunk index for a particle index Get local index within a chunk Destroy chunked buffer system Create wire constraint system Add a wire constraint between two particles Initialize wire constraint bind group Solve wire constraints Create SDF collision system Add an SDF collider Clear all SDF colliders (for per frame rebuild from entity shapes) Batch write SDF colliders from an array of collider descriptors. Much more efficient than calling addSDFCollider() in a loop. Parameters: (object) — SDF collision system (GPUDevice) — WebGPU device Initialize SDF collision bind group Parameters: (object) — SDF collision system (GPUDevice) — WebGPU device (GPUBuffer) — Particle positions buffer (GPUBuffer) — Particle velocities buffer (GPUBuffer) — Particle meta buffer (for per particle size) Execute SDF collision pass Parameters: (object) — SDF collision system (GPUDevice) — WebGPU device (number) — Number of particles to process (number) — Bounce coefficient (0 1) (number) — Friction coefficient (0 1) (object) — Additional options { contactRadius, barrierStiffness, dt, usePerParticleSize } Create GPU particle seeding system Initialize seeding bind group Seed particles on GPU Create


{ contactRadius, barrierStiffness, dt, usePerParticleSize } Create GPU particle seeding system Initialize seeding bind group Seed particles on GPU Create volumetric lighting system for particles Initialize volumetric lighting bind group Compute volumetric lighting for particles Create depth buffer collision system. Bind group is created separately via initDepthCollisionBindGroup (recreate on depth texture resize). Initialize or recreate the depth collision bind group. Must be called whenever the depth texture changes (e.g., on window resize). Execute depth buffer collision compute pass. Parameters: (Object) — Depth collision system (GPUDevice) — WebGPU device (number) — Number of particles to process (Float32Array) — 4x4 view projection matrix (column major, 16 floats) (Float32Array) — 4x4 inverse view projection matrix (column major, 16 floats) (Object) — { resolution, dt, bounciness, friction, particleRadius, depthBias } <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createAttributeReader(sourceWorld, options = {})

findParticlesInRadius(reader, queryPos, radius, maxResults = 32)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleAttributeReader.js Cross Emitter Attribute Reader (GAP 21) Allows one emitter to read particle data from another emitter's buffers. Enables leader follower, flocking, synchronized multi layer effects. Matches Niagara's Particle Attribute Reader data interface. Two modes: 1. Direct index: read specific particle by index (leader follower) 2. Nearest query: find closest particle to a given position (via spatial grid) Usage: const reader = createAttributeReader(sourceWorld); // In consumer emitter logic: const pos = readParticlePosition(reader, particleIndex); const vel = readParticleVelocity(reader, particleIndex); const nearest = findNearestParticle(reader, queryPos); Functions Create an attribute reader bound to a source particle world. Parameters: (Object) — Source particle world to read from (Object) — { enableSpatialQuery } Refresh CPU side cache from GPU buffers (async). Call once per frame before reading attributes. Parameters: (Object) — No description in source JSDoc. (number) — Current frame number (avoids redundant readbacks) Read a particle's position and age. Parameters: (Object) — No description in source JSDoc. (number) — Particle index Returns: null} Read a particle's velocity and lifetime. Parameters: (Object) — No description in source JSDoc. (number) — Particle index Returns: null} Read a particle's color and packed meta. Parameters: (Object) — No description in source JSDoc. (number) — Particle index Returns: null} Find the nearest alive particle to a query position (brute force). For large counts, use the spatial grid instead. Parameters: (Object) — No description in source JSDoc. (number[]) — [x, y, z] (number) — How many particles to search Returns:


use the spatial grid instead. Parameters: (Object) — No description in source JSDoc. (number[]) — [x, y, z] (number) — How many particles to search Returns: null} Find all particles within a radius of a query position. Parameters: (Object) — No description in source JSDoc. (number[]) — [x, y, z] (number) — No description in source JSDoc. (number) — Cap on results (default 32) Returns: } Destroy the reader. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


triggerImpact(bridge, material, position, speed = 2, temperature = 300, priorityClass = PRIORITYNORMAL, velocity = null)

updateAmbientLoop(bridge, emitterId, material, position, params = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleAudioBridge.js Real Time Procedural Spatial Audio for Particle Systems Zero latency audio driven by GPU particle events via onParticleEvent callbacks. Every collision triggers sound immediately — no polling, no timers. Architecture informed by FMOD, PopcornFX, and Web Audio API perf research: HRTF panning — binaural left/right ear simulation with elevation + front/back cues Spatial clustering — nearby same material impacts merge into single louder sound Priority classes — critical/high/normal/low tiers (FMOD style, not just volume) Fade out on voice steal — 5ms gain ramp prevents audible clicks Separate ambient bus — continuous loops bypass transient compressor (no pumping) Listener orientation — correct panning from camera forward/up vectors Shared AudioContext — accepts external context to avoid browser resource limits Per material spatial cooldown — dedupes only within a radius, not globally Dynamic compressor on impact bus — tames peak transients without affecting ambients Usage: const bridge = createAudioBridge({ maxVoices: 32, maxDistance: 100 }); wireEventCallbacks(bridge, world.eventSystem, getMaterialForEvent); // Per frame (for ambient loops + listener tracking): updateListenerFromCamera(bridge, camera); updateEmitterAmbients(bridge, emitters); // Cleanup: destroyAudioBridge(bridge); Functions Create an audio bridge with full voice management. Parameters: (Object) — No description in source JSDoc. (number) — Max concurrent one shot voices (default 32) (number) — Max audible distance (default 100) (number) — Master volume (default 0.5) (AudioContext) — External AudioContext to share (optional) Destroy the bridge and release all audio resources. Update listener


— Master volume (default 0.5) (AudioContext) — External AudioContext to share (optional) Destroy the bridge and release all audio resources. Update listener from a camera object. Sets both position AND orientation for correct spatial panning (research: without orientation, all panning is wrong). Trigger an impact sound immediately. Used for reaction events and manual triggers. For collision/death events, use the batched system (flushImpactBatches) instead. Parameters: (number) — PRIORITY NORMAL by default. Use PRIORITY HIGH for player caused. Wire the bridge into the ParticleEventSystem via onParticleEvent callbacks. Fires immediately when readbackEvents completes — zero polling, zero timers. Registers for collision events (type 2, 3) and death events (type 1). Parameters: (Object) — No description in source JSDoc. (Object) — From initParticleEventSystem (Function) — (evt) = substanceKey or materialIndex. Unwire event callbacks (for cleanup). Actually removes the callback functions from the event system's callback arrays. Immediately silence ALL particle audio — impacts + ambients. Called when the editor exits play mode (Stop button). Update reverb parameters at runtime (e.g., when entering a cave or outdoor area). Parameters: (Object) — { wetLevel, decay, preDelay } all optional Set impact bus volume independently (0 1). Smoothed to avoid zipper noise. Set ambient bus volume independently (0 1). Smoothed to avoid zipper noise. Resume AudioContext after browser autoplay policy suspension. Research (Chrome/Safari): Context starts 'suspended' until user gesture. Call this from your first click/keydown handler. Auto unlock AudioContext on first user interaction (Safari/iOS workaround). Research (Matt Montag): Safari requires resume() from touch/click handler. Registers one


unlock AudioContext on first user interaction (Safari/iOS workaround). Research (Matt Montag): Safari requires resume() from touch/click handler. Registers one shot listeners that self remove after first successful resume. Pause all audio (suspend context). Use when tab hidden or game paused. Research (web.dev Fieldrunners): every game should pause audio on tab hide to prevent wasted CPU and audio buildup. Resume all audio after pause. Hook into Page Visibility API to auto pause/resume audio. Call once after createAudioBridge. Set an occlusion callback. The function receives (sourcePos, listenerPos) and returns 0 1 (0=fully occluded, 1=clear). Used to modulate LPF cutoff for obstruction. Game code provides th


stepBondFormation(world, bondSystem, options = {})

stepBondBreaking(world, bondSystem, options = {})

stepBondSystem(world, bondSystem, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleBonds.js Dynamic Bond Formation & Breaking System Manages runtime creation and destruction of particle bonds (WELD, STICKY constraints) driven by proximity, temperature, and particle flags. Features: Bond formation: WELDABLE particles within threshold + temperature conditions → WELD constraint Bond breaking: Constraints with FLAG BROKEN get cleaned up + optional break effects Temperature driven dynamics: Freezing forms bonds, melting breaks them Rate limiting: Max bonds per frame to prevent GPU stalls Functions Create a bond management system. Parameters: (Object) — Particle sim world Returns: Bond system Attempt to form bonds between nearby particles. Called each frame from the simulation loop. Parameters: (Object) — Particle sim world (Object) — Bond system from createBondSystem (Object) — { thermalData, positions, particleCount, flags, freezePoint } Process broken bonds and clean them up. Call after constraint solver has run. Parameters: (Object) — Particle sim world (Object) — Bond system (Object) — { thermalData, meltPoint } Step the full bond system (formation + breaking). Get bond system stats. Destroy bond system and clear all bonds. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is


Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


initChemistryBindGroups(system, device, positionBuffer, velocityBuffer, gridBuffers, elementTable, thermalBuffer)

initParticleValence(system, device, elementData, startIndex, count)

executeChemistry(system, device, particleCount, dt)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleChemistry.js Chemical Reaction System (GAP 38) GPU compute: valence electron driven bond formation/breaking. Bonds form when electronegativity difference permits, release/absorb energy that feeds directly into the thermal system. Features: Valence electron tracking per particle (from element table) Bond formation: electronegativity difference → ionic vs covalent Reaction energy ΔH → feeds thermal buffer Temperature dependent reaction rate (Arrhenius: k = A·e^( Ea/RT)) Bond dissociation at high temperature Uses neighbor grid (GAP 25) for spatial queries Outputs bond pairs to CPU for constraint creation (GAP existing) Two pass approach: Pass 1 (GPU): scan neighbors, compute bond eligibility, write bond candidates Pass 2 (CPU): read back candidates, create constraints, update valence Usage: const chem = createChemistrySystem(device, maxParticles); initChemistryBindGroups(chem, device, posBuffer, velBuffer, gridBuffers, elementTable); executeChemistry(chem, device, particleCount, dt); Functions Create the chemistry system. Initialize bind groups. Initialize valence electrons for a range of particles based on their element. Execute chemistry compute (bond formation + dissociation). Get the valence buffer for external use. Destroy. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision


particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


initClassifierBindGroups(system, device, positionBuffer, velocityBuffer, thermalBuffer, sphDensityBuffer)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleClassifier.js GPU Particle Classification for Fluid Rendering Classifies each liquid particle into categories based on SPH density and velocity. Used by renderers to route particles to different visual styles: Bulk fluid → SSFR surface rendering (smooth continuous surface) Surface → SSFR + edge highlight Spray → Small SDF billboard with fading alpha Foam → White tinted SDF billboard on surface Bubble → Tiny transparent rising sphere Output: per particle u32 classification buffer (binding for vertex shaders). Classification IDs: 0 = unclassified / non liquid 1 = bulk (dense interior) 2 = surface (boundary) 3 = spray (isolated, fast) 4 = foam (isolated, slow, near surface) 5 = bubble (isolated, rising) Usage: const cls = createClassifierSystem(device, maxParticles); initClassifierBindGroups(cls, device, posBuffer, velBuffer, thermalBuffer, sphDensityBuffer); executeClassifier(cls, device, particleCount); // cls.classBuffer is a storage buffer readable by vertex shaders Functions Create the classifier system. Initialize bind groups. Execute the classification compute pass. Get the classification buffer for use by renderers. Update classifier thresholds at runtime. Destroy classifier system. Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units :


physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createColorGradient(stops, resolution = 64)

gradientFromLegacy(color, colorEnd, alphaOverLife = [1, 1, 1])

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleColorGradient.js N point color gradient for particles Niagara/PopcornFX parity: arbitrary color ramps over particle lifetime. Replaces the 2 point linear (color → colorEnd) with full gradient control. CPU builds a 1D RGBA LUT texture, GPU samples with t = age/lifetime. Usage: const grad = createColorGradient([ { t: 0.0, color: [1, 0.6, 0.1, 0.0] }, // orange, transparent { t: 0.2, color: [1, 0.8, 0.2, 1.0] }, // bright yellow, full { t: 0.7, color: [0.8, 0.2, 0.0, 0.8] }, // red { t: 1.0, color: [0.3, 0.3, 0.3, 0.0] }, // grey smoke, fade out ]); const texture = uploadGradientTexture(device, grad); Functions Create a color gradient from an array of color stops Each color is [r, g, b] or [r, g, b, a] with values 0 1 Parameters: (number) — LUT texture width (default 64, power of 2) Returns: } Sample a color gradient at a given t value Parameters: (number) — Position along gradient (0 1) Returns: [r, g, b, a] Upload a color gradient as a 1D GPU texture for shader sampling Parameters: (GPUDevice) — No description in source JSDoc. Returns: } Destroy a gradient texture Convert a legacy color/colorEnd pair to a gradient Parameters: (number[]) — Start color [r, g, b] (number[]) — End color [r, g, b] (number[]) — [start, mid, end] alpha curve Returns: } Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints


phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


catmullRomInterpolate(p0, p1, p2, p3, t, tension = 0.5)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleCompression.js Compression utilities for particle snapshots Extracted from ParticleSnapshotDelta.js for modularity Includes: Run length encoding Variable length integer packing PCA + DCT compression Position/velocity quantization Interpolation algorithms Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/particles/ParticleConfig.js
Constants
Re-exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Constants Re exports , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createRopeConstraintSystem(device, maxConstraints = 100000)

initRopeConstraintBindGroup(system, device, positionsBuffer, velocitiesBuffer, thermalBuffer)

addDistanceConstraint(system, device, particleA, particleB, restLength, stiffness = 0.9)

addAttachmentConstraint(system, device, particleIndex, worldPos, stiffness = 1.0)

addRopeInextensibleConstraint(system, device, particleA, particleB, restLength, opts = {})

updateAttachmentTarget(system, device, constraintIndex, worldPos)

updateRopeConstraintPhysics(system, device, constraintIndex, opts)

addBendingConstraint(system, device, particleA, particleB, particleC, restAngle = Math.PI, opts = {})

addSpringConstraint(system, device, particleA, particleB, restLength, opts = {})

addStickyConstraint(system, device, particleA, target, opts = {})

addCohesionConstraint(system, device, particleA, particleB, opts = {})

addCollisionConstraint(system, device, particleA, particleB, opts = {})

addWeldConstraint(system, device, particleA, particleB, restDistance = 0)

applyMaterialPreset(system, device, presetName, constraintIndices)

createRopeConstraints(system, device, particleStart, particleCount, opts = {})

solveRopeConstraints(system, device, iterations = 8, dt = 1/60, opts = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleConstraints.js GPU Constraint Solver for Rope/Wire/Cloth Unified constraint system for particle based physics: Distance constraints (maintain rest length between particles) Attachment constraints (pin particle to world position) Angle constraints (maintain angle between 3 particles) [future] Bending constraints (maintain curvature) [future] Part of the Unified Rope Particle System (Phase 2) Functions Create rope/constraint solver system Parameters: (GPUDevice) — WebGPU device (number) — Maximum number of constraints Returns: Constraint system object Initialize constraint system bind group Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (GPUBuffer) — Particle positions buffer (GPUBuffer) — Particle velocities buffer Add a distance constraint between two particles Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First particle index (number) — Second particle index (number) — Rest length (number) — Stiffness (0 1) Returns: Constraint index or 1 if failed Add an attachment constraint (pin to world position) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — Particle to attach (Array<number ) — [x, y, z] world position (number) — Stiffness (1.0 = hard constraint) Returns: Constraint index or 1 if failed Add a rope inextensible constraint (mass aware, with breaking support) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First particle index (number) — Second particle index (number) — Rest length (Object) — Rope physics options Returns: Constraint index or 1 if failed Update an attachment constraint's target position Parameters: (Object) — Constraint system


— Rope physics options Returns: Constraint index or 1 if failed Update an attachment constraint's target position Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — Constraint index (Array<number ) — New [x, y, z] world position Update rope constraint physics properties Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — Constraint index (Object) — { chainStiffness, tensionStiffness, maxTension, massA, massB } Add a bending/angle constraint between 3 particles UNTESTED Maintains angle at center particle (particleB) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First endpoint (number) — Center particle (angle vertex) (number) — Second endpoint (number) — Rest angle in radians (default: PI = straight) (Object) — { stiffness } Returns: Constraint index or 1 if failed Add a spring constraint UNTESTED Unlike distance, springs can compress AND extend (Hooke's law) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First particle (number) — Second particle (number) — Rest length (Object) — { stiffness, massA, massB } Returns: Constraint index or 1 if failed Add a sticky/adhesion constraint UNTESTED Particle sticks to a world position or another particle Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — Particle to make sticky (Array<number number) — [x,y,z] world position OR particle index (Object) — { stiffness, adhesionStrength, breakDistance } Returns: Constraint index or 1 if failed Add a cohesion constraint UNTESTED Particles attract each other within a radius (like water droplets) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First particle (number) — Second particle (Object) — {


(like water droplets) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First particle (number) — Second particle (Object) — { cohesionRadius, stiffness, massA, massB } Returns: Constraint index or 1 if failed Add a collision constraint UNTESTED Particle particle collision with friction and restitution (bounce) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (number) — First particle (number) — Second particle (Object) — { collisionRadius, friction, restitution, massA, massB } Returns: Constraint index or 1 if failed Add a weld constraint UNTESTED Permanently joins two particles (rigid connection) Parameters: (Object) — Constraint system (GPUDevice) — WebGPU device (numb


feedCollisionEvents(spawner, eventData, eventCount, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleDecalSpawner.js Spawn Decals from Particle Collisions (GAP 22) Consumes GPU event readback data (collision events) to spawn projected texture decals at impact points. Integrates with the GPU event system (GAP 6) via CPU readback callbacks. Each collision event provides: position, velocity (impact direction), and event type. The spawner creates decal descriptors that the game's decal system can render (projected quads aligned to surface normal). Usage: const spawner = createDecalSpawner({ maxDecals: 200 }); // Register with event system: onParticleEvent(world.eventSystem, (events) = { feedCollisionEvents(spawner, events); }); // Each frame: const decals = getActiveDecals(spawner); // Render decals with your decal system Functions Create a decal spawner with a fixed size ring buffer pool. Parameters: (Object) — No description in source JSDoc. (number) — Maximum active decals (ring buffer, default 200) (number) — How long decals persist in seconds (default 10) (number) — Default decal world size (default 1.0) (number) — Minimum impact speed to spawn a decal (default 2.0) (number) — Seconds before death to start fading (default 2.0) (Function) — Callback when a decal is spawned: (decal) = void Feed collision events from GPU event readback into the decal spawner. Events are expected to be Float32Array with 8 floats per event: [posX, posY, posZ, velX, velY, velZ, eventType, particleIndex] Parameters: (Object) — Decal spawner (Float32Array) — Raw event data from GPU readback (number) — Number of events in the buffer (Object) — { color, sizeScale, eventTypeMask } Update decal ages, fade, and expire old decals. Parameters: (Object) — No description in source JSDoc. (number) —


— { color, sizeScale, eventTypeMask } Update decal ages, fade, and expire old decals. Parameters: (Object) — No description in source JSDoc. (number) — Delta time in seconds Get all active decals as an array of descriptors. Parameters: (Object) — No description in source JSDoc. Returns: Active decal descriptors Get active decal count. Clear all decals. Destroy the spawner. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createForcePointBuffer(device, maxPoints = MAXFORCEPOINTS)

calculateDissolve(startTime, duration, direction = 'in')

createTrailBuffer(device, maxParticles, historyLength = 8)

generateParticleAtlas(device, size = 512, tilesPerRow = 4)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create force point buffer for attractors/repellers Each force point: [x, y, z, strength] where negative = repel Update force points in the buffer Calculate dissolve factor for fade in/out Process sub emitter spawning from dead particles This CPU fallback scans all slots and has 1 2 frame latency from GPU readback. Create trail history buffer Stores N previous positions per particle for trail rendering Generate a procedural particle texture atlas Constants — Sub emitter configuration — Particle texture atlas configuration Re exports , , , , , , , , <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


initEMBindGroups(system, device, positionBuffer, velocityBuffer, gridBuffers, chargeBuffer, thermalBuffer)

executeElectromagnetic(system, device, particleCount, dt)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleElectromagnetic.js Electromagnetic Forces (GAP 35) GPU compute: Coulomb electrostatic + Lorentz magnetic force. F coulomb = k · q₁·q₂ / r² (along r) F lorentz = q · (v × B) (perpendicular to v and B) Per particle charge from element table (GAP 33) charge buffer. Optional: sample E/H fields from FDTDSolver.js if attached. Uses neighbor grid (GAP 25) for O(N) spatial queries. Debye shielding at high density to prevent runaway forces. Usage: const em = createElectromagneticSystem(device, maxParticles); initEMBindGroups(em, device, positionBuffer, velocityBuffer, gridBuffers, chargeBuffer); setExternalField(em, { Ex, Ey, Ez, Bx, By, Bz }); executeElectromagnetic(em, device, particleCount, dt); Functions Create the electromagnetic system. Initialize bind groups. Set external E and B fields. Execute the electromagnetic compute pass. Destroy. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics


collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


setRegistryTrace(enabled, throttleMs = 500)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleElementRegistry.js Unified Element Registry Bridges the two previously disconnected element systems: Particle ELEMENTS (fire, water, magic, smoke) from ParticleEmitterSystem.js Spell SPELL ELEMENTS (fire, ice, lightning, arcane, nature, dark, holy) from SpellGenerator.js Each unified element defines particle properties (color, materialIndex, temperature, physics modifiers), spell properties (spellColors, effects, damageType), and combination rules (from SpellElementMixer). Also provides bridge functions: elementMixToEmitterConfig(elements[]) → full emitter config derived from mix getElementCombination(a, b) → combination result Functions Enable or disable element registry trace logging. When enabled, logs every element mix derivation with full pipeline details. Parameters: (boolean) — No description in source JSDoc. (number) — =500] Minimum ms between log messages (prevents spam) Get a registry element by ID. Handles backward compat aliases (e.g., "magic" → "arcane"). Falls back to REACTION PRODUCTS for byproduct IDs (e.g., "smoke"). Parameters: (string) — No description in source JSDoc. Check if an element ID is a primary element (user selectable) vs reaction product. Parameters: (string) — No description in source JSDoc. Get all registry elements as an array. Get element IDs grouped by category. Returns: } Look up the combination result for two elements. Parameters: (string) — No description in source JSDoc. (string) — No description in source JSDoc. Returns: Combination data or null if no predefined combo Get all combinations involving a specific element. Parameters: (string) — No description in source JSDoc. Returns: } Given an array of active element layers [{id,


all combinations involving a specific element. Parameters: (string) — No description in source JSDoc. Returns: } Given an array of active element layers [{id, power, enabled}], derive a complete emitter property set: color, colorEnd, temperature, materialIndex, gravityMod, and combination info. This replaces the separate deriveColorFromElements + deriveTemperatureFromElements + deriveMaterialIndexFromElements calls with one unified function. Returns: Derived emitter properties Convert meta slider values (Intensity 0 1, Spread 0 1, Lifetime 0 1) into concrete emitter physics parameters. Used by Simple Mode to provide easy controls. Returns: Physics overrides Convert an active element mix into spell generator parameters. Used by the "Create Spell From This" button. Returns: } Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


setParticleElements(system, device, startIndex, count, atomicNumber)

setParticleCharges(system, device, startIndex, count, charge)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleElementTable.js Element Property System / Periodic Table (GAP 33) Data foundation for universal matter simulation. Every other physics system (Lennard Jones, Coulomb, SPH, Chemistry) reads element properties from here. Provides: Full periodic table data for 118 elements Per particle element buffer (GPU storage, u32 per particle) Element lookup by atomic number or symbol Common molecule/compound presets LJ parameters (epsilon, sigma) per element Integration with existing thermal material system Usage: const table = createElementTable(device, maxParticles); setParticleElement(table, device, particleIndex, ELEMENTS.Fe); const iron = getElement(26); // by atomic number const gold = getElementBySymbol('Au'); Functions Get element by atomic number (1 118). Parameters: (number) — No description in source JSDoc. Get element by symbol ('H', 'Fe', 'Au', etc.). Parameters: (string) — No description in source JSDoc. Get all elements. Compute Lennard Jones cross interaction parameters using Lorentz Berthelot rules. Parameters: (number) — Atomic number of element 1 (number) — Atomic number of element 2 Returns: } Create the element table system with per particle element buffer. Parameters: (GPUDevice) — No description in source JSDoc. (number) — No description in source JSDoc. Set element type for a range of particles. Parameters: (Object) — No description in source JSDoc. (GPUDevice) — No description in source JSDoc. (number) — No description in source JSDoc. (number) — No description in source JSDoc. (number) — (1 118) Set charge for a range of particles (overrides element default). Destroy the element table system. Constants — Quick access: ELEMENTS.H = 1, ELEMENTS.Fe = 26, etc. —


for a range of particles (overrides element default). Destroy the element table system. Constants — Quick access: ELEMENTS.H = 1, ELEMENTS.Fe = 26, etc. — Common molecule presets — arrays of { element, count, charge }. — WGSL struct and accessor for element LUT. Bind elementLUT as storage buffer, elementTypes and charges as storage buffers. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


evaluateEmitterLOD(lod, cameraPos, emitterPos, dt = 1/60)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleEmitterLOD.js Emitter Level LOD System (GAP 19) Distance/screen size based LOD for particle emitters. Unlike per particle quality fade, this operates at the EMITTER level: Reduce spawn rate by LOD tier Disable expensive features (collision, turbulence) at distance Switch renderer (billboard → point → cull) by distance Scale particle lifetime to reduce total particle count Matches Niagara scalability / PopcornFX LOD layers. Usage: const lod = createEmitterLOD({ tiers: [...] }); // Each frame: const tier = evaluateEmitterLOD(lod, cameraPos, emitterPos); // Use tier.spawnRateScale, tier.features, etc. to drive emitter config Functions Create an emitter LOD controller. Parameters: (Object) — No description in source JSDoc. (Array) — Array of LOD tier definitions (sorted by maxDistance) (number) — Distance hysteresis to prevent LOD flicker (default 5.0) (number) — Blend speed between tiers (default 3.0, units/sec) Evaluate LOD tier for an emitter based on camera distance. Returns the active tier config with interpolated values. Parameters: (Object) — LOD controller (number[] Float32Array) — Camera position [x, y, z] (number[] Float32Array) — Emitter world position [x, y, z] (number) — Delta time for smooth transitions Returns: Active LOD tier with potentially interpolated values Evaluate LOD by screen space size instead of distance. Useful for effects that vary in world scale. Parameters: (Object) — LOD controller (number) — Approximate screen space diameter in pixels (number[]) — Pixel thresholds per tier [ultra, high, medium, low] Get the current LOD tier without re evaluation. Force a specific LOD tier. Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration


medium, low] Get the current LOD tier without re evaluation. Force a specific LOD tier. Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


buildEffectKeyFromElements(elementPower, options = {})

computeVisualPower(elementPower, options = {})

createEmittersForEffect(effectId, options = {})

stepEmitters(emitters, particleWorld, dt, options = {})

ageAndCullParticles(particles, hiddenDuration, options = {})

buildColliderBuffer(particleWorld, entities, options = {})

buildFluidSources(emitters, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Resolve a substance string to { atomicNumber, temperature, charge, element }. Accepts element symbols ("Fe"), compound keys ("H2O"), preset names ("fire"), or null. Parameters: (string null) — No description in source JSDoc. Returns: null} Derive the state of matter from temperature and element melt/boil points. Parameters: (number) — Kelvin (Object null) — Element data from getElement() Returns: } Derive which physics systems an emitter needs based on substance + temperature. Returns a physics profile object. Parameters: (string null) — Substance key or null for legacy (number) — Override the preset temperature Returns: Physics profile Derive color from element layers (weighted blend) Derive materialIndex from element layers (picks highest power element's material) Get available states of matter Get available elements Get all presets grouped by category for UI consumption. Returns: } } Apply a preset to an emitter config object, mutating it in place. Sets substance, temperature, charge, emitter type, elements, and physics. Parameters: (Object) — Emitter config to mutate (string) — Key from EMITTER PRESETS Returns: True if preset was applied Get available emitter type IDs. Get emitter type preset by ID. ============================================================================ CREATE PARTICLE EMITTER ============================================================================ Creates an emitter instance from a preset type. The emitter controls all aspects of its particles: visual appearance, physics, and timing. Parameters: (Object) — Emitter configuration (string) —


preset type. The emitter controls all aspects of its particles: visual appearance, physics, and timing. Parameters: (Object) — Emitter configuration (string) — Preset type ID: "fire", "smoke", "sparks", (Array<number ) — [x, y, z] spawn position in world space (Array<number ) — Override preset color [r, g, b] (0 1 each) (number) — Override preset particle size (number) — Override preset emission rate (particles/sec) (boolean) — If true, emitter runs forever (default: true) Returns: Emitter instance with all properties needed for simulation Step all emitters and emit particles into the particle world. Returns the number of new particles emitted. Update particle counts by scanning for dead particles. Adds dead slots to freeSlots array and updates live/dead counts. Call this periodically (e.g., every 0.5s) to refresh counts. Parameters: (Object) — Particle state with slotInfo, freeSlots, etc. (number) — Current time in seconds Returns: { liveCount, deadCount, freeSlots } Age all particles by a given duration and cull those that died. Call this when resuming from hidden/minimized to skip dead particles. Parameters: (Object) — Particle state with positions, slotInfo, etc. (number) — How long the tab was hidden (seconds) (Object) — { logger } Returns: Number of particles culled Initialize slot tracking for a particle system. Call once after creating particles state. Build AABB collider buffer from ECS entities for particle collisions. Returns the number of colliders written. Build fluid sources from emitters for density splatting. Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics


provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them befo


createEulerianFluidSolver(device, config = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleEulerianFluid.js Self Contained Eulerian Fluid Solver (GAP 32) GPU grid based 3D fluid simulation using the Stable Fluids algorithm: 1. Advect velocity field (semi Lagrangian) 2. Apply external forces (buoyancy, source injection) 3. Compute divergence 4. Pressure solve (Jacobi iteration) 5. Subtract pressure gradient (make divergence free) 6. Advect density/temperature fields Particles can sample this velocity field via the existing fluidVelocity binding in ParticleSimWorld (attachFluidWorld). Matches Niagara Fluids Grid3D Gas simulation. Usage: const fluid = createEulerianFluidSolver(device, { gridSize: [32, 32, 32] }); addFluidSource(fluid, { position: [0, 0, 0], density: 1, temperature: 500 }); // Each frame: stepEulerianFluid(fluid, device, dt); // Connect to particles: attachFluidWorld(particleWorld, fluid, worldMin, worldMax); Functions Create a self contained Eulerian fluid solver. Parameters: (GPUDevice) — No description in source JSDoc. (Object) — No description in source JSDoc. (number[]) — [x, y, z] grid dimensions (default [32, 32, 32]) (number[]) — World space origin (default [ 5, 1, 5]) (number[]) — World space extent (default [5, 9, 5]) (number) — Velocity/density decay (default 0.995) (number) — Density weight for buoyancy (default 0.1) (number) — Temperature weight for buoyancy (default 0.3) (number) — Pressure solver iterations (default 20) Build bind groups (call once after creation). Add a fluid source (emitter of density/temperature/velocity). Parameters: (Object) — No description in source JSDoc. (Object) — { position, radius, density, temperature, velocity } Step the fluid simulation. Destroy the solver. <! HUMAN NOTES Notes & Examples Physics


JSDoc. (Object) — { position, radius, density, temperature, velocity } Step the fluid simulation. Destroy the solver. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createEventSpawnSystem(device, options = {})

setEventSpawnConfig(system, config = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleEventSpawn.js GPU driven sub emitter spawning from particle events Exceeds Niagara parity: Niagara events are CPU only, this is fully GPU. Zero frame latency — sub particles appear the same frame as the trigger event. Pipeline: 1. Main sim shader appends events to eventBuffer (death, collision, kill zone) 2. IndirectDispatch builds freeList of dead particle slot indices 3. THIS SHADER reads events + consumes free slots + writes new particles Each workgroup handles one event. Threads within the workgroup spawn sub particles. Free slots are consumed atomically from the free list (no CPU involvement). Functions Create the GPU event spawn system Parameters: (GPUDevice) — No description in source JSDoc. (Object) — No description in source JSDoc. Initialize bind groups for the event spawn system Parameters: (Object) — Event spawn system (Object) — Particle world (for event buffer + particle buffers) Update sub emitter spawn configuration Parameters: (Object) — No description in source JSDoc. (Object) — No description in source JSDoc. Execute the event spawn compute pass Call AFTER stepParticleSimWorld (events generated) and AFTER executeIndirectScan (free list built) Parameters: (GPUCommandEncoder) — No description in source JSDoc. (Object) — No description in source JSDoc. (Object) — Particle world (for event count) Destroy event spawn system <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies


mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


initParticleEventSystem(world, options = {})

registerEventHandler(system, config = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleEventSystem.js GPU Particle Event System (exceeds Niagara parity) Niagara events are CPU only. This system is fully GPU driven with zero frame latency. Architecture: 1. Main sim shader appends events to eventBuffer (death, collision, kill zone) 2. IndirectDispatch builds freeList of dead particle slot indices 3. EventSpawn compute shader reads events + consumes free slots + writes new particles 4. (Optional) CPU readback for gameplay callbacks (sound, damage, etc.) Usage: const evtSys = initParticleEventSystem(world); registerEventHandler(evtSys, { event: 'death', subCount: 4, speed: 2 }); // In render loop (after stepParticleSimWorld + executeIndirectScan): stepEventSystem(evtSys, world); // Optional async readback for gameplay: const events = await readbackEvents(evtSys); Functions Initialize the GPU particle event system on a particle world. Call after createParticleSimWorld + initAllAdvancedSystems (needs indirectSystem.freeList). Parameters: (Object) — Particle world with eventBuffer, eventCounterBuffer, indirectSystem (Object) — { enabled: true } Returns: Event system instance Register/update the sub emitter event handler configuration. Parameters: (Object) — Event system (Object) — Sub emitter configuration: Register a CPU callback for a specific event type (called after readback) Parameters: (Object) — No description in source JSDoc. (number) — EVENT DEATH, EVENT GROUND COLLISION, etc. (Function) — (event) = void, where event = { position, velocity, temperature, type } Remove all callbacks for an event type Step the event system: execute GPU event spawn. Call AFTER stepParticleSimWorld + executeIndirectScan. Parameters: (Object) — Event system Async readback of


Step the event system: execute GPU event spawn. Call AFTER stepParticleSimWorld + executeIndirectScan. Parameters: (Object) — Event system Async readback of particle events from GPU for gameplay callbacks. Returns array of events. Tolerates 1 2 frame latency. Parameters: (Object) — No description in source JSDoc. Returns: Array of { position: [x,y,z], velocity: [x,y,z], temperature, type } Get the last readback events (non async, returns cached result) Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createFmmSystem(device, maxParticles, options = {})

initFmmBindGroups(system, device, positionBuffer, velocityBuffer, metaBuffer, thermalBuffer,)

executeFmm(system, device, particleCount, dt, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Uniform octree Fast Multipole Method for open boundary gravitational forces. The GPU path is deliberately self contained and opt in. It performs the full FMM sequence P2M M2M M2L L2L L2P + P2P. The first implementation uses monopole source expansions and first order Cartesian local expansions; the direct solver remains the accuracy oracle and small N fallback. Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


initFlockingBindGroups(system, device, positionBuffer, velocityBuffer, gridBuffers)

executeFlocking(system, device, particleCount, dt)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleFlocking.js GPU Flocking / Boids System (GAP 27) Dedicated GPU compute shader implementing classic boid rules: 1. Separation — steer away from nearby neighbors 2. Alignment — match velocity direction of nearby neighbors 3. Cohesion — steer toward center of mass of nearby neighbors 4. Goal seeking — steer toward target position(s) 5. Obstacle avoidance — steer away from repulsion points 6. Speed regulation — maintain target speed range Uses the NeighborGrid (GAP 25) for O(N) spatial queries instead of O(N²). Each force has independent radius + weight for fine tuned behavior. Matches PopcornFX CParticleEvolver Flocking. Usage: const flock = createFlockingSystem(device, maxParticles); initFlockingBindGroups(flock, device, positionBuffer, velocityBuffer, gridBuffers); setFlockingParams(flock, { separationWeight: 1.5, alignmentWeight: 1.0, ... }); // Each frame (after neighbor grid is built): executeFlocking(flock, device, particleCount, dt); Functions Create the flocking system. Parameters: (GPUDevice) — No description in source JSDoc. (number) — No description in source JSDoc. Initialize bind groups. Requires neighbor grid buffers. Update flocking parameters. Execute the flocking compute pass. Destroy the system. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD)


Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


spawnParticleEmitterEntity(world, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createIndirectDispatchSystem(device, maxParticles, workgroupSize = 256)

initIndirectDispatchBindGroups(system, device, positionsBuffer, velocitiesBuffer)

executeIndirectScan(system, device, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ParticleIndirectDispatch.js GPU driven indirect draw + dispatch Replaces CPU side particle count tracking for rendering and compute dispatch. A small "scan alive" compute pass runs once per frame, atomically counting alive particles and finding the highest alive slot. A "finalize" micro pass writes the results into draw indirect and dispatch indirect buffers. Benefits: Eliminates CPU→GPU sync for particle counts drawIndirect uses GPU computed instance count dispatchWorkgroupsIndirect uses GPU computed workgroup count Prepares infrastructure for full alive list compaction (Phase 3) Ref: Wicked Engine GPU particle architecture, UE5 Niagara indirect dispatch Functions Create the indirect dispatch system. Parameters: (GPUDevice) — No description in source JSDoc. (number) — Maximum particle count (number) — Workgroup size for compute shaders (default 256) Initialize bind groups. Call after position/velocity buffers are available. Execute the scan + finalize passes. Run ONCE per frame, before any other particle work. After this call, drawIndirectBuffer and dispatchIndirectBuffer contain GPU computed values. Update maxSlots (e.g., when particle capacity changes). Destroy indirect dispatch system resources. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units :


physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine