collab/PhysicsGrab.js

Functions Compute mass proportional spring damper grab force. Uses frequency/damping ratio parameterization so the convergence rate is identical regardless of object mass. Critical damping (ζ=1) means the object reaches the cursor as fast as possible with zero overshoot. Parameters: (number[]) — [x,y,z] current object world position (number[]) — [x,y,z] current object linear velocity (number[]) — [x,y,z] where the player wants the object to go (number) — player's effective strength (kg equivalent) (number) — object mass in kg (for mass proportional kp/kd) Returns: } Update fatigue based on load this frame. Parameters: (number) — current fatigue [0,1] (1 = fresh) (number) — fraction of max strength being used [0,1] (number) — frame delta time seconds Returns: updated fatigue Effective strength considering fatigue. Even fully exhausted players retain 20% strength (adrenaline). Check if an object is too heavy to pick up at all. Returns false if mass 4x strength (can't apply meaningful force). Create a local grab state for the player's own grab. Build a play grab force op to broadcast our cursor target to peers. Other peers apply the same spring force, creating tug of war physics. Apply all active grab forces to a PhysX actor. Call this BEFORE stepPhysicsWorld each frame. Parameters: (Object) — PhysX PxRigidBody actor (Object) — PhysX WASM module (number[]) — [x,y,z] current world position (number[]) — [x,y,z] current linear velocity (Object[]) — array of { targetPos, strength, fatigue } (number) — object mass in kg for mass proportional springs Returns: } Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


collab/SpatialHashGrid.js

createSpatialHashGrid(cellSize, options = {})

gridQueryRect(grid, minX, minZ, maxX, maxZ)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: SpatialHashGrid.js O(1) spatial lookup grid for interest management and zone queries. Uses a 2D grid (XZ plane) where each cell stores a Set of entity IDs. Supports radius and AABB queries without iterating all entities. Inspired by: Photon Fusion AoI grid, SpatialOS worker partitioning. Functions Create a spatial hash grid. Parameters: (number) — Side length of each grid cell (world units) Returns: grid state Insert an entity into the grid. Parameters: (Object) — No description in source JSDoc. (number string) — Entity ID (number) — World X position (number) — World Z position Remove an entity from the grid. Parameters: (Object) — No description in source JSDoc. (number string) — No description in source JSDoc. Clear all entities from the grid. Query all entity IDs within a radius of a point (XZ plane). Returns entities whose grid position is within the radius. Parameters: (Object) — No description in source JSDoc. (number) — Center X (number) — Center Z (number) — No description in source JSDoc. Returns: matching entity IDs Query all entity IDs within an axis aligned bounding box (XZ plane). Parameters: (Object) — No description in source JSDoc. (number) — No description in source JSDoc. (number) — No description in source JSDoc. (number) — No description in source JSDoc. (number) — No description in source JSDoc. Get the stored position for an entity. Returns: null} Get the total number of entities in the grid. Constants — Update an entity's position. Alias for insert (handles cell migration). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


collab/index.js

collab/index.js
Exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/collab/index.js Barrel export for all collab modules. Exports No ES module exports detected in this file. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/bootloader.js

async bootExternalApp(options, ctx = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: bootloader.js — the Engine Compatibility Bootloader entry point. Boot flow (Phases 1 2 implemented here; 3 7 plug in via ctx hooks): 1. load source (source loader) 2. parse HTML (html ingestor) 3. static probe → profile (probe scanner + profile builder) 4. merge with cached profile(profile cache) 5. [validate] (ctx.validate — schema registry, Phase 3) 6. [heal] (ctx.heal — healing pipeline, Phase 4) 7. build scoped realm + heal DOM + scope CSS (runtime realm) 8. [interpose] (ctx.interpose — interposers, Phase 5) 9. execute guest scripts 10. cache profile, install error recovery, return an app handle The bootloader is engine agnostic: pass a with optional { storage, profileCache, gpu, scheduler, validate, heal, interpose, onError }. Classes Method Signature Summary Boot a guest app into . A booted guest app handle. Method Signature Summary Build the scoped realm for against a freshly parsed , then run it. Hard isolation path: run the guest in a sandboxed iframe (opaque origin). No host interposers/surface — the guest is self contained and can't reach the OS. Navigation is routed up via ctx.onOpenWindow. Note: the healing pipeline is skipped here (its asset healer emits parent origin blob URLs the iframe can't read; the iframe inlines assets as data: URLs instead). Rebuild and re run the guest from its cached source (Phase 7 recovery). Used by the recovery ladder and the manual Restart button. A snapshot for recovery / debugging. Functions Convenience one shot boot without holding a CompatBootloader instance. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/css-healer.js

compat/css-healer.js
Functions
scopeCss(css, scope)
scopeSelectorFor(appId)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: css healer.js — scope a guest app's CSS so it cannot style the OS shell. External WebGPU apps routinely style globally. rewrites every style rule so it only applies inside the guest's realm container (e.g. ): html, body → [data engine app="id"] canvas → [data engine app="id"] canvas → [data engine app="id"] .hud .row → [data engine app="id"] .hud .row At rules are handled correctly: @media/@supports/@container/@layer/@scope have their inner rules scoped; @keyframes/@font face/@page/@property/@import are left intact (their "selectors" are not element selectors). Functions Scope a full stylesheet string to (a selector like ). Convenience: the canonical realm scope selector for an app id. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/dom-healer.js

compat/dom-healer.js
Functions
healDom(rootEl, profile)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: dom healer.js — create DOM elements a guest app requires but that are missing. Many single file WebGPU apps assume , an overlay , a HUD , etc. already exist. The compatibility profile lists those in ; this healer ensures each exists inside the guest's realm container BEFORE the guest's scripts run, so and friends resolve instead of throwing. Functions Ensure every entry exists under . Parameters: (HTMLElement) — — the guest realm container (object) — — compatibility profile Returns: } ids that were created <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/error-recovery.js

