makeReceipt

Summary: Build a full CSE witness receipt for a transaction commit decision (spec §7). The receipt proves WHAT was checked and WHAT the engine decided — it does not claim the input observations were objectively true. Every committed transition has exactly one receipt (safety invariant, spec §19).


state/workflow/Inbox

Summary: state/workflow/Inbox.js — idempotent inbox / effect receiver (spec §11, rule 42).  The outbox delivers at-least-once, so the receiving side MUST deduplicate by the stable effect id to make the end-to-end behavior effectively-once. The inbox records the first result for each effect id; a redelivery returns the stored result and does NOT re-run the handler (mirrors the transaction IdempotencyRegistry, but for inbound external effects).


state/workflow/Outbox

Summary: state/workflow/Outbox.js — transactional outbox (spec §11, rule 41).  A canonical commit cannot atomically control an unrelated email server, payment processor, OS call, or device. CSE solves this dual-write problem by writing an external-effect INTENT into the same atomic transaction as the internal state change (the CommitCoordinator appends intents here on commit); a separate worker later delivers each intent and receivers deduplicate by a stable effect id (rule 42). This module owns the durable intent queue and its status lifecycle:  pending → delivering → delivered → acked ↘ failed → (reconcile | retry)  Re-recording the same effect id is a no-op, so commit retries never enqueue an effect twice. Delivery is at-least-once; idempotent receivers (see Inbox.js) make the end-to-end behavior effectively-once.


makeEffectIntent

Summary: Declare an external-effect intent. Every effect must state its reversibility profile so the workflow plane knows whether it can be compensated, retried, or must pause for approval (spec §11).


state/workflow/Reconciler

Summary: state/workflow/Reconciler.js — external-effect reconciler (spec §11, rule 43).  When a delivery outcome is unknown (timeout, crash between send and ack, etc.) the effect is parked in the outbox as RECONCILE rather than guessed. The reconciler queries the external system's authoritative status for each parked effect and resolves it: confirm (it actually happened → ack), retry (it did not happen and is safe to resend → back to pending), or escalate (needs human authority attention). Ambiguity is resolved by EVIDENCE, never assumption.


state/workflow/Saga

Summary: state/workflow/Saga.js — saga coordinator + compensation registry (spec §11).  For multi-step workflows that span commit domains or external systems, true distributed atomic commit is avoided where possible (rule 40). Instead a saga runs a sequence of LOCAL steps, each with a forward action and a compensating action. If a step fails, the already-completed steps are compensated in reverse order. Compensation is a NEW action, not deletion of history (rule 44), and some effects cannot be perfectly undone — every saga declares a PIVOT step after which forward-only recovery applies because compensation is no longer possible (rule 45, the irreversible pivot).


sagaStep

Summary: Define a saga step.


state/worldmodel/AffordanceRegistry

Summary: state/worldmodel/AffordanceRegistry.js — declares LEGAL actions rather than letting the model invent tool syntax (spec §15 "Affordance registry", rule 34/50).  Each affordance binds an action to an object type and declares: preconditions (named predicates evaluated against context), the capability required to do it, predicted effects, a risk level, and a rollback/compensation hint. The planner asks "what may I legally do to this object?" and the registry answers from explicit declarations. High-risk / irreversible actions require explicit approval — the registry surfaces this but NEVER authorizes by itself (the capability + commit layer remains the authority).


state/worldmodel/BeliefStore

Summary: state/worldmodel/BeliefStore.js — separates the AI's belief model from canonical state (spec §15, rules 46–48).  The world model maintains five strictly-separated worlds:  CANONICAL — authoritative committed state (mirror, written ONLY by commit) OBSERVED  — currently sensed / retrieved information BELIEF    — inferences and uncertain interpretations PREDICTED — counterfactual futures from the model/sandbox PROPOSED  — the branch an agent wants to commit  Hard rule (47): a prediction or belief can NEVER become canonical directly. This store exposes NO method to write CANONICAL except `syncCanonical`, which represents the commit gate mirroring an already-committed result back into the model. predict()/believe()/observe()/propose() can never touch it.  Rule 48: uncertainty grows with prediction horizon unless new evidence reduces it — predict() decays confidence by horizon; observe() can restore it.


state/worldmodel/CausalDynamics

Summary: state/worldmodel/CausalDynamics.js — AI World Model causal-dynamics model (spec §15 "Causal dynamics model", rules 47–49).  Predicts how the world MAY change under an action: a registry of declared transition functions, each producing a predicted next state plus an effect summary the sandbox/planner can score. Predictions are hypotheses only — they never mutate canonical state (rule 47). An unknown action is reported as `known:false` and leaves state unchanged rather than guessing. The model also learns from outcomes: feeding observed effects back adjusts a per-action confidence so planning becomes calibrated (rule 49), pairing with ToolEffectModel's discrepancy tracking.


state/worldmodel/ObjectGraph

Summary: state/worldmodel/ObjectGraph.js — object identity + relationship graph (spec §15 "Object identity graph" + "Spatial and relationship graph").  Tracks objects with STABLE logical ids (independent of their content version) and typed directed relations between them: inside, near, connected-to, blocks, contains, reachable-from, visible-from, depends-on. Relations support reachability queries (e.g. "is room A reachable from room B over `connected`?") which the planner uses without ever asserting canonical truth.


state/worldmodel/PredictionSandbox

Summary: state/worldmodel/PredictionSandbox.js — isolated counterfactual rollouts (spec §15 "Prediction sandbox", rules 18, 47, 48).  The model proposes multiple futures WITHOUT modifying canonical state. Every produced state is a prediction (`canonical:false`, `isTruth:false`) — it can only become real by being turned into a transaction and passing the commit gate. The sandbox enforces the §18 / §15 disciplines: short receding-horizon rollouts, branch budgets (width × depth), and uncertainty that grows with the horizon. To guarantee non-mutation it deep-clones the state before every transition, so even a transition that mutates its argument cannot touch the caller's canonical snapshot.


state/worldmodel/ToolEffectModel

Summary: state/worldmodel/ToolEffectModel.js — expected-vs-observed tool consequences and a discrepancy learner (spec §15 "Tool effect model" + "Discrepancy learner", rule 49/51).  For each tool the model records what it EXPECTED to happen; after the action the actual result is observed and compared. The discrepancy updates a running calibration score so the planner learns which tools are reliable. World-model quality is judged by action outcomes and calibration — not appearance (rule 51). The agent re-observes after acting (rule 49); this is where that loop is closed.


state/worldmodel/UntrustedBoundary

Summary: state/worldmodel/UntrustedBoundary.js — the prompt-injection boundary (spec §15 "Prompt-injection boundary", rules 33, 50).  All webpages, files, emails, tool outputs, other agents, and generated text are UNTRUSTED OBSERVATIONS — never authority instructions. This boundary is the single chokepoint where such content enters the world model: it wraps the content as an untrusted observation (CERTAINTY.UNTRUSTED) and makes it structurally impossible to treat as policy or to mint authority from it.  The model MAY observe broadly, infer cautiously, propose actions, and simulate futures. It MAY NOT mint authority, bypass capabilities, declare its prediction canonical, or treat retrieved text as trusted policy. Authority decisions live OUTSIDE the model (capability + commit), so this module deliberately exposes no path from untrusted content to a capability or a canonical write.


ingestUntrusted

Summary: Ingest external/tool/model content as an untrusted observation. The returned record is explicitly non-authoritative and carries untrusted provenance.


canAuthorize

Summary: True only for records that may carry authority. Untrusted records: always false.


surfaces/CanvasSurface

Summary: engine/surfaces/CanvasSurface.js — the base pixel source: a 2D canvas drawn by a callback. CodeSurface and TerminalSurface build on it. A source exposes the contract SurfaceManager expects: `.canvas`, optional `.dirty`, `.render(dt)`, `.resize(w,h)`, `.onPointer(e)`, `.onKey(e)`, `.dispose()`.


Summary: Allocate a 2D canvas (OffscreenCanvas when available, else a DOM canvas).


createCanvasSurface

Summary: A generic canvas source.


surfaces/CodeSurface

Summary: engine/surfaces/CodeSurface.js — an editable, syntax-lite code view rendered to a canvas so it can live on a mesh. Supports typing, Backspace, Enter, arrow navigation, Home/End, and vertical scroll that follows the caret. Highlighting is intentionally lightweight (comments / strings / numbers / keywords) — enough to read code on a surface without pulling in a full language grammar.


surfaces/MediaSurface

Summary: Browser-media producers for RenderSurface. These sources only expose pixels that the caller explicitly supplies or requests; camera capture is never started implicitly and owned MediaStreams are always stopped on dispose.


createImageSurface

Summary: Wrap an ImageBitmap, image element, canvas, or URL as a static pixel source. URL-created images default to anonymous CORS and expose a `ready` promise.


createVideoSurface

Summary: Wrap an HTMLVideoElement or create one from a URL/MediaStream.


createCameraSurface

Summary: Request a camera only after an explicit caller action, then expose it as a video source. The returned source owns and stops every acquired track.


surfaces/RenderSurface

Summary: engine/surfaces/RenderSurface.js — a RenderSurface is a live, drawable texture fed by a source (canvas / code / terminal / camera / webgpu / image / video) that can be mapped onto a mesh as baseColor/emissive and optionally receive pointer/keyboard input via UV hit-testing.  This module owns the schema + update policy (when a surface should re-upload to the GPU) and is deliberately GPU-free: SurfaceManager performs the upload, the source produces pixels, and RenderSurfaceMaterial binds it to a mesh. Keeping these concerns separate makes surfaces reusable across demos, editor, runtime.


createRenderSurface

Summary: Create a RenderSurface descriptor.


markSurfaceDirty

Summary: Flag a surface as needing a GPU re-upload.


resizeSurface

Summary: Resize a surface (also resizes its source canvas) and flag it dirty.


surfaceNeedsUpload

Summary: Decide whether a surface should upload to the GPU this tick. Pure (no side effects) so it is unit-testable; SurfaceManager applies the result.


Summary: What feeds a surface's pixels.


Summary: Update cadence. `dirty` only re-uploads when the source flags a change; `interval` re-uploads at most every intervalMs; `realtime` every frame the surface is visible. `static` uploads once.


surfaces/RenderSurfaceMaterial

Summary: engine/surfaces/RenderSurfaceMaterial.js — bind a RenderSurface onto a mesh as baseColor or emissive, in world- or screen-space, reusing the EngineMaterial schema so surfaces flow through the same material/binding path as imported textures. The GPU resource accessor lets any renderer drop the surface's live texture into a bind group without knowing how it is produced.


createSurfaceMaterial

createSurfaceMaterial(surface, opts = {})

Summary: Create an EngineMaterial that samples a RenderSurface. Screens usually want the UNLIT workflow + the EMISSIVE slot (they emit their own light) so they stay bright regardless of scene lighting.


surfaceTextureResource

Summary: Live GPU resource for a surface, for inserting into a bind group.


materialSurfaceBinding

Summary: Is this material backed by a render surface? Returns its binding block or null.


surfaceIdFromTextureId

Summary: Map a virtual surface texture id (`surface://id`) back to the surface id.


surfaces/SurfaceInputMapper

