@holtjs/stage 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holtjs/stage",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Zero-dependency TypeScript stage engine for 2D WebGPU/WebGL2/Canvas2D games, GPU SDF UI, procedural audio, StageKernel plugins, tracing-native observability, and deterministic 60 FPS headless image & video rendering.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Botiverse, Inc.",
@@ -104,6 +104,26 @@
104
104
  "./webgpu": {
105
105
  "types": "./dist/renderer-webgpu.d.ts",
106
106
  "default": "./dist/renderer-webgpu.js"
107
+ },
108
+ "./rig2d": {
109
+ "types": "./dist/rig2d.d.ts",
110
+ "default": "./dist/rig2d.js"
111
+ },
112
+ "./tilemap": {
113
+ "types": "./dist/tilemap.d.ts",
114
+ "default": "./dist/tilemap.js"
115
+ },
116
+ "./projection": {
117
+ "types": "./dist/projection.d.ts",
118
+ "default": "./dist/projection.js"
119
+ },
120
+ "./lighting": {
121
+ "types": "./dist/lighting.d.ts",
122
+ "default": "./dist/lighting.js"
123
+ },
124
+ "./world": {
125
+ "types": "./dist/world.d.ts",
126
+ "default": "./dist/world.js"
107
127
  }
108
128
  },
