createUniversalCollider

createUniversalCollider(world, meshType, geometryFn, halfExtents = [0.5, 0.5, 0.5], material = null, density = 1.0)


sim/physics/FragmentPhysics

Summary: FragmentPhysics.js - Physics Integration for Mesh Fragments Handles physics simulation for fracture fragments using PhysX. Features: - Convex hull generation for rigid body collision - Mass distribution based on volume/material - Structural connection graph for progressive collapse - Fragment → particle conversion for small pieces


StructuralConnection

Summary: Represents a connection between two fragments


PhysicsFragment

Summary: A mesh fragment with physics properties


FragmentManager

Summary: Manages all physics fragments in the world


meshFragmentToIndexedMesh

meshFragmentToIndexedMesh(meshFragment, options = null)


sim/physics/GPUArticulationSolver

Summary: GPUArticulationSolver.js - WebGPU Articulation Physics GPU-based articulation solver using vGPU compute shaders. Replaces PhysX WASM articulation with pure WebGPU implementation. Based on: - Stable Cosserat Rods (SIGGRAPH 2025) - Split position/rotation optimization - Direct PBD Solver for Stiff Rods (Bender et al. 2018) - XPBD compliance for stable stiffness Key Features: - Parallel Jacobi solver for position constraints - Quaternion orientation updates for twist - Graph coloring for dependency-free parallel solving - Warm starting for faster convergence


sim/physics/GPUClothSolver

Summary: GPU Cloth Physics Solver Position-based dynamics (PBD) solver running entirely on GPU Handles cloth, ropes, soft bodies with collision detection **Small Substeps Approach (Miles Macklin, NVIDIA 2019):** Uses 8 substeps with 1 iteration each for better stability than 1 substep with 8 iterations. This is especially important for stiff constraints like ropes and tightly-woven cloth. **OGC Contact Model (Chen et al., SIGGRAPH 2025):** Uses Offset Geometric Contact for penetration-free simulation. Barrier energy prevents penetration before it occurs, with orthogonal contact forces along face normals.


Summary: Default substeps (small substeps approach)


Summary: Default iterations per substep


sim/physics/GPUSpatialHash

Summary: CPU-based spatial hash grid for physics broad-phase


GPUSpatialHashGrid

Summary: GPU-accelerated spatial hash grid using WebGPU compute shaders


Summary: Calculate Morton code for 3D position


hashCell

Summary: Simple hash function for cell coordinates


createSpatialHashFromVGPU

async createSpatialHashFromVGPU(vgpu, options = {})

Summary: Factory function to create GPUSpatialHashGrid from VirtualGPU


sim/physics/MLSMPMSolver

Summary: MLSMPMSolver.js - Moving Least Squares Material Point Method Hybrid Lagrangian-Eulerian simulation for: - Soft body deformation (jelly, flesh) - Fracturing materials (snow, sand) - Fluid-solid interaction - Large deformation scenarios Algorithm Overview: 1. P2G (Particle to Grid): Transfer mass/momentum using quadratic B-splines 2. Grid Update: Apply forces, boundaries, compute velocities 3. G2P (Grid to Particle): Gather velocity, update deformation gradient 4. Advection: Move particles Key Features: - Fixed-point atomics for P2G scatter (WebGPU has no f32 atomics) - SoA (Structure of Arrays) for GPU coalescing - Multiple constitutive models (Neo-Hookean, Fixed Corotated, Snow) Performance Target: 100k particles < 10ms


quadraticBSpline

Summary: Quadratic B-spline weight


quadraticBSplineGrad

Summary: Quadratic B-spline derivative


computeWeight

computeWeight(px, py, pz, gx, gy, gz, cellSize = 1.0)

Summary: Compute 3D weight and gradient for a particle-grid pair


Summary: Grid cell size (1 unit typical)


Summary: Default grid dimensions


Summary: Quadratic B-spline support radius (3 cells)


ConstitutiveModel

Summary: Constitutive model types


MaterialPresets

Summary: Material presets


sim/physics/MeshCutter

Summary: MeshCutter.js - Mesh Cutting and Fragment Generation System Cuts meshes along Voronoi cell boundaries to create realistic fragments. Uses plane-triangle intersection to split geometry. Features: - Triangle classification (front/back/spanning) - Edge-plane intersection computation - Cap geometry generation for cut faces - UV coordinate preservation - Convex hull generation for PhysX


sim/physics/MeshDecimation

Summary: MeshDecimation.js - Mesh Simplification for Debris Reduces triangle count for debris meshes to maintain performance. Two algorithms available: 1. Grid-Based (Fast): O(n) - Good for realtime debris - Snap vertices to grid - Merge coincident vertices - Remove degenerate triangles 2. QEM (Quality): O(n log n) - Better for LOD generation - Quadric Error Metrics - Edge collapse with priority queue - Preserves shape better Performance Targets: - Grid: 10k verts → 500 verts in <1ms - QEM: 10k verts → 500 verts in <50ms


decimateGrid

decimateGrid(vertices, indices, gridSize = DEFAULT_GRID_SIZE)

Summary: Fast grid-based mesh decimation


decimateQEM

decimateQEM(vertices, indices, targetRatio = DEFAULT_TARGET_RATIO, maxIterations = Infinity, options = null)

Summary: QEM-based mesh decimation


Summary: Default grid cell size for grid-based decimation


Summary: Default target reduction ratio


Summary: Maximum QEM iterations per frame (for realtime)


sim/physics/MeshParticles

Summary: Single debris chunk with mesh, physics, and rendering state


Summary: Maximum active debris particles


Summary: LOD distance thresholds


Summary: LOD decimation ratios


Summary: Minimum voxels to create debris (smaller clusters become particles)


Summary: Maximum voxels per debris chunk


Summary: Debris lifetime in seconds


DebrisState

Summary: Debris states


sim/physics/OGCContact

Summary: OGCContact.js - Offset Geometric Contact Model Implementation of the SIGGRAPH 2025 paper: "Offset Geometric Contact for Real-Time Simulation" Chen et al., 2025 Key features: - Guaranteed penetration-free simulation - Orthogonal contact forces (along face normals, not radial) - Large contact radius support (2-5mm without artifacts) - No CCD required - uses conservative displacement bounds - GPU-efficient parallel local operations The offset geometry approach inflates primitives by a contact radius, computes distance to the offset surface, and applies smooth barrier energy that activates before penetration occurs.


OGCContactManager

Summary: Manages OGC contacts for a simulation


barrierEnergy

Summary: OGC Barrier energy function g(d) = d²(2r - d)² Smooth C1 continuous, zero at d=0 and d=2r Maximum at d=r


barrierForce

Summary: Derivative of barrier energy: g'(d) = 2d(2r-d)(2r-2d) Used for force computation


normalizedBarrierEnergy

Summary: Normalized barrier energy for stability Scales to [0, 1] range with maximum at d=r


conservativeDisplacementBound

Summary: Compute conservative displacement bound for a vertex This is the maximum safe movement before barrier check is needed


distanceToOffsetSphere

distanceToOffsetSphere(p, center, radius, r)

Summary: Distance from point to offset sphere (sphere with radius inflated by r)


distanceToOffsetPlane

distanceToOffsetPlane(p, planePoint, planeNormal, r)

Summary: Distance from point to offset plane (plane pushed by r along normal)


distanceToOffsetCapsule

distanceToOffsetCapsule(p, a, b, radius, r)

Summary: Distance from point to offset capsule


distanceToOffsetBox

distanceToOffsetBox(p, center, halfExtents, rotation, r)

Summary: Distance from point to offset box (OBB with offset shell) Handles rotated boxes by transforming into local space.


evaluateAnalyticSDF

evaluateAnalyticSDF(shape, params, lx, ly, lz)

Summary: Evaluate an analytic SDF in local space (no transform — caller handles that).


distanceToOffsetEdge

Summary: Distance from point to offset edge (line segment with offset radius)


distanceToOffsetTriangle

distanceToOffsetTriangle(p, v0, v1, v2, r)

Summary: Distance from point to offset triangle (triangle with offset shell) Uses the face normal for orthogonal contact


applyOGCForce

applyOGCForce(particle, distance, normal, contactRadius, stiffness, dt)

Summary: Apply OGC barrier force to a particle


applyOGCPositionCorrection

applyOGCPositionCorrection(particle, distance, normal, contactRadius, compliance, dt)

Summary: Apply OGC position correction (for PBD-style solvers)


Summary: Default contact radius (meters) - paper recommends 2-5mm for cloth


Summary: Barrier energy activation distance (multiple of contact radius)


Summary: Minimum distance to prevent numerical issues


Summary: Fixed-point scale for GPU atomics


Summary: WGSL snippet for OGC barrier functions


Summary: WGSL snippet for offset geometry distance functions


Summary: WGSL snippet for OGC contact solving


Summary: Complete WGSL module for OGC


sim/physics/PBDRagdoll

Summary: Bone identifiers


RagdollBone

Summary: Bone identifiers


JointType

Summary: Joint types


RagdollState

Summary: Ragdoll states


Summary: Default humanoid measurements (meters)


Summary: Joint angle limits (radians)


sim/physics/PBDSolver

Summary: PBDSolver.js - Position-Based Dynamics Solver Implements XPBD (Extended Position-Based Dynamics) for: - Rope/cable physics (line segments) - Soft body deformation - Ragdoll skeletons - Cloth simulation Key Algorithms: - Verlet integration (position-based) - Gauss-Seidel constraint projection - Graph coloring for GPU parallelization - XPBD compliance for stable stiffness **Small Substeps Approach (Miles Macklin, NVIDIA 2019):** "n small timesteps with 1 iteration each > 1 large timestep with n iterations" This provides better stability for stiff systems (ropes, cloth). We use 8 substeps with 1 iteration each by default (equivalent to but more stable than 1 substep with 8 iterations). **OGC Contact Model (Chen et al., SIGGRAPH 2025):** Uses Offset Geometric Contact for penetration-free collision. Barrier energy prevents penetration before it occurs. Performance Targets: - 1000 particles + 3000 constraints: <5ms - 8 substeps, 1 iteration per substep (small substeps approach)


PBDParticle

Summary: PBD Particle with position, velocity, and inverse mass


PBDConstraint

Summary: Base constraint class


DistanceConstraint

class DistanceConstraint extends PBDConstraint

Summary: Distance constraint - maintains rest length between two particles


AngleConstraint

class AngleConstraint extends PBDConstraint

Summary: Angle constraint - limits angle between three particles


AttachmentConstraint

class AttachmentConstraint extends PBDConstraint

Summary: Attachment constraint - pins particle to world position Simple and stable: directly moves particle toward target


BendingConstraint

class BendingConstraint extends PBDConstraint

Summary: Bending constraint - maintains angle between 3 particles - UNTESTED Used for hair, grass, stiff ropes


SpringConstraint

class SpringConstraint extends PBDConstraint