Summary: engine/surfaces/SurfaceInputMapper.js — route input to a focused RenderSurface.  Pointer events arrive as a UV hit (from the renderer's raycast against the mesh the surface is mapped to); this maps UV → surface pixel coords and dispatches to the surface's source. Keyboard events go to whichever surface is "focused" (typically the last one clicked). Only surfaces whose `permissions.input` is true receive events — surfaces are inert by default.


uvToPixel

Summary: Convert a UV hit (with v measured top-down) to integer surface pixels.


createSurfaceInputMapper

Summary: Create an input mapper over a set of surfaces (or a SurfaceManager).


surfaces/SurfaceManager

Summary: engine/surfaces/SurfaceManager.js — owns the GPU texture lifetime and the update scheduler for a set of RenderSurfaces. Each tick it asks the policy (surfaceNeedsUpload) which surfaces changed/are due/are realtime-and-visible, renders just those sources, and uploads them — so nothing touches the GPU unless it must (dirty-only by default, interval-capped, slept when off-screen).  The actual GPU calls are isolated behind an injectable `uploader`, so the scheduling logic is testable headless (gates) without a WebGPU device.


surfaceImageSource

Summary: The uploadable image source backing a surface (canvas / img / video).


surfaceImageReady

Summary: True when an external-image source has decoded enough pixels to copy.


createSurfaceManager

Summary: Create a surface manager.


surfaces/TerminalSurface

Summary: engine/surfaces/TerminalSurface.js — an interactive terminal/REPL rendered to a canvas so it can live on a mesh. It keeps a scrollback buffer + an input line, echoes typing, and dispatches a command on Enter via `onCommand(line) -> string | string[] | void`. Safe by design: it only renders its OWN buffer — there is no shell, no eval, nothing external (the host wires whatever onCommand does).


surfaces/WebGPUSurface

Summary: engine/surfaces/WebGPUSurface.js — a surface source that ADOPTS an externally rendered GPU texture instead of uploading pixels from a canvas. The host renders into its own render target(s) and hands the current texture/view to the surface each frame via `adopt()`; SurfaceManager then exposes it like any other surface (sampleable on a mesh) with zero copies. This backs feedback/mirror effects and "stream the screen onto a screen" use-cases (SURFACE_SOURCE.WEBGPU).  Safety: it only ever adopts textures the host already owns — there is no capture of arbitrary external content.


surfaces/index

Summary: engine/surfaces/index.js — Render Surfaces barrel (spec Phase 4).  A RenderSurface turns a live source (canvas / code / terminal / camera / webgpu / image / video) into a GPU texture that can be mapped onto a mesh as baseColor or emissive and optionally receive pointer/keyboard input via UV hit-testing. The SurfaceManager owns texture lifetime + an update scheduler so nothing touches the GPU unless it must (dirty-only, interval-capped, slept when off-screen). Sources only ever render their OWN content (safety by design).


tools/IntegrationTests

Summary: Test result


TestResult

Summary: Test result


TestSuite

Summary: Test suite for organizing tests


TestStatus

Summary: Test result status


tools/aiming/GlobalAim

Summary: Get an entity's world position with an optional vertical offset. Returns null if the entity or Transform is missing.


getEntityWorldPosition

getEntityWorldPosition(ecsWorld, entityId, heightOffset = 0)


computeAimBetweenEntities

computeAimBetweenEntities(ecsWorld, sourceEntityId, targetEntityId, options = {},)

Summary: Compute an aim line from one entity to another. Returns { origin, target, direction, distance } or null if invalid.


computeAimFromEntityToPoint

computeAimFromEntityToPoint(ecsWorld, sourceEntityId, worldPoint, options = {},)

Summary: Compute an aim line from an entity to an arbitrary world-space point.


tools/animation/FBXAscii


buildMixamoSkeletonFromFBX

buildMixamoSkeletonFromFBX(fbx, opts = {})


sampleMixamoFBXAnimationClip

sampleMixamoFBXAnimationClip(fbx, skeleton, opts = {})


computeClipLocalMatricesAtFrame

computeClipLocalMatricesAtFrame(clip, skeleton, frameIndex, out = null)


computeClipGlobalMatricesAtFrame

computeClipGlobalMatricesAtFrame(clip, skeleton, frameIndex, out = null)


extractRootTranslationTrack

extractRootTranslationTrack(clip, skeleton, opts = {})


extractRootMotion

extractRootMotion(clip, skeleton, opts = {})


buildTeacherJointPositionDataset

buildTeacherJointPositionDataset(clip, skeleton, opts = {})


tools/camera/CameraController

Summary: CameraController.js - admitted state management around StandardCameraController.


cameraFocusReport

cameraFocusReport(camera, target, options = {})


cameraEntityFocusReport

cameraEntityFocusReport(camera, subjects, options = {})


focusThirdPersonCamera

focusThirdPersonCamera(camera, target, options = {})


focusThirdPersonCameraOnEntities

focusThirdPersonCameraOnEntities(camera, subjects, options = {})


cameraFocusTransitionReport

cameraFocusTransitionReport(camera, deltaSeconds, options = {})


updateCameraFull

updateCameraFull(camera, input, options = {})


cameraModeSwitchReport

cameraModeSwitchReport(camera, mode, options = {})


switchCameraMode

switchCameraMode(camera, mode, options = {})


tools/camera/StandardCameraController


standardCameraMovementResponseReport

standardCameraMovementResponseReport(currentAxes, targetAxes, options = {})


standardCameraZoomReport

standardCameraZoomReport(distance, options = {})


standardCameraBoomReport

standardCameraBoomReport(target, desiredEye, hit = null, options = {})


standardCameraMovementIntentReport

standardCameraMovementIntentReport(keys, yaw, distance, movementAxes = [0, 0, 0], responseOptions = {},)


standardCameraSphereFitReport

standardCameraSphereFitReport(radius, options = {})


standardCameraBoundsFocusReport

standardCameraBoundsFocusReport(bounds, options = {})


standardCameraFocusReport

standardCameraFocusReport(state, target, options = {})


tools/console/HtmlConsole

Summary: Render console-hook arguments without invoking getters or leaking common credential fields. Output is deliberately bounded so one diagnostic object cannot freeze the in-OS console or flood a durable log.


formatConsoleHookArguments

formatConsoleHookArguments(args, options = {})


tools/gizmos/RopeGizmo

Summary: RopeGizmo - Visual handles for manipulating rope attachment points Features: - Draggable spheres at start/end attachment points - Catenary curve visualization between endpoints - Entity snapping when dragging near entities - Visual feedback for hover/drag states Based on common patterns from Unity/Unreal constraint gizmos: - Anchor points shown as spherical handles - Lines/curves connecting attachment points - Snapping to nearby entities for easy attachment


tools/gizmos/TransformGizmo

Summary: TransformGizmo - Visual handles for manipulating entity transforms Now powered by vGPU driver


tools/gizmos/index

Summary: Gizmos - Visual manipulation handles for editor and runtime


tools/input/StandardInputController

Summary: Create an input controller state object.


standardInputActionMapReport

standardInputActionMapReport(actionMap, options = {})


rebindStandardInputAction

rebindStandardInputAction(ctrl, action, bindings, options = {})


standardGamepadMovementReport

standardGamepadMovementReport(gamepad, options = {})


standardGamepadButtonReport

standardGamepadButtonReport(button, options = {})


standardGamepadHapticEffectReport

standardGamepadHapticEffectReport(gamepad, options = {})


playStandardGamepadHaptics

async playStandardGamepadHaptics(gamepad, options = {})


standardGamepadInputReport

standardGamepadInputReport(gamepad, options = {})


pollInputGamepad

pollInputGamepad(ctrl, gamepads = undefined)


attachInputListeners

attachInputListeners(ctrl, callbacks = {})

Summary: Attach input listeners to the controller. Returns a cleanup function to remove all listeners.


detachInputListeners

Summary: Remove all input listeners.


consumeMouseDelta

Summary: Reset mouse deltas after consuming them for camera update.


consumeZoomDelta

Summary: Get current keyboard state.


getLastMousePosition

Summary: Get last mouse position.


tools/inspector/EntitiesInspectorPanel


initEntitiesInspectorPanel

initEntitiesInspectorPanel(doc, entitiesPanel, options = {})


tools/inspector/EntityInspector


createEntityInspectorModel

createEntityInspectorModel(world, options = {})


setEntityComponentFromInspector

setEntityComponentFromInspector(world, entityId, componentName, value)


tools/inspector/InspectorConfigFactory

Summary: Create a standard inspector configuration.


tools/inspector/InspectorPanel


tools/inspector/NavInspector


tools/inspector/PhysicsSandboxInspector


tools/inspector/WorldInspector


createWorldInspectorModel

createWorldInspectorModel(world, options = {})


tools/inspector/entityEditors/CameraComponentEditor


tools/inspector/entityEditors/JsonComponentEditor


renderJsonComponentEditor

renderJsonComponentEditor(doc, container, editor, value)


tools/inspector/entityEditors/LightComponentEditor


tools/inspector/entityEditors/ModelAnimationEditor


renderModelAnimationEditor

async renderModelAnimationEditor(doc, container, options = {})


tools/inspector/entityEditors/ModelMorphEditor


renderModelMorphEditor

async renderModelMorphEditor(doc, container, options = {})


tools/inspector/entityEditors/PhysicalMaterialComponentEditor

Summary: Physical Material Component Editor — renders preset dropdown + property sliders for density, elasticity, hardness, brittleness, strength, friction, restitution, deformable/breakable flags, fracture pattern, and damage status.


tools/inspector/entityEditors/PhysicsRopeComponentEditor

Summary: PhysicsRopeComponentEditor.js - Rope Property Editor Renders rope-specific properties in the entity inspector when a rope entity is selected. Uses shared ROPE_INSPECTOR_SCHEMA from RopeSchema.js for full consistency with RopeTool.


renderPhysicsRopeComponentEditor

Summary: Render the PhysicsRope component editor using shared schema


tools/inspector/entityEditors/RenderableComponentEditor


tools/inspector/entityEditors/TransformComponentEditor


tools/inspector/panels/EntitiesInspectorPanel


tools/inspector/panels/InspectorStyles

Summary: Inject shared inspector styles into the document. Safe to call multiple times - will only inject once.


applyPanelContainerStyles

Summary: Apply standard inspector panel container styles to a DOM element.


areStylesInjected

Summary: Check if inspector styles have been injected


tools/inspector/panels/NavInspectorPanel


initNavInspectorPanel

initNavInspectorPanel(doc, navPanel, options = {})


tools/inspector/panels/SpawnerInspectorPanel


initSpawnerInspectorPanel

initSpawnerInspectorPanel(doc, spawnerPanel, options = {})


tools/inspector/panels/SpellBookPanel

Summary: Spell Book Inspector Panel Browse, manage, and organize saved spells. Integrates with SpellBook for persistence.


initSpellBookPanel

initSpellBookPanel(container, options = {})


tools/inspector/panels/SpellBuilderPanel

Summary: Spell Builder Inspector Panel Real-time spell effect editor integrated with the engine inspector. Allows creating, customizing, and previewing particle-based spells.


initSpellBuilderPanel

initSpellBuilderPanel(container, options = {})


tools/inspector/panels/WorldInspectorPanel


initWorldInspectorPanel

initWorldInspectorPanel(doc, worldPanel, options = {})


tools/inspector/panels/index


tools/inspector/panels/spawner/ElementLayers


createElementLayers

createElementLayers(doc, { elements, onChange })


tools/inspector/panels/spawner/EmitterInspectorCard

Summary: EmitterInspectorCard.js - Shared emitter property card component Modular emitter editor used by both Spawner and Entities inspector panels. Configurable sections: header, elements, physics, aim.


createEmitterInspectorCard

createEmitterInspectorCard(doc, options = {})

Summary: Create a modular emitter inspector card.


tools/inspector/panels/spawner/GyroAimControl


tools/inspector/panels/spawner/PhysicsProps

Summary: Physics properties grid component Uses slider-based controls with value readouts to match element styling.


createMatterProps

createMatterProps(doc, { emitterCfg, onProfileChange })

Summary: Create the Matter / Substance section for the emitter inspector. Shows substance dropdown, temperature slider, charge slider, state badge, active physics badges, and conditional SPH params.


tools/inspector/panels/spawner/StateSelector


tools/inspector/panels/spawner/index

Summary: Deep copy element defaults for a state


getElementsForState

Summary: Deep copy element defaults for a state


Summary: Default element configurations for each state of matter


tools/inspector/panels/spell-configs/SpellBook

Summary: SpellBook.js — local stub for the external spell book persistence system.


tools/inspector/panels/spell-configs/SpellConfig

Summary: SpellConfig.js — local stub for the external spell configuration system.


tools/inspector/panels/spell-configs/SpellEffectFactory

Summary: SpellEffectFactory.js — local stub for the external spell particle effect factory.


tools/inspector/ui/InspectorControls

Summary: Create a themed section box (card-like container)


createThemedBox

createThemedBox(doc, title, options = {})


createStatItem

createStatItem(doc, label, value, color)

Summary: Create a themed stat item (for performance stats, etc.)


createThemedCheckboxRow

createThemedCheckboxRow(doc, label, checked, onChange)

Summary: Create a themed checkbox row


createThemedSlider

Summary: Create a themed slider with label and value display


getSnapPoints

getSnapPoints(min, max, snapPoints, tickCount = 6)


formatSliderValue

formatSliderValue(value, formatter, precision = 2)


createCollapsibleSection

createCollapsibleSection(doc, container, titleText, startCollapsed = false)


addSelectRow

addSelectRow(doc, section, labelText, items, getValue, setValue)


addVectorRow

addVectorRow(doc, section, options = {})


renderInspectorSchema

renderInspectorSchema(doc, container, schema, ctx = {})


addNumberRow

addNumberRow(doc, section, labelText, getValue, setValue, step)


showInspectorTextInputModal

showInspectorTextInputModal(doc, options = {})


showInspectorContextMenu

showInspectorContextMenu(doc, options = {})


addSliderRow

addSliderRow(doc, section, labelText, min, max, step, getValue, setValue, options = {},)


addCheckboxRow

addCheckboxRow(doc, section, labelText, getValue, setValue)


addTextRow

addTextRow(doc, section, labelText, getValue, setValue)


tools/inspector/ui/InspectorTheme

Summary: Apply theme styles to an element


applyThemeStyles

Summary: Apply theme styles to an element


createThemedButton

createThemedButton(doc, text, variant = "primary", onClick)

Summary: Create a themed button


createThemedInput

Summary: Create a themed input


createThemedLabel

Summary: Create a themed label


createThemedSectionHeader

createThemedSectionHeader(doc, text, icon = "")

Summary: Create a themed section header


createThemedTab

createThemedTab(doc, text, isActive = false, onClick)

Summary: Create a themed tab button


createThemedBadge

createThemedBadge(doc, text, color = "info")

Summary: Create a themed badge


Summary: InspectorTheme.js - Unified theme system for all inspector panels Provides consistent colors, spacing, and styling across all inspector UI.


tools/interaction/GrabController

Summary: Hold-to-grab interaction for the engine's picking demo path. This controller intentionally suspends rigid-body simulation while an entity follows a pick ray. Play-mode force grabs remain owned by PhysicsGrab.js. Rotational handles, collision-aware sweeps, constraints, and throw momentum remain explicit gaps rather than being approximated here.


grabControllerTimingReport

grabControllerTimingReport(distance, holdMs = 750)


startGrabCandidate

startGrabCandidate(grabState, ecsWorld, entityId, distance, holdMs = 750)


updateGrabbedEntity

Summary: Update a grabbed entity position along an admitted pick ray.


clearGrabForEntity

Summary: Clear only grab state owned by a deleted entity.


tools/picking/RayPicking

Summary: RayPicking.js - Unified, admitted camera and room/entity picking wrappers.


resolvePickFovRadians

resolvePickFovRadians(options = {}, camera = null, config = null)


getPickRayFromState

getPickRayFromState(canvas, camera, clientX, clientY, options = {})


tools/picking/RoomPicking


pickRoomSurfaceFromRay

pickRoomSurfaceFromRay(ray, options = {})


pickEntityFromRay

pickEntityFromRay(ray, ecsWorld, spawnedEntities, options = {})


tools/picking/ScreenRayCaster


screenPickInputReport

screenPickInputReport(canvas, clientX, clientY, fovRadians = SCREEN_RAY_LIMITS.defaultFovRadians)


getPickRayForCanvas

getPickRayForCanvas(canvas, cameraState, clientX, clientY, options = {})


tools/rigging/SkinWeightTransfer


transferSkinWeightsGPU

async transferSkinWeightsGPU(device, opts, limits = {})


tools/scene/SceneSerializer

Summary: Serialize spawned entities to JSON-compatible object.


exportSceneToJson

Summary: Export scene to JSON string.


downloadScene

downloadScene(options, filename = "scene.json")

Summary: Download scene as JSON file.


parseSceneJson

Summary: Parse scene JSON data.


loadSceneFromJson

Summary: Load scene from JSON and spawn entities.


loadSceneFromFile

Summary: Load scene from file input.


createSceneFileInput

Summary: Create a file input for loading scenes.


tools/spawn/GhostPreviewController


tools/spawn/PhysicsSpawnController


spawnPhysicsObjectAtPosition

spawnPhysicsObjectAtPosition(ecsWorld, position, type = "cube", spawnerProps = null, logger = null,)


tools/spawn/SpawnManager

Summary: Spawn a physics object with full render resource setup.


spawnParticleEmitter

Summary: Spawn a particle emitter at position.


tools/spawn/SpawnTypeDefaults

Summary: Get all available spawn types.


getAvailableSpawnTypes

Summary: Get all available spawn types.


getSpawnTypesByCategory

Summary: Get spawn types by category.


getSpawnTypeColor

Summary: Get the default color for a spawn type.


getSpawnTypeMeshKey

Summary: Get the mesh type for a spawn type.


resolveSpawnAppearance

Summary: Resolve color and mesh for a spawned entity. Uses spawnerProps.color if provided, otherwise falls back to type defaults.


createMeshLookup

Summary: Create a mesh lookup object from individual mesh references.


Summary: Default colors for each spawn type


Summary: Mesh type mapping (which mesh to use for each spawn type)


Summary: Spawn type categories for UI organization


version

Summary: ============================================================ Particle Realms — Canonical Version Source ============================================================ Import this module from anywhere in the engine or editor. The landing page (tests/index.html) also reads these values. ============================================================


voxel/ChunkCullCompute


voxel/ChunkRegistry

Summary: ChunkRegistry.js - Central Chunk Existence and Integrity Registry Solves: 1. Duplicate generation - fast O(1) existence check before generating 2. Corruption detection - content hash verification 3. Race conditions - atomic claim/release for chunk operations 4. Missing chunks - tracks all known chunks with metadata Uses: - In-memory Map for fast lookups - Content hashing (xxHash) for integrity verification - Temp file staging for atomic saves - Persistent index file for cross-session awareness


BloomFilter

Summary: Bloom Filter for ultra-fast chunk existence checks - O(1) time for add/check - No false negatives (if says "no", definitely doesn't exist) - Small false positive rate (~0.8%) - Uses ~2% memory of equivalent Set


Summary: Fast 32-bit hash for chunk content verification


hashVoxels

Summary: Hash voxel data for quick integrity check Uses sampling for very large arrays (faster)


Summary: Encode 3D chunk coordinates to Morton code (Z-order) Interleaves bits for better cache locality in spatial queries


Summary: Decode Morton code back to 3D coordinates


appendTrailer

Summary: Append trailer canary to data for torn write detection


verifyTrailer

Summary: Verify trailer canary is present (write was complete)


getChunkRegistry

Summary: Get the global ChunkRegistry instance


initChunkRegistry

Summary: Initialize the global registry with a storage backend


voxel/ChunkSorter

Summary: ChunkSorter - Manages chunk draw order and visibility


getCameraForward

Summary: Utility function to extract camera forward from view matrix


getCameraPosition

Summary: Utility function to extract camera position from inverse view matrix


voxel/ColoredLighting

Summary: Pack RGB + Sky into a 16-bit value


packLight

Summary: Pack RGB + Sky into a 16-bit value


unpackLight

Summary: Unpack light into components


getChannel

Summary: Get single channel from packed light


lightMax

Summary: Component-wise maximum of two light values


lightDecrement

Summary: Component-wise decrement with saturation (no underflow)


hasLight

Summary: Check if light value is non-zero


lightToRGB

Summary: Convert light to normalized RGB (0-1 range)


voxel/DirtyChunkManager

Summary: Represents a dirty chunk entry


DirtyChunkEntry

Summary: Represents a dirty chunk entry


GeometryDirtyTracker

class GeometryDirtyTracker extends DirtyChunkManager

Summary: Geometry-specific dirty tracker (for mesh rebuilds)


LightingDirtyTracker

class LightingDirtyTracker extends DirtyChunkManager

Summary: Lighting-specific dirty tracker (for DDGI updates)


parseChunkKey

Summary: Parse chunk key to coordinates


makeChunkKey

Summary: Create chunk key from coordinates


Summary: Maximum chunks that can be processed per frame


ChunkState

Summary: Chunk states


voxel/FaceListMesher


voxel/FacePool


voxel/MC33Tables

Summary: Evaluate the asymptotic decider for a face Given 4 corner values of a face (v0, v1, v2, v3 in order around face), determine how the isosurface crosses the face. For a face to be ambiguous, corners must alternate in sign: (v0 > 0, v1 < 0, v2 > 0, v3 < 0) or vice versa The asymptotic decider computes: A = v0 + v2 (diagonal sum) B = v1 + v3 (other diagonal sum) If A * (v0 - v1) > 0: connect (v0,v2) pair Else: connect (v1,v3) pair Equivalently, compute Q = v0*v2 - v1*v3 Q > 0: separating, Q < 0: connecting


isFaceAmbiguous

Summary: Check if a face has ambiguity given cube configuration


getAmbiguousFaces

Summary: Get all ambiguous faces for a cube configuration


interiorTest

Summary: Test for interior ambiguity in Case 13 configurations Case 13 has a potential tunnel through the cube center The interior test computes the bilinear patch at cube center and checks if it separates or connects the corner groups


Summary: Compute the MC33 subcase for a given cube configuration


generateWGSLTables

Summary: Generate WGSL constant arrays for MC33 tables For use in compute shaders


rotateEdges

Summary: Apply rotation to edge indices


Summary: MC33 base case for each of the 256 cube configurations Standard MC has 15 cases, MC33 extends to 33 by splitting ambiguous ones Cases 0-14: Standard unambiguous cases Cases with face ambiguity: 3, 4, 6, 7, 10, 12, 13 Cases with interior ambiguity: 4, 6, 7, 10, 12, 13


Summary: Number of subcases for each MC33 case Most cases have 1 subcase (no ambiguity) Ambiguous cases have 2-6 subcases depending on face/interior tests


Summary: Face indices for the 6 cube faces Each face defined by 4 corner indices in CCW order (from outside)


Summary: For each ambiguous case, which faces need to be tested Bit flags: bit 0 = face 0, bit 1 = face 1, etc.


Summary: Subcase lookup for each ambiguous case Index by face test results (bit flags)


Summary: Triangle configurations for MC33 subcases For ambiguous cases, provides alternate triangulations Format: [case][subcase] = [edge indices for triangles, -1 terminated] Note: This is a subset of the full 1296-entry table Full table would be generated programmatically or loaded from binary


Summary: Rotation lookup to map arbitrary configs to canonical form MC33 uses 48 symmetries (24 rotations × 2 reflections) This reduces the 256 configurations to ~23 canonical cases Each entry: [canonical_index, rotation_index]


voxel/MarchingCubesMesher

Summary: MarchingCubesMesher.js - Smooth Voxel Terrain via Isosurface Extraction INTEGRATION: - GPU compute shader for parallel cube processing - Uses VoxelMeshCompute for output buffer management - Integrates with ChunkManager for chunk-based meshing Implements the Marching Cubes algorithm for smooth terrain: - Extracts isosurface from 3D density field - Produces smooth, organic terrain instead of blocky voxels - Supports interpolated vertex positions for smooth gradients - Generates per-vertex normals for proper lighting - fBM SDF terrain (Inigo Quilez style) for native smooth noise MC33 Extension (Chernyaev 1995): - Resolves topological ambiguities for watertight meshes - Uses asymptotic decider for face ambiguity resolution - Interior tests for tunnel cases (Case 13) - 33 distinct cases vs standard 15 Based on: - Lorensen & Cline's Marching Cubes (1987) - Chernyaev's Marching Cubes 33 (1995) - Inigo Quilez fBM SDF: https://iquilezles.org/articles/fbmsdf/ Usage: const mesh = meshChunkSmooth(chunk, getDensity); const meshMC33 = meshChunkMC33(chunk, getDensity); // Watertight // Or with SDF: const density = sdfTerrain(x, y, z, config);


MarchingCubesMesher

Summary: Marching Cubes Mesher class for integration with existing systems


meshChunkSmooth

meshChunkSmooth(chunk, getDensity, options = {})

Summary: Mesh a chunk using Marching Cubes for smooth terrain


meshChunkMC33(chunk, getDensity, options = {})

Summary: Mesh a chunk using MC33 for watertight meshes Resolves topological ambiguities that cause holes in standard MC


resolveFaceAmbiguity

Summary: Test if a face is ambiguous and resolve using asymptotic decider Exported for use in GPU shader validation


smin

Summary: Smooth minimum (polynomial) - blends two distances smoothly


Summary: fBM (Fractal Brownian Motion) noise


sdfTerrain

Summary: SDF Terrain density function (Inigo Quilez style) Returns negative inside terrain, positive outside


sdfSphere

Summary: SDF Sphere primitive


sdfBox

Summary: SDF Box primitive


sdfUnion

Summary: Union of two SDFs


sdfSmoothUnion

Summary: Smooth union of two SDFs


sdfSubtract

Summary: Subtraction of SDFs (d2 from d1)


sdfIntersect

Summary: Intersection of SDFs


generateTransitionCell

generateTransitionCell(densityHigh, densityLow, face, cellSize, isolevel = 0)

Summary: Generate transition cell mesh for LOD boundary


needsTransitionCell

Summary: Check if chunk needs transition cells on a face


getTransitionRatio

Summary: Get transition cell size ratio


dualContourVertex

dualContourVertex(density, gradients, isolevel = 0)

Summary: Dual Contouring vertex placement using QEF (Quadric Error Function) Unlike Marching Cubes, places vertex at optimal position inside cell


dualContourCell

Summary: Check if cell contains surface using Dual Contouring


calculateWorldSpaceAO

calculateWorldSpaceAO(sampleDensity, wx, wy, wz, radius = 2, samples = 8)

Summary: Calculate world-space AO from density field


calculateGradientAO

calculateGradientAO(sampleDensity, wx, wy, wz)

Summary: Calculate AO from density gradient (faster, smoother)


voxel/MaterialSchema

Summary: Get material ID by name (safe lookup)


getMaterialId

Summary: Get material ID by name (safe lookup)


getMaterialName

Summary: Get material name by ID (safe lookup)


getMaterialColor

Summary: Get material color by ID


getMaterialProperties

Summary: Get material properties by ID


isTransparent

Summary: Check if material is transparent


isSolid

Summary: Check if material is solid


isFluid

Summary: Check if material is fluid


isEmissive

Summary: Check if material is emissive


validateSchema

Summary: Validate schema integrity


Summary: Material definition schema Each material has: - name: Unique identifier (used as enum key) - color: RGBA array [0-255, 0-255, 0-255, 0-255] - colorNormalized: RGBA array [0-1, 0-1, 0-1, 0-1] (auto-generated) - properties: Material behavior flags


voxel/MeshletCullCompute


voxel/NeighborCache

Summary: ChunkNeighborCache - Per-chunk neighbor references


NeighborCacheManager

Summary: NeighborCacheManager - Manages neighbor caches for all chunks


voxel/ProceduralMaterialBaker


voxel/SubChunkMeshCompute


voxel/TextureArrayManager

Summary: TextureArrayManager.js - Texture Array for Voxel Materials Uses a 2D texture array instead of a texture atlas for voxel materials. Benefits over atlas: - No UV calculation needed (just use material index) - Proper mipmapping per texture (no bleeding) - Cleaner shader code - Easy to add/remove materials Usage in shader: @group(0) @binding(X) var materials: texture_2d_array<f32>; let color = textureSample(materials, sampler, uv, materialIndex);


TextureArrayManager

Summary: TextureArrayManager - Manages a texture array for voxel materials


textureArrayMaterialNoiseDelta

textureArrayMaterialNoiseDelta(px, py, materialIndex, amplitude = 0.1)


voxel/VoxelAO

Summary: VoxelAOCalculator - GPU compute shader for AO calculation


calculateVertexAO

calculateVertexAO(isOpaque, x, y, z, face, corner)

Summary: Calculate vertex AO for a single corner


calculateFaceAO

calculateFaceAO(isOpaque, x, y, z, face)

Summary: Calculate all 4 corner AO values for a face


packAO

Summary: Pack 4 AO values into a single u32 (8 bits each)


unpackAO

Summary: Unpack u32 to 4 AO values


shouldFlipQuad

Summary: Determine if face vertices should be flipped for better AO interpolation Fixes the "anisotropy" problem where diagonal looks different based on quad orientation


voxel/VoxelConstants

Summary: Get the depth tier configuration for a given Y coordinate


getDepthTierBlend

Summary: Interpolate between depth tiers for smooth transitions


Summary: Depth tiers define how terrain generation changes with depth. Each tier has different noise parameters, materials, and features.


voxel/VoxelMeshCompute


voxel/VoxelMesher

Summary: Check if a material is transparent


isTransparentMaterial

Summary: Check if a material is transparent


isChunkFaceSolid

Summary: Check if a chunk's boundary face is fully solid (all voxels on that face are non-air) Used to skip meshing faces that are completely hidden by a solid neighbor


getChunkOcclusionMask

getChunkOcclusionMask(getNeighborChunk, cx, cy, cz)

Summary: Get occlusion mask for a chunk based on neighbor chunk boundaries Returns a bitmask where bit N is set if face N is fully occluded


getViewCullingMask

getViewCullingMask(cx, cy, cz, cameraPos)

Summary: Get view-dependent face culling mask Skips chunk faces that face away from camera (backface culling at chunk level)


meshChunk

meshChunk(chunk, getNeighborVoxel = null, occludedFaces = 0)

Summary: Generate mesh for a voxel chunk using simple per-face meshing with AO Returns separate meshes for opaque and transparent (water) geometry


meshChunkLOD

meshChunkLOD(chunk, lodLevel = 0, getNeighborVoxel = null, neighborLODs = null)


meshChunkGreedy

meshChunkGreedy(chunk, getNeighborVoxel = null)

Summary: Generate mesh using greedy meshing (fewer quads, better performance) Note: Currently does not separate water - falls back to simple meshing for chunks with water


createChunkBuffers

Summary: Create GPU buffers for chunk mesh (both opaque and water)


meshSubChunk

meshSubChunk(chunk, subSize, sx, sy, sz, getNeighborVoxel = null)

Summary: Mesh a sub-region of a chunk (8³ or 16³) Used for ultra-fast partial updates in cascaded chunk architecture


initGPUSubChunkMeshing

Summary: Initialize GPU sub-chunk meshing


hasGPUSubChunkMeshing

Summary: Check if GPU sub-chunk meshing is available


async meshSubChunk4GPU(chunk, sx, sy, sz)

Summary: Mesh a 4³ sub-chunk on GPU (10× faster than CPU)


async meshSubChunk8GPU(chunk, sx, sy, sz)

Summary: Mesh an 8³ sub-chunk on GPU (10× faster than CPU)


releaseGPUSubChunkMesh

Summary: Return GPU sub-chunk output buffers to the engine pool.


returnGPUBuffers

Summary: Return GPU buffers to pool for reuse


getGPUSubChunkStats

Summary: Get GPU sub-chunk meshing statistics


getMeshGranularity

getMeshGranularity(distance, hasRecentModifications = false, modCount = 0)

Summary: Get mesh granularity based on distance from camera (4-Tier System)


voxel/VoxelModifyCompute

Summary: VoxelModifyCompute.js - GPU Voxel Modification System Now powered by vGPU driver Performs sphere and box removal operations on voxel chunks using compute shaders. Outputs removed voxels for particle spawning.


voxel/VoxelRaycast

Summary: GPU-accelerated batch voxel raycasting system Use when processing 100+ rays per frame


raycastVoxels

raycastVoxels(origin, direction, getVoxel, options = {})

Summary: Raycast through voxel world using DDA algorithm Returns first solid voxel hit along ray


hasVoxelLineOfSight

hasVoxelLineOfSight(from, to, getVoxel, options = {})

Summary: Check line of sight between two points through voxels Returns true if no solid voxels block the path


pickBlock

pickBlock(origin, direction, getVoxel, maxDistance = 10)

Summary: Block picking - raycast from camera with face/placement info Returns both the hit block and the adjacent empty block for placement


traceVoxelPath

traceVoxelPath(origin, direction, getVoxel, maxDistance = 50, options = {})

Summary: Trace ray through voxels collecting all intersected voxels Useful for beam weapons, explosion rays, etc.


createVoxelGetter

Summary: Create a voxel getter function from ChunkManager


hasLineOfSightCombined

hasLineOfSightCombined(from, to, obstacles, getVoxel, options = {})

Summary: Combined LOS check - uses voxels AND AABB obstacles Drop-in replacement for AIAiming.hasLineOfSight


computePixelToRayMatrix

computePixelToRayMatrix(cameraPos, cameraRotation, fovRad, screenWidth, screenHeight)

Summary: Compute a single matrix that transforms screen pixel coords to world-space ray directions. This avoids per-pixel matrix multiplications in shaders. Usage: rayDir = normalize((pixelToRay * vec4(pixelX, pixelY, 1, 1)).xyz - cameraPos)


screenPixelToRay

screenPixelToRay(pixelX, pixelY, pixelToRay, cameraPos)

Summary: Generate ray from screen pixel using precomputed pixel-to-ray matrix


raycastVoxelsDebug

raycastVoxelsDebug(origin, direction, getVoxel, maxDistance = 100)

Summary: Raycast with step counting for performance debugging


stepsToHeatColor

Summary: Convert step count to heat map color (inferno palette)


triangleVoxelIntersect

triangleVoxelIntersect(a, b, c, voxelMin, voxelMax)

Summary: Check if a triangle intersects a voxel using separating axis theorem. Based on DeadlockCode's implementation.


voxelizeMesh

voxelizeMesh(vertices, triangles, resolution, boundsMin, boundsMax)

Summary: Voxelize a triangle mesh into a voxel grid


Summary: Debug render modes for raycast visualization


voxel/VoxelRenderer


voxel/VoxelSdfBrickBridge

Summary: Adapter only: voxel storage and dirty-queue ownership remain with the voxel subsystem. Callers pass the dirty entries they already admitted this frame.


buildVoxelSdfBrickPair

Summary: Convert one voxel chunk plus a one-voxel neighbor apron into independently generated coarse and fine sampled-field pages. The coarse page is an intentionally expanded conservative proxy, so a fine-page miss degrades shape accuracy instead of silently removing occupied geometry.


voxel/VoxelShaders

Summary: VoxelShaders.js - WGSL shader strings for VoxelRenderer Extracted from VoxelRenderer.js for modularity


voxel/index

Summary: engine/voxel/index.js - Voxel System Barrel Export Core voxel functionality. Other systems have been moved to: - engine/render/passes/ - Post-processing passes - engine/render/atmosphere/ - Sky and atmospheric rendering - engine/world/ - World generation, streaming, storage, time - engine/sim/physics/ - Physics systems - engine/sim/fluids/ - Fluid simulation - engine/core/gpu/ - GPU utilities - engine/core/math/ - Math utilities - engine/core/memory/ - Memory management - engine/core/profiler/ - Profiling - engine/game/ - Gameplay systems


world/FDTDSolver


world/FloatingOrigin

Summary: Shift an array of objects by the rebase offset Objects must have x, y, z properties


shiftObjects

shiftObjects(objects, shiftX, shiftY, shiftZ)


shiftPosition

shiftPosition(pos, shiftX, shiftY, shiftZ)

Summary: Shift a position array [x, y, z] by the rebase offset


Summary: Distance from local origin at which to trigger a rebase (in world units)


Summary: Chunk size for coordinate snapping during rebase


Summary: Sector-based rebase threshold (rebase when crossing sector boundaries)


world/HierarchicalCoords

Summary: Represents a position using sector + local coordinates Sector is integer grid position, local is f32-safe offset within sector


BigHierarchicalPosition

Summary: Extended hierarchical position using BigInt for extreme planet scales Use only when sector coordinates exceed MAX_SAFE_SECTOR


getSectorsInRadius

Summary: Get all sector keys within radius of a position


parseSectorKey

Summary: Parse sector key back to coordinates


getChunkKeyHierarchical

Summary: Calculate sector-aligned chunk key Useful for chunk loading that respects sector boundaries


worldToHierarchical

Summary: Convert world coordinates to hierarchical


hierarchicalToWorld

Summary: Convert hierarchical to world coordinates


toCameraSpace

Summary: Get camera-relative coordinates (f32 safe for GPU)


Summary: Size of one sector in world units (10km)


Summary: Half sector size for boundary checks


Summary: Inverse for fast division


Summary: Maximum safe integer for sector coords (before BigInt needed)


world/PhasorRays


world/PhotonicCrystal


world/PlanetPhysics

Summary: Double-precision 3D vector using hi/lo split


splitDouble

Summary: Split a double into hi/lo f32 pair for GPU precision


combineDouble

Summary: Combine hi/lo f32 pair back to double


G

Summary: Gravitational constant (scaled for game)


Summary: Default planet radius (180,000 km = 180,000,000 m)


Summary: Default planet mass (for Earth-like surface gravity)


Summary: Default rotation period in seconds (24 hours)


Summary: Minimum gravity magnitude (to avoid division issues)


world/PlanetaryCoords

Summary: Planetary world configuration


PlanetaryWorld

Summary: Planetary world configuration


ascProject

Summary: ASC (Adjusted Spherified Cube) projection Maps a point on a cube face to a point on a unit sphere


ascInverse

Summary: Inverse ASC projection Maps a direction on unit sphere back to cube face coordinates


faceToDirection

Summary: Convert face coordinates to a direction on the unit sphere


planetaryToWorld

planetaryToWorld(face, shell, u, v, planetRadius = DEFAULT_PLANET_RADIUS)

Summary: Convert planetary coordinates to world position


worldToPlanetary

worldToPlanetary(x, y, z, planetRadius = DEFAULT_PLANET_RADIUS)

Summary: Convert world position to planetary coordinates


getGravityDirection

Summary: Get gravity direction at a world position (points toward center)


getUpDirection

Summary: Get "up" direction at a world position (away from center)


planetaryChunkKey

Summary: Get chunk key for planetary coordinates


parsePlanetaryChunkKey

Summary: Parse planetary chunk key


worldToPlanetaryChunk

worldToPlanetaryChunk(x, y, z, chunkSize = 32, planetRadius = DEFAULT_PLANET_RADIUS)

Summary: Convert world position to planetary chunk coordinates


world/SurfaceAttachment

Summary: Represents a point on a surface where attachment occurs


SurfaceAttachment

Summary: Manages attachment state for a single entity


AttachmentManager

Summary: Manages attachments for multiple entities


AttachmentType

Summary: Attachment types


BreakCondition

Summary: Break conditions


Summary: Default attachment parameters


world/WorldSchema

Summary: Get biome type ID from name


getBiomeTypeId

Summary: Get biome type ID from name


getBiomeTypeName

Summary: Get biome type name from ID


validateTerrain

Summary: Validate terrain config


validateWeather

Summary: Validate weather config


validateWorldConfig

Summary: Validate world config


createDefaultTerrain

Summary: Create default terrain config


createDefaultWeather

Summary: Create default weather


createDefaultWorldConfig

Summary: Create default world config


createClimateFromPosition

Summary: Create climate from biome position


getBiomeFromClimate

Summary: Get biome from climate


getWeatherPreset

Summary: Get weather preset


getTimePhase

Summary: Get time phase for hour


Summary: Biome type definitions


Summary: Climate parameter ranges (0-1)


Summary: Climate schema for biome selection


Summary: Biome definition schema


Summary: Noise parameters schema


Summary: Erosion types


Summary: Terrain generation schema


Summary: Chunk sizes


Summary: Zone types for streaming


Summary: Chunk streaming schema


Summary: Weather types


Summary: Weather schema


Summary: Time of day phases


Summary: World time schema


Summary: Complete world configuration


world/WorldTime

Summary: WorldTime.js - Comprehensive Temporal Architecture Implements robust server-side time tracking based on: - Tick-based architecture with 64-bit precision (BigInt) - Hierarchical Timing Wheels for O(1) event scheduling - Custom calendar system derived from total ticks - Timescale ratios (game time vs real time) - Offline progression support - Network clock synchronization Reference: "Temporal Architecture in Virtual Environments"


GameDate

Summary: GameDate - A view of the world time as calendar date Never store date components directly - always derive from ticks


HierarchicalTimingWheel

Summary: HierarchicalTimingWheel - Multi-level timing wheel for efficient scheduling Level 0: Ticks (20 slots = 1 second at 20 TPS) Level 1: Seconds (60 slots = 1 minute) Level 2: Minutes (60 slots = 1 hour) Level 3: Hours (24 slots = 1 day) Level 4: Days (28 slots = 1 month)


WorldTimeSystem

Summary: WorldTimeSystem - Main time tracking system Features: - 64-bit tick precision - Configurable timescale - Event scheduling via timing wheel - Offline progression - Network sync support


Summary: Tick duration in milliseconds


Summary: High-precision ticks (100-nanosecond intervals, like .NET DateTime.Ticks)


TIMESCALE

Summary: Timescale presets (game:real ratios)


Summary: Calendar configuration


Summary: Derived constants


Summary: Moon phases


SEASON

Summary: Season names


world/ZoneManager

Summary: Represents a single zone in the world


Zone

Summary: Represents a single zone in the world


ZoneManager

Summary: Manages all zones in the world


Summary: Zone types


Summary: Zone shapes


world/generation/GPUWorldGenerator


world/generation/HydraulicErosion

Summary: HydraulicErosion - GPU particle-based erosion with momentum


world/generation/LayerMap

Summary: LayerMap - GPU-resident stratigraphic terrain data structure


world/generation/ProceduralTreeGenerator

Summary: GPU Grass Instancer - Generates millions of grass blades via mesh shaders INTEGRATION: - Uses shared particle system for grass blade physics - Uses SpatialHashCompute for wind field queries - Uses WindSimulation for dynamic wind effects Uses indirect instancing with per-blade data generated on GPU: - Position jittered from grid - Height/width variation - Wind animation parameters - LOD based on camera distance


Summary: Hash function for position-based determinism


world/generation/TectonicSimulation

Summary: TectonicSimulation - GPU plate tectonics using clustered convection


world/generation/ThermalErosion

Summary: ThermalErosion.js - GPU Material-Specific Talus Angle Erosion Implements thermal erosion (slippage) with: - Per-material talus angles (angle of repose) - Mass-conserving material transfer between cells - Support for LayerMap stratigraphy Based on: SoilMachine thermal erosion Key concept: If slope > tan(θ_material), mass transfers downhill - Sand: ~30° (gentle slopes) - Rock: ~85° (near-vertical cliffs)


ThermalErosion

Summary: ThermalErosion - GPU material-specific talus angle erosion


world/generation/UnifiedTerrainPipeline

Summary: UnifiedTerrainPipeline.js - Complete Procedural Geomorphology System Orchestrates the full terrain generation and simulation pipeline: 1. TECTONICS (Initialization Phase) - Clustered Convection plate simulation - JFA Voronoi for plate boundaries - Subduction/collision → bedrock heightmap 2. HYDROLOGY (Real-time Simulation) - Momentum-based particle erosion - Meandering river formation - Sediment transport & deposition 3. STRATIGRAPHY (LayerMap) - Multi-layer terrain storage - Per-material properties - Talus angle enforcement 4. THERMAL EROSION (Real-time) - Material-specific slippage - Cliff formation - Scree slopes Based on: Nick McDonald's research (Clustered Convection, SimpleHydrology, SoilMachine)


UnifiedTerrainPipeline

Summary: UnifiedTerrainPipeline - Orchestrates all terrain generation systems


world/generation/VoronoiTextureBlend

Summary: Sample Voronoi data at a world position (CPU fallback)


world/generation/WindErosion


world/generation/WorldGenerator


world/generation/WorldMapGenerator

Summary: WorldMapGenerator.js - Full World Map Preview Generator Generates a top-down world map from all loaded chunks, similar to Minecraft's world maps. Used for save file previews. Features: - Scans all chunks to build a complete heightmap - Color-codes terrain by material type - Height-based shading for 3D effect - Exports as PNG data URL or blob


world/generation/index


world/index


world/storage/ChunkNetworking

Summary: Versioned multiplayer chunk synchronization with legacy read compatibility. V1 remains the write format during the expand phase. V1, V2, and the original unversioned response shape can be read, allowing rolling upgrades without relabelling or discarding old traffic.


world/storage/ChunkPersistence

Summary: ChunkPersistence.js - Chunk Save/Load System Manages chunk persistence with: - Multiple save formats (binary, JSON, compressed) - Delta saves (only modified blocks) - Auto-save with configurable interval - Backup management


prepareChunkPersistenceRecord

Summary: Validate one exact v1/v2 chunk record without manufacturing an upcast.


world/storage/ChunkSerializer

Summary: Serialize complete chunk state


serializeChunk

Summary: Serialize complete chunk state


deserializeChunk

Summary: Deserialize chunk from binary data


applyDelta

applyDelta(voxels, modifications, forward = true)

Summary: Apply delta modifications to voxel array


chunkKey

Summary: Create chunk key from coordinates


parseChunkKey

Summary: Parse chunk key to coordinates


estimateChunkSize

Summary: Get serialized chunk size estimate


world/storage/DiskMeshCache

Summary: DiskMeshCache - IndexedDB-backed mesh cache


world/storage/PaletteCompression

Summary: CompressedChunk - Palette-compressed voxel storage


ChunkCompressor

Summary: ChunkCompressor - Manages compression for multiple chunks


world/storage/RLECompression

Summary: RLEChunkCompressor - RLE compression for entire chunks


HybridChunkCompressor

Summary: Hybrid compression: Palette + RLE First applies palette compression, then RLE on the indices


encodeColumn

Summary: Encode a single column using RLE


decodeColumn

Summary: Decode RLE column back to raw data


world/storage/RegionFile

Summary: RegionFile - Manages a single region file containing 32x32 chunks


RegionManager

Summary: RegionManager - High-level interface for region-based chunk storage


world/storage/StorageBackends

Summary: StorageBackends.js - Storage backend implementations Extracted from WorldStorage.js for modularity Includes: - OPFSBackend (Origin Private File System) - IndexedDBBackend (fallback) - FileSystemBackend (user-selected folder)


world/storage/VoxelCompression

Summary: Calculate CRC32 checksum


Summary: Calculate CRC32 checksum


Summary: Verify data integrity


Summary: Encode 3D coordinates to Morton code (Z-order)


Summary: Decode Morton code to 3D coordinates


generateMortonIndices

Summary: Generate Morton-order traversal indices for a cubic chunk


getMortonIndices

Summary: Get cached Morton indices for chunk size


linearToMorton

Summary: Reorder voxel data from linear to Morton order


mortonToLinear

Summary: Reorder voxel data from Morton to linear order


buildPalette

Summary: Build palette from voxel data


bitsForPalette

Summary: Calculate bits needed for palette size


paletteCompress

Summary: Compress voxels using palette compression


paletteDecompress

paletteDecompress(palette, bits, packed, count)

Summary: Decompress palette-compressed data


rleEncode

Summary: RLE compress data (auto-trigger: only encodes when beneficial) Format: Literal: byte (if byte != ESCAPE) Escape:  ESCAPE, 0, ESCAPE (literal escape byte) Run:     ESCAPE, count-3, value (run of count bytes)


rleDecode

Summary: RLE decompress data


compressChunk

Summary: Full compression pipeline for voxel chunk Pipeline: Morton → Palette → RLE


decompressChunk

decompressChunk(compressed, chunkSize = 32)

Summary: Decompress voxel chunk


encodeDelta

Summary: Encode chunk modifications as delta


decodeDelta

Summary: Decode delta modifications


compressionStats

Summary: Create a compression statistics report


testRoundtrip

Summary: Test compression roundtrip


world/storage/WorldStorage

Summary: WorldStorage - Main API for world persistence


validateWorldMetadata

Summary: Validate decoded world metadata without mutating it.


parseWorldWalHeader

Summary: Parse and validate a WAL header without mutating or persisting the input.


parseWorldWal

Summary: Strictly parse and validate an entire WAL before any recovery mutation.


world/storage/index


world/streaming/AdaptiveChunkBudget

Summary: AdaptiveChunkBudget.js - Self-optimizing chunk memory management Uses PID-style control with EMA smoothing for smooth, responsive adaptation. Based on game engine best practices for adaptive performance.


world/streaming/ChunkHistory

Summary: HistoryManager - Global history management


world/streaming/ChunkJobCoordinator

Summary: Encode 3D coordinates to Morton code (Z-order curve) Preserves spatial locality for cache-friendly iteration


Summary: Decode Morton code back to 3D coordinates


mortonBigmin

Summary: BIGMIN optimization: Find next Morton code inside query box Skips irrelevant ranges when iterating Morton-ordered data


Summary: ChunkJobCoordinator.js - Central Job Assignment for Chunk Loading Prevents duplicate chunk loads across multiple systems: - PriorityChunkLoader - ChunkStreaming - ChunkStreamingCompute - ChunkManager.updateStreaming Single source of truth for chunk job state.


world/streaming/ChunkLoadingZone

Summary: ChunkLoadingZone - Manages player movement boundaries


Summary: ChunkLoadingZone.js - Virtual Buffer Wall System Prevents players from advancing past unloaded terrain. Creates an invisible barrier at the edge of generated chunks. Benefits: - Players never see unloaded terrain - Prevents falling through world - Smooth loading experience - Configurable buffer distance Zones: - SAFE: Fully loaded, player can move freely - BUFFER: Loading in progress, soft warning - BARRIER: Not yet loaded, cannot pass


world/streaming/ChunkSeamSystem


chunkSeamSeededStructureHash3D(x, y, z, seed)


chunkSeamChunkSeed3D(cx, cy, cz, seed = 0)


chunkSeamPositionSeed3D(x, y, z, seed = 0)


world/streaming/ChunkStreaming


world/streaming/ChunkStreamingCompute


world/streaming/ChunkUpdater

Summary: ChunkUpdater.js - Block Update Queue Manager Manages block updates with: - Rate-limited updates per frame - Propagation for lighting/physics - Lazy update batching - Update coalescing


world/streaming/ChunkWorkerPool

Summary: ChunkWorkerPool - Manages a pool of Web Workers


world/streaming/MovementPredictor

Summary: MovementPredictor - Predicts player movement for chunk prefetch


world/streaming/PriorityChunkLoader

Summary: PriorityChunkLoader.js - Distance-Based Chunk Loading Loads chunks in order from closest to player outward. Uses spiral/ring pattern for optimal loading experience. Benefits: - Player sees nearby terrain first - Smooth loading experience - Efficient resource usage - Integrates with ChunkLoadingZone Patterns: - SPIRAL: Classic spiral from center - RINGS: Concentric rings outward - DIRECTIONAL: Prioritize direction player is facing


PriorityChunkLoader

Summary: PriorityChunkLoader - Manages chunk load ordering


world/streaming/ProgressiveChunkLoader

Summary: ProgressiveChunkLoader - Manages progressive LOD loading


world/streaming/index


boot

Summary: ============================================================================ PLAUNA ENGINE BOOTSTRAP ============================================================================ PlaunaDevShell is the main entry point for the Plauna UI system. It: 1. Initializes the rendering pipeline (WidgetRenderer, DOMRenderer) 2. Loads and applies themes from plauna/themes/{id}/theme.json 3. Sets up the workspace system for virtual desktops (optional GPU panels) 4. Injects base CSS for the widget gallery/showcase 5. Provides a public API for theme switching and widget rendering ARCHITECTURE FLOW: - PlaunaDevShell.boot(root, options) → PlaunaDevShell instance - _init() → loads styles, theme, workspace manager - ThemeLoader applies CSS variables to :root - WidgetRenderer converts UINode trees to DOM - WorkspaceManager (optional) handles GPU-accelerated panels USAGE: const shell = await PlaunaDevShell.boot(document.body, { logger: console }); shell.setTheme('dark'); const element = shell.render(myUINode); document.body.appendChild(element); THEME SYSTEM: - Themes live in plauna/themes/{id}/theme.json - Themes can extend other themes via "extends": "parent" - CSS variables are written to <style data-plauna-theme="1"> tags - Per-session overrides can be applied via applyOverrides() WORKSPACE SYSTEM (OPTIONAL): - Requires gpuDevice option for WebGPU support - Creates virtual desktop layers for multi-panel layouts - Supports DOM panels and GPU panels (WebGPU textures) - Managed by WorkspaceManager class


console/PlaunaConsole

Summary: PlaunaConsole - Main console system for Plauna Integrates HtmlConsole with Plauna-specific features and debugging capabilities


core/BindingEngine

Summary: Lifecycle-safe StateStore -> UINode bindings and UINode -> intent dispatch. Two-way bindings never promote local UI values into authoritative state.


core/DOMRenderer

Summary: ============================================================================ DOMRenderer - Visual Tree to DOM Renderer ============================================================================ DOMRenderer connects Plauna's retained-mode UINode system to the browser DOM. It takes a VisualTree (rooted UINode tree) and renders it to actual DOM elements. DIFFERENCES FROM WidgetRenderer: - WidgetRenderer: Converts single UINode widgets to DOM (used by widgets themselves) - DOMRenderer: Renders entire visual tree from game/engine to DOM (used by PlaunaApp) RENDERING FLOW: 1. render(visualTree) - Entry point, renders entire tree to container 2. renderNode(node) - Recursively renders node and all children 3. createDOMElement(node) - Creates DOM element based on node type 4. Applies styles, attributes, and content 5. Updates mapping tables for bidirectional lookup MAPPING TABLES: - nodeToDOM: Map<UINode, HTMLElement> - UINode → DOM element - domToNode: Map<HTMLElement, UINode> - DOM element → UINode (reverse lookup) - renderedNodes: Set<UINode> - Track which nodes have been rendered ELEMENT TYPE HANDLING: - 'text': Renders as <div> with text content - 'button': <button> element - 'input': <input> element with type, value, placeholder, validation attributes - 'image': <img> element with src, alt - 'svg': SVG namespace elements for graphics - Other: <div> as fallback DIRTY FLAG PROCESSING: - DIRTY.STYLE: Re-apply inline styles to DOM - DIRTY.LAYOUT: Re-compute position/size - DIRTY.PAINT: Re-render entire node - DIRTY.TEXT: Update text content - DIRTY.CHILDREN: Re-render child subtree UPDATE MECHANISM: - updateNode(node): Incrementally updates a single node based on dirty flags - updateDOMElement(element, node): Applies node properties to DOM element - processStyleDirty(nodes): Batch updates for style changes TEXT SERVICE: - Optional textService for internationalization - If provided, wraps text content through translation layer


core/DirtyGraph

Summary: DirtyGraph - Optimized dirty flag propagation and update scheduling. Dirty flag management pattern: - Efficient dirty flag propagation for large UI trees - Categorizes dirty flags by type (STYLE, LAYOUT, PAINT, etc.) - Batch processing of dirty nodes - Performance tracking for propagation timing Propagation rules: - LAYOUT dirtiness propagates to parent - PAINT dirtiness propagates to parent if node affects parent's paint - CHILDREN dirtiness propagates to descendants - STYLE dirtiness propagates to descendants if style affects them Architecture: - dirtyNodes: Set of all dirty nodes - dirtySets: Map of flag → Set of nodes (categorized by flag type) - propagationQueue: Queue for deferred propagations - isProcessing: Flag to prevent re-entrant propagation


core/ModuleTester

Summary: PlaunaModuleTester - Smoke-test runner for modules/widgets. Module testing pattern: - Verifies module registration and instantiation - Exposes widget properties for console diagnostics - Summarizes complex values for readable output - Tracks widget registry and available widgets Testing features: - Module registration verification - Widget instantiation testing - Property exposure and summarization - Value normalization for comparison Helper functions: - summarizeValue(): Human-readable value summaries - normalizeComparableValue(): Normalize values for comparison - isPlainObject(): Check if value is plain object


core/StateStore

Summary: Observable projection store used by Plauna bindings. The store is intentionally authority-neutral: networked UI writes arrive as projections, while user actions leave through BindingEngine intent handlers.


createStore

createStore(initialState = {}, options = {})


useStore

Summary: Framework-neutral compatibility helper. The third tuple item subscribes to future values; no React global or hidden lifecycle is required.


core/UINode

Summary: ============================================================================ UINode - Retained Visual Tree Node ============================================================================ UINode is the base class for all UI nodes in Plauna's retained visual tree. It represents a node in a virtual DOM-like tree that can be rendered to actual DOM. KEY CONCEPTS: - Retained Mode: The tree persists in memory and is incrementally updated - Dirty Flags: Bits that track what parts of the node need re-rendering - Layout Box: Computed layout metrics (position, size, margins, padding) - Event Handlers: Map of event types to handler functions - Accessibility: ARIA attributes and role information DIRTY FLAGS (bitmask): - STYLE: CSS styles changed → re-apply styles to DOM - LAYOUT: Position/size changed → re-compute layout - PAINT: Visual appearance changed → re-render to DOM - TEXT: Text content changed → update text nodes - ACCESSIBILITY: ARIA attributes changed → update DOM attributes - CHILDREN: Child nodes added/removed → re-render subtree - FOCUS: Focus state changed → update focus ring NODE STATE (bitmask): - VISIBLE: Node is visible - FOCUSED: Node has keyboard focus - HOVERED: Mouse is over the node - ACTIVE: Node is being pressed/clicked - DISABLED: Node is disabled - FOCUSABLE: Node can receive focus - CHECKED: Checkbox/radio is checked - SELECTED: Option is selected - LOADING: Node is in loading/processing state - ERROR: Node is in error/validation failure state INPUT FLAGS (bitmask): - POINTER_CAPTURE: Node captures pointer events - KEYBOARD_CAPTURE: Node captures keyboard events - DRAG_TARGET: Node is a drag target - DROP_TARGET: Node is a drop target - SCROLLABLE: Node can be scrolled RENDER FLAGS (bitmask): - CLIPS_CONTENT: Children outside bounds are clipped - OPAQUE: Node is fully opaque (optimization hint) - REQUIRES_LAYER: Needs separate compositing layer - TRANSFORM_CHANGED: Transform property changed - OPACITY_CHANGED: Opacity property changed TREE STRUCTURE: - parent: Reference to parent UINode - children: Array of child UINodes - firstChild/lastChild: Linked list pointers for fast traversal - nextSibling/previousSibling: Linked list pointers for siblings LAYOUT BOX: - x, y: Position relative to parent - width, height: Computed size - minX, minY, maxX, maxY: Computed bounds - paddingLeft, paddingTop, paddingRight, paddingBottom: Padding - marginLeft, marginTop, marginRight, marginBottom: Margin - borderLeft, borderTop, borderRight, borderBottom: Border width


DIRTY

Summary: UINode - Retained visual tree node. UINode pattern: - Base class for all UI nodes in Plauna's retained visual tree - Virtual DOM-like tree that persists in memory - Incrementally updated via dirty flags - Supports tree structure (parent/children/siblings) - Event handling and accessibility support Key concepts: - Dirty flags: Track what needs re-rendering - Layout box: Computed layout metrics - Event handlers: Map of event types to functions - Accessibility: ARIA attributes and role information


core/VisualTree

Summary: VisualTree - Manages the retained visual tree and dirty propagation. Visual tree management pattern: - Manages UINode hierarchy with root node - Dirty flag management and propagation - Update scheduling with requestAnimationFrame - Performance tracking for update timing - Callback hooks for layout, paint, accessibility updates Features: - setRoot(): Change root node (marks subtree dirty) - markDirty(): Mark node as dirty (schedules update) - markSubtreeDirty(): Mark entire subtree as dirty - update(): Main update loop (processes dirty nodes) Update queues: - layoutQueue: Nodes needing layout recalculation - paintQueue: Nodes needing paint updates - textQueue: Nodes needing text content updates - accessibilityQueue: Nodes needing ARIA updates Architecture: - root: Root UINode of the tree - dirtyNodes: Set of all dirty nodes - isUpdating: Flag to prevent re-entrant updates - updateScheduled: Flag for RAF scheduling


core/app

Summary: ============================================================================ PlaunaApp - Main Plauna Application Class ============================================================================ PlaunaApp is the main application class that integrates Plauna UI with the Particle Engine. It manages the visual tree, rendering, events, and development tools. CORE COMPONENTS: - VisualTree: Retained-mode UI tree (UINode hierarchy) - DOMRenderer: Renders visual tree to DOM elements - PlaunaEventSystem: Event handling and dispatching - ThemeManager: Theme management and CSS variable application - TransitionEngine: Animation and transition system - PlaunaTextService: Text internationalization (pretext) - PlaunaSurfaceManager: Surface/layer management - PlaunaGPUBridge: GPU integration bridge - PlaunaRegistry: Component registry DEVELOPMENT TOOLS: - TreeInspector: Visual tree inspector for debugging - StyleInspector: Style inspector for debugging - HotReload: Hot module replacement for development - PlaunaModuleTester: Module testing framework - PlaunaSmartContextMenu: Context-aware right-click menu INTEGRATION WITH PARTICLE ENGINE: - Uses ECS World from engine/ecs/world/World.js - Integrates with GPU via PlaunaGPUBridge - Uses PlaunaSurfaceManager for surface management - Text engine integration (pretext or custom) INITIALIZATION FLOW: 1. createPlaunaApp(options) - Factory function 2. PlaunaApp constructor - Sets up core components 3. initialize() - Initializes all subsystems 4. mount() - Mounts to root DOM element OPTIONS: - root: Required DOM element to mount to - getVGPU: Function to get VGPU instance - engine: Particle engine instance - editor: Editor instance (optional) - useCSS: Enable CSS injection (default: true) - textEngine: Text engine to use ('pretext' or custom) - enableModuleTester: Enable module tester (default: true) - enableSmartContextMenu: Enable smart context menu (default: true) PUBLIC API: - mount(): Mount app to root element - destroy(): Cleanup and destroy app - addComponent(): Add component to registry - getComponent(): Get component from registry - visualTree: Access visual tree instance - renderer: Access DOM renderer instance - eventSystem: Access event system instance - themeManager: Access theme manager instance LIFECYCLE: - Created via createPlaunaApp() factory - Must call mount() to display UI - Call destroy() to cleanup USAGE: const app = await createPlaunaApp({ root: document.body, getVGPU: () => vgpuInstance, engine: particleEngine }); await app.mount(); // ... use app app.destroy();


PlaunaApp

Summary: PlaunaApp - Main Plauna application class. Application architecture: - Integrates Plauna UI with Particle Engine - Manages visual tree, rendering, events, and development tools - Provides public API for component registration and access Core systems: - uiWorld: ECS World for UI entities - textService: Internationalization service - surfaceManager: Surface/layer management - gpuBridge: GPU integration bridge - registry: Component registry - events: Event system Retained-mode systems: - visualTree: UINode hierarchy - domRenderer: DOM renderer - themeManager: Theme management - transitionEngine: Animation system Development tools: - treeInspector: Visual tree inspector - styleInspector: Style inspector - hotReload: Hot module replacement - moduleTester: Module testing framework - smartContextMenu: Context-aware menu


createPlaunaApp

Summary: PlaunaApp factory function. Application factory pattern: - Creates PlaunaApp instance with provided options - Initializes core components (visual tree, renderer, events) - Sets up development tools if enabled - Returns ready-to-use app instance


core/events

Summary: PlaunaEventSystem - Event system for Plauna. Event bus pattern: - Simple publish-subscribe event system - Follows existing engine/ editor patterns - Supports multiple listeners per event - Returns unsubscribe function for cleanup - Error handling for faulty event handlers Features: - on(): Subscribe to event with callback - off(): Unsubscribe from event - emit(): Dispatch event to all listeners - once(): Subscribe for single event occurrence - removeAllListeners(): Clean up listeners


core/registry

Summary: PlaunaRegistry - Registry for views, surfaces, and templates. Registry pattern: - Centralized registration system for UI components - Follows existing engine registry patterns - Supports views, surfaces, templates, and factories - Warns on duplicate registrations (overwrites) - Provides getters for retrieving registered items Registry types: - views: UI view configurations with render mode, size, closability - surfaces: Surface definitions for GPU rendering (viewport, texture) - templates: Reusable template configurations - factories: Factory functions for component instantiation


ecs/components

Summary: Plauna ECS Components Follow existing engine component registration patterns.


editor/HotReload

Summary: HotReload - Live development tool for Plauna Provides hot module replacement and live style updates with robust validation


editor/StyleInspector

Summary: StyleInspector - Live style debugging tool for Plauna Provides real-time style inspection and editing capabilities


editor/TreeInspector

Summary: TreeInspector - Visual tree inspector for Plauna Provides debugging and inspection of the UI visual tree


index

Summary: Plauna - Advanced UI System for Particle Engine Browser-first UI runtime with hybrid DOM/GPU rendering ============================================================================ MODULE STRUCTURE ============================================================================ This is the main entry point for the Plauna UI system. It re-exports all public APIs in a structured, organized manner. Export Categories: Core System: - createPlaunaApp: Main application entry point - PlaunaModuleTester: Module testing utilities - UINode, DIRTY, NODE_STATE: Core retained-mode UI tree - VisualTree: Visual tree management UI Components: - PlaunaSmartContextMenu: Type-aware context menu for debugging - PlaunaTextService: Internationalization service (Pretext) - PlaunaSurfaceManager: Surface/layer management - PlaunaGPUBridge: WebGPU integration bridge Widget System: - Layout widgets: Grid, Divider, Spacer - Primitive widgets: Button, Panel, Text, Modal, Tooltip, Badge, Avatar, Progress, Skeleton - Form widgets: Input, Checkbox, Radio, Switch, Select, Textarea, Slider, Rating - Navigation widgets: Tabs, Dropdown, Breadcrumb, Pagination - Data view widgets: ListView, Card Utilities: - Style system: Design tokens, theme management - Console system: PlaunaConsole for debugging - Notification system: Toast, Notify - Showcase system: WidgetShowcase for widget gallery - Particle controller: ParticleController for particle integration Lab/Development: - mountPlaunaWorkbenchLab: Workbench development environment - mountShowcaseApp: Widget showcase application


input/EventRouter

Summary: EventRouter - Event capture/target/bubble routing system for Plauna Handles DOM-style event propagation with capture and bubble phases


lab/showcase-app

Summary: ShowcaseApp - Thin shell that boots the Plauna engine and mounts WidgetGallery


lab/workbench-lab


layout/Constraints

Summary: Constraints - Size constraint system for Plauna layout Handles min/max/preferred sizes and constraint resolution


layout/FlexLayout

Summary: FlexLayout - Flexbox-inspired layout engine for Plauna Provides CSS Flexbox-like layout functionality with constrained feature set


layout/LayoutSizing


resolvePlaunaLayoutSize

resolvePlaunaLayoutSize(value, containerSize, options = {})


resolvePlaunaLayoutConstraints

resolvePlaunaLayoutConstraints(style = {}, containerSize = 0)


motion/MPAFallback

Summary: MPAFallback - Cross-document view transition fallback for mobile/legacy browsers. Browsers that don't support the CSS @view-transition at-rule for MPA navigation get a minimal fade-in of the new page instead of a hard cut. This is a graceful degradation, not a full polyfill; the real cross-document transition only works in browsers that support the View Transitions API Level 2. Usage: include synchronously in the <head> of any landing page: <script src="/plauna/motion/MPAFallback.js"></script>


motion/PageTransition

Summary: PageTransition - Modern page/view blending for Plauna. Wraps the native View Transitions API (Level 1/2) where available and falls back to CSS class/transition-based cross-fades for older browsers. Designed for SPA "page" swaps, tab changes, and content fades inside a Plauna app. Usage: const pt = new PageTransition({ type: 'slide-left', duration: 350 }); await pt.start(() => { // update the DOM here });


startPageTransition

startPageTransition(update, options = {})

Summary: Convenience function for one-off transitions.


motion/PageTransitionContracts


UnsupportedPageTransitionVersionError

class UnsupportedPageTransitionVersionError extends Error


motion/PageTransitionManager

Summary: PageTransitionManager - Cross-document (MPA) view transition orchestration. This module runs on every page that opts in. It injects a shared stylesheet containing the PageTransition presets and, on supported browsers, sets the active view transition type for cross-document navigations via the pageswap and pagereveal events. Pages can control their transition with a data attribute on the <html> element: <html data-transition-preset="etch"> <html data-transition-preset="random"> <html data-transition-preset="cycle"> The default is the project's default preset (etch). If the attribute is absent or the value is unknown, the default is used.


motion/PageTransitionPresets

Summary: PageTransitionPresets - Shared transition presets and stylesheet generation. This module is the single source of truth for the keyframes and CSS used by both the same-document PageTransition engine and the cross-document PageTransitionManager. Keeping the presets in one place means SPA demos and MPA page navigation can share the same effects and the same default.


resolvePreset

resolvePreset(name, state = { index: 0 })


motion/TransitionEngine

Summary: TransitionEngine - Property animation system for Plauna Provides smooth transitions and animations for UI properties


notifications/NotificationSystem

Summary: ============================================================================ NotificationSystem - Centralized Notification Management ============================================================================ NotificationSystem provides a unified API for user notifications, separating them from debug logging and integrating with ToastManager for UI feedback. NOTIFICATION CHANNELS: 1. Toasts: UI notifications via ToastManager (top-right corner) 2. Console: Browser console.log/error/warn for debugging 3. Sounds: Optional audio feedback using Web Audio API NOTIFICATION LEVELS (priority order): - debug (0): Development debugging information - info (1): General informational messages - success (2): Success confirmations - warning (3): Warning messages - error (4): Error messages - critical (5): Critical errors requiring immediate attention NOTIFICATION TYPES: - system: System-level notifications (startup, shutdown, etc.) - action: User action feedback (clicks, submissions, etc.) - validation: Form validation errors - performance: Performance metrics and warnings - security: Security-related alerts - network: Network request status GROUPING: - createGroup(name, options): Create a notification group - Groups collect related notifications and report summary - Useful for batch operations or multi-step processes CONVENIENCE METHODS: - debug(message, type, data): Debug-level notification - info(message, type, data): Info-level notification - success(message, type, data): Success-level notification - warning(message, type, data): Warning-level notification - error(message, type, data): Error-level notification - critical(message, type, data): Critical-level notification SOUND EFFECTS: - Uses Web Audio API to generate simple beep sounds - Different frequencies for different levels - Can be disabled via enableSounds option MIN LEVEL FILTERING: - minLevel option filters notifications below specified level - Useful for suppressing debug messages in production INTEGRATION: - Uses global Toast from ToastManager for UI toasts - Toast position defaults to top-right - Console output includes prefix (default: '[Plauna]') USAGE: const notify = new NotificationSystem({ minLevel: 'info' }); notify.success('File saved successfully', 'action'); notify.error('Failed to load data', 'network', { url: '/api/data' });


particle/ParticleController

Summary: ParticleController - Manages particle effects and animations Handles particle system initialization and control for showcase


particle/bridge

Summary: PlaunaParticleBridge - Connects Plauna to Particle Engine's VGPU Follows existing VGPU patterns from ViewportPanel


style/AdaptiveThemeFactory


style/CSSGenerator

Summary: CSSGenerator - Runtime CSS generation from DesignTokens and LayerManager. CSS generation pattern: - Generates CSS custom properties from design tokens - Supports theme-based variable sets (bright/night) - Caches generated CSS for performance - Injects CSS into document via style tags - Supports z-index layer variables Architecture: - tokens: DesignTokens instance for token resolution - layerValues: LayerManager z-index values - generatedCSS: Map of cached CSS strings - styleElement: DOM style element for CSS injection - themes: Pre-defined theme variable sets


style/ComputedStyle

Summary: ComputedStyle - Style resolution and caching system for Plauna. Style resolution pattern: - Handles style inheritance from parent nodes - Resolves design token references - Computes final style values for rendering - Caches computed styles for performance - Tracks performance statistics Architecture: - cache: Map of computed style results - tokenCache: Map of resolved token values - styleCache: Map of style property resolutions - performanceStats: Metrics for cache hits/misses and timing Style categories: - Position and layout: position, display, flex properties - Sizing: width, height, min/max dimensions, flex basis/grow/shrink - Spacing: margin, padding - Visual: colors, borders, shadows, opacity - Typography: font family, size, weight, line height, alignment - Interaction: pointer events, cursor - Accessibility: visibility, z-index - Transform and animation


style/DesignTokenContracts

Summary: Accept legacy raw token maps and return a canonical, safely cloned v1 envelope.


UnsupportedDesignTokenVersionError

class UnsupportedDesignTokenVersionError extends Error


createDesignTokenExport

Summary: Emit metadata additively so legacy readers still see token categories at the root.


style/DesignTokens

Summary: DesignTokens - Design system token management. Token management pattern: - Centralized token system for Plauna styling - Manages spacing, typography, color, motion, borderRadius, shadows, zIndex - Observer pattern for token change notifications - Caching for performance optimization - Deep merge strategy for token inheritance Architecture: - tokens: Merged token object (defaults + custom) - observers: Set of callback functions - cache: Map of cached token lookups


style/LayerManager

Summary: LayerManager - Semantic z-index management system. Z-index management pattern: - Centralized z-index constants organized by stacking context - Arithmetic relationships for self-documenting code - Prevents z-index wars by providing semantic layer names - Uses isolation: isolate for stacking context isolation Stacking contexts (lowest to highest): - Layout: backdrop, surface, widget gallery - Modal: backdrop, panel - Dropdown: backdrop, dropdown - Tooltip - Notification: toast, alert Arithmetic pattern: - base = 0 - above = 1 - below = -1 - Each layer is defined relative to the previous layer


getStackingContextCSS

Summary: Create CSS for stacking context isolation. Stacking context pattern: - Uses isolation: isolate to create new stacking context - Prevents side effects from parent stacking contexts - Returns CSS object with isolation and z-index


getLayerZIndex

Summary: Get z-index value for a layer


getLayerCSSVariables

Summary: Get all layer values as CSS custom properties


style/StyleSizing


resolvePlaunaStyleSize

resolvePlaunaStyleSize(value, options = {})


style/ThemeController

Summary: ThemeController - Runtime theme management and switching. Theme switching pattern: - Manages bright/night theme switching with live CSS updates - Persists theme preference to localStorage - Listens to system theme preference (prefers-color-scheme) - Observer pattern for theme change notifications - Applies theme via data-theme attribute and CSS variables Features: - Auto-switch based on system preference - Manual theme switching with setTheme() - Theme persistence across sessions - Observer notifications for reactive updates


style/ThemeManager

Summary: ThemeManager - Theme management system for Plauna. Theme management pattern: - Provides theme registration and switching - Supports custom token overrides - Observer pattern for theme change notifications - Deep merge strategy for token inheritance - Pre-registered themes (light, dark) Architecture: - themes: Map of registered theme definitions - observers: Set of callback functions for change notifications - customTokens: Map of custom token overrides - currentTheme: Currently active theme ID


style/index

Summary: Style Module Exports Central export point for all Plauna styling utilities and managers. Exported modules: - LayerManager: Semantic z-index management system - ThemeManager: Theme registration and management - DesignTokens: Design system token management - WidgetStyleManager: Theme-aware widget styling - CSSGenerator: Runtime CSS generation - ThemeController: Runtime theme switching Usage: import { tokens, ThemeManager, layerValues } from './style/index.js';


surface/surface-manager

Summary: PlaunaSurfaceManager - Manages GPU surfaces and rendering Integrates with existing VGPU patterns


text/pretext-service

Summary: PlaunaTextService - DOM-free text measurement and layout Implements Pretext-style text measurement for Plauna


themes/ThemeContracts


validateThemeId

validateThemeId(value, label = 'Theme id')


prepareThemeVariables

prepareThemeVariables(input, { allowNull = true } = {})


themes/ThemeLoader

Summary: ============================================================================ ThemeLoader - File-Based Theme Discovery and Loading ============================================================================ ThemeLoader is a file-based theme system inspired by WordPress but modernized. It loads themes from plauna/themes/{id}/theme.json and applies CSS variables. THEME STRUCTURE: plauna/themes/ ├── _base/              # Base theme with all token defaults (required) │   └── theme.json      # Defines every possible CSS variable ├── dark/               # Dark theme (extends _base) │   └── theme.json      # Only overrides what's different from _base ├── light/              # Light theme (extends _base) │   └── theme.json ├── high-contrast/      # High contrast theme (extends dark) │   └── theme.json ├── custom/             # User starter template (extends dark) │   └── theme.json └── index.json          # Registry of discoverable themes THEME MANIFEST (theme.json): { "name": "Theme Name", "description": "Theme description", "extends": "parent-theme-id",  // Optional: parent theme to inherit from "variables": { "color-primary": "#3b82f6",  // CSS variable name → value "spacing-md": "16px", // null or omitted values inherit from parent } } THEME RESOLUTION CASCADE (highest priority wins): 1. _base theme defaults (all variables defined) 2. Parent theme variables (if extends is set) 3. Current theme variables (overrides parent) 4. Runtime overrides (applyOverrides() - per-session changes) CSS VARIABLE APPLICATION: - Variables are written to <style data-plauna-theme="1"> tag on :root - Format: --variable-name: value; - Overrides use separate <style data-plauna-overrides="1"> tag REGISTRY (themes/index.json): { "themes": ["dark", "light", "high-contrast", "custom"] } Add your theme folder name here to make it discoverable without code changes. METHODS: - discover(): Load themes/index.json and return available theme IDs - load(id): Load raw theme.json without resolving parent chain - resolve(id): Resolve full theme with parent chain merged - apply(id): Apply theme CSS variables to DOM - applyOverrides(vars): Apply per-session variable overrides - clearOverrides(): Remove runtime overrides - listThemes(): Return theme metadata for all discoverable themes


ThemeLoader

Summary: ThemeLoader - File-based theme discovery and loading. Theme loading pattern: - Loads themes from plauna/themes/{id}/theme.json - Supports theme extension via "extends" property - Resolves parent chain with cascading variable inheritance - Applies CSS variables to :root via style tags - Caches resolved themes for performance Architecture: - _cache: Resolved theme manifests (parent chain merged) - _rawCache: Raw theme.json files - _registry: Discoverable theme IDs from index.json - _styleEl: CSS variable style tag - _overrideEl: Runtime override style tag


themes/ThemePreference

Summary: Expand legacy state into both namespaced keys without contracting the old key. Older tabs may still be reading it during a rolling browser rollout.


ui/SmartContextMenu

Summary: ============================================================================ PlaunaSmartContextMenu - Context-Aware Right-Click Menu ============================================================================ PlaunaSmartContextMenu provides a context-aware right-click menu that scans the visual tree near the cursor and builds a smart action panel based on nearby UI nodes. SCANNING ALGORITHM: 1. On right-click, collectNearbyNodes() scans the visual tree around cursor 2. Uses adaptive radius based on node density (shrinks when many nodes nearby) 3. Scores each node based on type, role, text content, and distance 4. Returns top N nodes within scan radius NODE SCORING: - Inside node: +1000 + inset depth (prioritizes deeper inside) - Has role: +22 - Has text content: +10 - Has className: +8 - Button type: +25 - Input type: +18 - Menu type: +15 - Small area: +6 (prefers compact elements) ADAPTIVE RADIUS: - Base radius: 140px (configurable) - Density >= 8: 48% of base (72px min) - Density >= 6: 55% of base (80px min) - Density >= 4: 65% of base (90px min) - Density >= 2: 80% of base (112px min) - Density < 2: 100% of base (140px) DOM FALLBACK: - If visualTree is unavailable (e.g., in showcase shell), falls back to DOM scanning - Uses element._plaunaNode back-reference set by WidgetRenderer - Scans all elements in root and collects associated UINodes ACTION GENERATION: - For each nearby node, generates contextual actions - Actions include: inspect, copy text, copy ID, copy styles, toggle visibility - Actions are sorted by relevance and displayed in a radial menu VISUAL FEEDBACK: - Draws a scan ring around cursor during scanning - Highlights nearby nodes with visual indicators - Shows tie nodes (nodes with similar scores) with special styling INTEGRATION: - Requires: app (PlaunaApp), root (DOM element), visualTree (optional) - Optional: domRenderer (WidgetRenderer instance), console (logger) - Configurable: radius, maxNearby, maxActions, enabled flag USAGE: const menu = new PlaunaSmartContextMenu({ app: plaunaApp, root: document.body, visualTree: app.visualTree, domRenderer: app.domRenderer, radius: 140, maxNearby: 6, maxActions: 6 }); menu.enable();


PlaunaSmartContextMenu

Summary: PlaunaSmartContextMenu - Context-aware right-click menu. Context menu pattern: - Scans visual tree near cursor on right-click - Builds smart action panel based on nearby UI nodes - Adaptive radius based on node density - Node scoring for relevance ranking - Visual feedback with scan ring and highlights Integration: - Requires: app (PlaunaApp), root (DOM element), visualTree (optional) - Optional: domRenderer (WidgetRenderer), console (logger) - Configurable: radius, maxNearby, maxActions, enabled flag