109
129
  "files": [
@@ -1,25 +1,33 @@
1
1
  ---
2
2
  name: stage
3
- description: Build zero-dependency WebGL2/Canvas2D 2D games, GPU SDF UIs, simulations, and zero-browser 60 FPS programmable videos/images with @holtjs/stage (PanelObject, Flex/Wrap layout, damped springs, VirtualJoystick, SurfaceTree barriers, SoaWorld ECS, SpatialHashGrid, FlowFieldGrid/A* nav, deterministic hit/knockback, ParticlePool/JuiceController, procedural audio DSP, headless 60 FPS frame/video recorder, and zero-PII buildSceneDigest tracing).
3
+ description: Build zero-dependency WebGPU/WebGL2/Canvas2D 2D & 2.5D games, GPU SDF UIs, StageKernel plugins, survival sandboxes, and zero-browser 60 FPS programmable videos/images with @holtjs/stage (RendererWebGpu, StageKernel, InputTimeline, Rig2D cutout skeletons, Dual-Grid ChunkedTilemap, Camera25D projection, DayNightCycle & 2D normal-map lighting, WorldDeltaSave, PanelObject, Flex/Wrap layout, damped springs, SurfaceTree barriers, SoaWorld ECS, SpatialHashGrid, FlowFieldGrid/A* nav, deterministic hit/knockback, ParticlePool/JuiceController, procedural audio DSP, headless 60 FPS recorder, and zero-PII buildSceneDigest tracing).
4
4
  ---
5
5
 
6
- # Building Games, UI & Programmable 60 FPS Video with `@holtjs/stage`
6
+ # Building 2D/2.5D Games, WebGPU UI & 60 FPS Video with `@holtjs/stage`
7
7
 
8
- Use this skill whenever creating or modifying a browser 2D game, canvas UI, interactive simulation, or pure-Node headless image/storyboard/60 FPS video pipeline built on `@holtjs/stage`.
8
+ Use this skill whenever creating or modifying a browser 2D/2.5D game, WebGPU/WebGL2 canvas UI, survival sandbox, automated `InputTimeline` test, or pure-Node headless image/storyboard/60 FPS video pipeline built on `@holtjs/stage` (`v0.5.0`, 20 subpaths).
9
9
 
10
- For the exhaustive exported symbol list across all 13 subpaths, see [references/subpaths.md](references/subpaths.md).
10
+ For the exhaustive exported symbol list across all 20 subpaths, see [references/subpaths.md](references/subpaths.md).
11
11
 
12
- ## 1. Install & Choose the Right Subpaths
12
+ ## 1. Install & Choose from the 20 Subpaths
13
13
 
14
14
  ```bash
15
15
  pnpm add @holtjs/stage
16
16
  ```
17
17
 
18
- `@holtjs/stage` is pure ESM, `sideEffects: false`, zero runtime dependencies. Import only what you need:
18
+ `@holtjs/stage` is pure ESM, `sideEffects: false`, zero runtime dependencies:
19
19
 
20
20
  | Need | Import path | Works in Node/Worker (no DOM)? |
21
21
  |---|---|---|
22
- | Canvas engine, `Game`, `Scene`, `Panel`, `Graphics`, `Container`, `Text`, `InputPlugin` | `@holtjs/stage` | Browser |
22
+ | Core engine (`Game`, `Scene`, `WEBGPU`/`WEBGL`/`CANVAS`, `InstancedBatch`, `Panel`, `Graphics`, `Container`, `Text`) | `@holtjs/stage` | Browser |
23
+ | Native WebGPU WGSL batch & analytical SDF renderer (`RendererWebGpu`, `requestWebGpuDevice`) | `@holtjs/stage/webgpu` | Browser WebGPU |
24
+ | `StageKernel` plugins, `ActionMap`, semantic `createInputTimeline`, recorder/replay | `@holtjs/stage/kernel` | Yes |
25
+ | Zero-browser 60 FPS Node PNG, storyboard & stereo video (`createHeadlessStage`) | `@holtjs/stage/headless` | Yes (`@napi-rs/canvas`) |
26
+ | 2D cutout skeletal rig, O(1) equipment/skin swap, 2-layer bone-masked mixer | `@holtjs/stage/rig2d` | Yes |
27
+ | Sparse `ChunkedTilemap`, 16-tile Dual-Grid & 47-tile Blob autotilers, island generator | `@holtjs/stage/tilemap` | Yes |
28
+ | Rotatable oblique `Camera25D` + `mountStage25D` upright cylindrical billboards | `@holtjs/stage/projection` | Yes |
29
+ | `DayNightCycle`, Sobel normal-map baker, `Lighting2DSystem`, WebGL2 normal-lit sprite pass | `@holtjs/stage/lighting` | Yes |
30
+ | `ItemRegistry`, `InventoryContainer` (spoilage), `RecipeRegistry`, `WorkstationScheduler`, `HWLD` delta save | `@holtjs/stage/world` | Yes |
23
31
  | Pure Flexbox & Wrap layout | `@holtjs/stage/flex` | Yes |
24
32
  | Deterministic tweens & damped springs | `@holtjs/stage/tween` | Yes |
25
33
  | Multi-touch joystick & 4/8-way D-pad math | `@holtjs/stage/joystick` | Math helpers: Yes |
@@ -31,139 +39,167 @@ pnpm add @holtjs/stage
31
39
  | Zero-GC particles, ambient emitters, hitstop + trauma shake | `@holtjs/stage/particles` | Yes |
32
40
  | Procedural WebAudio foley DSP, stereo pan, sfxr voices, WAV | `@holtjs/stage/audio` | Yes |
33
41
  | Dense TypedArray `SoaWorld` ECS, depth sort, 2.5D `DepthBand`s | `@holtjs/stage/ecs` | Yes |
34
- | Deterministic 60 FPS headless Node PNG, storyboard & stereo video | `@holtjs/stage/headless` | Yes (with `@napi-rs/canvas`) |
35
- | `StageKernel` plugins, `ActionMap`, `createInputTimeline`, replay | `@holtjs/stage/kernel` | Yes |
36
- | Native WebGPU WGSL batch & SDF renderer (`RendererWebGpu`) | `@holtjs/stage/webgpu` | Browser WebGPU |
37
42
 
38
- ## 2. One-Line HiDPI / DPR Camera & Follow Setup
39
-
40
- Use `camera.configureHiDpi()` to map logical CSS pixels `(0, 0)..(vw, vh)` onto crisp physical `vw * dpr` pixels without manual origin/scroll math:
43
+ ## 2. WebGPU-First + HiDPI Camera Bootstrap
41
44
 
42
45
  ```ts
43
46
  import { AUTO, Game, Scene, Scale, WEBGL, WEBGPU } from '@holtjs/stage';
47
+ import { requestWebGpuDevice } from '@holtjs/stage/webgpu';
44
48
 
45
49
  class MyScene extends Scene {
46
50
  dpr = 1;
47
- vw = 640;
48
- vh = 480;
51
+ vw = 960;
52
+ vh = 540;
49
53
 
50
54
  create() {
51
55
  const parentEl = document.getElementById('stage')!;
52
56
  const maxDpr = this.game.renderer?.type === WEBGL || this.game.renderer?.type === WEBGPU ? 2 : 1;
53
- this.vw = Math.max(300, Math.round(parentEl.clientWidth || 640));
54
- this.vh = Math.max(280, Math.round(parentEl.clientHeight || 480));
57
+ this.vw = Math.max(320, Math.round(parentEl.clientWidth || 960));
58
+ this.vh = Math.max(240, Math.round(parentEl.clientHeight || 540));
55
59
  this.dpr = this.cameras.main.configureHiDpi(this.scale, this.vw, this.vh, window.devicePixelRatio || 1, maxDpr);
56
60
  // Optional smooth camera follow:
57
61
  // this.cameras.main.startFollow(player, { lerpX: 0.12, lerpY: 0.12, deadzoneWidth: 64, deadzoneHeight: 48 });
58
62
  }
59
63
  }
60
64
 
65
+ const canvas = document.createElement('canvas');
66
+ document.getElementById('stage')!.appendChild(canvas);
67
+ const gpu = await requestWebGpuDevice(canvas, { powerPreference: 'high-performance' });
68
+
61
69
  new Game({
62
- type: AUTO,
63
- parent: document.getElementById('stage')!,
64
- width: 640,
65
- height: 480,
66
- backgroundColor: '#236e9c',
70
+ type: gpu ? WEBGPU : AUTO,
71
+ canvas,
72
+ webgpu: gpu ?? undefined,
73
+ width: 960,
74
+ height: 540,
75
+ backgroundColor: '#131722',
67
76
  scale: { mode: Scale.NONE },
68
77
  scene: [MyScene],
69
78
  });
70
79
  ```
71
80
 
72
- Pointer coordinates in `this.input.on('pointerdown', (p) => ...)` are in backing pixels: divide by `this.dpr` (`const x = p.x / this.dpr; const y = p.y / this.dpr;`) to convert into logical scene coordinates, and pass `resolution: this.dpr` to `this.add.text(...)`.
81
+ ## 3. `StageKernel` Plugins, `ActionMap` & Semantic `InputTimeline` (`@holtjs/stage/kernel`)
73
82
 
74
- ## 3. Zero-GC 2D Game Loop Recipe (`ecs` + `spatial` + `nav` + `hit` + `particles`)
83
+ Never hardcode separate input paths for gameplay vs. tests/trailers. Bind actions on `game.kernel.actions` and drive automated clicks by `trackId`:
75
84
 
76
85
  ```ts
77
- import { SoaWorld, defineComponent, sortSlotsByDepth } from '@holtjs/stage/ecs';
78
- import { resolveCircleObstacles, knockbackDecay, stepKnockback } from '@holtjs/stage/hit';
79
- import { FlowFieldGrid, buildCircleObstacleGrid } from '@holtjs/stage/nav';
80
- import { ParticlePool, JuiceController, drawParticlePool, PARTICLE_SPARKLE, FADE_PUNCH } from '@holtjs/stage/particles';
86
+ import { createInputTimeline, type StagePlugin } from '@holtjs/stage/kernel';
87
+
88
+ // 1. Semantic key bindings
89
+ game.kernel.actions
90
+ .bind('rotateCCW', ['KeyQ'])
91
+ .bind('rotateCW', ['KeyE'])
92
+ .bind('chop', ['Space']);
93
+
94
+ // 2. Composable kernel plugin with LIFO cleanup & SceneDigest telemetry
95
+ const autosavePlugin: StagePlugin = {
96
+ id: 'world.autosave',
97
+ update(_dtMs, kernel) {
98
+ // runs deterministically every frame before Scene.update
99
+ },
100
+ digest() {
101
+ return { ok: true };
102
+ },
103
+ };
104
+ game.kernel.use(autosavePlugin);
105
+
106
+ // 3. Scripted InputTimeline (clicks HUD buttons by trackId, renders virtual cursor + ripples)
107
+ const timeline = createInputTimeline({ showCursor: true });
108
+ timeline
109
+ .click('craft.axe', 400, { moveDurationMs: 250 })
110
+ .pressKey('KeyE', 900, 600);
111
+ game.kernel.use(timeline);
112
+ ```
81
113
 
82
- const Pos = defineComponent('Pos', { x: 'f32', y: 'f32', depth: 'f32' });
83
- const Vel = defineComponent('Vel', { vx: 'f32', vy: 'f32' });
84
- const Knock = defineComponent('Knock', { kx: 'f32', ky: 'f32' });
114
+ ## 4. 2.5D Survival Sandbox Recipe (`rig2d` + `tilemap` + `projection` + `lighting` + `world`)
85
115
 
86
- const world = new SoaWorld(256);
87
- let pos = world.store(Pos);
88
- let vel = world.store(Vel);
89
- let knock = world.store(Knock);
90
- const sortBuf = new Int32Array(256);
116
+ ```ts
117
+ import { bakeCutoutAtlas, defineRig2DSkeleton, Rig2DInstance, mountRig2D } from '@holtjs/stage/rig2d';
118
+ import {
119
+ ChunkedTilemap, SurvivalBiomes, bakeDualGridTileset, createIslandBiomeGenerator, mountChunkedTilemap,
120
+ } from '@holtjs/stage/tilemap';
121
+ import { Camera25D, mountStage25D } from '@holtjs/stage/projection';
122
+ import { DayNightCycle, Lighting2DSystem } from '@holtjs/stage/lighting';
123
+ import {
124
+ ItemRegistry, InventoryContainer, RecipeRegistry, WorkstationInstance, WorkstationScheduler,
125
+ captureWorldDelta, encodeWorldDeltaBytes,
126
+ } from '@holtjs/stage/world';
127
+
128
+ // 1. Infinite/Island Chunked Tilemap + 16-tile Oskar Stålberg Dual-Grid Autotiler
129
+ const tilemap = new ChunkedTilemap({
130
+ chunkSize: 16,
131
+ tileSize: 36,
132
+ generator: createIslandBiomeGenerator({ seed: 1337, islandRadiusTiles: 24 }),
133
+ });
134
+ const dgAtlas = bakeDualGridTileset('island_dg', 36, [
135
+ { id: 'beach', fillColor: 0xe6c88c, edgeColor: 0xfef3c7, matches: (t) => t >= SurvivalBiomes.BEACH },
136
+ { id: 'meadow', fillColor: 0x5c8d3e, edgeColor: 0x3f6212, matches: (t) => t >= SurvivalBiomes.MEADOW },
137
+ ]);
138
+
139
+ // 2. Rotatable 2.5D Oblique Camera + Upright Cylindrical Billboards
140
+ const cam25 = new Camera25D({ viewportWidth: 1280, viewportHeight: 720, pitch: 0.84, zoom: 1.4 });
141
+ const stage25 = mountStage25D(scene, cam25, { depth: 10 });
142
+ const mountedTerrain = mountChunkedTilemap(scene, tilemap, dgAtlas);
143
+ mountedTerrain.container.removeFromDisplayList();
144
+ stage25.groundWorld.add(mountedTerrain.container);
145
+
146
+ // 3. 2D Cutout Skeletal Rig: O(1) equipment swap + 2-layer bone-masked overlay animation
147
+ const rig = new Rig2DInstance(heroSkeleton);
148
+ rig.play('walk');
149
+ rig.setAttachment('tool', 'axe_iron'); // swaps weapon slot in O(1) without resetting walk phase!
150
+ rig.playOverlay('chop', { maskBones: ['arm_r', 'hand_r', 'torso'] }); // chops while legs keep walking!
151
+ const heroView = mountRig2D(scene, rig, { depth: 20, trackId: 'actor.survivor' });
152
+ stage25.registerBillboard(heroView.container, 0, 0);
153
+
154
+ // 4. Day/Night Cycle + Offscreen MULTIPLY 2D Lightmap with Flickering Torches
155
+ const dayNight = new DayNightCycle({ dayLengthMs: 60_000, initialTime01: 0.72 }); // dusk -> night
156
+ const lighting = new Lighting2DSystem(scene, { width: 1280, height: 720, depth: 500 });
157
+ lighting.addLight({ id: 'torch', x: 0, y: 0, z: 24, radius: 240, color: 0xffa94d, intensity: 1.0, flicker: 0.18 });
158
+
159
+ // Inside Scene.update(_t, deltaMs):
160
+ if (scene.game.kernel.actions.justPressed('rotateCW')) cam25.rotateSteps(1);
161
+ stage25.update(deltaMs);
162
+ mountedTerrain.update(cam25.getGroundViewportBounds());
163
+ heroView.update(deltaMs);
164
+ const env = dayNight.step(deltaMs);
165
+ lighting.update(env, scene.clock.simTimeMs, (wx, wy, wz, out) => cam25.worldToScreen(wx, wy, wz, out));
166
+
167
+ // 5. Compact Binary World Delta Save (only modified tiles + inventories + workstations)
168
+ const deltaBytes = encodeWorldDeltaBytes(captureWorldDelta({ seed: 1337, simTimeMs: 42_000, tilemap }));
169
+ ```
91
170
 
92
- const obstacles = [{ x: 240, y: 200, r: 42 }];
93
- const flowField = new FlowFieldGrid(
94
- buildCircleObstacleGrid(obstacles, { width: 640, height: 480, cellSize: 28, wallMargin: 12, obstacleMargin: 8 }),
95
- );
96
- flowField.compute(0, 520, 260);
97
-
98
- const particles = new ParticlePool({ capacity: 256 });
99
- const juice = new JuiceController({ level: 2, shakePx: [0, 3, 7] });
100
- const flowOut: [number, number] = [0, 0];
101
- const sepOut = { x: 0, y: 0 };
102
- const tmpPos = { x: 0, y: 0 };
103
- const tmpVel = { x: 0, y: 0 };
104
-
105
- // Inside Scene.update(_time, deltaMs):
106
- const effDt = juice.tick(deltaMs, scene.clock.simTimeMs);
107
- const dt = Math.min(0.05, effDt);
108
- if (dt > 0 && world.count > 0) {
109
- const grid = world.syncSpatial(pos.x, pos.y, { originX: 0, originY: 0, width: 640, height: 480, cellSize: 28 });
110
- const kbDecay = knockbackDecay(dt, 0.14);
111
-
112
- for (let s = 0; s < world.count; s++) {
113
- let x = pos.x[s], y = pos.y[s], vx = vel.vx[s], vy = vel.vy[s];
114
-
115
- // IMPORTANT: flowField.sample() returns WORLD WAYPOINT [wx, wy] when an obstacle blocks LOS, or null when LOS is clear!
116
- const wp = flowField.sample(0, x, y, targetX, targetY, undefined, { out: flowOut });
117
- const gx = wp ? wp[0] : targetX;
118
- const gy = wp ? wp[1] : targetY;
119
- const dx = gx - x, dy = gy - y, d = Math.hypot(dx, dy);
120
- if (d > 4) { vx += (dx / d) * 260 * dt; vy += (dy / d) * 260 * dt; }
121
-
122
- sepOut.x = 0; sepOut.y = 0;
123
- grid.accumulateSeparation(s, x, y, 16, pos.x, pos.y, sepOut);
124
- vx += sepOut.x * 240 * dt; vy += sepOut.y * 240 * dt;
125
-
126
- tmpVel.x = knock.kx[s]; tmpVel.y = knock.ky[s];
127
- if (stepKnockback(tmpVel, kbDecay, 4)) { knock.kx[s] = tmpVel.x; knock.ky[s] = tmpVel.y; }
128
- else { knock.kx[s] = 0; knock.ky[s] = 0; }
129
-
130
- tmpPos.x = x + (vx + knock.kx[s]) * dt;
131
- tmpPos.y = y + (vy + knock.ky[s]) * dt;
132
- resolveCircleObstacles(tmpPos, 6, obstacles);
133
- pos.x[s] = tmpPos.x; pos.y[s] = tmpPos.y; pos.depth[s] = tmpPos.y;
134
- vel.vx[s] = vx * Math.exp(-3 * dt); vel.vy[s] = vy * Math.exp(-3 * dt);
135
- }
136
- }
171
+ ## 5. Zero-GC 2D Crowd Loop (`ecs` + `spatial` + `nav` + `hit` + `particles`)
137
172
 
138
- for (let s = 0; s < world.count; s++) sortBuf[s] = s;
139
- sortSlotsByDepth(sortBuf, world.count, pos.depth);
140
- // Render using juice.ox / juice.oy camera shake offset, then drawParticlePool(particleGfx, particles)
173
+ ```ts
174
+ import { SoaWorld, defineComponent, sortSlotsByDepth } from '@holtjs/stage/ecs';
175
+ import { resolveCircleObstacles, knockbackDecay, stepKnockback } from '@holtjs/stage/hit';
176
+ import { FlowFieldGrid, buildCircleObstacleGrid } from '@holtjs/stage/nav';
177
+ import { ParticlePool, JuiceController, drawParticlePool } from '@holtjs/stage/particles';
178
+
179
+ // IMPORTANT: flowField.sample(slot, x, y, tx, ty, dist, { out }) returns WORLD WAYPOINT [wx, wy] when an
180
+ // obstacle blocks LOS, or null when direct LOS is clear (steer straight toward tx, ty).
141
181
  ```
142
182
 
143
- ## 4. Canvas UI, Layout, Springs & SurfaceTree Barrier Recipe
183
+ ## 6. Canvas UI, Layout, Springs & `SurfaceTree` Barrier Recipe
144
184
 
145
185
  ```ts
146
186
  import { computeFlexLayout, createSurfaceTree } from '@holtjs/stage';
147
187
 
148
188
  const surfaces = createSurfaceTree();
149
-
150
- // 1. Pure Flexbox layout (no DOM)
151
189
  const row = computeFlexLayout(
152
190
  { dir: 'row', w: 480, h: 96, gap: 12, padding: 12, align: 'stretch' },
153
191
  [{ w: 0, h: 72, grow: 1 }, { w: 0, h: 72, grow: 1 }],
154
192
  );
155
193
 
156
- // 2. Analytic GPU SDF rounded panel (zero texture baking)
157
194
  const card = scene.add.panel(row.rects[0].x, row.rects[0].y, row.rects[0].w, row.rects[0].h, {
158
195
  fillColor: 0xfff8e7,
159
196
  borderColor: 0x2c241d,
160
197
  borderWidth: 2,
161
- radius: 14, // or [tl, tr, br, bl], plus optional pixelStep: 2 for crisp pixel-art corners
198
+ radius: 14,
162
199
  });
163
200
  card.trackId = 'hud.card.primary';
164
201
  card.role = 'button';
165
202
 
166
- // 3. Damped spring auto-cancelled when `card` is destroyed
167
203
  scene.tweens.spring({
168
204
  from: card.y + 16,
169
205
  to: card.y,
@@ -172,60 +208,12 @@ scene.tweens.spring({
172
208
  owner: card,
173
209
  onUpdate: (y) => { card.y = y; },
174
210
  });
175
-
176
- // 4. Unified visual stacking == input barrier (never scatter ad-hoc modal booleans)
177
- const disposeModal = surfaces.register({
178
- id: 'shop.modal',
179
- band: 'modal',
180
- barrier: 'modal',
181
- onCancel: () => { closeShop(); return true; },
182
- });
183
- // Gate world clicks/joysticks on `!surfaces.isWorldBlocked()` and dispatch Escape via `surfaces.dispatchCancel(...)`.
184
- ```
185
-
186
- ## 5. Procedural WebAudio Foley Recipe (Zero Audio Asset Files)
187
-
188
- ```ts
189
- import { renderFoley, buildStepWoodFoley, renderVoices, hz, spatialMix } from '@holtjs/stage/audio';
190
-
191
- const ac = new AudioContext();
192
- const pcm = renderFoley(buildStepWoodFoley(0), ac.sampleRate);
193
- const buf = ac.createBuffer(1, pcm.length, ac.sampleRate);
194
- buf.getChannelData(0).set(pcm);
195
-
196
- const chimePcm = renderVoices([
197
- { w: 'tri', f: hz('e5'), d: 0.09, vol: 0.24 },
198
- { w: 'sin', f: hz('b5'), t: 0.035, d: 0.14, vol: 0.18 },
199
- ], ac.sampleRate);
200
- const mix = spatialMix(dx, dy, 2, 12); // { vol, pan } | null when out of hearing range
201
- ```
202
-
203
- ## 6. Tracing-First Debugging Loop
204
-
205
- Always attach semantic `trackId` and `role` to key panels/actors/dialogs, and inspect runtime state via `buildSceneDigest()` instead of ad-hoc DOM queries:
206
-
207
- ```ts
208
- import { buildSceneDigest } from '@holtjs/stage/trace';
209
-
210
- const digest = buildSceneDigest(scene, {
211
- traceId: 'playtest-01',
212
- dpr: scene.dpr,
213
- surfaces: {
214
- active: () => surfaces.active(),
215
- topBarrier: () => surfaces.topBarrier(),
216
- isWorldBlocked: () => surfaces.isWorldBlocked(),
217
- },
218
- });
219
- // Contains clock.frameSeq, renderer.{type,drawCalls,tris,sdfPanels}, tweens.active, surfaces, and sanitized nodes (zero PII).
220
211
  ```
221
212
 
222
213
  ## 7. Zero-Browser 60 FPS Image, Storyboard & Video Rendering (`@holtjs/stage/headless`)
223
214
 
224
- AI agents and CI jobs can draw scenes, inspect `buildSceneDigest()` bounds, export multi-frame storyboard contact sheets, and pipe 60 FPS raw RGBA + stereo WAV audio into `ffmpeg` in pure Node (`pnpm add -D @napi-rs/canvas`) — **zero Chromium / zero DOM required**:
225
-
226
215
  ```ts
227
216
  import { createCanvas, Path2D } from '@napi-rs/canvas';
228
- import { Scene } from '@holtjs/stage';
229
217
  import { createHeadlessStage, renderStoryboard, createAudioTimeline } from '@holtjs/stage/headless';
230
218
  import { renderFoley, buildStepWoodFoley } from '@holtjs/stage/audio';
231
219
 
@@ -236,37 +224,32 @@ const stage = createHeadlessStage({
236
224
  height: 720,
237
225
  fps: 60,
238
226
  backgroundColor: '#131722',
239
- scene: MyMotionScene,
227
+ scene: MyScene,
240
228
  });
241
229
 
242
- // 1. Export a 3x2 keyframe storyboard PNG + paired zero-PII SceneDigest array for visual self-review
230
+ // Fast-forward simulation without rasterizing intermediate frames, or render a 3x2 storyboard PNG:
243
231
  const board = renderStoryboard(stage, {
244
- frames: [0, 30, 60, 90, 120, 150],
232
+ frames: [0, 60, 120, 180, 240, 300],
245
233
  columns: 3,
246
234
  tileScale: 0.5,
247
235
  createCanvas,
248
236
  });
249
237
 
250
- // 2. Mix frame-accurate stereo WAV audio & stream raw 60 FPS RGBA frames to ffmpeg
251
238
  const audio = createAudioTimeline({ sampleRate: 44100 });
252
239
  audio.addAtFrame(12, 60, renderFoley(buildStepWoodFoley(0), 44100), { pan: -0.4, gain: 0.7 });
253
- const wavBytes = audio.toWav(4000);
240
+ const wavBytes = audio.toWav(5000);
254
241
  stage.destroy();
255
242
  ```
256
243
 
257
244
  ## 8. High-Value Gotchas (Avoid These Mistakes!)
258
245
 
259
- 1. **`FlowFieldGrid.sample()` returns world coordinates `[wx, wy] | null`, NOT a unit direction vector**:
260
- - When an obstacle blocks line-of-sight, it returns `[wx, wy]` (center of the next BFS cell). Compute `dx = wx - x; dy = wy - y;` and normalize!
261
- - When direct LOS is clear, it returns `null` — steer straight toward `(targetX, targetY)`.
262
- - Pass `{ out: reusableTuple }` in hot loops to keep allocations at zero.
263
- 2. **Re-fetch `world.store(Comp)` after spawning past initial `SoaWorld` capacity**:
264
- - Growing `SoaWorld` reallocates its TypedArray backing stores. After bulk `spawn()` calls that may grow capacity, re-bind `pos = world.store(Pos)` and resize any parallel `sortBuf`.
265
- 3. **Push spawned entities and FlowField targets out of obstacles**:
266
- - Call `resolveCircleObstacles(pt, radius, obstacles)` on spawn positions and interactive targets so `flowField.compute()` always seeds from a walkable cell.
267
- 4. **Always register cleanup via `node.onDispose(fn)` and pass `owner` to `tweens.to()` (or `tweens.add()`) / `tweens.spring()`**:
268
- - Destroying a parent `Container` unwinds children and disposers in strict LIFO order, preventing zombie callbacks on screen transitions.
269
- 5. **Respect `SurfaceTree` barriers everywhere**:
270
- - Pass `canCapture: () => !surfaces.isWorldBlocked()` to `VirtualJoystick` and check `!surfaces.isWorldBlocked()` in world pointer handlers. Never invent parallel `isModalOpen` flags or hardcoded CSS `z-index` values — use `computeSurfaceDomZ()`.
271
- 6. **Never scrape user text into `trackId` / `alt`**:
272
- - Keep `trackId` static semantic tokens (`'hud.shop.buy'`, `'world.boss'`). `buildSceneDigest()` intentionally never reads `TextObject.text`.
246
+ 1. **Use `scene.textures.exists(key)` (NOT `!scene.textures.get(key)`) to check whether a texture is registered**:
247
+ - `scene.textures.get(key)` returns the 1×1 fallback `__DEFAULT` texture when `key` is missing so sprite creation never crashes. Always guard procedural atlas registration with `if (!scene.textures.exists(key))`.
248
+ 2. **`FlowFieldGrid.sample()` returns world coordinates `[wx, wy] | null`, NOT a unit direction vector**:
249
+ - When an obstacle blocks line-of-sight, it returns `[wx, wy]`; compute `dx = wx - x; dy = wy - y;` and normalize. When LOS is clear, it returns `null` — steer straight toward `(targetX, targetY)`.
250
+ 3. **Re-fetch `world.store(Comp)` after spawning past initial `SoaWorld` capacity**:
251
+ - Growing `SoaWorld` reallocates TypedArray columns; re-bind `pos = world.store(Pos)` after bulk spawns.
252
+ 4. **Always pass `onUpdate` to `tweens.spring({ from, to, onUpdate, owner })` and register cleanup via `node.onDispose(fn)`**:
253
+ - Destroying a parent `Container` unwinds children and disposers in strict LIFO order.
254
+ 5. **Respect `SurfaceTree` barriers everywhere & keep `trackId` PII-free**:
255
+ - Gate world input on `!surfaces.isWorldBlocked()` and keep `trackId` static semantic tokens (`'craft.torch'`, `'hud.inventory'`). `buildSceneDigest()` never scrapes `TextObject.text`.
@@ -1,82 +1,90 @@
1
1
  # `@holtjs/stage` Subpath API Quick Reference
2
2
 
3
- All symbols verified against `src/*.ts` (`@holtjs/stage@0.4.0`, 15 subpaths).
3
+ All symbols verified against `src/*.ts` (`@holtjs/stage@0.5.0`, 20 subpaths).
4
4
 
5
- ## `@holtjs/stage` (Core Engine Barrel)
6
- - **Bootstrap & Lifecycle**: `Stage` / `Stage2D` (namespaces), `AUTO`, `WEBGPU`, `WEBGL`, `CANVAS`, `Scale`, `Scenes`, `Game`, `Scene`, `SceneManager`, `ScaleManager`, `GameLoop`, `EngineClock`, `LoaderPlugin`, `JsonCache`, `GameObjectFactory` (`scene.add.instancedBatch`, `customPass`, `panel`, etc.)
7
- - **Display Graph**: `DisplayList`, `DisplayObject`, `Container`, `ImageObject`, `NineSliceObject`, `TileSpriteObject`, `RectangleObject`, `PanelObject`, `MsdfIconObject`, `TextObject`, `Graphics`, `BlitterObject`, `InstancedBatchObject`, `CustomPassObject`
8
- - **Renderers & GPU Batchers**: `RendererWebGpu`, `requestWebGpuDevice`, `RendererGl`, `Renderer2D`, `SdfPanelBatcher`, `MsdfIconBatcher`, `PixelAaBatcher`, `Camera` (`.configureHiDpi()`, `.startFollow()`, `.stopFollow()`, `.screenToWorld()`, `.worldToScreen()`), `Texture`, `CanvasTexture`, `TextureSource`, `Frame`, `TextureManager`
5
+ ## `@holtjs/stage` (~57.3 kB gz · Core Engine Barrel)
6
+ - **Bootstrap & Lifecycle**: `Stage` / `Stage2D` (namespaces), `AUTO`, `WEBGPU`, `WEBGL`, `CANVAS`, `Scale`, `Scenes`, `Game` (`.stepSimOnly()`, `.kernel`), `Scene`, `SceneManager`, `ScaleManager`, `GameLoop`, `EngineClock`, `LoaderPlugin`, `JsonCache`, `GameObjectFactory` (`scene.add.instancedBatch`, `customPass`, `panel`, `blitter`, etc.)
7
+ - **Display Graph**: `DisplayList`, `DisplayObject`, `Container`, `ImageObject`, `NineSliceObject`, `TileSpriteObject`, `RectangleObject`, `PanelObject`, `MsdfIconObject`, `TextObject`, `Graphics`, `BlitterObject`, `InstancedBatchObject`, `CustomPassObject` (`restoreState: true` default)
8
+ - **Renderers & GPU Batchers**: `RendererWebGpu`, `requestWebGpuDevice`, `RendererGl` (`.createRenderTarget()`, `.renderToTarget()`, `.restoreState()`), `Renderer2D`, `SdfPanelBatcher`, `MsdfIconBatcher`, `PixelAaBatcher`, `Camera` (`.configureHiDpi()`, `.startFollow()`, `.stopFollow()`, `.screenToWorld()`, `.worldToScreen()`), `Texture`, `CanvasTexture`, `TextureSource`, `Frame`, `TextureManager` (`.exists()`, `.addCanvas()`, `.get()`)
9
9
  - **Kernel & Input**: `StageKernel`, `ActionMap`, `createInputTimeline`, `createInputRecorder`, `createInputReplay`, `EventEmitter`, `Pointer`, `KeyboardPlugin` (`.isDown()`, `.justPressed()`, `.justReleased()`, `.injectKey()`), `InputPlugin`
10
10
  - **Math & Color**: `BlendModes` (`NORMAL`, `ADD`, `MULTIPLY`, `SCREEN`), `TintModes`, `FilterMode`, `WHITE_RGB`, `BLACK_RGB`, `HEX_MASK`, `createMatrix2D`, `parseColor`, `rgbToCss`, `packColorAbgr`
11
11
  - **Bundled UI/Observability Re-exports**: `computeFlexLayout`, `computeWrapLayout`, `resolvePadding`, `Easings`, `TweenManager`, `VirtualJoystick`, `clampJoystickOrigin`, `computeJoystickVector`, `isInJoystickZone`, `pullJoystickOrigin`, `quantizeJoystickDpad`, `SURFACE_BAND`, `createSurfaceTree`, `resolveSurfacePriority`, `surfacePriorityToDomZ`, `computeSurfaceDomZ`, `buildSceneDigest`, `sanitizeTrackToken`
12
12
 
13
+ ## `@holtjs/stage/webgpu` (~7.4 kB gz · Native WebGPU Renderer)
14
+ - `RendererWebGpu`: WGSL textured quad/polygon batcher + WGSL analytical 4-corner rounded/pixel-stepped SDF `PanelObject` pipelines across `NORMAL`, `ADD`, `MULTIPLY`, `SCREEN` blends
15
+ - `requestWebGpuDevice(canvas, opts?)` -> `Promise<WebGpuBootstrapResult | null>`
16
+ - Types: `WebGpuDeviceLike`, `WebGpuCanvasContextLike`, `RendererWebGpuOptions`, `RequestWebGpuOptions`, `WebGpuBootstrapResult`
17
+
18
+ ## `@holtjs/stage/kernel` (~4.8 kB gz · zero DOM)
19
+ - `StageKernel` (`game.kernel`): `.use(plugin)`, `.remove(id)`, `.get(id)`, `.addInputProvider(p)`, `.actions`, `.digest()`
20
+ - `ActionMap`: `.bind(action, codes)`, `.unbind(action)`, `.isDown(action)`, `.justPressed(action)`, `.justReleased(action)`, `.axis(negAction, posAction)`
21
+ - `createInputTimeline(opts?)`: `.moveTo()`, `.click(trackIdOrPt, atMs, opts?)`, `.drag()`, `.pressKey()`, `.typeText()` (with optional rendered virtual cursor & click ripples via `showCursor: true`)
22
+ - `createInputRecorder(id?)`, `createInputReplay(entries, id?)`
23
+ - Types: `StagePlugin`, `InputProvider`, `StageInputEvent`, `InputTargetSpec`, `TimelineClickOptions`, `TimelineDragOptions`, `TimelineKeyOptions`, `InputTimelineOptions`, `InputTimelinePlugin`, `InputRecorderPlugin`, `RecordedInputEntry`
24
+
25
+ ## `@holtjs/stage/headless` (~38.6 kB gz · pure Node with `@napi-rs/canvas`)
26
+ - `createHeadlessStage(opts)`: `.step()`, `.stepToMs()`, `.stepToFrame()`, `.fastForward(frames)`, `.pointerDown/Move/Up()`, `.keyDown/Up()`, `.toRgba()`, `.toPng()`, `.digest()`, `.recordFrames()`
27
+ - `renderStoryboard(stage, opts)` -> `{ png, width, height, digests }`
28
+ - `createAudioTimeline(opts?)`: `.addAtMs()`, `.addAtFrame()`, `.renderStereo()`, `.toWav()`
29
+ - Types: `HeadlessCanvasLike`, `CreateHeadlessCanvas`, `HeadlessStageOptions`, `HeadlessRecordedFrame`, `RecordFramesOptions`, `HeadlessStage`, `StoryboardOptions`, `StoryboardResult`, `AudioCueOptions`, `AudioTimelineOptions`, `AudioTimeline`
30
+
31
+ ## `@holtjs/stage/rig2d` (~5.7 kB gz · zero DOM)
32
+ - Skeleton & Mixer: `defineRig2DSkeleton(def)`, `Rig2DInstance` (`.play(clip, opts?)`, `.playOverlay(clip, { maskBones?, loop? })`, `.clearOverlay()`, `.setAttachment(slot, attachment)`, `.applySkin(skinNameOrMap)`, `.setSlotTint()`, `.setBoneManualOffset()`, `.onEvent(fn)`, `.step(deltaMs)`, `.getBoneWorldTransform(bone, out?)`)
33
+ - Scene Mounting & Procedural Cutout Baker: `mountRig2D(scene, instance, opts?)` (`.container`, `.update(deltaMs?)`, `.sync()`, `.destroy()`), `bakeCutoutAtlas(textureKey, parts, createCanvas?)` (`.registerOnScene(scene)`), `wrapAngleDelta`, `evalRigCurve`
34
+ - Types: `RigCurveKind`, `RigBoneDef`, `RigSlotDef`, `RigAttachmentDef`, `RigKeyframe`, `RigEventKeyframe`, `RigClipDef`, `RigSkeletonDef`, `CompiledBone`, `CompiledSlot`, `Rig2DSkeleton`, `RigPlayOptions`, `RigOverlayOptions`, `RigWorldTransform`, `RigEventListener`, `MountRig2DOptions`, `Rig2DView`, `CutoutShapeOp`, `CutoutPartSpec`, `BakedCutoutAtlas`
35
+
36
+ ## `@holtjs/stage/tilemap` (~3.5 kB gz · zero DOM)
37
+ - Sparse Chunk Storage: `ChunkedTilemap` (`.getGround(tx, ty)`, `.setGround(tx, ty, turfId)`, `.getOverlay(tx, ty)`, `.setOverlay(tx, ty, id, solid?)`, `.isWalkable(tx, ty)`, `.sampleDualGridMask()`, `.sampleOverlayBlob47()`, `.extractWalkGrid(...)`, `.exportModifiedCells()`), `TileCellFlags`, `packChunkKey`, `unpackChunkX`, `unpackChunkY`, `floorDiv`, `positiveMod`
38
+ - Autotilers & Procedural Biomes: `computeDualGridMask(...)` (16-tile Oskar Stålberg Dual-Grid), `computeBlob47Index(...)` (47-tile Blob), `bakeDualGridTileset(textureKey, tileSize, layers, createCanvas?)`, `SurvivalBiomes`, `createIslandBiomeGenerator(cfg)`, `hash2D`, `valueNoise2D`, `fbm2D`
39
+ - Scene Streaming Adapter: `mountChunkedTilemap(scene, tilemap, atlas, opts?)` -> `MountedChunkedTilemap` (`.container`, `.update(viewBounds)`, `.destroy()`)
40
+ - Types: `TileChunk`, `ChunkGeneratorFn`, `ChunkedTilemapOptions`, `IslandBiomeConfig`, `DualGridLayerSpec`, `BakedDualGridAtlas`, `MountedChunkedTilemap`
41
+
42
+ ## `@holtjs/stage/projection` (~1.6 kB gz · zero DOM)
43
+ - `Camera25D`: `.worldToScreen(wx, wy, wz?, out?)`, `.screenToGround(sx, sy, planeZ?, out?)` (exact inverse across any 360° `yaw`), `.rotateSteps(steps, stepAngleRad?)`, `.setYawImmediate(yawRad)`, `.step(deltaMs)`, `.getGroundViewportBounds()`, `.computeSunShadowVector(...)`
44
+ - `mountStage25D(scene, cam, opts?)` -> `Stage25DRig` (`.groundWorld`, `.shadowLayer`, `.billboardLayer`, `.registerBillboard(node, wx, wy, opts?)`, `.removeBillboard(entryOrNode)`, `.update(deltaMs?)`, `.destroy()`)
45
+ - Types: `Camera25DConfig`, `ProjectedPoint25D`, `BillboardEntry`, `Stage25DRig`
46
+
47
+ ## `@holtjs/stage/lighting` (~4.1 kB gz · zero DOM)
48
+ - `DayNightCycle`: `.step(deltaMs)`, `.setTime01(t)`, `.sample(out?)` -> `DayNightState` (`phase`, `ambientRgb`, `ambientIntensity`, `sunAzimuth`, `sunElevation`, `shadowScale`), `lerpRgb`
49
+ - Normal Maps & Per-Pixel Evaluation: `computeNormalMapPixels(rgba, w, h, opts?)` (3×3 Sobel height-to-normal), `bakeNormalMapCanvas(srcCanvas, createCanvas?, opts?)`, `evaluateNormalLitPixel(...)`
50
+ - Scene Lightmap & WebGL2 Normal Pass: `Lighting2DSystem` (`.addLight(light)`, `.getLight(id)`, `.removeLight(id)`, `.setAmbientOverride(rgb)`, `.update(dayNight, simTimeMs, projectToScreen?)`, `.destroy()`), `createNormalLitSpritePass(scene, opts)`
51
+ - Types: `DayPhase`, `DayNightConfig`, `DayNightState`, `NormalMapBakeOptions`, `PointLight2D`, `Lighting2DSystemOptions`, `NormalLitQuad`
52
+
53
+ ## `@holtjs/stage/world` (~2.8 kB gz · zero DOM)
54
+ - Items, Spoilage & Crafting: `ItemRegistry`, `InventoryContainer` (`.addItem()`, `.removeItem()`, `.countItem()`, `.hasItems()`, `.stepSpoilage(deltaMs)`), `RecipeRegistry` (`.canCraft()`, `.craftInstant()`), `WorkstationInstance` (`.enqueue()`, `.step()`), `WorkstationScheduler` (`.stepAll(deltaMs)` offline catch-up)
55
+ - Binary Delta Save (`HWLD`): `captureWorldDelta(...)`, `applyWorldDelta(...)`, `encodeWorldDeltaBytes(snapshot)`, `decodeWorldDeltaBytes(bytes)`
56
+ - Types: `ItemDef`, `ItemStack`, `RecipeDef`, `WorkstationJob`, `WorkstationSnapshot`, `WorldEntityRecord`, `TileCellDelta`, `WorldDeltaSnapshot`
57
+
13
58
  ## `@holtjs/stage/flex` (~2.3 kB gz · zero DOM)
14
- - `resolvePadding(p)`
15
- - `computeFlexLayout(container, items)` -> `FlexResult` (`{ w, h, rects }`)
16
- - `computeWrapLayout(container, items)` -> `WrapResult` (`{ w, h, rects }`)
17
- - Types: `FlexDir`, `FlexAlign`, `FlexJustify`, `FlexPadding`, `FlexContainerSpec`, `FlexItemSpec`, `FlexItemRect`, `FlexResult`, `WrapJustify`, `WrapContainerSpec`, `WrapItemSpec`, `WrapItemRect`, `WrapResult`
59
+ - `resolvePadding(p)`, `computeFlexLayout(container, items)`, `computeWrapLayout(container, items)`
18
60
 
19
61
  ## `@holtjs/stage/tween` (~1.4 kB gz · zero DOM)
20
- - `TweenManager`: `.to(opts)` (and `.add(opts)` alias), `.spring(opts)`, `.step(deltaMs)`, `.clear()`, `.stats()`
21
- - `Easings`: standard easing functions (`linear`, `inQuad`, `outQuad`, `inOutQuad`, `inCubic`, `outCubic`, `inOutCubic`, `outQuart`, `inOutSine`, `outBack`)
22
- - Types: `EasingFn`, `EasingName`, `DisposableOwner`, `TweenOptions`, `SpringOptions`, `TweenHandle`, `SpringHandle`, `TweenStats`
62
+ - `TweenManager`: `.to(opts)` (`.add(opts)` alias), `.spring(opts)`, `.step(deltaMs)`, `.clear()`, `.stats()`
63
+ - `Easings`: `linear`, `inQuad`, `outQuad`, `inOutQuad`, `inCubic`, `outCubic`, `inOutCubic`, `outQuart`, `inOutSine`, `outBack`
23
64
 
24
65
  ## `@holtjs/stage/joystick` (~4.4 kB gz)
25
- - `VirtualJoystick` (multi-touch `pointer.id`-isolated floating/fixed joystick)
26
- - Pure math helpers (zero DOM): `computeJoystickVector`, `isInJoystickZone`, `clampJoystickOrigin`, `pullJoystickOrigin`, `quantizeJoystickDpad`
27
- - Types: `VirtualJoystickMode`, `JoystickVector`, `JoystickState`, `JoystickZoneRect`, `JoystickZonePredicate`, `JoystickZone`, `JoystickViewport`, `VirtualJoystickStyle`, `JoystickDpad`, `JoystickDpadOptions`, `VirtualJoystickOptions`
66
+ - `VirtualJoystick`, `computeJoystickVector`, `isInJoystickZone`, `clampJoystickOrigin`, `pullJoystickOrigin`, `quantizeJoystickDpad`
28
67
 
29
68
  ## `@holtjs/stage/surfaces` (~2.2 kB gz · zero DOM)
30
- - `SURFACE_BAND`: ordered layer bands (`world`, `hud`, `panel`, `sheet`, `modal`, `popover`, `toast`, `fullscreen`, `system`)
31
- - `createSurfaceTree()` -> `SurfaceTree` (`.register()`, `.active()`, `.topBarrier()`, `.isWorldBlocked()`, `.dispatchCancel()`, `.dispatchKey()`, `.dispatchFocus()`)
32
- - DOM z-index projection: `resolveSurfacePriority`, `surfacePriorityToDomZ`, `computeSurfaceDomZ`
33
- - Types: `SurfaceBandName`, `SurfaceBand`, `SurfaceScope`, `SurfaceBarrier`, `SurfaceNodeInput`, `SurfaceNodeInfo`, `SurfaceDomEntry`, dispatch context & result types
69
+ - `SURFACE_BAND`, `createSurfaceTree()`, `resolveSurfacePriority`, `surfacePriorityToDomZ`, `computeSurfaceDomZ`
34
70
 
35
71
  ## `@holtjs/stage/trace` (~1.9 kB gz · zero DOM)
36
- - `buildSceneDigest(scene, opts?)` -> `SceneDigest` (PII-free snapshot: `clock`, `viewport`, `renderer`, `lifecycle`, `tweens`, `overlays`, `surfaces`, `sandbox`, `nodes`)
37
- - `sanitizeTrackToken(token)`
72
+ - `buildSceneDigest(scene, opts?)`, `sanitizeTrackToken(token)`
38
73
 
39
74
  ## `@holtjs/stage/spatial` (~1.2 kB gz · zero DOM)
40
- - `SpatialHashGrid`: `.rebuild(count, xs, ys)`, `.queryRect(minX, minY, maxX, maxY, visitor)`, `.queryRadius(cx, cy, r, xs, ys, visitor)`, `.accumulateSeparation(selfIdx, x, y, minDist, xs, ys, out)`
41
- - Functional helpers: `createSpatialHashBuffers`, `rebuildSpatialHash`, `querySpatialNeighborhood`, `querySpatialRadius`, `querySpatialRect`, `accumulateSpatialSeparation`
42
- - Types: `Vec2`, `SpatialHashBuffers`, `SpatialHashOptions`
75
+ - `SpatialHashGrid`, `createSpatialHashBuffers`, `rebuildSpatialHash`, `querySpatialNeighborhood`, `querySpatialRadius`, `querySpatialRect`, `accumulateSpatialSeparation`
43
76
 
44
77
  ## `@holtjs/stage/hit` (~1.1 kB gz · zero DOM)
45
- - Continuous & geometric hit tests: `sweptCircleHit(ax, ay, sx, sy, cx, cy, radius)` (displacement `(sx, sy)`, returns `t in [0, 1]` or `-1`), `arcSweepFirstContact`, `arcSweepTouches`, `circleOverlapsCircle`, `aabbOverlapsAabb`, `circleOverlapsAabb`, `pointToSegmentDistSq`, `segmentHitsCircle`, `capsuleHitsCircle`
46
- - Collision push-out & knockback: `resolveCircleObstacles`, `resolveCircleAabb`, `knockbackDecay`, `knockbackInitialSpeed`, `stepKnockback`
47
- - Types: `Point2`, `CircleObstacle`, `RectBounds`
78
+ - `sweptCircleHit`, `arcSweepFirstContact`, `arcSweepTouches`, `circleOverlapsCircle`, `aabbOverlapsAabb`, `circleOverlapsAabb`, `pointToSegmentDistSq`, `segmentHitsCircle`, `capsuleHitsCircle`, `resolveCircleObstacles`, `resolveCircleAabb`, `knockbackDecay`, `knockbackInitialSpeed`, `stepKnockback`
48
79
 
49
80
  ## `@holtjs/stage/nav` (~2.3 kB gz · zero DOM)
50
- - Multi-target FlowField: `buildCircleObstacleGrid`, `buildTileWalkGrid`, `computeFlowField`, `isFlowLineClear`, `sampleFlowStep`, `FlowFieldGrid` (`.compute(slot, tx, ty)`, `.sample(slot, x, y, tx, ty, dist?, opts?)` -> `[wx, wy] | null`)
51
- - Point-to-point grid pathfinding: `hasGridLineOfSight`, `findGridPath`, `steerToward`
52
- - Types: `TileWalkable`, `CircleGridOptions`, `FlowSampleOptions`, `GridLosOptions`, `GridPathOptions`
81
+ - `FlowFieldGrid`, `buildCircleObstacleGrid`, `buildTileWalkGrid`, `computeFlowField`, `isFlowLineClear`, `sampleFlowStep`, `hasGridLineOfSight`, `findGridPath`, `steerToward`
53
82
 
54
83
  ## `@holtjs/stage/particles` (~3.0 kB gz · zero DOM)
55
- - Shapes & fade curves: `PARTICLE_RECT`, `PARTICLE_SPARKLE`, `PARTICLE_BUBBLE`, `PARTICLE_WAKE`, `FADE_PUNCH`, `FADE_SINE`, `FADE_FLICKER`, `FADE_EASE`, `FADE_LINEAR`, `FLAG_SIZE_POP`
56
- - `ParticlePool`: `.spawn(opts)`, `.burst(x, y, opts)`, `.sparks(x, y, opts)`, `.puff(x, y, opts)`, `.step(dt, nowMs)`, `.activeCount`
57
- - `drawParticlePool(gfx, pool)`
58
- - `AmbientEmitterPool`: `.setEmitters(specs)`, `.step(dt, nowMs, view, opts?)`
59
- - `JuiceController`: `.hitstop(ms, nowMs, cooldownMs?)`, `.shake(trauma)`, `.tick(deltaMs, nowMs)` -> effective `dt` (updates `.ox`, `.oy`, `.trauma`)
84
+ - `ParticlePool`, `drawParticlePool`, `AmbientEmitterPool`, `JuiceController`, `PARTICLE_RECT`, `PARTICLE_SPARKLE`, `PARTICLE_BUBBLE`, `PARTICLE_WAKE`, `FADE_PUNCH`, `FADE_SINE`, `FADE_FLICKER`, `FADE_EASE`, `FADE_LINEAR`, `FLAG_SIZE_POP`
60
85
 
61
86
  ## `@holtjs/stage/audio` (~4.0 kB gz · zero DOM)
62
- - Procedural Foley DSP: `renderFoley`, `renderFoleyVariants`, `createVariantPicker`, `buildSwimStrokeFoley`, `buildDiveInFoley`, `buildClimbOutFoley`, `buildStepWoodFoley`, `buildStepGrassFoley`, `buildStepSandFoley`, `buildStepStoneFoley`, `buildStepSoftFoley`
63
- - Synth & Spatial Audio: `midi`, `noteNum`, `hz`, `synthVoice`, `tune`, `renderVoices`, `spatialMix`, `encodeWavPcm16`, `mulberry32`, `onePoleAlpha`, `softClipSample`
87
+ - `renderFoley`, `renderFoleyVariants`, `createVariantPicker`, `buildSwimStrokeFoley`, `buildDiveInFoley`, `buildClimbOutFoley`, `buildStepWoodFoley`, `buildStepGrassFoley`, `buildStepSandFoley`, `buildStepStoneFoley`, `buildStepSoftFoley`, `midi`, `noteNum`, `hz`, `synthVoice`, `tune`, `renderVoices`, `spatialMix`, `encodeWavPcm16`
64
88
 
65
89
  ## `@holtjs/stage/ecs` (~3.5 kB gz · zero DOM)
66
- - Entity & Schema: `defineComponent(name, schema)`, `entityIndex(id)`, `entityGeneration(id)`
67
- - `SoaWorld`: `.spawn()`, `.despawn(e)`, `.alive(e)`, `.slotOf(e)`, `.entityAt(slot)`, `.register(def)`, `.store(def)`, `.maskOf(...defs)`, `.add(e, def, init?)`, `.remove(e, def)`, `.has(e, def)`, `.query(includeMask, outSlots, excludeMask?)`, `.syncSpatial(xCol, yCol, opts)`, `.queryRadius(...)`, `.queryRect(...)`, `.clear()`, `.stats()`
68
- - 2.5D Sorting & Instanced Bands: `sortSlotsByDepth(slots, count, depthCol, tieCol?)`, `cullAndSortSlots(...)`, `partitionDepthBands(sortedSlots, sortedCount, depthCol, blockerDepths, blockerCount, outBands)`
69
- - Types: `ComponentFieldType`, `ComponentSchema`, `ComponentColumns`, `ComponentDef`, `EntityId`, `DepthBand`, `EcsSpatialOptions`, `SoaWorldStats`
70
-
71
- ## `@holtjs/stage/headless`
72
-
73
- - Functions: `createHeadlessStage` (with `.step()`, `.fastForward()`, `.pointerDown/Move/Up()`, `.keyDown/Up()`, `.recordFrames()`), `renderStoryboard`, `createAudioTimeline`
74
- - Types: `HeadlessCanvasLike`, `CreateHeadlessCanvas`, `HeadlessStageOptions`, `HeadlessRecordedFrame`, `RecordFramesOptions`, `HeadlessStage`, `StoryboardOptions`, `StoryboardResult`, `AudioCueOptions`, `AudioTimelineOptions`, `AudioTimeline`
75
-
76
- ## `@holtjs/stage/kernel` (~2.8 kB gz · zero DOM)
77
- - Classes & Factories: `StageKernel`, `ActionMap`, `createInputTimeline` (click by `trackId` or `{ x, y }`, drag, `pressKey`, `typeText`, optional visual cursor), `createInputRecorder`, `createInputReplay`
78
- - Types: `StagePlugin`, `InputProvider`, `StageInputEvent`, `InputTargetSpec`, `InputTimelineOptions`, `InputTimelinePlugin`, `InputRecorderPlugin`, `RecordedInputEntry`
79
-
80
- ## `@holtjs/stage/webgpu` (~3.8 kB gz)
81
- - `RendererWebGpu`, `requestWebGpuDevice(canvas, opts)`
82
- - Types: `WebGpuDeviceLike`, `WebGpuCanvasContextLike`, `RendererWebGpuOptions`, `RequestWebGpuOptions`, `WebGpuBootstrapResult`
90
+ - `SoaWorld`, `defineComponent`, `entityIndex`, `entityGeneration`, `sortSlotsByDepth`, `cullAndSortSlots`, `partitionDepthBands`