Summary: Spring constraint - UNTESTED Unlike distance constraint, springs can compress AND extend (Hooke's law)


CohesionConstraint

class CohesionConstraint extends PBDConstraint

Summary: Cohesion constraint - UNTESTED Particles attract each other within a radius (like water droplets)


LongRangeAttachmentConstraint

class LongRangeAttachmentConstraint extends PBDConstraint

Summary: Long Range Attachment (LRA) Constraint Creates distance constraints from fixed/anchor particles to all particles in a rope. This dramatically improves convergence for long ropes (100+ segments). Reference: Kim et al. 2012 "Long Range Attachments - A Method to Simulate Inextensible Clothing in Computer Games" Reference: Müller 2017 "Long Range Constraints for Rigid Body Simulations" Key idea: Instead of only having adjacent distance constraints, we create constraints from the anchor to every Nth particle along the rope. This allows the solver to propagate length corrections globally in fewer iterations.


VolumeConstraint

class VolumeConstraint extends PBDConstraint

Summary: Volume constraint - preserves volume of a tetrahedron (4 particles) C = V - V0 = 0, where V = (1/6) * (p1-p0) · ((p2-p0) × (p3-p0))


ShapeMatchingConstraint

class ShapeMatchingConstraint extends PBDConstraint

Summary: Shape Matching constraint - restores N particles to their original shape Based on "Meshless Deformations Based on Shape Matching" (Müller 2005)


PressureConstraint

class PressureConstraint extends PBDConstraint

Summary: Pressure constraint - internal pressure for closed meshes (balloons) Works with N particles forming a closed surface


DensityConstraint

class DensityConstraint extends PBDConstraint

Summary: SPH Density constraint - maintains constant density (fluids) Based on "Position Based Fluids" (Macklin & Müller 2013)


colorConstraints

Summary: Greedy graph coloring for constraint parallelization Constraints with same color can be solved in parallel


groupByColor

Summary: Group constraints by color for batched dispatch


Summary: Default solver iterations per substep (small substeps: use 1-2)


Summary: Default substeps per frame (small substeps: use 8-16 for stability)


ConstraintType

Summary: Constraint types


ParticleFlags

Summary: Particle flags


sim/physics/PhysXArticulations

Summary: PhysXArticulations.js - PhysX Articulation Support Articulations are optimized for chains of connected bodies like: - Ropes and cables - Ragdolls - Robotic arms - Vehicles (suspensions) Per NVIDIA PhysX Best Practices: "Articulations are much better at simulating articulated objects. They can be used to model better ropes, bridges, vehicles, or ragdolls out-of-the-box, without the need for workarounds." Articulations provide: - Better stability than joint chains - Reduced jitter - More accurate constraint solving - Built-in tendon support for muscle simulation


createArticulation

Summary: Create a reduced coordinate articulation (PhysX 5.x)


createRootLink

createRootLink(articulation, options = {})

Summary: Create the root link of an articulation


createChildLink

createChildLink(articulation, parentLink, options = {})

Summary: Create a child link attached to a parent link


addArticulationToScene

Summary: Add articulation to scene (must be called after all links are created)


createRope

createRope(world, startPos, endPos, segments = 10, options = {})

Summary: Create a rope using articulations Per NVIDIA: "Use spheres instead of capsules. A rope made of spheres will be more stable."


getArticulationLinkTransforms

Summary: Update articulation link positions from simulation


destroyArticulation

Summary: Destroy an articulation and clean up resources


sim/physics/PhysXJoints

Summary: PhysX Joint Creation API Exposes D6, revolute, distance, and spherical joints for articulated bodies


createD6Joint(world, bodyA, bodyB, options = {})

Summary: Create a D6 joint (6 degrees of freedom - most flexible joint type)


createRevoluteJoint

createRevoluteJoint(world, bodyA, bodyB, options = {})

Summary: Create a revolute joint (hinge joint - 1 rotational DOF)


createSphericalJoint

createSphericalJoint(world, bodyA, bodyB, options = {})

Summary: Create a spherical joint (ball-and-socket - 3 rotational DOF)


createDistanceJoint

createDistanceJoint(world, bodyA, bodyB, options = {})

Summary: Create a distance joint (maintains distance between two points)


sim/physics/PhysXMeshCooking

Summary: Local register helpers (avoid circular import with PhysXPhysicsWorld)


cookAndRegisterTriangleMeshForWorld

cookAndRegisterTriangleMeshForWorld(world, meshId, positions, indices)


sim/physics/PhysXModule


sim/physics/PhysXPhysicsWorld

Summary: Move a kinematic body to a new pose (PhysX setKinematicTarget — the solver sweeps it there over the next step, pushing dynamic bodies out of the way instead of teleporting through them). Used for script-driven obstacles (e.g. AI traffic cars that dynamic bodies must collide with).


setKinematicPose

setKinematicPose(world, handle, position, rotation = [0, 0, 0, 1])


updateBodyFilterData

Summary: Update a body's collision filter data based on EntityFlags Call this when EntityFlags.collisionLayer, collisionMask, or collisionMode changes


raycastWorld

raycastWorld(world, origin, direction, maxDistance)


sim/physics/PhysXVehicle

Summary: Compatibility entry point. Implementation is split by vehicle subsystem in ./vehicle so existing engine and playground import paths remain stable.


sim/physics/PhysicalMaterialPresets

Summary: PhysicalMaterialPresets.js — Real-world material property presets Each preset defines how a shape behaves physically: density for mass, elasticity for springback, hardness for deformation resistance, brittleness for shatter vs bend, and fracture configuration. Used by the PhysicalMaterial ECS component and EditorPhysicalMaterial bridge.


getMaterialPreset

Summary: Get a full material preset by key (returns a shallow copy).


createPhysicalMaterial

createPhysicalMaterial(presetKey, overrides = {})

Summary: Create a PhysicalMaterial component value from a preset key, with optional property overrides.


computeMassFromMaterial

Summary: Compute mass from material density and collider volume.


Summary: All preset keys.


sim/physics/PhysicsSchema

Summary: PhysicsSchema.js - Unified JSON Schema for Physics System Defines consistent data structures for: - Body types (dynamic, kinematic, static) - Collider shapes (box, sphere, capsule, mesh) - Joint types (D6, revolute, spherical, distance) - Collision layers and masks - Material properties (friction, restitution) All physics code should use these schemas for consistency.


getSimModeId

Summary: Get simulation mode ID from name


getSimModeName

Summary: Get simulation mode name from ID


getColliderShapeId

Summary: Get collider shape ID from name


getColliderShapeName

Summary: Get collider shape name from ID


getCollisionMask

Summary: Get collision layer mask from layer names


layersCollide

Summary: Check if two layer masks collide


validatePhysicsBody

Summary: Validate physics body configuration


validateCollider

Summary: Validate collider configuration


validatePhysicsMaterial

Summary: Validate physics material


createDefaultPhysicsBody

Summary: Create default physics body config


createDefaultCollider

Summary: Create default collider config


createDefaultJoint

Summary: Create default joint config


createDefaultPhysicsWorld

Summary: Create default physics world config


getPhysicsMaterial

Summary: Get physics material by name


Summary: Physics simulation modes


Summary: Collider shape types


Summary: Joint types for articulated bodies


Summary: D6 joint axis motion types


Summary: D6 joint axes


Summary: Collision layer definitions (bitmask)


Summary: Physics material schema **Compliant Contacts (PhysX 5.1+):** Set restitution to a NEGATIVE value to enable spring-damper contact model. This provides more stable collision behavior for complex contact configurations. - restitution = -springStiffness (negative enables compliant mode) - damping = damping ratio for the spring - compliantAcceleration = true to use acceleration spring (mass-independent)


Summary: Preset physics materials Note: Negative restitution enables compliant (spring-damper) contacts


Summary: Physics body schema


Summary: Collider schema


Summary: Joint schema


Summary: Physics world configuration


Summary: Standard convex collider mesh IDs


sim/physics/PhysicsWorld


sim/physics/SDFCollision

Summary: SDFCollision.js - Signed Distance Field Collision Detection Based on GPU Gems 3, Chapter 34: "Signed Distance Fields Using Single-Pass GPU Scan" and PhysX 5.x SDF collision geometry. SDFs provide: - Accurate collision for concave shapes without decomposition - Efficient distance queries for soft body interactions - Smooth contact normals for stable simulation - Fast ray/sphere casting The SDF stores the signed distance to the nearest surface at each point: - Negative inside the object - Positive outside the object - Zero on the surface


SDFGrid

Summary: 3D SDF Grid for collision detection


createSDFFromMesh

createSDFFromMesh(vertices, indices, options = {})

Summary: Create SDF collider from mesh using jump flooding algorithm This is a simplified CPU version - GPU version would be faster


SDFPrimitives

Summary: SDF primitive functions


SDFOperations

Summary: SDF combination operations


sim/physics/SeismicSystem

Summary: SeismicSystem.js - Tectonic Simulation and Earthquake Events Simulates geological activity on the planet: - Tectonic fault lines with stress accumulation - Earthquake event triggering when stress exceeds threshold - Seismic wave propagation (P-waves, S-waves, surface waves) - Distance-based attenuation - Character/entity response integration Wave Types: - P-waves (Primary): Compressional, fastest, travels through solids/liquids - S-waves (Secondary): Shear, slower, solids only - Surface waves: Slowest, most destructive, along surface


FaultLine

Summary: Represents a tectonic fault line


SeismicWave

Summary: Propagating seismic wave


Earthquake

Summary: Complete earthquake event with multiple wave types


WaveType

Summary: Wave types


Summary: Wave speeds (m/s, scaled for game)


MagnitudeScale

Summary: Earthquake magnitude scales


Summary: Default seismic parameters


sim/physics/ShockPropagation

Summary: ShockPropagation.js - Shock Propagation for Stable Stacking Based on "Nonconvex Rigid Bodies with Stacking" (Guendelman et al., SIGGRAPH 2003) and NVIDIA PhysX best practices. Problem: Standard iterative solvers struggle with deep stacks of objects. Objects at the bottom don't "know" about the weight above them, causing jitter and instability. Solution: Process contacts in a specific order, propagating forces from the ground upward through the contact graph. This ensures each layer is stable before processing the next. Key Techniques: - Contact graph construction - Topological sorting by "height" from ground - Bottom-up constraint solving - Velocity-level shock propagation


ShockPropagationSolver

Summary: Shock propagation solver for stable stacking


applyShockPropagation

Summary: Integrate shock propagation with existing physics world Call this after broad/narrow phase but before velocity integration


sim/physics/SpatialIntegritySystem

Summary: SpatialIntegritySystem.js - Coordinate Validation & Correction Ensures spatial integrity for planetary-scale worlds: - O(1) position lookup via composite keys - Fast checksum validation for corruption detection - World-tick based temporal tracking - Authority snapshots for rollback/sync - Drift correction for network sync Designed for minimal overhead while providing strong guarantees.


ChunkIntegrityTracker

Summary: Specialized integrity tracking for chunk positions Uses integer coordinates for exact matching


sim/physics/SpeculativeContacts

Summary: SpeculativeContacts.js - Speculative Continuous Collision Detection Based on "Speculative Contacts" (Bullet Physics) and PhysX eSPECULATIVE_CCD. Traditional CCD is expensive as it requires time-of-impact (TOI) calculations. Speculative contacts provide a cheaper alternative: 1. Expand AABBs by velocity * dt to predict where objects will be 2. Generate contacts for all potentially overlapping pairs 3. Add velocity constraints to prevent future penetration Benefits: - Cheaper than sweep-based CCD - Prevents tunneling for most cases - Works well with iterative solvers Limitations: - Can cause "ghost collisions" with thin objects - Not as accurate as full CCD for very fast objects


SpeculativeContactsSolver

Summary: Speculative contacts solver


expandAABBByVelocity

expandAABBByVelocity(aabb, velocity, dt, margin = 0.01)

Summary: Expand AABB by velocity to get speculative bounds


timeOfClosestApproach

timeOfClosestApproach(posA, velA, radiusA, posB, velB, radiusB)

Summary: Calculate time of closest approach between two moving spheres Used for speculative contact timing


enablePhysXSpeculativeCCD

Summary: Enable speculative CCD on a PhysX rigid body This configures the PhysX-specific flags for speculative contacts


sim/physics/StandardColliderMeshes


sim/physics/StructuralIntegrity

Summary: StructuralIntegrity.js - Structural Integrity and Collapse System Implements realistic structural mechanics for destructible buildings: - Iterative relaxation solver for force propagation - Stress accumulation and breaking thresholds - Connectivity analysis with flood-fill from anchors - Chain reaction cascading collapse Based on constraint relaxation similar to Verlet physics but for structural connections rather than particle positions.


StructuralNode

Summary: A node in the structural graph (corresponds to a fragment or chunk)


StructuralEdge

Summary: An edge connecting two structural nodes


StructuralIntegritySolver

Summary: Main structural integrity system


sim/physics/TreePhysics

Summary: TreePhysics.js - Teardown-style Tree Physics System Features: - Trees must spawn on solid ground (validated placement) - Root connection tracking (trees anchored at base) - Structural integrity - cut trees fall realistically - Physics body conversion when disconnected Based on Teardown's structural integrity system where objects fall when disconnected from anchors (ground).


TreeVoxelBody

Summary: Represents a tree's voxel structure for physics


TreePhysicsSystem

Summary: Manages all tree physics in the world


sim/physics/UnifiedDamageSystem

Summary: UnifiedDamageSystem.js - Cross-System Damage Integration Connects all destruction systems so everything affects everything: - Particles damage voxels (erosion, accumulation) - Particles damage meshes (impact fracture) - Mesh debris creates voxel craters - Voxel explosions affect mesh structures Acts as the central hub for damage propagation between systems.


DamageEvent

Summary: Represents a damage event that propagates through systems


UnifiedDamageSystem

Summary: Central damage system that coordinates between all subsystems


Summary: Damage types


sim/physics/VoronoiFracture

Summary: VoronoiFracture.js - GPU-accelerated Voronoi Fracture System Uses Jump Flooding Algorithm (JFA) to compute 3D Voronoi diagrams for realistic mesh fracturing. Seeds are placed based on impact location and fracture patterns. Algorithm: 1. Place seed points (impact-based or pattern-based) 2. Run JFA to compute nearest seed for each voxel 3. Extract cell boundaries as fracture planes 4. Cut mesh along planes to create fragments


Summary: Predefined fracture patterns for different impact types


sim/physics/VoxelMeshCollision

Summary: VoxelMeshCollision.js - Voxel-based Mesh Collision for Particles and Ropes Voxelizes meshes into an occupancy grid with compressed normals for efficient GPU collision detection. This allows particles and ropes to collide with arbitrary mesh geometry beyond simple AABBs. Representation (per voxel, 32 bits total): - Bit 31: Occupancy flag (1 = solid) - Bits 30-21: Normal X (10 bits, signed normalized) - Bits 20-11: Normal Y (10 bits, signed normalized) - Bits 10-1: Normal Z (10 bits, signed normalized) - Bit 0: Reserved Features: - GPU mesh voxelization via compute shader - Compressed normal storage (10-10-10-2 format) - Cascaded/multi-resolution support - GPU collision queries for particles - Cache and reuse voxelized meshes


CascadedVoxelCollider

Summary: CascadedVoxelCollider - Multi-resolution voxel collision with LOD levels Uses multiple grid resolutions for efficient collision: - LOD 0: Fine (128³) - Near particles, high accuracy - LOD 1: Medium (64³) - Mid-range particles - LOD 2: Coarse (32³) - Far particles, fast queries


VoxelCacheManager

Summary: VoxelCacheManager - Persistent cache for voxelized meshes Saves/loads voxelized mesh data to avoid re-voxelization. Uses IndexedDB for persistence.


meshToTriangleBuffer

Summary: Helper: Convert mesh vertices/indices to triangle buffer format


computeMeshBounds

Summary: Helper: Compute mesh AABB


createVoxelMeshCollider

createVoxelMeshCollider(device, options = {})


createCascadedVoxelCollider

createCascadedVoxelCollider(device, options = {})


sim/physics/gpu/GPUBroadphase

Summary: GPUBroadphase.js — GPU Compute Spatial Hash Broadphase Spatial hash broad-phase collision detection on GPU. Computes AABBs from collider shapes + world transforms, inserts into spatial hash grid, finds candidate collision pairs. Based on: - GPU Gems 3 Ch.32: Broad-Phase Collision Detection with CUDA - GPU Gems 3 Ch.29: Uniform grid with 27-neighbor cell queries - Existing GPUSpatialHash.js patterns (morton codes, hash primes) Uses atomicAdd for pair output (modern WebGPU, no multi-pass needed). Collision layer/mask filtering happens during pair generation.


createBroadphase

async createBroadphase(device, worldBuffers, options = {})

Summary: Create and initialize a GPU broadphase.


sim/physics/gpu/GPUCharacterController

Summary: GPUCharacterController.js — Kinematic Character Controller PhysX-style character controller (CCT) for player/NPC movement. Kinematic body that sweeps through the scene, resolves collisions, handles ground detection, slope limits, step climbing, and skin width. Based on: - PhysX PxController: kinematic move with depenetration, auto-step, slope limit - Quake/Source: slide-move along wall normals, stair stepping - Jolt CharacterVirtual: predictive contacts, inner body shape Architecture: - CPU-driven (character movement is inherently sequential per-character) - Uses GPURaycast (CPU fallback) for ground probes and sweep tests - Applies final position to a kinematic body in GPURigidBodyWorld - Supports capsule and box shapes The controller does NOT use GPU compute shaders directly because character movement is latency-sensitive (needs immediate response to input) and typically only a handful of characters exist. CPU is the right choice here.


sim/physics/gpu/GPUConstraintSolver

Summary: GPUConstraintSolver.js — GPU Compute XPBD/TGS Constraint Solver Solves contact constraints and joint constraints on GPU. Uses TGS_Soft approach (Erin Catto, Box2D v3): - Sub-step contact separation update via local-frame anchors - Accumulated impulse clamping (Sequential Impulses) - Warm starting from previous frame's Lagrange multipliers - Relaxation pass to drain bias energy - Coulomb friction with tangent clamping - Restitution via velocity-level bounce Joint constraints use D6 as sole native type (PhysX 5 GPU best practice). Ball, hinge, fixed, distance, prismatic are D6 presets. Parallel solving via graph-colored Gauss-Seidel (Fratarcangeli et al.): - CPU-side graph coloring groups non-conflicting constraints - One GPU dispatch per color group Based on: - XPBD (Macklin 2016): Δλ = -(C + α̃·λ) / (w_a + w_b + α̃) - Small Steps (Macklin 2019): sub-stepping > iteration - Box2D v3 Solver2D: TGS_Soft, relaxation, accumulated impulse clamping - PhysX 5 GPU: D6 joints native, soft constraint compliance


createConstraintSolver

async createConstraintSolver(device, worldBuffers, narrowphaseBuffers, options = {})


sim/physics/gpu/GPUContinuousCollision

Summary: GPUContinuousCollision.js — GPU Speculative CCD (Continuous Collision Detection) Prevents fast-moving objects from tunneling through thin geometry. Uses speculative contacts: expand AABBs by velocity, generate conservative contacts at predicted future positions. Based on: - PhysX CCD: PxPairFlag::eDETECT_CCD_CONTACT, PxRigidBodyFlag::eENABLE_CCD - Bullet Physics: speculative contacts (Erwin Coumans GDC 2013) - Existing engine SpeculativeContacts.js (CPU) — this is the GPU version Architecture: - GPU shader expands AABBs by linear velocity * dt - Broadphase runs on expanded AABBs (catches potential tunneling pairs) - For CCD-flagged bodies, compute time of impact (TOI) via conservative advancement - Clamp body position to TOI * displacement if tunneling detected - Generates speculative contacts at predicted impact point When to enable CCD: - Bullets, projectiles, fast vehicles - Small objects near thin walls - Any body with speed > size/dt (tunneling risk)


createContinuousCollision

async createContinuousCollision(device, worldBuffers, narrowphaseBuffers, options = {})


sim/physics/gpu/GPUConvexHull

Summary: GPUConvexHull.js — CPU-side Quickhull 3D + GPU Buffer Helpers Computes convex hulls from vertex data (runs once at cook time, not per-frame). Produces GPU-compatible hull data for narrowphase collision detection. PhysX 5 GPU limits enforced: - Max 64 vertices per hull - Max 32 vertices per face - Hulls exceeding these limits are simplified Algorithm: Incremental Quickhull 3D - Find initial tetrahedron from extreme points - Iteratively add furthest point from each face - Expand horizon edges, rebuild faces Also builds precomputed support maps for GJK: - For 128 sampled directions, store the support vertex index - Enables O(1) support queries on GPU


computeConvexHull

computeConvexHull(vertices, options = {})

Summary: Compute a 3D convex hull from a set of vertices.


buildSupportMap

buildSupportMap(hull, numDirections = SUPPORT_MAP_DIRECTIONS)

Summary: Build precomputed support map for fast GPU GJK. For each of N uniformly sampled directions, stores the index of the furthest vertex in that direction.


hullToGPUBuffer

hullToGPUBuffer(device, hull, supportMap = null)

Summary: Upload hull data to a GPU buffer for narrowphase use. Layout: [vertexCount(u32), faceCount(u32), pad, pad] + [vertices (vec4)] + [normals (vec4)] + [supportMap (u32)]


hullHalfExtents

Summary: Compute AABB half-extents from hull vertices (for broadphase).


sim/physics/gpu/GPUHeightfield

Summary: GPUHeightfield.js — GPU Terrain Heightfield Collider Heightmap-based terrain collision for GPU physics. Stores a 2D grid of heights, generates contacts against rigid bodies via GPU compute shader. Based on: - PhysX PxHeightField: regular grid, per-sample materials, hole support - Bullet btHeightfieldTerrainShape: bilinear interpolation - Jolt HeightFieldShape: hierarchical BVH for large terrains Features: - Bilinear height interpolation for smooth normals - Per-cell material index (for surface types: grass, rock, mud, etc.) - Hole support (cells with height = NaN are passthrough) - GPU shader: one thread per body, probes heightfield under body AABB - CPU upload of heightmap data (set once or update regions) - Supports terrains up to 1024×1024 (configurable)


createHeightfield

async createHeightfield(device, worldBuffers, narrowphaseBuffers, options = {})


sim/physics/gpu/GPUMeshDeform

Summary: GPUMeshDeform.js — GPU-accelerated vertex displacement for impact dents Fast-path for small impacts: pushes vertices inward within a radius around the impact point, weighted by distance. Runs in <1ms on GPU vs 50-200ms for the full voxelize→SDF→marching cubes CPU pipeline. Also includes a normal recalculation pass (GAP 4). Usage: const deformer = new GPUMeshDeform(device); const result = await deformer.applyDent(positions, indices, { impactPoint: [x, y, z], impactNormal: [nx, ny, nz], radius: 0.3, depth: 0.1, }); // result.positions — Float32Array of deformed positions // result.normals   — Float32Array of recalculated normals


sim/physics/gpu/GPUNarrowphase

Summary: GPUNarrowphase.js — GPU Compute Contact Generation Analytic shape-shape collision tests on GPU compute shaders. Processes candidate pairs from GPUBroadphase, generates contact manifold. Supported shape pairs: - sphere–sphere, sphere–box, sphere–capsule - box–box (SAT, 15 separating axes) - capsule–capsule (closest points on two line segments) - capsule–box (segment vs box faces) - ground plane (infinite y=0, special-cased) Contact manifold uses Persistent Contact Manifold (PCM) approach: - Contacts stored with local-frame anchors for sub-step updating - Feature IDs for warm-start matching across frames - OGC barrier energy for penetration prevention Based on: - PhysX 5 GPU: PCM required for GPU contact gen - PhysX 5: convex hulls capped at 64 verts for GPU compat - Box2D v3 TGS: sub-step contact separation update via local anchors - OGCContact.js: barrier energy WGSL module


createNarrowphase

async createNarrowphase(device, worldBuffers, broadphaseBuffers, options = {})


sim/physics/gpu/GPURaycast

Summary: GPURaycast.js — GPU Compute Parallel Raycast Casts rays against all rigid bodies on the GPU. Each thread tests one body, writes closest hit to output. Reduction pass finds global closest hit across all threads. Result returned via async readback (Promise). Also provides CPU fallback for synchronous raycasting against CPU shadow data (1-frame lag, but instant). Shape-ray tests: - ray-sphere (geometric closest approach) - ray-box (slab method) - ray-capsule (ray-segment closest point + sphere test)


gpuRaycastCPU

gpuRaycastCPU(world, origin, direction, maxDistance = 1000)

Summary: Synchronous CPU raycast against CPU shadow data (1-frame lag). Use when async GPU raycast is too slow or when GPU is busy.


createGPURaycast

async createGPURaycast(device, worldBuffers, options = {})


gpuRaycast

async gpuRaycast(rc, world, origin, direction, maxDistance = 1000)

Summary: GPU raycast (async).


sim/physics/gpu/GPURigidBodyWorld

Summary: GPURigidBodyWorld.js — GPU Compute Rigid Body Physics World Custom WebGPU compute-based rigid body simulation engine. Runs broadphase, narrowphase, constraint solving, and integration entirely on the GPU via WGSL compute shaders. Architecture based on: - TGS_Soft solver (Erin Catto, Box2D v3 Solver2D, Feb 2024) Sub-stepping + warm starting + soft constraints + relaxation - XPBD compliance (Macklin 2016) for stiffness-independent constraints - Small Steps (Macklin 2019) for sub-step contact updating - PhysX 5 GPU rigid bodies: fixed pre-allocated buffers, D6-native joints - Jolt + Box2D v3: simulation islands via union-find, per-island sleep - Delta-position formulation (Catto) to avoid FP cancellation far from origin - Graph-colored parallel Gauss-Seidel (Fratarcangeli et al.) - GPU Gems 3 Ch.29: spatial hash broadphase, 27-neighbor cell queries SoA buffer layout for cache-coherent GPU access. All WGSL shaders embedded as template literals (matches codebase pattern).


createGPUPhysicsWorld

async createGPUPhysicsWorld(device, options = {})

Summary: Create a GPU physics world.


gpuApplyForce

gpuApplyForce(world, handle, fx, fy, fz)


gpuApplyTorque

gpuApplyTorque(world, handle, tx, ty, tz)


gpuStepWorld

gpuStepWorld(world, dt, broadphase, narrowphase, solver)

Summary: Step the GPU physics world.


sim/physics/gpu/GPUSceneQuery

Summary: GPUSceneQuery.js — GPU Scene Queries (Overlap, Sweep, Shape Cast) PhysX-style scene query system for spatial queries against the physics world. Supports overlap tests, sweep/shape casts, and multi-hit collection. Features: - Sphere/Box/Capsule overlap tests (find all bodies overlapping a shape) - Sphere/Box sweep (shape cast along a direction, find first/all hits) - Closest-hit and multi-hit modes - Layer/mask filtering - CPU-side for low-latency (synchronous results), uses CPU shadow data Based on: - PhysX PxScene::overlap(), sweep(), raycast() - PhysX PxOverlapBuffer, PxSweepBuffer - Jolt NarrowPhaseQuery: CastShape, CollideShape CPU-only implementation (not GPU compute) because: - Scene queries are typically 1-10 per frame (not thousands) - Need synchronous results (gameplay logic depends on them immediately) - GPU readback latency would negate the benefit


sim/physics/gpu/GPUSoftBody

Summary: GPUSoftBody.js — GPU FEM Soft Body Simulation Finite Element Method (FEM) soft body using tetrahedral meshes. PhysX 5's signature GPU feature — deformable materials like rubber, jelly, flesh, foam, etc. Based on: - PhysX 5 FEM Soft Bodies: tetrahedral simulation mesh + collision mesh - Müller et al. "Real Time Physics" (XPBD for FEM) - Smith et al. "Stable Neo-Hookean Flesh Simulation" (SIGGRAPH 2018) - Irving et al. "Invertible Finite Elements" (SIGGRAPH 2004) Architecture: - Tetrahedral mesh defines volume elements - Each tet has a rest-state inverse matrix (Dm_inv) - Per-frame: compute deformation gradient F, strain, stress → nodal forces - GPU shader: one thread per tetrahedron - Supports Neo-Hookean and co-rotational constitutive models - Nodes can be pinned (fixed) or coupled to rigid bodies Material properties: - Young's modulus E: stiffness (rubber ~1MPa, steel ~200GPa) - Poisson's ratio ν: incompressibility (rubber ~0.49, steel ~0.3) - Damping: velocity proportional damping


lameParameters

Summary: Lamé parameters from Young's modulus and Poisson's ratio.


createSoftBodySolver

async createSoftBodySolver(device, options = {})


Summary: Material presets (Young's modulus in Pa, Poisson's ratio).


sim/physics/gpu/GPUTriangleMesh

Summary: GPUTriangleMesh.js — GPU Triangle Mesh Static Collider Collision detection against static triangle meshes on GPU. Used for environment geometry (terrain, buildings, props) that doesn't move but needs accurate concave collision. Based on: - PhysX PxTriangleMeshGeometry: cooked triangle mesh with BVH - PhysX GPU: buildGPUData flag for GPU-accelerated triangle mesh contacts - Embree-style BVH: AABB tree for triangle culling Architecture: - CPU: Cook mesh → build BVH → upload to GPU buffers - GPU: Per-body shader traverses BVH, tests triangles in leaf nodes - Generates contacts into the shared narrowphase contact buffer Limitations (matching PhysX): - Triangle meshes are STATIC only (no deformation at runtime) - For deformable meshes, use GPUSoftBody.js instead - Max 65536 triangles per mesh (GPU buffer limit, configurable) - Max 16 meshes registered simultaneously


buildTriangleMeshBVH

Summary: Build a BVH from triangle data for GPU traversal. Uses surface area heuristic (SAH) median split.


createTriangleMesh

async createTriangleMesh(device, worldBuffers, narrowphaseBuffers, options = {})


sim/physics/gpu/GPUTriggerSystem

Summary: GPUTriggerSystem.js — Trigger Volumes & Contact Event System GPU-accelerated trigger overlap detection and contact event generation. Mirrors PhysX's onContact/onTrigger callback system. Features: - Trigger volumes: AABB overlap tests on GPU, event dispatch on CPU - Contact events: begin/persist/end contact tracking with entity IDs - Event buffering: GPU writes events, CPU reads back and dispatches - Pair tracking: persistent pair state across frames for begin/end detection Based on: - PhysX PxSimulationEventCallback: onContact, onTrigger, onConstraintBreak - PhysX PxPairFlag: eNOTIFY_TOUCH_FOUND, eNOTIFY_TOUCH_PERSISTS, eNOTIFY_TOUCH_LOST - PhysX PxShapeFlagEnum: eTRIGGER_SHAPE (no contact response, only overlap events)


createTriggerSystem

async createTriggerSystem(device, worldBuffers, broadphaseBuffers, narrowphaseBuffers, options = {})


sim/physics/gpu/GPUVehicle

Summary: GPUVehicle.js — GPU-Accelerated Vehicle Physics Arcade-to-simulation vehicle system running on GPU compute. Models wheels, suspension, engine, transmission, steering, and drivetrain. Based on: - PhysX 5 Vehicle SDK: suspension raycasts, tire model, drivetrain - Bullet Vehicle: raycast vehicle with Pacejka tire friction - Marco Monster's "Car Physics for Games" (classic reference) - Brian Beckman's "Physics of Racing" series Architecture: - Vehicle is a rigid body in GPURigidBodyWorld with attached wheel descriptors - Each frame: suspension raycasts → tire forces → engine torque → apply to chassis body - GPU shader handles all wheels in parallel (one thread per wheel across all vehicles) - CPU manages gear shifts, input mapping, and vehicle creation Tire model: simplified Pacejka "Magic Formula" F = D * sin(C * atan(B * slip - E * (B * slip - atan(B * slip)))) Simplified to: F = peakForce * sin(2 * atan(slip / peakSlip))


createVehicleManager

async createVehicleManager(device, worldBuffers, options = {})


Summary: Default wheel presets for common vehicle types.


Summary: Default engine/transmission presets.


sim/physics/gpu/index

Summary: GPU Physics Engine — Barrel Export Standalone WebGPU compute-based rigid body physics engine. Full PhysX 5 feature parity via WebGPU compute shaders. Import from this file to access all GPU physics components. Usage: import { createGPUPhysicsWorld, createBroadphase, ... } from './gpu/index.js'; ═══════════════════════════════════════════════════════════════ Core Rigid Body Pipeline (7 files): GPURigidBodyWorld   — World, bodies, integration, islands, readback GPUBroadphase       — Spatial hash broadphase, AABB, pair finding GPUNarrowphase      — Shape-shape contact generation (PCM) GPUConstraintSolver  — TGS_Soft contacts + D6 joints + relaxation GPUConvexHull       — Quickhull 3D, support maps, GPU upload GPURaycast          — GPU parallel raycast + CPU fallback GPUContinuousCollision — Speculative CCD (AABB expansion + TOI) Extended Simulation (4 files): GPUVehicle              — Wheels, suspension, Pacejka tires, drivetrain GPUCharacterController  — Kinematic CCT (slide-move, step climb, slope limit) GPUSoftBody             — FEM soft body (tetrahedral, co-rotational elasticity) GPUTriggerSystem        — Trigger volumes + contact events (enter/stay/exit) Geometry & Queries (4 files): GPUSceneQuery       — Overlap tests, sweep/shape casts GPUHeightfield      — Terrain heightfield collider (bilinear, materials, holes) GPUTriangleMesh     — Static triangle mesh collider (BVH traversal) ═══════════════════════════════════════════════════════════════ Existing Engine Systems (already built, import from parent): ../GPUClothSolver.js       — PBD cloth (small substeps + OGC contact) ../GPUArticulationSolver.js — Articulated chains (Cosserat rods) ../GPUSpatialHash.js       — Morton-code spatial hash (GPU Gems 3) ../SDFCollision.js         — SDF mesh geometry (PhysX 5 style) ../PBDSolver.js            — Position-Based Dynamics (XPBD, graph coloring) ../MLSMPMSolver.js         — MLS-MPM soft body (snow, sand, jelly) ../OGCContact.js           — Offset Geometric Contact (SIGGRAPH 2025) ../SpeculativeContacts.js  — CPU speculative CCD ../ShockPropagation.js     — Shock propagation (Guendelman 2003) ../VoronoiFracture.js      — Voronoi destruction (Blast SDK equivalent) ../ConvexDecomposition.js  — V-HACD convex decomposition ../VoxelMeshCollision.js   — Voxelized mesh collider (LOD) ../DynamicMeshCollider.js  — Runtime mesh collider updates ═══════════════════════════════════════════════════════════════


sim/physics/index

Summary: engine/sim/physics/index.js - Physics Systems Barrel Export


sim/physics/rig/ActiveRigController


sim/physics/rig/ActiveRigSchema


frequencyToDrive

frequencyToDrive({ frequencyHz = 4.5, dampingRatio = 1.0, effectiveMass = 1, mode = DRIVE_MODES.acceleration } = {})


getJointTorqueBudget

getJointTorqueBudget(jointType, massKg = 80, presetName = 'HumanAverage', tier = 'avg')


createDriveProfile

createDriveProfile({ joints = [], massKg = 80, preset = 'HumanAverage', frequencyHz = 4.5, dampingRatio = 1.0, driveMode = DRIVE_MODES.acceleration } = {})


sim/physics/rig/BalanceController


estimateCenterOfMass

estimateCenterOfMass(joints = {}, fallback = [0, 0, 0])


Summary: engine/sim/physics/rig/CharacterPhysicsAssetAdapter.js — converts a CharacterPhysicsAsset (engine/assets/rig/CharacterPhysicsAsset.js) into the { parts, joints, bodies } rig shape ActiveRigController expects.  This is the Phase 1 fix for the ragdoll stack's root-cause bug: StickmanActiveRigAdapter.js only ever read the hand-authored StickmanRagdoll ECS shape, completely disconnected from RagdollBuilder/JointLimits' output — meaning PhysX built joints from different axis/limit data than RagdollSim did, so systems disagreed about which way an elbow/knee should bend. This adapter reads the SAME asset.jointDefs (axis/swingDeg/twistDeg/motion/ frameA/frameB) that RagdollSim consumes, so PhysX and the Verlet fallback now agree by construction.


createActiveRigFromCharacterPhysicsAsset(asset, options = {})

Summary: Build an ActiveRigController-compatible rig descriptor from a CharacterPhysicsAsset.


createActiveRigControllerOptionsFromCharacterPhysicsAsset(asset, options = {})

Summary: Build the full option bag `new ActiveRigController(options)` expects, from a CharacterPhysicsAsset — the CharacterPhysicsAsset equivalent of `createActiveRigControllerOptionsFromStickman`.


createRetargetGraphFromBodyDefs

Summary: Trivial identity retarget graph (physics joint id === render bone id/slot).


sim/physics/rig/MuscleLayer


sim/physics/rig/PoseStateGraph


resolveRequestedPoseState

resolveRequestedPoseState(intent = {}, fallback = 'idle_stand')


sim/physics/rig/RetargetGraph


sim/physics/rig/StickmanActiveRigAdapter


createActiveRigFromStickman

createActiveRigFromStickman(stickman = {}, options = {})


createActiveRigControllerOptionsFromStickman(stickman = {}, options = {})


sim/physics/rig/index


sim/physics/vehicle/VehicleBindings

Summary: Vehicle2 WebIDL capability adapters. The generated declaration exposes several helpers as statics while the emitted JavaScript places them on the constructor prototype, so all vehicle code crosses that mismatch here.


sim/physics/vehicle/VehicleChassis


configureVehicleChassis

configureVehicleChassis(PhysX, vehicle, config, alloc)


initializeVehicleActor

initializeVehicleActor(PhysX, topLevel, world, vehicle, config, alloc)


sim/physics/vehicle/VehicleConfig


sim/physics/vehicle/VehicleController


createVehicleController

createVehicleController({ PhysX, world, topLevel, vehicle, actor, context, sweepMesh, tracked, config, gears, })


sim/physics/vehicle/VehicleDrivetrain


sim/physics/vehicle/VehicleEngine


sim/physics/vehicle/VehicleWheels


configureVehicleWheels

configureVehicleWheels(PhysX, topLevel, vehicle, config, alloc)


sim/physics/vehicle/index

Summary: Build a complete PhysX Vehicle2 car from independently owned subsystems.


sim/world/WindSimulation

Summary: Procedural Weather System - Grid-based weather simulation Simulates coupled ODE system for: - Temperature (fed by sunshine, decreased by rain/altitude) - Humidity (fed by water evaporation, lost to rain) - Clouds (appear above temp/humidity thresholds) - Precipitation (impulsive rain from cooling humid air) - Wind (convects temperature and humidity)


VolumetricClouds

Summary: Volumetric Cloud Generator - Raymarched 3D density clouds INTEGRATION: - Uses GPU particles for cloud puffs/wisps - Uses WindSimulation for cloud advection - Uses SpatialHashCompute for LOD particle culling Uses multi-octave noise for cloud density with: - Wind advection from LBM simulation - Rayleigh/Mie scattering for realistic lighting - LOD based on ray distance


sim/world/WindSystem

Summary: WindSystem.js - Global Wind Simulation Provides wind data for vegetation, particles, cloth, etc. Features gusts, turbulence, and directional wind


sim/world/WorldSim


stepWorldSim

stepWorldSim(worldSim, deltaSeconds, options = {})


exportWorldSimState

exportWorldSimState(worldSim, options = {})


state/authority/Capability

Summary: state/authority/Capability.js — scoped, attenuable, revocable authority (spec §12).  Observation does NOT imply permission (spec rule 29). A capability names a principal, an object, an allowed action, scope/constraints, expiry, and whether it is single-use. Following Macaroons, a capability can be ATTENUATED by adding caveats (narrowing who/where/when/what) — never widened. Critical single-use capabilities are themselves USOs (consumed on use). Authority is re-checked at commit, closing the time-of-check/time-of-use gap.


makeCapability

Summary: Mint a capability.


attenuate

Summary: Attenuate a capability by adding a caveat. The result is a NEW capability that is strictly narrower; it can never grant more than its parent (spec rule 30, CSE rule "a capability cannot grant rights beyond its issuer's rights").


authorizes

authorizes(cap, { principal, object, action, epoch, context = {} } = {})

Summary: Test whether a capability authorizes an action in a context. Checks object/action match, expiry, and every caveat predicate. Does NOT check revocation — that lives in the registry (online status, spec rule 31).


state/authority/CapabilityRegistry

Summary: state/authority/CapabilityRegistry.js — registry + revocation (spec §6,§12).  Holds issued capabilities and a revocation set. A revoked critical capability can never commit (safety invariant, spec §19). Revocation-sensitive capabilities require an online status check at commit, so the coordinator asks the registry — not a cached plan — whether a capability is still valid.


state/authority/Identity

Summary: state/authority/Identity.js — pluggable signer for the Authority plane (spec §12).  Authority is explicit and bound to a signing key, not an ambient bearer token (spec rule 30, CSE rule 1). This wraps the engine's existing ECDSA P-256 identity (engine/collab/CollabIdentity.js) behind a minimal signer interface so the commit coordinator can verify signatures at commit time. When SubtleCrypto is unavailable it degrades to a deterministic FNV stamp — usable for local dev, but `secure:false` flags that it carries no cryptographic guarantee.


createSigner

async createSigner(principal, opts = {})

Summary: Create an authority signer bound to a principal id. Each distinct principal gets its OWN persisted ECDSA P-256 keypair (via CollabIdentity's named-key support) rather than sharing the single default device key. This lets the same device host multiple unlinkable signers — e.g. a stable `profile:<id>` identity and per-group pseudonymous `membership:<groupId>:<profileId>` identities (engine/network/identity) — without one leaking the other's fingerprint.


verifyWithKey

async verifyWithKey(publicKeyHex, data, signatureHex)

Summary: Verify a signature against an explicit public key (cross-actor verification).


state/authority/PolicyEngine

Summary: state/authority/PolicyEngine.js — Authority-plane policy engine + approval/risk gates (spec §3 plane 6, rules 30, 34).  Capabilities say WHAT a principal may do; policy says under WHICH conditions it is currently allowed, and which actions need human/authority approval before they may commit. The engine evaluates ordered rules (deny overrides allow) and classifies an action's risk; irreversible / high-risk actions are gated behind an explicit approval that must be present at commit time — closing the time-of-check/time-of-use gap together with the capability re-check (rule 31). Policy is versioned (rule 5) so receipts can record which policy decided.


state/causal/CausalParents

Summary: state/causal/CausalParents.js — partial order over committed events (spec §2,§9).  Lamport's happened-before: causal relationships establish a partial order; concurrent events need not have a global order. This Causal Plane tracks the DAG of committed ids (commits, observations) so a new transaction can declare `causalParents` and the coordinator can verify those parents are known before committing. It reuses the partial-order toposort from facts/Causality.js for deterministic projection of the known causal graph.


state/causal/DottedVersionVector

Summary: state/causal/DottedVersionVector.js — precise concurrent-version causality (spec §9 "Causal time", rule 8/9).  A VersionVector summarizes "what I have seen" per node and gives a partial order: equal / before / after / concurrent. Dotted version vectors (Preguiça et al.) add the ability to track each write as an isolated event (a "dot") so concurrent writes are kept as explicit SIBLINGS instead of being silently lost or forcing per-client metadata to grow without bound. This is the causality backbone the Causal Plane uses to decide when order is genuinely required.


DVVSet

Summary: A dotted-version-vector set for ONE logical key: stores the current value(s) plus the causal history at which each was written. Concurrent writes survive as siblings; a write that causally dominates a value replaces it.


state/causal/HLC

Summary: state/causal/HLC.js — Hybrid Logical Clock (spec §9 "Operational time", rule 11).  An HLC (Kulkarni et al.) combines a logical clock's causal guarantees with a timestamp that stays close to physical time. Each timestamp is (l, c): `l` tracks the max physical time observed, `c` is a bounded counter that breaks ties when events share the same `l`. HLC gives a total order consistent with causality (if A → B then ts(A) < ts(B)) while remaining readable as wall time.  IMPORTANT (rule 11): a timestamp NEVER establishes authority, ownership, or uniqueness on its own — HLC orders events; the commit protocol decides truth.


compareHLC

Summary: Compare two HLC timestamps {l,c}. Returns -1, 0, or 1.


state/codebook/CodeEntry

Summary: state/codebook/CodeEntry.js — the layered code packet. NOT one magic number: each field has exactly one job and never pretends to be another.  denseID        fast runtime handle exactID        literal pattern identity (9-bit packed / canonical) spatialID      where it belongs in space   (filled by the spatial layer, M2) resonanceVector what it resembles          (filled by the resonance layer, M3) correctionCode how to repair corruption    (filled by the correction layer, M5) hashID         have we seen this exact thing symbolicSig    what it MEANS (optional)


makeCodeEntry

Summary: Build a CodeEntry for a raw 3x3 pattern. Later layers enrich the null fields: spatialID (M2 SpatialCode), resonanceVector (M3 Transforms), correctionCode (M5 CorrectionGate). Keeping them explicitly null preserves the layer law — a missing layer is visibly missing, never faked.


state/codebook/PatternCodebook

Summary: state/codebook/PatternCodebook.js — Phase 1 of the URC pipeline: raw 3x3 block -> 9-bit exact id -> canonical (rotations/flips) -> dense id + hash id + nearest legal attractor (Hamming distance).  This is the smallest stable codebook. Bigger blocks (8x8 DCT, 32x32 wavelets) plug into the resonance layer later; the contract here is: a raw pattern maps deterministically to a stable codebook entry.


packPattern

Summary: Pack a length-9 array of truthy/0 cells (row-major) into a 9-bit id (0..511).


unpackPattern

Summary: Unpack a 9-bit id back into a length-9 Uint8Array (row-major).


hammingDistance

Summary: Number of differing cells between two packed 3x3 patterns.


symmetries

Summary: All 8 dihedral symmetries of a packed pattern.


canonicalId

Summary: Canonical id = smallest packed id over all dihedral symmetries (rotation/flip invariant).


patternHashId

Summary: Stable content fingerprint for a pattern (hash = identity).


state/codebook/SymbolicSig

Summary: state/codebook/SymbolicSig.js — symbolic *meaning* via prime INDICES.  Layer law: "Primes = symbolic meaning". We never multiply giant prime products at runtime (that would be slow and pretend to be storage). A symbolic signature is just a sorted set of prime indices; identity stays in hashes, speed stays in dense ids. Two things that look alike (resonance) can still mean opposite things — meaning is checked HERE, not by similarity.


primeAt

Summary: Prime value for a given index (bounds-checked).


symbolicSig

Summary: Build a symbolic signature: a sorted, de-duplicated vector of prime indices.


sigEquals

Summary: Meaning equality — compares index sets, NEVER products.


sigContains

Summary: True if `sub`'s meanings are all present in `sig` (symbolic containment).


state/commit/CommitGate

Summary: state/commit/CommitGate.js — only commit gates decide FINAL truth.  Core law: "Similarity may suggest. Facts may branch. Constraints may reject. But only commit gates decide final truth." Used for the orderless-unsafe things: inventory, permissions, ownership, money, save overwrite, security, multiplayer hit-confirm, choosing a canonical branch.  A commit applies a delta (adds + tombstones) to a CLONE of the base store, runs COMMIT-strength constraints, then an optional authority check. It never mutates the base — truth is the returned store, with a witness either way.


createCommitGate

createCommitGate({ constraints = [], authority = null } = {})


state/commit/CorrectionGate

Summary: state/commit/CorrectionGate.js — correction is NOT authority.  Tiered policy (the layer law for repair): VISUAL    state may auto-correct (particles, cache, chunk, network-with-confidence) SEMANTIC  state must verify before applying (inventory, save, ...) SECURITY  state must NEVER silently repair (permission, ownership, security)  When unsure: branch / quarantine / request authority — never silently fix. Resonance (nearestAttractor) may SUGGEST the repaired value, but acceptance is decided here, and a security tier can only escalate, never apply.


correct

correct({ tier, repaired, verify, unsure = false })

Summary: Decide what to do with a (resonance-)repaired candidate.


state/consistency/CRDT

Summary: state/consistency/CRDT.js — approved mergeable types (spec §4 "Mergeable state", rule 14/36).  State-based CRDTs (CvRDTs): every type exposes a `merge(other)` that is a least-upper-bound join — associative, commutative, and idempotent — so replicas that exchange state in any order/any number of times converge to the same value WITHOUT coordination (CALM / coordination-avoidance). Each merge is non-mutating and returns a NEW instance so the join algebra is easy to test.  IMPORTANT (rule 36): CRDT convergence is NOT proof of application validity. A CRDT may only be used for a value after `InvariantConfluence` confirms its operations preserve the relevant invariants. These types are the approved building blocks, not a license to make any value mergeable.


state/consistency/InvariantConfluence

Summary: state/consistency/InvariantConfluence.js — coordination-avoidance classifier (spec §4, §8 "Consistency Plane", rule 35/36).  Invariant confluence (Bailis et al.) is the precise test for whether a set of operations can run WITHOUT coordination: a set of operations is I-confluent with respect to an invariant I if, for any I-valid states reachable from a common ancestor, their merge is also I-valid. If so, replicas may diverge and merge freely (CALM); if not, those operations need a coordinating commit (Exclusive/serializable profile).  This is a BOUNDED, honest classifier (a finite-model property check, in the spirit of §19) — it explores states reachable within `depth` operations and reports a concrete counterexample when it finds one. A "confluent" result is evidence within the explored bound, not a closed-form proof.


classifyConfluence

classifyConfluence({ initial, merge, invariant, operations, depth = 2 })

Summary: Classify a set of operations for invariant confluence.


state/consistency/OptimisticValidator

Summary: state/consistency/OptimisticValidator.js — optimistic read-set / predicate validation and write-skew detection (spec §6, §8, rule 22/24).  The "Optimistic" consistency profile reads versions, proposes a replacement, and commits only if every read remained current (MVCC validation). Checking only WRITTEN objects is insufficient: snapshot execution can admit write-skew anomalies involving predicates or separately-read objects. So validation must cover the full declared read-set AND predicates, and a serializability check must detect dangerous rw-antidependency structures between concurrent transactions.


OptimisticValidator

Summary: Validate a transaction's declared read-set and predicates against the current state. Used standalone or alongside the CommitCoordinator's version check.


detectWriteSkew

Summary: Detect a write-skew (non-serializable) hazard between two CONCURRENT transactions. Write-skew occurs when each transaction reads data the other writes — two rw-antidependency edges — so both can pass snapshot validation yet jointly violate an invariant coupling the items.


state/consistency/Reservation

Summary: state/consistency/Reservation.js — reservations + bounded-counter escrow (spec §5 fragmentation fix, §10, rule 16).  Two coordination-avoidance tools that sit in front of the commit path:  • ReservationManager — a reservation is itself a USO (single-use, exclusive). Reserving a scarce resource creates a reservation output; it is later CONSUMED on commit or RELEASED/expired. A reservation can never be consumed twice (inherits the USO double-commit guarantee), and an expired reservation cannot mutate protected state (liveness: aborted reservation is eventually released).  • BoundedCounterEscrow — divides decrement rights for a scarce quantity among holders so each can withdraw from its local grant WITHOUT coordination, while preserving the lower-bound invariant (quantity never drops below the floor). Coordination is only needed when a holder exhausts its grant and must be rebalanced. This is the escrow / bounded-counter CRDT pattern.


state/consistency/SerializableQueue

Summary: state/consistency/SerializableQueue.js — Consistency-plane serializable commit queue (spec §3 plane 3, §6, §8 "Serializable", rule 24).  The "Exclusive"/serializable consistency profile needs commits to be applied in an order equivalent to some serial schedule. This queue admits transactions (each declaring a read-set and write-set), assigns a monotonic commit sequence, and detects when admitting a transaction would create a non-serializable schedule against already-queued/committed transactions (a read-write or write-write conflict on overlapping items). Conflicting transactions are not silently interleaved — the queue rejects them for retry, preserving serializability for the invariants that require it.


state/entity/EntityRegistry

Summary: state/entity/EntityRegistry.js — versioned entity state (spec §4, rule 2).  A mutable logical object is represented as a chain of immutable versions. The logical entity id stays stable; each version's id is the content hash of its canonical bytes. "Editing" creates a new version pointing at its parent — the old version is never mutated. This is what optimistic concurrency reads against: a transaction's readSet declares the version it expected, and the commit fails if the entity has since advanced (write-skew protection).


state/entity/ProvenanceStore

Summary: state/entity/ProvenanceStore.js — every observation, inference, prediction, and commit carries provenance (spec §14, rule 4). Vocabulary follows W3C PROV (entities, activities, agents, generation, derivation). Provenance lets the engine distinguish directly-observed vs inferred vs model-predicted vs stale vs untrusted data — crucial for the prompt-injection boundary (spec §15): retrieved/tool/model content is recorded as untrusted observation, never as authority.


makeProvenance

Summary: Build a provenance record for a subject (a fact, version, or transaction).


isUntrusted

Summary: True if a provenance record came from an untrusted external source.


state/entity/SchemaRegistry

Summary: state/entity/SchemaRegistry.js — meaning from schemas, not numeric tricks (spec rule 3). Every schema/validator/policy is versioned (spec rule 5) so migrations can reference exact stamps. A schema declares a name, a version, and a validate(value) predicate; validation is structural (legality), never a claim of semantic truth — that comes from commit logic.


state/facts/Branch

Summary: state/facts/Branch.js — split non-commuting possibilities; merge equivalent; prune invalid.  Core law: "If A + B = B + A, merge them. If A + B != B + A, branch them." An operation is a pure function (store) => void that adds facts / tombstones.


applySequence

Summary: Apply a sequence of operations to a (cloned) store. Returns the store.


commutes

Summary: Does applying opA then opB yield the same projection as opB then opA?


branchOrders

Summary: Produce both order-branches [A→B, B→A] from a base store.


mergeEquivalent

Summary: Collapse branches with identical projections (merge equivalent).


prune

Summary: Drop branches that fail commit-strength constraints (prune invalid).


state/facts/Causality

Summary: state/facts/Causality.js — partial order ONLY when a dependency forces it.  Layer law: "Only causality creates before/after". Facts with no dependency link stay unordered; we never invent sequence. Independent nodes get a deterministic tie-break (canonical sort) purely for reproducibility, not as claimed truth.


link

Summary: A causal link: effect depends on cause (cause must precede effect).


toposort

Summary: Partial-order sort. Nodes only ordered where links force it; otherwise deterministic by string. Throws on a causal cycle (an impossible order).


dependsOn

Summary: Transitive dependency test: does `effect` (transitively) depend on `cause`?


state/facts/Constraints

Summary: state/facts/Constraints.js — the laws of the system.  Layer law: runtime uses simple validators; commit uses stronger validators (a superset). A constraint never repairs — it accepts or rejects. When a commit constraint fails, the caller branches / quarantines / requests authority (see CommitGate, M5) rather than silently fixing.


constraint

Summary: Define a constraint.


validateFacts

validateFacts(liveFacts, constraints, { phase = SCOPE_RUNTIME } = {})

Summary: Validate live facts. phase 'runtime' runs only runtime constraints; phase 'commit' runs ALL (runtime + commit) — commit is strictly stronger.


atMostOne

Summary: No more than one live fact matching a regex (single source of truth).


mutuallyExclusive

Summary: Two facts must never be live at once (mutual exclusion).


state/facts/Fact

Summary: state/facts/Fact.js — canonical facts + tombstones.  Layer law: facts are MONOTONIC. We prefer adding facts, never deleting them. "Deletion" is a tombstone fact `revoked(<fact>)`; projection later decides what is currently valid. A fact is just a canonical string predicate so that {A,B} and {B,A} hash identically (see util/hashing.canonicalSetHash).


fact

Summary: Build a canonical fact string: fact('hasKey','player','red') → "hasKey(player,red)".


revoke

Summary: Wrap a fact as a tombstone (the monotonic stand-in for deletion).


isTombstone

Summary: Is this fact a tombstone?


tombstoneTarget

Summary: The fact a tombstone revokes, or null.


state/facts/FactStore

Summary: state/facts/FactStore.js — the unordered, monotonic fact set.  No sequence is stored. `id()` is the order-independent hash of ALL facts (history identity); `liveId()` is the hash of the currently-valid projection (tombstones applied). Merge is a set union — naturally commutative and idempotent (a CRDT-style anti-entropy merge), so two peers that saw events in different orders converge to the same id.


state/index

Summary: state/index.js — public barrel for the Causal State Engine (CSE), formerly the Universal Resonance State Engine (URC).  Order-on-demand: unordered facts encoded through a resonance codebook, organized spatially, compared by wave-like similarity, repaired through correction codes, branched when order matters, committed only when reality must choose one truth, and projected by observers into experienced sequence.  The CSE upgrade (see plans/causal-state-engine-upgrade-59657d.md) layers a partially-ordered, capability-secured, transactionally-committed world-state system on top of the URC core. The codebook/resonance/spatial layers are kept as the optional indexing/perception extension (spec §16) — never in the trusted authority/correctness path.  Build status: URC core: [x] M0 [x] M1 codebook [x] M2 spatial [x] M3 resonance [x] M4 facts [x] M5 commit [x] M6 observer CSE:      [x] P1 formal core (USO, tx envelope, idempotency, causal, 14-step commit, receipts) [x] P2 single-authority (entity/version, schema, provenance, capabilities, identity, event log, state roots, checkpoints) [x] P3 reliability (outbox, idempotent inbox, sagas+compensation, reconciler, reservations + bounded-counter escrow) [x] P4 concurrency (CRDTs, invariant-confluence classifier, optimistic/write-skew validator, dotted version vectors, HLC) [x] P5 world model (belief vs canonical, object graph, affordances, tool-effect/discrepancy, prediction sandbox, untrusted boundary) [x] P6 distributed (shard router, replicated log, Raft adapter, cross-shard 2PC + recovery, quorum checkpoints) [x] P7 sim/resonance (independent sim clocks, deterministic world dynamics, approximate-retrieve→exact-verify perception index) [x] P8 completeness (proposal pool, serializable queue, policy engine+risk gates, encryption/retention crypto-erase, GC, causal dynamics, TLA+ core stub) [x] P9 hardening (WebCrypto AES-GCM retention, Byzantine adapter, executable bounded model checker + TLC config) CSE COMPLETE: all 12 planes implemented + verified in verify.html.


state/integrity/Checkpoint

Summary: state/integrity/Checkpoint.js — compaction + fast restoration (spec §13).  A checkpoint summarizes history without pretending it never existed: it links to the previous checkpoint and the event range it covers, and pins the canonical state root, unspent-output root, and policy/schema/validator versions. A restored system must verify its state root before accepting new commits (spec rule 64). Checkpoints carry an optional authority signature.


makeCheckpoint

Summary: Build a checkpoint record.


verifyCheckpoint

verifyCheckpoint(checkpoint, computedStateRoot, predecessor = null)

Summary: Verify a checkpoint's stateRoot matches a freshly computed root, and (if a predecessor is provided) that the chain links correctly (spec rule 60,64).


state/integrity/EventLog

Summary: state/integrity/EventLog.js — append-only commit stream (spec §13).  Committed changes are appended to an immutable, hash-chained event log. Materialized views can be rebuilt without altering history (event sourcing). Each entry links to the previous entry's hash, so any tampering with earlier history changes every subsequent link — a lightweight Merkle chain. The hash is the fast tagged id of the canonical entry (hot path); authority signatures live on the witness receipts the entries reference.


state/integrity/GarbageCollector

Summary: state/integrity/GarbageCollector.js — Integrity-plane garbage collection (spec §3 plane 8, rule 61; liveness "GC never removes pinned authoritative state").  GC reclaims storage by collecting objects that are no longer reachable from a set of SIGNED ROOTS (latest checkpoint, unspent outputs, retained branches) and not protected by a retention policy. It is mark-and-sweep over the reference graph: anything reachable from a root — or explicitly pinned — is retained; everything else is eligible. The hard invariant is that GC can NEVER remove pinned authoritative state, even if it looks unreferenced.


state/integrity/Retention

Summary: state/integrity/Retention.js — Integrity-plane encryption & retention manager (spec §13 "Privacy and deletion", rule 62).  Append-only logs conflict with deletion requirements. The resolution: store sensitive payloads ENCRYPTED under a scoped key, leaving only minimal, non-sensitive audit metadata in the permanent record. Destroying the scope key renders the encrypted payload infeasible to recover — NIST "cryptographic erase" — so the audit trail survives while the sensitive bytes are irrecoverable. The cipher here is a deterministic keyed stream (model-grade, not production crypto): the point is the KEY-LIFECYCLE invariant, i.e. erase the key ⇒ payload unrecoverable, metadata retained.


state/integrity/SecureCrypto

Summary: state/integrity/SecureCrypto.js — production-grade authenticated encryption (spec §13 privacy, §17 deterministic-core boundary).  Real AEAD via Web Crypto AES-256-GCM. Used by SecureRetention for sensitive payloads so that destroying the key (cryptographic erase) renders ciphertext infeasible to recover, and any tampering with ciphertext/AAD fails the GCM authentication tag. This is the production swap-in for the model-grade keyed stream used elsewhere. All operations are async (SubtleCrypto); callers that need a sync path keep the deterministic fallback in RetentionManager.


generateAesKey

Summary: Generate a fresh AES-256-GCM key (extractable, for raw export/erase tests).


aeadSeal

async aeadSeal(key, plaintext, aad = '')

Summary: AEAD-seal a plaintext string. `aad` (additional authenticated data) binds the ciphertext to a context (e.g. the scope id) without encrypting it.


aeadOpen

Summary: AEAD-open an envelope. Returns plaintext, or null if the key is wrong/erased or the ciphertext/AAD was tampered with (GCM tag check fails).


state/integrity/SecureRetention

Summary: state/integrity/SecureRetention.js — production AES-256-GCM retention manager (spec §13, rule 62). The cryptographic counterpart of RetentionManager.  Sensitive payloads are sealed under a per-scope AES-GCM key held only in memory as a non-extractable-by-policy CryptoKey reference. Cryptographic erase drops that reference, after which the ciphertext is infeasible to recover (NIST crypto-erase), while non-sensitive audit metadata on the envelope survives. GCM's authentication tag also makes any tampering with the ciphertext or the scope-bound AAD fail closed (open → null).


state/integrity/StateRoot

Summary: state/integrity/StateRoot.js — Merkle-style canonical state root (spec §13,§19).  A state root is the hash of the canonical, ORDER-INDEPENDENT summary of the authoritative state: the live fact set, the unspent-output id set, and the entity head version ids. The committed state root must exactly match the committed outputs (safety invariant). A hash proves exact content only — not correctness — so the root is used for integrity/restoration, never as a semantic-truth or authority claim (spec rule 52).


computeStateRoot

computeStateRoot({ facts = [], unspent = [], entityHeads = [] } = {})

Summary: Compute a state root from the authoritative components. Any iterable is accepted; members are sorted for order-independence.


rootFromStores

rootFromStores({ factStore = null, usoRegistry = null, entityRegistry = null } = {})

Summary: Convenience: derive a state root from live engine registries.


state/observer/Projection

Summary: state/observer/Projection.js — the observer creates EXPERIENCED order.  Core truth may be unordered or branched. An observer sees one path, but that is only a projection: render order is not truth, UI order is not truth, debug order is not truth. Only committed facts are canonical — so every projection here carries `isTruth: false` and a witness. Turning a projection into truth requires a CommitGate.


projectSequence

Summary: Project one experienced sequence from a fact store. Independent facts stay deterministically ordered (reproducible), causal links force precedence.


chooseBranch

Summary: Choose one branch for an observer to experience. Does NOT commit — the other branches remain possible (recorded as "rejected/not observed" in the witness) until a CommitGate finalizes one as canonical.


state/perception/ResonanceIndex

Summary: state/perception/ResonanceIndex.js — the Resonance/Perception extension reattached as an OPTIONAL indexing layer (spec §16, rules 52–56).  This is where the codebook / resonance / spatial layers belong: approximate retrieval, never the trusted authority path. The discipline is strict and one-directional:  approximate similarity  → retrieves CANDIDATES   (cosine over feature vectors) exact identity (hash)    → verifies BYTES         (cryptographic/fast hash) semantic constraints     → verify MEANING         (predicate over content) commit logic             → establishes TRUTH      (elsewhere; not here)  A near match is only ever a suggestion. This module will NEVER return a similar-but-not-byte-identical item as a verified match — similarity suggests candidates; it never establishes identity (rule 53). Nearest-neighbour search may repair a visual cache or rank suggestions, but must never silently repair inventory, permissions, ownership, or other authoritative semantic state.


state/replication/ByzantineAdapter

Summary: state/replication/ByzantineAdapter.js — optional Byzantine-fault-tolerant authority (spec §8 hostile peer-to-peer profile, rule 38).  This is the explicitly-separate hostile-P2P profile, NOT implied by the default crash-fault deployment. It tolerates up to f Byzantine (arbitrary / malicious) nodes given n ≥ 3f+1 members, committing a value only when at least a 2f+1 quorum cast MATCHING votes for it. Two safety mechanisms:  • Equivocation detection — a node that votes for two different values in the same round is provably faulty; it is marked Byzantine and ALL its votes are discarded, so a double-voter cannot help two values reach quorum. • 2f+1 quorum — with n ≥ 3f+1 and ≤ f faulty nodes, any value with 2f+1 votes has ≥ f+1 honest votes, so two conflicting values can never both commit (their honest supporters would have to overlap).  Votes are expected to be signed; an optional verifier rejects unsigned/forged votes. Membership/Sybil control is a deployment policy declared separately.


state/replication/CheckpointQuorum

Summary: state/replication/CheckpointQuorum.js — quorum-signed checkpoint proofs (spec §13 checkpoints + §8 replication, rule 64).  A checkpoint summarizes history with a canonical state root. In a replicated deployment a checkpoint becomes authoritative only when a QUORUM of members attest to the SAME state root — this is the proof a restored node verifies before accepting commits (rule 64). Members that attest a different root are recorded as DIVERGENT and never counted toward the quorum, so a minority of faulty/forked replicas cannot finalize a bad checkpoint.


state/replication/CrossShardCoordinator

Summary: state/replication/CrossShardCoordinator.js — cross-domain atomic commit (spec §10, rule 40).  Cross-domain atomicity is the most expensive operation, so it is used only when true all-or-nothing behavior is required. This coordinator implements two-phase commit with the §10 hardening: • locks are acquired in CANONICAL order (sorted shard/key) to avoid deadlock; • a durable PREPARED record is written so a coordinator that crashes after prepare can be recovered and the commit completed (classic 2PC blocks on coordinator failure; the prepared record makes it recoverable); • for operations that do NOT need atomicity, a SAGA fallback is offered instead, since compensation is cheaper than distributed commit.


state/replication/RaftAdapter

Summary: state/replication/RaftAdapter.js — crash-fault replicated authority (spec §8 Replication, rules 37–39).  An in-memory Raft cluster used where authority is genuinely SHARED. It manages leader election (with the Raft up-to-date restriction so a leader never lacks a committed entry) and quorum commit: a command is committed only once it lives on a majority of the cluster, so it survives any minority of crashes. The failure model is explicitly CRASH-FAULT (not Byzantine), and progress requires a quorum — when too many nodes are down the cluster correctly STALLS rather than risking divergence (rule 38/39: declare the failure model; partitions force an availability/consistency choice).


state/replication/ReplicatedLog

Summary: state/replication/ReplicatedLog.js — a single replica's replicated commit log (spec §8 "Replication", §11 consensus-backed commit record).  Implements the Raft log model: each entry is { index, term, command }. The LOG-MATCHING property is enforced on replication — an AppendEntries is rejected unless the follower's entry at prevIndex has prevTerm; conflicting suffixes are truncated before appending. Consequently, if two logs hold an entry with the same index and term, the logs are identical up to that index. `commitIndex` only advances over entries known durable on a quorum (the RaftAdapter drives that), so a committed entry is never lost under the declared crash-fault model.


state/replication/ShardRouter

Summary: state/replication/ShardRouter.js — deterministic key→shard routing and commit-domain boundaries (spec §10, rule 1 of cross-domain preference order).  A shard is a commit domain: state strongly related to an invariant should land in ONE shard so its commit is local and atomic. The router maps a logical key to a shard deterministically (same key → same shard on every node) using the engine's canonical fast hash, so routing needs no coordination. Transactions touching more than one shard are flagged as cross-shard (handled by the CrossShardCoordinator) — the router never silently spans domains.


state/resonance/ResonanceVector

Summary: state/resonance/ResonanceVector.js — build + compare resonance signatures and snap to the nearest attractor by SIMILARITY.  Layer law: "resonance suggests". This module reports closeness; it never decides identity (hash) or meaning (symbolicSig) or truth (commit). Two patterns can be near in resonance yet mean opposites (potion vs poison) — callers must still check symbolicSig / hash / constraints before trusting.


resonanceWHT

Summary: Resonance vector for a tiny 3x3 pattern (Walsh/Hadamard; integer-exact).


resonanceDCT

Summary: Resonance vector for an NxN visual block (DCT-II).


cosineSimilarity

Summary: Cosine similarity in [-1, 1] (1 = identical direction). 0 if either is null.


Summary: Euclidean (L2) distance between two equal-length vectors.


nearestAttractor

nearestAttractor(vec, attractors, { metric = 'cosine' } = {})

Summary: Nearest attractor by similarity. metric 'cosine' (higher score = closer) or 'l2' (score = negative distance so higher is always closer).


state/resonance/Transforms

Summary: state/resonance/Transforms.js — Phase 3 transforms.  Walsh/Hadamard  tiny binary patterns (3x3, 4x4)   [new] DCT-II          small visual blocks (8x8, 16x16)  Scale routing (per the plan): Walsh for tiny binary, DCT for small visual, wavelets for 32x32+/3D (added later). These produce the "resonance vector": a compressed signature of what a pattern RESEMBLES — never its identity.


walshHadamard

Summary: In-place-style fast WHT. Integer input → integer output. Length must be a power of two. WHT(WHT(v)) === n * v (involutive up to the length scale).


Summary: Map a packed 3x3 pattern to a length-16 bipolar vector ({0,1} → {-1,+1}, zero-padded to the next power of two) ready for the WHT.


Summary: 1-D DCT-II (orthonormal).


Summary: 1-D inverse DCT-II (orthonormal).


Summary: 2-D DCT-II of an NxN block (row-major Float array of length N*N).


Summary: 2-D inverse DCT-II.


quantize

Summary: Quantize a coefficient vector to integers by step `q` (lossy resonance).


state/sim/WorldDynamics

Summary: state/sim/WorldDynamics.js — deterministic stepped world dynamics over simulation time (spec §17 CPU deterministic core, rules 66/68 deterministic replay).  World dynamics advance simulated state one tick at a time. To keep canonical state reproducible (and replayable for verification), any randomness comes from a SEEDED deterministic PRNG — never Math.random or wall-clock. Running the same dynamics from the same seed and inputs always yields byte-identical results, which deterministic replay and fault-injection testing depend on.


state/spatial/SpatialCode

Summary: state/spatial/SpatialCode.js — Phase 2: a pattern knows WHERE it belongs.  Layer law: "Morton = hot runtime, Hilbert = cold storage / large chunk packing". We reuse the engine's deterministic MathBits curves rather than re-deriving them; this module only adds chunk addressing + neighbor lookup and the URC contract that spatialID is "where", never "what" or "truth".


Summary: 2D Morton/Z-order spatial id (16 bits per axis).


Summary: Inverse of spatialId2D → [x, y].


Summary: 3D Morton spatial id (10 bits per axis).


Summary: Inverse of spatialId3D → [x, y, z].


Summary: Hilbert distance for (x,y) on a 2^k grid of side `n`.


Summary: Inverse of hilbertId2D → [x, y].


Summary: World coords → chunk coords for a square chunk grid.


Summary: Stable chunk id (Morton of chunk coords) for GPU-buffer packing + cache locality.


neighbors2D(x, y, { diagonal = false } = {})

Summary: Spatial ids of a cell's neighbors (non-negative coords only).


state/time/Fencing

Summary: state/time/Fencing.js — monotonic fencing tokens (spec §9, rule 12).  A lease optimizes liveness; it is NOT final authority. A paused client may resume after its lease expired. Correctness-critical resources therefore require a monotonically increasing fencing token that the PROTECTED RESOURCE itself verifies: a stale token can never mutate protected state (safety invariant, spec §19). Each commit domain issues strictly increasing tokens; the domain rejects any token <= the last one it accepted.


state/time/SimulationClock

Summary: state/time/SimulationClock.js — simulation time (spec §9 "Simulation time").  Simulation time is a domain-specific relationship between simulated changes (physics steps, biological cycles, world epochs, oscillator phases). There may be MANY simulation clocks and NO universal model clock — each advances independently. Simulation clocks are distinct from causal time (dependencies) and operational time (deadlines/leases); they never establish authority.  Advancing is deterministic: the same sequence of steps yields the same tick, which is required for deterministic replay (rule 66/68).


SimulationClockSet

Summary: A set of independent simulation clocks. Each domain advances on its own; there is deliberately no method to advance them all in lockstep to a global time.


state/time/TimeModel

Summary: state/time/TimeModel.js — time is NOT a counter.  A state only has "time" if it subscribes to a time source. Real time = change + comparison + memory + causality + irreversible direction. Different sources express different truths; a state can be timeless (NONE) while an observer experiences progression.


createTimeSource

Summary: Create a time source. `step(input)` advances per-mode and returns the new value; the engine never does `time++` globally. CAUSAL    input.causalSteps CLOCKED   input.dt (oscillator phase) ENTROPIC  input.irreversibleChange (abs — monotonic) OBSERVER  input.observed (boolean) MEMORY    input.stateDistance (>= 0) HYBRID    any combination of the above


state/transaction/CommitCoordinator

Summary: state/transaction/CommitCoordinator.js — the atomic commit protocol (spec §7).  No authoritative state change happens outside this pipeline (spec rule 19). It runs the 14-step protocol over a sealed transaction envelope and a set of canonical registries, then either commits atomically and returns a signed witness receipt, or rejects with a receipt explaining what failed. The pipeline enforces the CSE safety invariants: single-spend USOs, expected versions, valid + non-revoked authority, fencing-token freshness, predicate and invariant checks, idempotent replay, and a post-state root that matches the committed outputs.


createCommitCoordinator

Summary: Create a commit coordinator bound to a set of canonical registries.


state/transaction/Idempotency

Summary: state/transaction/Idempotency.js — replay protection (spec rule 21).  Every potentially duplicated operation carries an idempotency key (`actor:task:operation`). The default registry preserves canonical at-most- once receipts without eviction for CommitCoordinator and other durable callers. A bounded TTL/LRU policy is available only by explicit opt-in for process-local replay caches whose mutation safety lives in canonical state or a separate durable dispatch fence.


state/transaction/ProposalPool

Summary: state/transaction/ProposalPool.js — Transaction-plane proposal pool (spec §3 plane 5, rules 27–28).  Before a transaction reaches the CommitCoordinator it is a PROPOSAL: a candidate that has not yet won its conflict domain. Two proposals that consume the same USO conflict — they must COMPETE, never silently overwrite (rule 27). The pool groups proposals by the exclusive inputs they contend for, picks at most one winner per conflict set (deterministically), and marks the losers as `superseded` so they re-observe and re-plan (rule 28). The pool decides only candidacy; the commit gate still establishes truth.


state/transaction/Transaction

Summary: state/transaction/Transaction.js — the one canonical transaction envelope.  Every authoritative state change flows through this envelope (spec §6). A transaction must STATE everything whose correctness depends on current state: read-set (expected versions), predicates, consumed inputs (USOs), created outputs, capabilities and external-effect intents. Checking only written objects is insufficient — predicate/write-skew anomalies require the read+predicate sets to be declared up front (spec rule 20).  The envelope is a plain, canonicalizable object; its transactionID is the secure hash of its canonical bytes (signature excluded), so the id is stable and tamper-evident.


makeTransaction

Summary: Build a canonical transaction envelope. Missing fields default to safe empty values so the shape is always complete (no partial transactions).


transactionBody

Summary: Canonical bytes of an envelope EXCLUDING id + signature (the signed body).


sealTransactionFast

Summary: Attach a synchronous (fast) transactionID. Use for runtime/non-critical transactions where a 32-bit identity is enough.


sealTransaction

async sealTransaction(env, signer = null)

Summary: Attach a secure (SHA-256) transactionID and an optional signature produced by an authority signer. The signature covers the transactionID.


state/uso/USO

Summary: state/uso/USO.js — Unspent State Output: the single-spend primitive (spec §5).  Adapted from Bitcoin's UTXO model: an exclusive, consumable, finalizable, or scarce resource. A transaction consumes inputs and creates replacement outputs; a consumed output can never be accepted again. Spendability (defined here) is separate from which conflicting spend wins (decided by the commit coordinator), exactly as Bitcoin separates outputs from consensus.  Use USOs for: exclusive ownership, scarce inventory, single-winner decisions, object-mutation rights, permission use, branch finalization, irreversible commits. Do NOT use them for hover/particles/observations/debug notes.


makeUSO

Summary: Create an unspent state output. The id is derived from kind + entity + a discriminator (e.g. version) so distinct outputs get distinct ids and equal ones collapse. Payload is opaque domain data.


objectVersionOutput

objectVersionOutput(entity, versionId, payload = null)

Summary: Convenience: an object-version output (the common mutable-object case).


isUSO

Summary: True if a value looks like a USO (has a string id and a kind).


state/uso/USORegistry

Summary: state/uso/USORegistry.js — the unspent-output set + double-commit detector.  Tracks which outputs currently exist (unspent) and which have been consumed (spent). Enforces the core safety invariant: an output is never committed as spent twice (spec §19). A spend transaction's inputs must ALL be currently unspent; on commit they move to the spent set and the new outputs are created atomically by the caller (CommitCoordinator).


state/util/canonical

Summary: state/util/canonical.js — deterministic serialization + self-describing, algorithm-tagged hash IDs (CSE Integrity plane, spec §13).  Equivalent data MUST produce byte-identical bytes before hashing or signing (spec rule 58). We implement an RFC 8785-style canonical JSON: object keys are sorted by UTF-16 code unit, arrays keep order, no insignificant whitespace, and non-finite numbers are rejected. Hash IDs are multihash-style (`alg:bits:hex`) so the algorithm can migrate later (spec rule 59).  Two tiers, matching the engine's hybrid integrity policy: • hot-path id   — synchronous 32-bit FNV (runtime identity / state roots). • authority id  — async Web Crypto SHA-256 (capabilities, receipts, checkpoints) where security matters.


canonicalize

Summary: Produce a deterministic canonical JSON string for any JSON-compatible value. Object keys are sorted; Maps and Sets are normalized; arrays preserve order.


canonicalBytes

canonicalBytes(value, { domain = DOMAIN_SEPARATOR, schemaVersion = '' } = {})

Summary: Domain-separated canonical bytes string used as hash/sign input (spec §13).


hashIdFast

Summary: Synchronous hot-path id: 32-bit FNV over canonical bytes. Tagged so it is self-describing and migratable. Fast, NOT collision-resistant — identity for runtime state, never a security claim (spec rule 52).


hashIdSecure

Summary: Async authority id: Web Crypto SHA-256 over canonical bytes. Use for capabilities, witness receipts, checkpoints, and signed transactions. Throws if SubtleCrypto is unavailable (callers degrade explicitly).


parseHashId

Summary: Parse a tagged hash id into `{ alg, bits, hex }` or null.


hashIdEquals

Summary: True when two tagged hash ids are byte-equal (same algorithm + digest).


Summary: Domain separator prefix so hashes of different structures never collide.


state/util/hashing

Summary: state/util/hashing.js — canonical, order-independent identity hashing for the URC fact/state layers. Reuses the engine's deterministic ChecksumMath rather than rolling new hashes (layer law: "hash = identity", nothing more).


hashFactString

Summary: Deterministic 32-bit hash of a single string fact.


Summary: Deterministic 32-bit hash of an ordered sequence of uint32 (e.g. a packed pattern).


canonicalSetHash

Summary: Canonical, ORDER-INDEPENDENT hash of a set of facts. Facts are stringified, de-duplicated and sorted so that {A,B} and {B,A} collapse to the same id — this is what makes `State.id = hash(canonicalFacts)` sequence-free.


hexId

Summary: Stable hex fingerprint for an unsigned 32-bit value (cold-path display/keys).


Summary: Parse a tagged hash id's low 32-bit hex tail for deterministic bucketing/seeding.


state/verify/ModelCheck

Summary: state/verify/ModelCheck.js — browser-runnable bounded model checker for the CSE commit state machine (spec §19, rule 66: model-check the core protocol).  This is the executable companion to verify/cse-core.tla. Where TLC would exhaustively explore the TLA+ model, this performs the SAME exhaustive exploration in JavaScript so it runs inside the verify.html harness with no external tooling. It enumerates every reachable state under all interleavings of commit actions and checks the core safety invariants on each:  • NoDoubleSpend     — an output is never simultaneously unspent and spent. • SingleSpend       — no output is consumed by two committed transactions. • EveryCommitWitnessed — every committed transaction has a witness.  A transaction is enabled iff it is uncommitted and all of its inputs are still unspent; applying it consumes inputs, creates outputs, and records a witness.


exploreCommitMachine

Summary: Exhaustively explore the commit state machine.


state/version

Summary: ============================================================ Universal Resonance State Engine (URC) — version source. ============================================================ Order-on-demand state engine: unordered facts, a resonance codebook, causal order only when forced, branches when order matters, and commit gates that decide final truth. The machine runs in order; the MODEL does not assume order unless forced.  Versions are facts too: migration rules reference these stamps, e.g. "URC-v1 dense #88 maps to URC-v2 dense #402 iff hashID and symbolicSig match". ============================================================


urcVersionStamp

Summary: Version stamp embedded on every State/CodeEntry/Receipt for migration + audit.


state/witness/Witness

Summary: state/witness/Witness.js — debug proof for every projection / commit.  Replaces "1 happened, 2 happened, 3 happened" timelines with: these facts existed · these rules fired · these branches were possible · this projection was shown · this commit was chosen.