installErrorRecovery(app, { win = (typeof window !== 'undefined' ? window : null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: error recovery.js — keep a crashing guest from taking down the OS. Installs scoped error capture and drives a recovery ladder when a guest throws repeatedly within a short window: 1. tolerate isolated errors (already recorded), 2. reboot the realm (fresh parse + heal + run), 3. reboot in SAFE MODE (network off, shader heal off, GPU limits clamped), 4. render an in realm error panel with a manual Restart — OS stays alive. Errors counted toward escalation: runtime error, promise error, script, gpu device lost. Benign infos (warnings, clamps, recovery notices) are ignored. Functions A safer variant of a profile used for safe mode reboots. Render a friendly, non fatal error panel inside the guest's realm container. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/healers/asset-healer.js
Functions
healAssets({ model, files }, report)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: healers/asset healer.js — resolve bundled relative asset references. A multi file guest references , , etc. Those relative URLs won't resolve inside the realm, so this pass rewrites any reference present in the package map to a blob URL. The created URLs are recorded on so the realm revokes them on destroy. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/healers/error-healer.js
Functions
healErrorPolicy({ profile }, report)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: healers/error healer.js — enable scoped error capture for the guest. Marks the profile so the bootloader installs error/unhandledrejection capture (Phase 7's recovery layer reads ). Kept as its own pass so the recovery policy can grow independently. Functions healers/error healer.js — enable scoped error capture for the guest. Marks the profile so the bootloader installs error/unhandledrejection capture (Phase 7's recovery layer reads ). Kept as its own pass so the recovery policy can grow independently. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/healers/gpu-healer.js
Functions
healGpu({ profile }, report)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: healers/gpu healer.js — normalise GPU related profile fields before boot. Sets a sensible and ensures the runtime healing flags the interposer relies on ( , ) are populated. The actual limit clamping happens at runtime in . Functions healers/gpu healer.js — normalise GPU related profile fields before boot. Sets a sensible and ensures the runtime healing flags the interposer relies on ( , ) are populated. The actual limit clamping happens at runtime in . <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/healers/lifecycle-healer.js
Functions
healLifecycle({ profile }, report)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: healers/lifecycle healer.js — ensure lifecycle healing flags are populated. These flags drive the interposers and the recovery layer (Phase 7): whether to recover on GPU context loss, namespace storage, and route downloads safely. Functions healers/lifecycle healer.js — ensure lifecycle healing flags are populated. These flags drive the interposers and the recovery layer (Phase 7): whether to recover on GPU context loss, namespace storage, and route downloads safely. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/healers/shader-healer.js
Functions
healShaders({ model, profile }, report)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: healers/shader healer.js — migrate deprecated WGSL attribute syntax. Older WGSL used / / / , which modern WebGPU rejects. This pass rewrites those tokens to the current / / / forms inside inline guest scripts. The patterns are WGSL specific and do not occur in normal JS, so the rewrite is safe. Gated by . Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/healing-pipeline.js

compat/healing-pipeline.js
Functions
runHealingPipeline(ctxObj)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: healing pipeline.js — ordered pre boot healing passes over a guest. Runs after probing and before the realm is built, mutating the parsed model and the profile in place. Ordered per the compat spec: DOM/CSS scoping happen in the realm itself; here we do the model/profile level passes: GPU flags → lifecycle flags → error policy → asset URL rewrite → WGSL repair. Each pass is isolated (a throwing healer never aborts the others) and appends to a human readable report returned to the caller. Functions Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/html-ingestor.js

compat/html-ingestor.js
Functions
parseHTML(html, baseUrl = null)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: html ingestor.js — parse a guest HTML document into a structured model. Uses DOMParser (scripts parsed this way are INERT — they will not execute on insertion), so we can safely inspect and relocate the DOM, then hand the extracted scripts to the runtime realm to execute in controlled order. The returned model: { doc, // the parsed Document (inert) title, scripts: [{ module, src, code, async, defer }], // document order styles: [{ inline, href, code }], // document order links: [{ rel, href }], canvases:[{ id, width, height }], assets: string[], // referenced asset URLs (img/src, etc.) } Functions html ingestor.js — parse a guest HTML document into a structured model. Uses DOMParser (scripts parsed this way are INERT — they will not execute on insertion), so we can safely inspect and relocate the DOM, then hand the extracted scripts to the runtime realm to execute in controlled order. The returned model: { doc, // the parsed Document (inert) title, scripts: [{ module, src, code, async, defer }], // document order styles: [{ inline, href, code }], // document order links: [{ rel, href }], canvases:[{ id, width, height }], assets: string[], // referenced asset URLs (img/src, etc.) } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/iframe-realm.js

compat/iframe-realm.js
Classes
class IframeRealm
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: iframe realm.js — a hard isolation execution root for UNTRUSTED guest apps. Unlike RuntimeRealm (light DOM, shared OS origin — best effort isolation), this runs the guest inside a iframe WITHOUT , so it gets a unique opaque origin and cannot touch the OS document, cookies, localStorage/IndexedDB, or kernel globals. It is a real security boundary suitable for community/unverified packages and live remote sites. The guest document is assembled self contained (bundled JS → modules with imports rewritten; bundled CSS/assets → inline/ URLs) because parent origin blob URLs are unreachable from the opaque origin iframe. A tiny injected bridge routes window.open()/anchor navigations up to the host via postMessage (the host opens them in the OS Browser). Trade offs vs RuntimeRealm: no shared WebGPU device (the iframe requests its own), and no direct syscall access (a postMessage RPC would be needed). Used only when isolation is requested. Classes Method Signature Summary Generate an unguessable per document RPC token. Build the sandboxed iframe and write the self contained guest document. Resolve once the guest document has loaded (scripts run on load). True when the frame unblocker extension is present on this OS page. Service one RPC request from the guest, then post the result back. Allowlist of bridge methods the guest may call (nothing else is reachable). Injected before guest scripts: a postMessage RPC client that backs a synchronous localStorage/sessionStorage shim (hydrated from the host's per app encrypted store, persisted asynchronously) and a host mediated fetch (so the sandboxed app's connections are routed + permissioned). Conservative "blend with the OS" stylesheet, injected


compat/iframe-realm.js

asynchronously) and a host mediated fetch (so the sandboxed app's connections are routed + permissioned). Conservative "blend with the OS" stylesheet, injected only when the guest opts in via profile.adoptHostTheme. It sets a native dark color scheme and tints selection/scrollbars with the host accent (populated at runtime by the bridge script). It deliberately does NOT restyle the guest's own layout — forcing a full theme onto a third party site usually breaks it. Injected first: route window.open + anchor + programmatic navigations to the host. Graceful degradation shims for guests that STAY sandboxed (opaque origin). An opaque origin makes the browser DENY and the Web Locks API ( ) with a SecurityError. Apps that can't switch to live embedding would otherwise crash on those throws. We install best effort, in page replacements (non persistent) so reads/writes no op instead of throwing. Injected before any guest script; harmless on live frames (which never load this srcdoc) and a no op where the native APIs already work. Navigate this app's own iframe to a new URL (same frame navigation). Drops the sandboxed srcdoc and loads the live URL so the user stays inside the same panel rather than popping the OS Browser. Live http(s) URLs stay sandboxed (allow scripts). A CROSS ORIGIN live page additionally gets allow same origin so it functions as a real site (its ESM/CSS/cookies/storage work on ITS OWN origin) — it still cannot reach the OS document/storage because that origin differs from the OS. OS origin and proxied content never receive allow same origin (see setSandbox). Is cross origin to the OS document? (false on parse failure — fail safe.) Credentialless ("isolated") embedding mode. A loads in an ephemeral, cookieless context, which lets the OS embed cross origin


compat/iframe-realm.js

on parse failure — fail safe.) Credentialless ("isolated") embedding mode. A loads in an ephemeral, cookieless context, which lets the OS embed cross origin sites EVEN when the OS page is cross origin isolated (COEP: require corp — needed for SharedArrayBuffer / hi res timers), at the cost of no shared login/cookies inside the frame. Opt in (default OFF to preserve logged in sessions): set (OS settings) or a per app . No op where the attribute is unsupported. Set the iframe sandbox. is added ONLY for live cross origin documents (so third party sites work); it is always withheld from the trusted srcdoc wrapper and from any OS origin proxy/srcdoc content (where allow scripts + allow same origin would defeat the


compat/index.js

compat/index.js
Functions
createCompat(ctx = {})
Constants
Re-exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/compat/index.js — the Engine Compatibility namespace. returns the API used across the OS: await engine.compat.boot({ id, source, mount, mode, permissions }); wires the compat layer to the host engine/kernel (all optional): storage — kernel.storageManager (profile/snapshot persistence) gpu — { getOrCreateSharedDevice(adapter, desc), format, healDeviceDescriptor } scheduler — engine frame scheduler (RAF interposition, Phase 5/6) validate — async (profile) = { valid, errors } (Phase 3) heal — async ({ model, profile, files, appId }) (Phase 4) interpose — async ({ realm, profile, app, ctx }) (Phase 5) onError — (info) = void Phases 3 7 register their hooks onto the same ctx, so this factory stays the single, stable entry point as the pipeline grows. Functions Constants Re exports , , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


makeFetchShim({ profile, onError, realm = null } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/fetch.js — default deny network egress for guest apps + serving bundled package files. Resolution order: 1. If the ref resolves to a bundled package file (e.g. or a ), serve it directly from the file map — relative paths in a blob loaded module would otherwise 404 against the OS origin. 2. Same origin, relative, and requests pass through. 3. Cross origin requests are blocked unless the profile granted — preventing a wrapped third party app from phoning home. Functions interposers/fetch.js — default deny network egress for guest apps + serving bundled package files. Resolution order: 1. If the ref resolves to a bundled package file (e.g. or a ), serve it directly from the file map — relative paths in a blob loaded module would otherwise 404 against the OS origin. 2. Same origin, relative, and requests pass through. 3. Cross origin requests are blocked unless the profile granted — preventing a wrapped third party app from phoning home. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


makeUrlShim(realm, { metrics, onExport } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/file export.js — safe blob/download handling for a guest realm. Guests export files via + an click (or ). Two problems: created object URLs leak if never revoked, and downloads are invisible to the OS. This shim wraps so every is tracked (and revoked on realm destroy) and each export is counted into the app's metrics — without blocking the legitimate download. Functions interposers/file export.js — safe blob/download handling for a guest realm. Guests export files via + an click (or ). Two problems: created object URLs leak if never revoked, and downloads are invisible to the OS. This shim wraps so every is tracked (and revoked on realm destroy) and each export is counted into the app's metrics — without blocking the legitimate download. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/interposers/gpu.js
Functions
makeGpuShim({ metrics, onError } = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/gpu.js — wrap for a guest realm. The guest keeps using the real WebGPU implementation, but through a shim that: • clamps to what the adapter actually supports (a very common crash cause when an app hard codes limits from a beefier GPU), • drops unsupported instead of throwing, • counts calls into the app's metrics, • reports device loss (so the recovery layer can react) without spamming on intentional . It deliberately does NOT share the kernel's device — each guest gets its own device so it cannot corrupt OS GPU state. Sharing/surface hand off is Phase 6. Functions interposers/gpu.js — wrap for a guest realm. The guest keeps using the real WebGPU implementation, but through a shim that: • clamps to what the adapter actually supports (a very common crash cause when an app hard codes limits from a beefier GPU), • drops unsupported instead of throwing, • counts calls into the app's metrics, • reports device loss (so the recovery layer can react) without spamming on intentional . It deliberately does NOT share the kernel's device — each guest gets its own device so it cannot corrupt OS GPU state. Sharing/surface hand off is Phase 6. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


installInterposers({ realm, profile, ctx, app } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/index.js — install per realm API shims for a guest app. Guests run in the shared window, so we cannot replace globals process wide without breaking the OS. Instead we: 1. build a per realm of shims (gpu/raf/storage/fetch), 2. register it at , 3. return a code that prepends a tiny prelude to each guest script which LEXICALLY SHADOWS the relevant globals with the shims. Module scripts: the prelude's top level s shadow the globals within the module's own scope. Classic scripts: wrapped in an IIFE (only when there's a single classic script, to avoid breaking cross script global sharing). Which globals are shadowed is driven by , minimising both collision risk and overhead. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


makeOpenShim({ onOpenWindow, onError } = {})

makeWindowProxy(openShim, { onOpenWindow, onError } = {})

makeLocationProxy({ onOpenWindow, onError } = {})

installNavCapture(realm, { onOpenWindow, onError } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: navigation.js — keep a guest's "open a new window" / external navigation INSIDE the OS instead of spawning a real browser popup or navigating the whole OS page away. Guests run in the shared OS document (light DOM, not an iframe), so an unhandled click or would either pop a real browser window or unload the entire OS. We intercept both and hand the URL to the host via — the host decides where it goes (default: the in OS Browser app). Two mechanisms: 1. DOM click capture on the realm container — anchors that open a new window (target= blank/ new) or point off origin are cancelled and routed. Always installed (cheap, prevents the OS unload footgun). 2. Lexically shadowed / / — routes JS driven popups and redirects. Only bound when the probe detected such usage ( ), to minimise shadowing blast radius. Functions Replacement for window.open / open(): route the URL, return a harmless stub. Proxy over the real window that only overrides and writes. Proxy over location: reads pass through; href=/assign/replace are routed. Capture phase click handler on the realm container. Cancels + routes anchor navigations that would open a new window or leave the OS origin. Returns a cleanup function (also registered on the realm). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/interposers/raf.js
Functions
makeRafShim(realm)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/raf.js — managed requestAnimationFrame for a guest realm. Guest render loops are the 1 resource leak when an app's window closes: the raw loop keeps running forever. This shim tracks every pending frame and cancels them all on , so closing a guest window actually stops its GPU work. Errors thrown inside a frame callback are reported instead of silently killing the loop's owner. Functions interposers/raf.js — managed requestAnimationFrame for a guest realm. Guest render loops are the 1 resource leak when an app's window closes: the raw loop keeps running forever. This shim tracks every pending frame and cancels them all on , so closing a guest window actually stops its GPU work. Errors thrown inside a frame callback are reported instead of silently killing the loop's owner. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/interposers/storage.js
Functions
makeStorageShim(appId, backing)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/storage.js — per app namespaced localStorage / sessionStorage. Guests freely use and . Left unscoped they would collide with each other and with the OS. This shim transparently prefixes every key with and supports both the Storage method API and direct property access (via a Proxy). Falls back to an in memory store when Web Storage is unavailable. Functions interposers/storage.js — per app namespaced localStorage / sessionStorage. Guests freely use and . Left unscoped they would collide with each other and with the OS. This shim transparently prefixes every key with and supports both the Storage method API and direct property access (via a Proxy). Falls back to an in memory store when Web Storage is unavailable. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


makeWorkerShim(realm, RealWorker = (typeof Worker !== 'undefined' ? Worker : null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: interposers/worker.js — resolve guest Worker(url) references to bundled blobs. A guest's references a path relative to its original document, which won't resolve once the guest runs from blob URLs in the OS realm. This shim rewrites a relative/bundled worker URL to its pre linked module blob (imports already rewritten + shims applied), or a blob of the bundled file. Remote/absolute URLs pass through unchanged. Returns a Worker subclass, or null if Worker is unavailable. Functions interposers/worker.js — resolve guest Worker(url) references to bundled blobs. A guest's references a path relative to its original document, which won't resolve once the guest runs from blob URLs in the OS realm. This shim rewrites a relative/bundled worker URL to its pre linked module blob (imports already rewritten + shims applied), or a blob of the bundled file. Remote/absolute URLs pass through unchanged. Returns a Worker subclass, or null if Worker is unavailable. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/module-linker.js

buildModuleBlobs({ files, transform = null, onWarn = null, resolveBare = null, resolveExternal = null, urlKind = 'blob' } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: module linker.js — turn an in memory file map into runnable blob URL modules. Loading an ES module from a URL loses its path context, so relative imports ( ) and relative resolution break (the blob has no directory). Following the es module shims technique, we rewrite every relative / bundled import specifier in each JS module to the URL of its resolved target (created in dependency order), optionally apply a code transform (the interposer prelude / shader healing), and return a map plus a resolver for inline module imports. Bare specifiers ( ) may be resolved by the caller provided import resolver (import map / CDN fallback). Absolute/remote URLs are left untouched. Functions Build blob URL modules for every bundled JS file, with relative imports rewritten to reference each other's blob URLs. Parameters: (object) — No description in source JSDoc. Returns: {{ Build a resolver for BARE import specifiers ( , , subpaths) from a compat profile. Resolution order: 1. exact match in 2. longest trailing slash prefix match ( → base) in the map 3. CDN fallback when (default CDN https://esm.sh/, overridable via ) Returns null when nothing matches (the import is left unresolved). A bare specifier: not relative (./ ../ /), not an absolute/remote URL. Collect every (string literal) import specifier from module code. Replace import specifiers using . When it returns a falsy value the original specifier is kept (bare/remote/cyclic). Resolve an import specifier to a bundled file path, or null when it is bare (no leading ./ ../ or /) or absolute/remote. Tries the literal path, then / , then . <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see


compat/module-linker.js

Tries the literal path, then / , then . <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/probe-scanner.js

compat/probe-scanner.js
Functions
scanSource(model, files = null)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: probe scanner.js — statically detect what a guest app uses. Combines the parsed DOM model with a regex scan of all script source to infer the , , and sections of a compatibility profile. This is a heuristic pass (static, no execution) — the healing + interposition layers refine it at runtime and the profile cache promotes it once it boots. Functions Parameters: (object) — — from parseHTML() (Map<string,string Uint8Array ) — — bundled file map. When given, Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/profile-builder.js

compat/profile-builder.js
Functions
buildProfile(id, scan, opts = {})
mergeProfiles(saved, fresh)
profilePermissionList(profile)
async sha256Hex(str)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Build a full profile from a static scan result. Parameters: (string) — No description in source JSDoc. (object) — — { sourceType, sourceHash, liveSource } Merge a saved profile with a freshly scanned one. Saved healing/permissions decisions win (they were promoted as working); newly detected requirements and / flags are unioned in. Map a profile to a kernel/AppRegistry permission list (best effort). SHA 256 hex of a string (used for source/version hashing). Constants — profile builder.js — assemble & merge compatibility profiles. A profile is the durable description of what a guest app needs and how to heal it. The static scanner produces a fresh profile; the cache may hold a saved one from a previous version. reuses known good healing decisions and layers in newly detected requirements. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/profile-cache.js

compat/profile-cache.js
Classes
class ProfileCache
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: profile cache.js — persist & version compatibility profiles. Storage layout (via the kernel StorageManager facade): /os/compat/profiles/{id}.json ← active (stable or testing) profile /os/compat/index.json ← { [id]: { knownVersions: [...] } } /os/compat/snapshots/{id}/{ts}.json ← runtime snapshots (Phase 7) If no storage facade is provided (or a write fails), it degrades to an in memory cache so the bootloader still works in a bare harness/test. Classes Method Signature Summary Find a saved profile for an app id (or null). Save/promote a profile. Tracks knownVersions by sourceHash, marking the newest as 'testing' until flips it to 'stable'. Mark a hash as stable (it booted successfully). Known versions for an app id. True if this exact source hash was seen and marked stable before. Persist a runtime snapshot (Phase 7). Forget everything cached for an app id: in memory profile, persisted profile JSON, runtime snapshots, and the index entry. Used when an app is uninstalled with "also delete cached data". <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/runtime-realm.js

compat/runtime-realm.js
Classes
class RuntimeRealm
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: runtime realm.js — a controlled, scoped execution root for a guest app. Trusted same origin guests (Mode A/B) reference elements via , so the realm is a SCOPED LIGHT DOM container ( ) rather than a shadow root — must still resolve. Isolation comes from: • CSS scoping (css healer) so guest styles can't touch the OS shell, • API interposition (Phase 5) so guest browser calls route through the engine, • DOM healing so required elements exist before scripts run. Scripts parsed by DOMParser are inert; the realm re executes them in document order: classic inline → fresh <script ; module inline → blob import(); src → resolved against the package file map (blob) or left as a URL for the browser. Classes Method Signature Summary The guest's original base URL (set for live/remote sources; null for local packages). Register a code transform applied to every guest script before execution. Register a teardown hook run on destroy() (used by interposers). Number of classic (non module) guest scripts. Build the scoped DOM (styles + healed body), ready for execute(). Install interposers (if any) then execute guest scripts in order. Apply the interposer transform to inline guest code (not external src). Resolve a script/asset src against the package file map, else return as URL. Resolve a relative reference (href/src) to a bundled file path, trying the literal path then resolution against the entry's directory. Null if remote, absolute, or not bundled. Read a bundled text file (e.g. a linked stylesheet) as a string. Public: resolve a relative fetch ref to bundled file content + MIME type, or null. Lets the fetch shim serve / wasm from the package file map instead of hitting the network (and


compat/runtime-realm.js

relative fetch ref to bundled file content + MIME type, or null. Lets the fetch shim serve / wasm from the package file map instead of hitting the network (and 404ing). Public: resolve a Worker(url) reference to a runnable URL — preferring the pre linked module blob (imports rewritten + shims applied), else a blob of the bundled file. Returns the original url when it isn't a bundled file. Rewrite CSS url(...) references to bundled assets into blob URLs. Lightweight DOM snapshot for recovery (Phase 7 extends this). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/schema-registry.js

compat/schema-registry.js
Classes
class CompatSchemaRegistry
Functions
validateProfile(profile)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: schema registry.js — validate a compatibility profile before boot. Self contained: a tiny JSON Schema subset checker (type / required / enum / properties / items / additionalProperties) plus which also applies cross field consistency rules (e.g. GPU pipelines imply uses.webgpu). The bootloader calls this via ; Package Studio can call to preview problems before compiling. Classes Method Signature Summary Functions Validate a full compatibility profile: structural schema + consistency rules. Returns: } Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/schemas.js

compat/schemas.js
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: schemas.js — declarative schemas for the compatibility profile and its parts. Kept as plain JS descriptors (not .json) so the engine module is self contained and needs no fetch. Validated by 's tiny checker, which supports: type, required, enum, properties, items, additionalProperties. Constants — schemas.js — declarative schemas for the compatibility profile and its parts. Kept as plain JS descriptors (not .json) so the engine module is self contained and needs no fetch. Validated by 's tiny checker, which supports: type, required, enum, properties, items, additionalProperties. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/source-loader.js

compat/source-loader.js
Functions
async loadSource(source, ctx = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: source loader.js — load a guest app's source from any supported origin. Supported shapes: string → treated as raw HTML if it looks like HTML, else a URL { html } → raw HTML string { url, fetch? } → remote fetch (CORS aware; optional custom fetch) { file: File } → an imported File (uses .text()) { files: Map object, entry } → an in memory file map (folder/zip), entry = HTML path { vfsPath, storage } → read from the OS VFS via a StorageManager Returns: { html, files: Map<string,string ArrayBuffer , baseUrl, sourceType, sourceHash } Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: surface/engine texture surface.js — present the guest's render into an engine texture instead of a DOM canvas (so it can be composited in the 3D/GPU UI). STUB: the full implementation redirects the guest's WebGPU context to an offscreen target on the shared kernel device, then imports the result as an engine texture each frame. That requires the canvas interposer to hand the guest a wrapped context and the kernel compositor to accept an external texture. Until that lands, is false so falls back to the webgpu canvas surface — the profile can already request this mode, so flipping it on later needs no guest changes. Classes surface/engine texture surface.js — present the guest's render into an engine texture instead of a DOM canvas (so it can be composited in the 3D/GPU UI). STUB: the full implementation redirects the guest's WebGPU context to an offscreen target on the shared kernel device, then imports the result as an engine texture each frame. That requires the canvas interposer to hand the guest a wrapped context and the kernel compositor to accept an external texture. Until that lands, is false so falls back to the webgpu canvas surface — the profile can already request this mode, so flipping it on later needs no guest changes. Method Signature Summary <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/surface/offscreen-surface.js
Classes
class OffscreenSurface
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: surface/offscreen surface.js — render the guest on an OffscreenCanvas. STUB: intended for guests that can run their render loop on a worker / detached canvas (transferControlToOffscreen) for isolation and throttling. Behind the same Surface interface; is false until the offscreen transfer + present path is implemented, so falls back to webgpu canvas. Classes surface/offscreen surface.js — render the guest on an OffscreenCanvas. STUB: intended for guests that can run their render loop on a worker / detached canvas (transferControlToOffscreen) for isolation and throttling. Behind the same Surface interface; is false until the offscreen transfer + present path is implemented, so falls back to webgpu canvas. Method Signature Summary <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/surface/surface-manager.js
Functions
selectSurface(profile, deps = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: surface/surface manager.js — pick the presentation surface for a guest. Selected by . (and ) are fully implemented; / are stubs that report , so we transparently fall back to the canvas surface — the profile can request them today and they'll light up when implemented, with no guest changes. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compat/surface/webgpu-canvas-surface.js
Classes
class WebgpuCanvasSurface
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: surface/webgpu canvas surface.js — default presentation: the guest's own <canvas inside the realm container. For trusted same origin guests this is mostly pass through (the app configures its own WebGPU canvas context). The surface's job is to LOCATE the primary canvas and, when is enabled, keep its backing store sized to the container with a clamped device pixel ratio — fixing the common "canvas stuck at 300×150 / wrong DPR" class of bugs without fighting an app that manages its own sizing. Classes surface/webgpu canvas surface.js — default presentation: the guest's own <canvas inside the realm container. For trusted same origin guests this is mostly pass through (the app configures its own WebGPU canvas context). The surface's job is to LOCATE the primary canvas and, when is enabled, keep its backing store sized to the container with a clamped device pixel ratio — fixing the common "canvas stuck at 300×150 / wrong DPR" class of bugs without fighting an app that manages its own sizing. Method Signature Summary <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


config/EngineConfig.js

config/EngineConfig.js
Functions
parseSimpleYaml(text)
async loadEngineConfig(options = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


config/EngineDefaultConfig.js

config/EngineDefaultConfig.js
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


config/EngineState.js

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create GPU state object Create water pass state object Used for screen space fluid/water/metaball rendering Create scene configuration state (merge with engine.cfg overrides) Create physics configuration state Create ECS state object Create spawn/ghost state object Create particle system state object Create volumetric smoke state object Create render settings state Create camera state object Create input state object Create audio state object Create all state objects at once. Parameters: (Object) — Configuration options (Object) — Overrides for config state (Object) — Overrides for physics state (Object) — Overrides for render state Returns: All state objects Apply engine.cfg values to config state. Call this after loading engine.cfg. Parameters: (Object) — Config state to update (Object) — Loaded engine.cfg values Apply engine.cfg values to physics state. Parameters: (Object) — Physics state to update (Object) — Loaded engine.cfg values Constants — Default configuration values (can be overridden by engine.cfg) — Default physics values — Default render settings <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/AppBootstrap.js

core/AppBootstrap.js
Functions
async bootstrapApp(options)
createMainLoop(options)
async runApp(options)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: AppBootstrap.js Application bootstrap helper Consolidates common app initialization: WebGPU check, canvas ready, config loading, ECS world, GPU init, and main loop setup. Functions Bootstrap a complete application. Parameters: (Object) — Bootstrap options (HTMLCanvasElement) — Canvas element (Object) — GPU state object (Object) — ECS state object (Object) — Config state object (Object) — Physics state object (Object) — Render state object (string) — World name (default: "AppWorld") (string) — Config file URL (default: "./engine.cfg") (Function) — Function to apply config overrides (Function) — Logger Returns: { device, world } or throws on failure Create main loop with standard update/render pattern. Parameters: (Object) — Loop options (Object) — ECS state (Function) — World step function (Function) — World frame step function (Function) — Input sync function (Function) — Camera update function (Function) — Grab update function (Function) — Simulations step function (Function) — Scene draw function (Function) — Loop creator function (Object) — Render state for FPS tracking (Function) — Logger Full app bootstrap + loop in one call. Parameters: (Object) — All options combined Returns: { device, world, loop } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/EngineIntegration.js

async initResourceManagement(device, options = {})

submitStreamingJob(callback, data = null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes High performance particle emitter using SoA Method Signature Summary Emit a single particle Emit burst of particles Update all particles (call each frame) Get particle data for GPU upload Get statistics Render command builder using object pools Method Signature Summary Add a draw command Sort commands by sort key Execute all commands Clear and return commands to pool Functions Initialize resource management for the game Call this during game initialization after WebGPU device is ready Parameters: (GPUDevice) — WebGPU device (Object) — Configuration options Frame wrapper that handles resource management automatically Usage: Parameters: (Function) — Your frame update function Async frame wrapper for async game loops Submit physics job to scheduler Submit AI job to scheduler Submit streaming/loading job to scheduler Submit background cleanup job Constants — Schema for high performance particle system using Structure of Arrays — Schema for entity transforms using Structure of Arrays Re exports , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/EntitySystem.js

core/EntitySystem.js
Classes
class EntitySystem
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: EntitySystem — lightweight entity registry used by LIFE narrative systems. This is intentionally a simple in memory map. The ECS runtime lives in the engine simulation layer; narrative modules just need a stable handle to the active entity collection they are narrating. Classes EntitySystem — lightweight entity registry used by LIFE narrative systems. This is intentionally a simple in memory map. The ECS runtime lives in the engine simulation layer; narrative modules just need a stable handle to the active entity collection they are narrating. Method Signature Summary <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/ResourceManager.js

core/ResourceManager.js
Classes
class ResourceManager
Constants
Re-exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ResourceManager.js Unified High Performance Resource Management Central facade integrating: Host Memory (RAM): Slab Allocators, Object Pools, SoA Containers Device Memory (GPU): Ring Buffers, Buddy Allocators, Texture Management Task Scheduling: Job System, Worker Pools, Frame Budgeting Based on architectural specification for zero allocation, high throughput WebGPU applications targeting 60+ FPS. Classes Unified resource management facade Method Signature Summary Initialize the resource manager Begin a new frame call at START of render loop Process scheduled jobs within frame budget Update all registered systems End frame call at END of render loop Allocate float array from frame slab Allocate a 4x4 matrix Allocate vec3 (padded to vec4) Allocate vec4 Get object from pool Return object to pool Create or get an SoA container Allocate and upload uniform data Allocate and upload dynamic vertex data Allocate static geometry (persistent) Free static geometry Get or create cached bind group Create or get texture Get texture by ID Submit job Submit critical job Submit to worker pool Register system for ordered updates Get time remaining in frame budget Check if over frame budget Handle GPU device loss Restore after device loss Get current FPS Get frame time statistics Get comprehensive statistics Log comprehensive report Profile next frame Run comprehensive benchmark and return optimal settings Benchmark memory allocation Benchmark GPU operations Benchmark scheduler throughput Compute overall performance score (0 100) Generate optimal settings recommendations Apply benchmark recommendations to config Shutdown and cleanup Constants Re exports , , , , , , <! HUMAN NOTES Notes & Examples


core/ResourceManager.js

settings recommendations Apply benchmark recommendations to config Shutdown and cleanup Constants Re exports , , , , , , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compressAnimationTrack(track, options = {})

reduceKeyframes(track, tolerance = 0.001)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: AnimationCompression.js Animation Data Compression Compresses skeletal animation data using: Quaternion compression: 37.5% reduction (16 bytes → 10 bytes) DCT temporal compression: 60 80% reduction Delta encoding: Store only changed bones Keyframe reduction: Remove redundant frames Typical compression: 60 80% reduction for skeletal animations Functions Compress animation track (position, rotation, or scale) Parameters: (Object) — { times: Float32Array, values: Float32Array, type: 'position' 'rotation' 'scale' } (Object) — { lossless: boolean } Set lossless=true for zero quality loss Returns: Compressed track data Decompress animation track Compress full skeletal animation Parameters: (Object) — { name, duration, tracks: Map<boneName, track } Returns: Compressed animation Decompress skeletal animation Remove redundant keyframes that can be interpolated Parameters: (Object) — Animation track (number) — Maximum error tolerance Returns: Optimized track Compress multiple animations <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: CompressionUtils.js Unified Compression Utilities Provides compression techniques for various data types: Variable Length Integer Encoding (VLInt) Quantization (Float32 → Int16/Int8) Run Length Encoding (RLE) Delta Compression Octahedral Normal Encoding Quaternion Compression Based on research from particle snapshot compression achieving 390x compression Functions Pack small integers into fewer bytes using variable length encoding Most indices are small, so we can use 1 2 bytes instead of 4 Encoding: 1 byte: 0xxxxxxx (0 127) 2 bytes: 10xxxxxx xxxxxxxx (128 16,383) 3 bytes: 11xxxxxx xxxxxxxx xxxxxxxx (16,384 4,194,303) Unpack variable length encoded integers Quantize float to int16 within range [ range, +range] Achieves 50% memory reduction with minimal precision loss Dequantize int16 back to float Quantize array of floats to Int16Array Dequantize Int16Array back to Float32Array Quantize to int8 for even more compression (75% reduction) Use for data that doesn't need high precision (normals, colors) Encode 3D unit normal to 2D octahedral coordinates Industry standard technique used in AAA games Reference: "A Survey of Efficient Representations for Independent Unit Vectors" Decode octahedral coordinates back to 3D normal Encode array of normals (vec3) to Int16Array Input: Float32Array [nx, ny, nz, nx, ny, nz, ...] Output: Int16Array [x, y, x, y, ...] (66% smaller) Decode array of normals back to Float32Array Compress quaternion by dropping smallest component Technique: Store 3 largest components + index of dropped component Used in animation systems for skeletal rigs Decompress quaternion by reconstructing dropped component Run Length Encode an array of values Perfect for voxel


Used in animation systems for skeletal rigs Decompress quaternion by reconstructing dropped component Run Length Encode an array of values Perfect for voxel data with large empty regions Returns: [[value, count], [value, count], ...] Decode run length encoded data RLE with VLInt encoding for maximum compression Returns Uint8Array: [value, count, value, count, ...] Delta encode array (store differences instead of absolute values) Great for temporal data or sorted indices Decode delta encoded array Create palette from array of values Returns: { palette: unique values, indices: array of palette indices } Decode palette compressed data Calculate compression ratio and statistics Format bytes for display <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compressVoxelHybrid(voxels, options = {})

compressAnimationHybrid(track, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: HybridCompression.js Best of Both Worlds Intelligently combines lossless and lossy compression: Lossy techniques for high compression (quantization, RLE, etc.) Lossless encoding on top (LZ77 + Huffman) Result: Near lossless quality with near lossy compression ratios Achieves 80 90% of lossy compression ratio with <0.001% quality loss Functions Compress mesh with hybrid approach Parameters: (Object) — { positions, normals, uvs, indices } (Object) — { quality: 'high' 'medium' 'low' } Returns: Compressed mesh Decompress hybrid mesh Compress voxel chunk with hybrid approach Parameters: (Uint16Array) — Voxel data (Object) — { size, quality } Returns: Compressed chunk Decompress hybrid voxel chunk Compress animation with hybrid approach Parameters: (Object) — Animation track (Object) — { quality } Returns: Compressed track Decompress hybrid animation <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: LosslessCompression.js Zero Quality Loss Compression Implements truly lossless compression using: DEFLATE (zlib): Industry standard, 2 3x compression LZ77 dictionary compression: Fast, 1.5 2x compression Huffman coding: Entropy encoding Combination with existing techniques for maximum compression All compression is 100% lossless perfect reconstruction guaranteed Functions Simple LZ77 compression (basis of DEFLATE) Finds repeated sequences and replaces with back references 100% lossless Decompress LZ77 data Compress data using Huffman coding 100% lossless entropy encoding Decompress Huffman coded data Compress typed array with zero quality loss Combines LZ77 + Huffman for maximum compression Parameters: (TypedArray) — Input data Returns: Compressed data (100% lossless) Decompress losslessly compressed data Perfect reconstruction guaranteed Compress Float32Array losslessly Compress Int16Array losslessly Compress Uint8Array losslessly Test compression on sample data <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compressMeshForStreaming(mesh, lodLevels = [1.0, 0.5, 0.25])

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: MeshCompression.js Mesh Data Compression Compresses mesh data using: Position quantization (Float32 → Int16): 50% reduction Normal octahedral encoding: 66% reduction UV half float encoding: 50% reduction Index VLInt encoding: 30 50% reduction Typical compression: 70 90% reduction in mesh size Functions Compress mesh data Parameters: (Object) — { positions, normals, uvs, indices, bounds } (Object) — { lossless: boolean } Set lossless=true for zero quality loss Returns: Compressed mesh data Decompress mesh data Parameters: (Object) — Compressed mesh data Returns: Decompressed mesh { positions, normals, uvs, indices } Compress multiple meshes and combine into single buffer Useful for static scene geometry Decompress batch of meshes Compress mesh for streaming (progressive loading) Returns base LOD + detail layers <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


compressVoxelChunk(voxels, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: VoxelCompression.js Voxel Data Compression Compresses voxel data using: Run Length Encoding (RLE): 80 95% reduction for sparse data Octree structure: Hierarchical compression Palette compression: Reuse common materials Delta encoding: Store chunk changes Typical compression: 80 95% reduction for typical voxel worlds Functions Compress voxel chunk data Parameters: (Uint8Array Uint16Array) — Flat array of voxel IDs (Object) — { size: [x,y,z], usePalette, useRLE, useOctree, lossless } Returns: Compressed chunk data Decompress voxel chunk data Parameters: (Object) — Compressed chunk data Returns: Decompressed voxel data Compress changes between two chunk states Perfect for multiplayer sync or undo/redo Apply delta to chunk Compress entire voxel world Parameters: (Map) — Map of chunk coordinates to voxel data Returns: Compressed world data Decompress voxel world Compress chunk for streaming (progressive loading) <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/compression/index.js
Exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Compression Module Unified Compression System Provides compression for all engine data types: Particles: 390x compression (VLInt + Delta + Quantization + PCA/DCT) Meshes: 70 90% reduction (Quantization + Octahedral normals + VLInt indices) Voxels: 80 95% reduction (RLE + Octree + Palette) Animations: 60 80% reduction (Quaternion + DCT + Keyframe reduction) All compression techniques are lossless or near lossless with configurable quality. Exports No ES module exports detected in this file. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/events/EventBus.js
Functions
buildEventName(category, name)
createEventBus()
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/framegraph/FrameGraph.js
Functions
createFrameGraph()
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/framepipeline/FrameContext.js
Functions
createFrameContext(overrides)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: FrameContext — Per frame shared state passed to every pipeline stage. The engine provides a minimal base context with timing and GPU fields. Consumers (editor, game) extend it with their own fields via the overrides parameter. Usage: const ctx = createFrameContext({ dt: 0.016, currentTime: performance.now(), device: gpuDevice, camera: myCamera, editor: editorApp, scene: editorApp.scene, }); pipeline.execute(ctx); Functions Create a per frame context object. Parameters: (Object) — Consumer specific fields merged into the context Returns: FrameContext <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/framepipeline/FramePipeline.js
Classes
class FramePipeline
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: FramePipeline — Generic phased stage executor. Engine level primitive. Consumers (editor, game, tests) register their own stages via addStage(). The pipeline knows nothing about WebGPU, ECS, or any specific renderer — it just executes stages in order within named phases. Phases (run in this order by execute()): fixedStep — 0..N per frame (physics, PBD, fixed rate sim) update — 1/frame (camera, matrices, lights, animation) render — 1/frame (GPU render passes) postRender — 1/frame (composites, post FX, GPU submit) Inspired by: Unity — FixedUpdate / Update / LateUpdate / OnPostRender Unreal — TG PrePhysics → TG PostPhysics → TG PostUpdateWork Bevy — Extract → Prepare → Queue → Render → Cleanup Frostbite — Frame Graph (Setup → Compile → Execute) Complements engine/core/framegraph/FrameGraph.js which handles resource dependency scheduling; this handles execution scheduling. Classes Method Signature Summary Register a stage into a phase. Stages are sorted by . Remove a stage by name (from any phase). Runtime enable/disable toggle. Check if a stage is currently enabled. Execute all stages in a single phase. Execute fixedStep phase 0..N times (Unity FixedUpdate / Gaffer "Fix Your Timestep" pattern). The pipeline owns the accumulator internally. Each frame: 1. Scale dt by timeScale, clamp to maxFrameTime, add to accumulator 2. Drain accumulator in fixedDt sized steps (capped by maxFixedSteps) 3. Post drain clamp: if accumulator overflowed maxFixedSteps, discard excess (simulation gracefully slows instead of spiraling) 4. Expose fixedAlpha for future render interpolation Execute a phase with timing accumulation (adds to existing timing values). Used by executeFixedStep so multiple


fixedAlpha for future render interpolation Execute a phase with timing accumulation (adds to existing timing values). Used by executeFixedStep so multiple iterations sum correctly. Run a complete frame: fixedStep → update → render → postRender. Get per stage timing map (stage name → ms). Console friendly timing dump. Get ordered list of all registered stages (for debug UI / inspector). Get the fixed timestep value (seconds). Set the fixed timestep value (seconds). Get the max fixed steps per frame. Set the max fixed steps per frame. Max frame time added to accumulator per frame (seconds). Equivalent to Unity's Time.maximumDeltaTime. Prevents spiral of death by clamping input before accumulation. Simulation time scale (default 1.0). Equivalent to Unity's Time.timeScale. Scales the accumulator input rate — timeScale=2 means 2× more fixed steps, NOT 2× larger dt (which would destabilize physics). Current accumulator value (seconds). Read only diagnostic. Reset the accumulator (e.g. on play/stop transition). Total number of registered stages across all phases. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/framepipeline/index.js
Re-exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Frame Pipeline — Barrel exports Re exports , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


core/gpu/AdaptiveQualityGovernor.js
Classes
class AdaptiveQualityGovernor
Functions
createAdaptiveQualityGovernor(options)
Constants
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Canonical engine wide adaptive quality decision maker. It emits one immutable decision per frame so downstream systems cannot independently compound degradations. Correctness requirements are intentionally absent from tiers. Method Signature Summary Functions Constants <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


core/gpu/AsyncComputeScheduler.js
Classes
class AsyncComputeScheduler
class ComputeWorkGroup
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes AsyncComputeScheduler Manages async compute work Method Signature Summary Initialize the scheduler Begin frame reset timing Check if we have compute budget remaining Schedule a compute task Schedule high priority compute (culling, LOD selection) Schedule normal priority compute (meshing, physics) Schedule low priority background compute Execute high priority tasks immediately Call this before rendering for frame critical compute Execute normal and low priority tasks with budget Call this after rendering or during idle time Execute a single task in a compute pass Request async readback of compute results Mark a task as complete Get pending task count Get stats Clear all pending tasks Destroy resources ComputeWorkGroup Helper for organizing related compute work Method Signature Summary Add a task to this work group Wait for all tasks in group to complete <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and


granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


core/gpu/AsyncGPUWorkScheduler.js
Classes
class AsyncGPUWorkScheduler
class GPUFrameCoordinator
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Async GPU Work Scheduler Intelligent queue submission batching Eliminates redundant queue submissions and optimizes GPU pipeline utilization Based on WebGPU best practices for minimizing CPU GPU sync points Classes Async GPU Work Scheduler Intelligent queue submission batching Eliminates redundant queue submissions and optimizes GPU pipeline utilization Based on WebGPU best practices for minimizing CPU GPU sync points Method Signature Summary Schedule GPU work for batched submission Submit all pending work to GPU Force immediate submission of all pending work Configure batching behavior GPU Frame Coordinator Coordinates GPU work across frame boundaries Implements triple buffering and proper synchronization Method Signature Summary Begin a new frame Returns frame index for resource management Submit work for current frame End frame and ensure GPU work is submitted <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives.


requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Method Signature Summary Functions <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Sort key value pairs Sort particles by Morton code for cache locality Sort by camera depth for transparency Method Signature Summary Functions Calculate 30 bit Morton code for 3D position Parameters: (number) — X coordinate (0 1023) (number) — Y coordinate (0 1023) (number) — Z coordinate (0 1023) Returns: Morton code Calculate Morton code from world position Parameters: (number[]) — World position [x, y, z] (number[]) — Minimum bounds (number[]) — Maximum bounds CPU bitonic sort for small arrays or fallback Parameters: (number[]) — No description in source JSDoc. (number[]) — No description in source JSDoc. Constants — Sort key types — Maximum elements (must be power of 2) <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in


limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


createAlignedBuffer(device, size, usage, label = '')

createBufferWithData(device, data, usage, label = '')

createUniformBuffer(device, size, label = '')

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Convert float to fixed point integer Parameters: (number) — No description in source JSDoc. (number) — No description in source JSDoc. Convert fixed point integer back to float Parameters: (number) — No description in source JSDoc. (number) — No description in source JSDoc. Align a size/offset to the specified boundary Parameters: (number) — Current size in bytes (number) — Alignment boundary Returns: Aligned size Calculate padding needed to reach alignment Parameters: (number) — No description in source JSDoc. (number) — No description in source JSDoc. Validate that a size meets alignment requirements Parameters: (number) — No description in source JSDoc. (number) — No description in source JSDoc. Calculate buffer sizes for particle system Parameters: (number) — No description in source JSDoc. Calculate grid buffer size Parameters: (number) — Grid cells in X (number) — Grid cells in Y (number) — Grid cells in Z Create a WebGPU buffer with proper alignment Parameters: (GPUDevice) — No description in source JSDoc. (number) — Size in bytes (GPUBufferUsageFlags) — No description in source JSDoc. (string) — No description in source JSDoc. Create a mapped buffer for initial data upload Parameters: (GPUDevice) — No description in source JSDoc. (ArrayBuffer TypedArray) — No description in source JSDoc. (GPUBufferUsageFlags) — No description in source JSDoc. (string) — No description in source JSDoc. Create uniform buffer with proper padding Parameters: (GPUDevice) — No description in source JSDoc. (number) — No description in source JSDoc. (string) — No description in source


with proper padding Parameters: (GPUDevice) — No description in source JSDoc. (number) — No description in source JSDoc. (string) — No description in source JSDoc. Generate WGSL struct definition from layout Parameters: (string) — Struct name (Object) — Layout object with offsets Returns: WGSL code Constants — Uniform buffer alignment (must be 16 bytes) — Storage buffer preferred alignment (4 bytes min, 16 for performance) — Indirect dispatch buffer alignment — Minimum workgroup size for good occupancy — Maximum workgroup size (WebGPU limit) — WebGPU/WGSL has no native atomicAdd for f32. Solution: Scale floats to integers, use atomicAdd on i32, then descale. FIXED SCALE = 10000 gives us: 4 decimal places of precision Range: ±214,748 (i32 max / 10000) Good for velocities, forces, densities — High precision scale for positions (6 decimal places) Range: ±2147 units use only for local coordinates — MLS MPM Particle SoA Layout Buffer 0: Position + Mass (vec4f) 16 bytes [x, y, z, mass] Buffer 1: Velocity + Padding (vec4f) 16 bytes [vx, vy, vz, pad] Buffer 2: Deformation Gradient (mat3x3f) 48 bytes Row major 3x3 matrix for plasticity Buffer 3: Affine Momentum (mat3x3f) 48 bytes APIC affine velocity field Total per particle: 128 bytes — MLS MPM Grid Cell Layout (Fixed Point for Atomics) Each cell stores accumulated values from P2G scatter. Uses atomic<i32 for thread safe accumulation. Momentum: vec3 as 3x atomic<i32 12 bytes [mom x, mom y, mom z] (fixed point scaled) Mass: atomic<i32 4 bytes (fixed point scaled) Total per cell: 16 bytes (nicely aligned) — Grid velocity output (after grid update) Standard f32 for reading in G2P — FDTD Electromagnetic Field Cell Electric Displacement D: vec3f 12 bytes (padded to 16) Magnetic Induction B: vec3f 12 bytes (padded to 16) Permittivity


G2P — FDTD Electromagnetic Field Cell Electric Displacement D: vec3f 12 bytes (padded to 16) Magnetic Induction B: vec3f 12 bytes (padded to 16) Permittivity ε: f32 4 bytes Permeability μ: f32 4 bytes Padding: 8 bytes Total: 48 bytes per cell — Phasor Ray Layout Position: vec3f 12 bytes (padded to 16) Direction: vec3f 12 bytes (padded to 16) Amplitude, Frequency, Phase, Pad: vec4f 16 bytes Total: 48 bytes per ray — Indirect dispatch buffer layout — Indirect draw buffer layout (for instanced rendering) — Dirty chunk entry for conditional dispatch — Dirty flags bitmask <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native


core/gpu/BufferPool.js
Classes
class BufferPool
class StagingBufferRing
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPU Buffer Pool Zero allocation buffer recycling Eliminates per frame buffer creation overhead Classes GPU Buffer Pool Zero allocation buffer recycling Eliminates per frame buffer creation overhead Method Signature Summary Ring buffer for staging data eliminates mapAsync stalls Method Signature Summary <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


core/gpu/ComputeBatchSystem.js
Classes
class ComputeBatchSystem
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Compute Batch System Parallel GPU compute with indirect dispatch Enables dynamic workgroup sizing and batched compute operations Method Signature Summary Batch multiple compute dispatches into a single command encoder Create a compute operation descriptor Generate indirect dispatch arguments on GPU <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


core/gpu/DynamicUniformBuffer.js
Classes
class DynamicUniformBuffer
Re-exports
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: DynamicUniformBuffer.js Self sizing uniform buffer from WGSL struct Pass in your WGSL struct definition (the same string embedded in your shader) and this class handles: Parsing field names, types, and byte offsets (with correct WGSL alignment) Creating the GPU buffer at exactly the right size Typed CPU side Float32Array + Uint32Array views Named setters: buf.set('sunDir', [0.2, 1.0, 0.1]) Bulk setter: buf.setAll({ viewProj: mat, cameraPos: [x,y,z] }) Single upload() call to push to GPU Usage: const frame = new DynamicUniformBuffer(device, , 'MyFrame'); frame.set('viewProj', viewProjMatrix); frame.set('cameraPos', [x, y, z]); frame.set('sunDir', lightManager.sunDirection); frame.set('sunIntensity', 1.85); frame.upload(); // Or bulk: frame.setAll({ viewProj: mat, cameraPos: pos, sunDir: dir, sunIntensity: 1.0 }); frame.upload(); // Use in bind group: { binding: 0, resource: { buffer: frame.buffer } } Classes Method Signature Summary Set a single field by name. Accepts scalars, arrays, or Float32Array. buf.set('viewProj', float32x16); buf.set('cameraPos', [x, y, z]); buf.set('time', 1.5); buf.set('flags', 3); // u32 Set multiple fields at once. buf.setAll({ viewProj: matrix, cameraPos: [x, y, z], time: elapsed, }); Upload CPU data to GPU. Call once per frame after all sets. Get the byte offset for a field (useful for partial writes). Get the float index for a field. Check if a field exists in the layout. Get current field names. Convenience: create a bind group entry for this buffer. entries: [frame.bindEntry(0)] Destroy GPU buffer. Re exports <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the


GPU buffer. Re exports <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


core/gpu/GPUPageAllocator.js
Classes
class GPUPageAllocator
Constants
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes GPUPageAllocator Virtual heap for GPU memory Method Signature Summary Initialize the allocator Probe GPU memory by allocating until failure Sets maxPages based on detected available memory Initialize staging buffer ring Create a staging buffer (MAP WRITE + COPY SRC) Get a staging buffer for zero copy writes Commit staging buffer to GPU and re map for next use Begin a new frame reset frame tracking Process pending staging buffers Allocate a new page Get the active page, or allocate a new one Write data to the allocator (uses writeBuffer recommended by WebGPU spec) Zero copy write using staging buffer ring Use when data is being generated (not already in ArrayBuffer) Get pages used this frame for binding Get buffer binding entries for bind group Release pages not used for N frames Get allocation result for shader (page index + offset) Get stats for profiler Destroy all pages Constants — WGSL shader helper for page indirection <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition


supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


core/gpu/GPUProfiler.js
Classes
class GPUProfiler
Notes & Examples
Shared GPU device

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes GPUProfiler Timestamp query based GPU profiling Method Signature Summary Initialize the profiler Register a pass for profiling Get timestamp writes for a render/compute pass Add timestamp writes to a pass descriptor Resolve queries and copy to result buffer Call after all passes are complete, before submit Read results asynchronously Call after submit Get current timing results Get formatted stats string Copy detailed diagnostics to clipboard for analysis Includes all timing data, pass breakdown, and performance metrics Reset for next frame Check if profiling is available Load configuration from engine.cfg section Destroy resources <! HUMAN NOTES Notes & Examples Shared GPU device Engine subsystems should reuse the cached wrapper returned by . The wrapper owns the native , its queue, granted features, limits, and device loss callbacks. Resources created by one native device cannot be used by another, so pass the shared wrapper or native device into each subsystem that needs GPU access. Example: Acquire the shared engine device Request a feature only when the application cannot run without it. automatically requests the engine's supported optional feature set, while reports the features actually granted to the device. Feature and limit checks Device loss Gotchas: First acquisition defines requirements: caches the wrapper. Supply mandatory features and limits on the first call. Native access: use and when a subsystem needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together.


needs WebGPU primitives. Recovery: this module reports device loss but does not expose an in place API. Re bootstrap all device owned resources together. Limits: check the granted before large allocations. (Source: ) See also: GPU Device Sharing · Virtual GPU · GpuFormats


initRngState(pixelX, pixelY, frame, sampleIdx = 0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes RNG state wrapper for sequential random number generation Method Signature Summary Seed the RNG for deterministic sequences Seed from pixel/frame/sample for reproducible noise Get next random float in [0, 1) Get random float in range [min, max) Get random integer in [0, max) Get random value from normal distribution (Box Muller) Get random direction on unit sphere Get random direction in hemisphere around normal Get cosine weighted hemisphere direction (for diffuse) Get random point in unit disk Get random point in unit sphere Deterministic RNG for multiplayer synchronization. All clients with the same seed produce identical sequences. Usage: World generation: seed with worldSeed + chunkCoords AI decisions: seed with entityId + gameTick Combat rolls: seed with attackerId + defenderId + gameTick Loot drops: seed with containerId + gameTick Method Signature Summary Create a deterministic RNG Create RNG stream for a specific game tick Use for time based events that must sync across clients Create RNG stream for a specific entity Use for per entity random (AI, particles, animations) Create RNG stream for a world position (chunk generation, etc.) Create RNG for interaction between two entities (combat, trade, etc.) Get next random float in [0, 1) Get random float in range [min, max) Get random integer in [0, max) Get random integer in [min, max] Random boolean with probability Pick random element from array Shuffle array in place (Fisher Yates) Get random value from normal distribution Get random direction on unit sphere Get random point in unit sphere Get random point in unit


in place (Fisher Yates) Get random value from normal distribution Get random direction on unit sphere Get random point in unit sphere Get random point in unit disk Weighted random selection Functions PCG hash function high quality, fast Parameters: (number) — Input value (32 bit integer) Returns: Hashed value (32 bit integer) Hash 2D coordinates Parameters: (number) — X coordinate (number) — Y coordinate Returns: Hash value Hash 3D coordinates Parameters: (number) — X coordinate (number) — Y coordinate (number) — Z coordinate Returns: Hash value Initialize RNG state for deterministic per pixel random Parameters: (number) — Pixel X coordinate (number) — Pixel Y coordinate (number) — Frame number (number) — Sample index within frame Returns: Initial RNG state Calculate accumulation weight for progressive rendering Parameters: (number) — Current frame index (0 based) Returns: Weight for new sample (1/(frameIndex+1)) Accumulate color over frames (progressive rendering) Parameters: (number[]) — Previous accumulated color [r, g, b] (number[]) — New sample color [r, g, b] (number) — Current frame index Returns: Accumulated color [r, g, b] Exponential moving average accumulation (real time, non converging) Parameters: (number[]) — Previous color [r, g, b] (number[]) — New color [r, g, b] (number) — Blend factor (0 1, higher = more new) Returns: Blended color [r, g, b] Convert wavelength (nm) to RGB color Parameters: (number) — Wavelength in nanometers (380 780) Returns: [r, g, b] in 0 1 range Map normalized value to spectral color (violet to red) Parameters: (number) — Value in [0, 1] Returns: [r, g, b] spectral color Map count to spectral color with cutoff Parameters: (number) — Count value (number) — Maximum expected count Returns: [r, g, b] spectral color Generate blue noise


count to spectral color with cutoff Parameters: (number) — Count value (number) — Maximum expected count Returns: [r, g, b] spectral color Generate blue noise sample offset for a pixel Uses R2 sequence (generalized golden ratio) for low discrepancy sampling Parameters: (number) — Sample index Returns: [x, y] offset in [0, 1) R2 sequence for 3D sampling (quasi random, low discrepancy) Parameters: (number) — Sample index Returns: [x, y, z] in [0, 1) Halton sequence for quasi random sampling Parameters: (number) — Sample index (number) — Prime base (2, 3, 5, 7, etc.) Returns: Value in [0, 1) 2D Halton sequence Parameters: (number) — Sample index Returns: [x, y] in [0, 1) 3D Halton sequence Parameters: (number)