@holtjs/stage 0.0.0-stage → 0.3.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.
@@ -0,0 +1,147 @@
1
+ import { f as SceneInput, n as EngineClockSnapshot, r as Game, u as Scene } from "./game-NqFMKsuL.js";
2
+ import { SceneDigest, SceneDigestOptions } from "./trace.js";
3
+ /** Minimal Canvas2D surface compatible with `@napi-rs/canvas`, `node-canvas`, and browser `<canvas>`. */
4
+ export interface HeadlessCanvasLike {
5
+ width: number;
6
+ height: number;
7
+ getContext(contextId: '2d', options?: unknown): CanvasRenderingContext2D | null;
8
+ toBuffer?(mimeType: 'image/png'): Uint8Array;
9
+ }
10
+ export type CreateHeadlessCanvas = (width: number, height: number) => HeadlessCanvasLike;
11
+ export interface HeadlessStageOptions {
12
+ /** Canvas factory such as `createCanvas` from `@napi-rs/canvas`. */
13
+ readonly createCanvas: CreateHeadlessCanvas;
14
+ /** Optional `Path2D` constructor (e.g. from `@napi-rs/canvas`) so `MsdfIconObject` paths render in Node. */
15
+ readonly Path2D?: typeof Path2D;
16
+ /** Viewport width in pixels (default `1280`). */
17
+ readonly width?: number;
18
+ /** Viewport height in pixels (default `720`). */
19
+ readonly height?: number;
20
+ /** Deterministic simulation & recording frame rate in Hz (default `60`). */
21
+ readonly fps?: number;
22
+ /** Background color (`'#12161f'` or `0x12161f`); ignored when `transparent: true`. */
23
+ readonly backgroundColor?: string | number;
24
+ /** Clear to transparent instead of filling `backgroundColor` (default `false`). */
25
+ readonly transparent?: boolean;
26
+ /** Nearest-neighbor pixel-art filtering default (default `false`). */
27
+ readonly pixelArt?: boolean;
28
+ /** Optional custom WebGL/WebGL2 context when testing GPU shaders headlessly; defaults to `CANVAS` (`Renderer2D`). */
29
+ readonly glContext?: WebGL2RenderingContext | WebGLRenderingContext | null;
30
+ /** Scene instance or constructor to boot synchronously at frame 0. */
31
+ readonly scene: SceneInput;
32
+ }
33
+ export interface HeadlessRecordedFrame {
34
+ /** Zero-based recorded frame index (`0 .. frames - 1`). */
35
+ readonly index: number;
36
+ /** Engine `frameSeq` after stepping this frame. */
37
+ readonly frameSeq: number;
38
+ /** Deterministic simulation timestamp in milliseconds. */
39
+ readonly simTimeMs: number;
40
+ /** Raw RGBA8888 pixel buffer (`width * height * 4` bytes, ready for `ffmpeg -f rawvideo -pix_fmt rgba`). */
41
+ readonly rgba: Uint8Array;
42
+ /** Optional zero-PII `SceneDigest` snapshot when `includeDigest` is enabled. */
43
+ readonly digest?: SceneDigest;
44
+ }
45
+ export interface RecordFramesOptions {
46
+ /** Total number of frames to step and capture (`frames` or `durationMs` required). */
47
+ readonly frames?: number;
48
+ /** Total duration in milliseconds to step and capture at `stage.fps` (used if `frames` is omitted). */
49
+ readonly durationMs?: number;
50
+ /** Capture a `buildSceneDigest()` snapshot every N frames (`1` = every frame, `0` = never; default `0`). */
51
+ readonly digestEvery?: number;
52
+ /** Options forwarded to `buildSceneDigest()`. */
53
+ readonly digestOptions?: SceneDigestOptions;
54
+ /** Streaming frame consumer (may be sync or async, e.g. backpressure-aware `ffmpeg.stdin.write`). */
55
+ readonly onFrame: (frame: HeadlessRecordedFrame) => void | Promise<void>;
56
+ }
57
+ export interface HeadlessStage {
58
+ readonly game: Game;
59
+ readonly scene: Scene;
60
+ readonly canvas: HeadlessCanvasLike;
61
+ readonly width: number;
62
+ readonly height: number;
63
+ readonly fps: number;
64
+ readonly frameDurationMs: number;
65
+ /** Advance `frames` deterministic ticks (`dt = 1000 / fps`), rendering the final stepped frame. */
66
+ step(frames?: number): EngineClockSnapshot;
67
+ /** Advance deterministically until `clock.simTimeMs >= targetSimTimeMs`. */
68
+ stepToMs(targetSimTimeMs: number): EngineClockSnapshot;
69
+ /** Advance deterministically until `clock.frameSeq >= targetFrameSeq`. */
70
+ stepToFrame(targetFrameSeq: number): EngineClockSnapshot;
71
+ /** Synthesize a deterministic pointer-down event in canvas coordinates. */
72
+ pointerDown(x: number, y: number, button?: number): void;
73
+ /** Synthesize a deterministic pointer-move event in canvas coordinates. */
74
+ pointerMove(x: number, y: number): void;
75
+ /** Synthesize a deterministic pointer-up event in canvas coordinates. */
76
+ pointerUp(x: number, y: number, button?: number): void;
77
+ /** Read raw W3C RGBA8888 pixels (`width * height * 4` bytes). */
78
+ toRgba(): Uint8Array;
79
+ /** Encode current frame to PNG bytes (requires `canvas.toBuffer('image/png')` such as `@napi-rs/canvas`). */
80
+ toPng(): Uint8Array;
81
+ /** Capture a zero-PII structured `SceneDigest` for the active scene at the current frame. */
82
+ digest(options?: SceneDigestOptions): SceneDigest;
83
+ /** Step and stream raw RGBA frames (e.g. into `ffmpeg`) at deterministic `fps`. */
84
+ recordFrames(options: RecordFramesOptions): Promise<EngineClockSnapshot>;
85
+ /** Destroy the headless stage and release resources. */
86
+ destroy(): void;
87
+ }
88
+ /**
89
+ * Create a deterministic, zero-browser Stage instance backed by any Canvas2D implementation
90
+ * (such as `@napi-rs/canvas` in Node) for AI-agent drawing, CI visual assertions, and 60 FPS video rendering.
91
+ */
92
+ export declare function createHeadlessStage(options: HeadlessStageOptions): HeadlessStage;
93
+ export interface StoryboardOptions {
94
+ /** Ascending frame numbers to capture (e.g. `[0, 30, 60, 90, 120, 150]`). */
95
+ readonly frames: readonly number[];
96
+ /** Canvas factory used to allocate the contact sheet. */
97
+ readonly createCanvas: CreateHeadlessCanvas;
98
+ /** Number of columns in the grid (default `3`). */
99
+ readonly columns?: number;
100
+ /** Downscale factor per tile (`0.5` renders half-size tiles; default `0.5`). */
101
+ readonly tileScale?: number;
102
+ /** Gap/padding in pixels between tiles (default `12`). */
103
+ readonly gap?: number;
104
+ /** Draw `f#060 · 1000ms` timestamp badge on each tile (default `true`). */
105
+ readonly labels?: boolean;
106
+ /** Optional `SceneDigest` options captured alongside each keyframe. */
107
+ readonly digestOptions?: SceneDigestOptions;
108
+ }
109
+ export interface StoryboardResult {
110
+ readonly width: number;
111
+ readonly height: number;
112
+ readonly canvas: HeadlessCanvasLike;
113
+ readonly png: Uint8Array | null;
114
+ readonly digests: SceneDigest[];
115
+ }
116
+ /**
117
+ * Step a `HeadlessStage` across target keyframes and composite a single multi-panel
118
+ * storyboard contact sheet + paired `SceneDigest` array so AI agents can visually and
119
+ * structurally inspect an entire 60 FPS animation in one shot.
120
+ */
121
+ export declare function renderStoryboard(stage: HeadlessStage, options: StoryboardOptions): StoryboardResult;
122
+ export interface AudioCueOptions {
123
+ /** Linear gain multiplier (default `0.75`). */
124
+ readonly gain?: number;
125
+ /** Stereo pan in `[-1, +1]` (`-1` full left, `0` center, `+1` full right; default `0`). */
126
+ readonly pan?: number;
127
+ }
128
+ export interface AudioTimelineOptions {
129
+ /** Output sample rate in Hz (default `44100`). */
130
+ readonly sampleRate?: number;
131
+ }
132
+ export interface AudioTimeline {
133
+ readonly sampleRate: number;
134
+ /** Schedule a mono `Float32Array` buffer (from `renderFoley` / `renderVoices`) at `timeMs`. */
135
+ addAtMs(timeMs: number, monoSamples: Float32Array, options?: AudioCueOptions): void;
136
+ /** Schedule a mono `Float32Array` buffer at a specific video `frame` (`timeMs = (frame / fps) * 1000`). */
137
+ addAtFrame(frame: number, fps: number, monoSamples: Float32Array, options?: AudioCueOptions): void;
138
+ /** Mix all scheduled cues over `durationMs` into interleaved stereo 16-bit PCM (`L, R, L, R...`). */
139
+ toStereoPcm16(durationMs: number): Int16Array;
140
+ /** Mix all scheduled cues over `durationMs` into a complete stereo 16-bit PCM `.wav` file (`Uint8Array`). */
141
+ toWav(durationMs: number): Uint8Array;
142
+ }
143
+ /**
144
+ * Deterministic stereo audio timeline mixer for pairing `@holtjs/stage/audio` procedural foley &
145
+ * chiptune cues with 60 FPS headless video renders. Exports ready-to-mux stereo 16-bit `.wav` bytes.
146
+ */
147
+ export declare function createAudioTimeline(options?: AudioTimelineOptions): AudioTimeline;
@@ -0,0 +1,327 @@
1
+ import "./types-ChGhuDNX.js";
2
+ import { n as Game } from "./game-BHDcwovp.js";
3
+ import { buildSceneDigest } from "./trace.js";
4
+ // src/headless.ts
5
+ function createVirtualDomHost(createCanvas, width, height) {
6
+ const winStub = {
7
+ innerWidth: width,
8
+ innerHeight: height,
9
+ devicePixelRatio: 1,
10
+ addEventListener() {},
11
+ removeEventListener() {},
12
+ requestAnimationFrame() {
13
+ return 0;
14
+ },
15
+ cancelAnimationFrame() {}
16
+ };
17
+ const docStub = {
18
+ defaultView: winStub,
19
+ hidden: false,
20
+ activeElement: null,
21
+ body: null,
22
+ getElementById() {
23
+ return null;
24
+ },
25
+ createElement(tag) {
26
+ if (String(tag).toLowerCase() === "canvas") return decorateCanvas(createCanvas(1, 1));
27
+ return {
28
+ style: {},
29
+ addEventListener() {},
30
+ removeEventListener() {}
31
+ };
32
+ }
33
+ };
34
+ function decorateCanvas(raw) {
35
+ const target = raw;
36
+ if (!target.style) target.style = {};
37
+ if (!("ownerDocument" in target)) Object.defineProperty(target, "ownerDocument", {
38
+ value: docStub,
39
+ configurable: true,
40
+ enumerable: false
41
+ });
42
+ if (!("parentNode" in target)) target.parentNode = null;
43
+ if (typeof target.addEventListener !== "function") target.addEventListener = () => {};
44
+ if (typeof target.removeEventListener !== "function") target.removeEventListener = () => {};
45
+ if (typeof target.remove !== "function") target.remove = () => {};
46
+ if (typeof target.getBoundingClientRect !== "function") target.getBoundingClientRect = () => ({
47
+ x: 0,
48
+ y: 0,
49
+ left: 0,
50
+ top: 0,
51
+ right: raw.width,
52
+ bottom: raw.height,
53
+ width: raw.width,
54
+ height: raw.height,
55
+ toJSON: () => ({})
56
+ });
57
+ return raw;
58
+ }
59
+ return {
60
+ rootCanvas: decorateCanvas(createCanvas(width, height)),
61
+ doc: docStub,
62
+ win: winStub
63
+ };
64
+ }
65
+ /**
66
+ * Create a deterministic, zero-browser Stage instance backed by any Canvas2D implementation
67
+ * (such as `@napi-rs/canvas` in Node) for AI-agent drawing, CI visual assertions, and 60 FPS video rendering.
68
+ */
69
+ function createHeadlessStage(options) {
70
+ const width = Math.max(1, Math.round(options.width ?? 1280));
71
+ const height = Math.max(1, Math.round(options.height ?? 720));
72
+ const fps = Math.max(1, Math.min(240, options.fps ?? 60));
73
+ const dt = 1e3 / fps;
74
+ if (options.Path2D && typeof globalThis.Path2D !== "function") globalThis.Path2D = options.Path2D;
75
+ const { rootCanvas } = createVirtualDomHost(options.createCanvas, width, height);
76
+ const game = new Game({
77
+ type: options.glContext ? 2 : 1,
78
+ canvas: rootCanvas,
79
+ context: options.glContext ?? void 0,
80
+ width,
81
+ height,
82
+ backgroundColor: options.backgroundColor ?? "#12161f",
83
+ transparent: options.transparent ?? false,
84
+ pixelArt: options.pixelArt ?? false,
85
+ autoStart: false,
86
+ input: { keyboard: false },
87
+ scene: options.scene
88
+ });
89
+ const primaryScene = game.scene.scenes[0];
90
+ if (!primaryScene) throw new Error("createHeadlessStage: scene failed to initialize");
91
+ let simCursorMs = 0;
92
+ game.renderer.render(primaryScene._displayList, primaryScene.cameras.main);
93
+ const emitPointer = (eventName, x, y, isDown, button = 0) => {
94
+ const p = game.input.activePointer;
95
+ p.x = x;
96
+ p.y = y;
97
+ p.isDown = isDown;
98
+ p.button = button;
99
+ p.buttons = isDown ? 1 : 0;
100
+ p.updateWorldPoint(primaryScene.cameras.main);
101
+ game.input.emit(eventName, p);
102
+ };
103
+ const step = (frames = 1) => {
104
+ const count = Math.max(0, Math.floor(frames));
105
+ for (let i = 0; i < count; i++) {
106
+ simCursorMs += dt;
107
+ game.step(simCursorMs, dt);
108
+ }
109
+ return game.clock.snapshot();
110
+ };
111
+ const stepToMs = (targetSimTimeMs) => {
112
+ while (simCursorMs + dt * .5 <= targetSimTimeMs) {
113
+ simCursorMs += dt;
114
+ game.step(simCursorMs, dt);
115
+ }
116
+ return game.clock.snapshot();
117
+ };
118
+ const stepToFrame = (targetFrameSeq) => {
119
+ const target = Math.max(0, Math.floor(targetFrameSeq));
120
+ while (game.clock.frameSeq < target) {
121
+ simCursorMs += dt;
122
+ game.step(simCursorMs, dt);
123
+ }
124
+ return game.clock.snapshot();
125
+ };
126
+ const toRgba = () => {
127
+ if (game.renderer.type === 2 && game.renderer.gl) {
128
+ const gl = game.renderer.gl;
129
+ const out = new Uint8Array(width * height * 4);
130
+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, out);
131
+ return out;
132
+ }
133
+ const ctx = rootCanvas.getContext("2d");
134
+ if (!ctx) throw new Error("HeadlessStage.toRgba: 2D context unavailable");
135
+ const img = ctx.getImageData(0, 0, width, height);
136
+ return new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength);
137
+ };
138
+ const toPng = () => {
139
+ if (typeof rootCanvas.toBuffer === "function") {
140
+ const buf = rootCanvas.toBuffer("image/png");
141
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
142
+ }
143
+ throw new Error("HeadlessStage.toPng: canvas does not implement toBuffer(\"image/png\"); pass createCanvas from @napi-rs/canvas");
144
+ };
145
+ const digest = (digestOpts) => buildSceneDigest(primaryScene, digestOpts);
146
+ const recordFrames = async (recOpts) => {
147
+ const totalFrames = recOpts.frames !== void 0 ? Math.max(1, Math.floor(recOpts.frames)) : Math.max(1, Math.round((recOpts.durationMs ?? 1e3) / 1e3 * fps));
148
+ const digestEvery = Math.max(0, Math.floor(recOpts.digestEvery ?? 0));
149
+ for (let i = 0; i < totalFrames; i++) {
150
+ if (i > 0 || game.clock.frameSeq === 0) {
151
+ simCursorMs += dt;
152
+ game.step(simCursorMs, dt);
153
+ }
154
+ const snapDigest = digestEvery > 0 && i % digestEvery === 0 ? digest(recOpts.digestOptions) : void 0;
155
+ await recOpts.onFrame({
156
+ index: i,
157
+ frameSeq: game.clock.frameSeq,
158
+ simTimeMs: Math.round(simCursorMs),
159
+ rgba: toRgba(),
160
+ digest: snapDigest
161
+ });
162
+ }
163
+ return game.clock.snapshot();
164
+ };
165
+ return {
166
+ game,
167
+ scene: primaryScene,
168
+ canvas: rootCanvas,
169
+ width,
170
+ height,
171
+ fps,
172
+ frameDurationMs: dt,
173
+ step,
174
+ stepToMs,
175
+ stepToFrame,
176
+ pointerDown: (x, y, button = 0) => emitPointer("pointerdown", x, y, true, button),
177
+ pointerMove: (x, y) => emitPointer("pointermove", x, y, game.input.activePointer.isDown),
178
+ pointerUp: (x, y, button = 0) => emitPointer("pointerup", x, y, false, button),
179
+ toRgba,
180
+ toPng,
181
+ digest,
182
+ recordFrames,
183
+ destroy: () => game.destroy(false)
184
+ };
185
+ }
186
+ /**
187
+ * Step a `HeadlessStage` across target keyframes and composite a single multi-panel
188
+ * storyboard contact sheet + paired `SceneDigest` array so AI agents can visually and
189
+ * structurally inspect an entire 60 FPS animation in one shot.
190
+ */
191
+ function renderStoryboard(stage, options) {
192
+ const frames = [...options.frames].sort((a, b) => a - b);
193
+ if (frames.length === 0) throw new Error("renderStoryboard: frames array must not be empty");
194
+ const cols = Math.max(1, Math.min(frames.length, Math.floor(options.columns ?? 3)));
195
+ const rows = Math.ceil(frames.length / cols);
196
+ const scale = Math.max(.1, Math.min(2, options.tileScale ?? .5));
197
+ const gap = Math.max(0, Math.round(options.gap ?? 12));
198
+ const tileW = Math.max(1, Math.round(stage.width * scale));
199
+ const tileH = Math.max(1, Math.round(stage.height * scale));
200
+ const sheetW = cols * tileW + (cols + 1) * gap;
201
+ const sheetH = rows * tileH + (rows + 1) * gap;
202
+ const sheet = options.createCanvas(sheetW, sheetH);
203
+ const ctx = sheet.getContext("2d");
204
+ if (!ctx) throw new Error("renderStoryboard: 2D context unavailable");
205
+ ctx.fillStyle = "#0d1017";
206
+ ctx.fillRect(0, 0, sheetW, sheetH);
207
+ const digests = [];
208
+ for (let i = 0; i < frames.length; i++) {
209
+ const targetFrame = frames[i];
210
+ if (targetFrame > 0) stage.stepToFrame(targetFrame);
211
+ digests.push(stage.digest(options.digestOptions));
212
+ const col = i % cols;
213
+ const row = Math.floor(i / cols);
214
+ const tx = gap + col * (tileW + gap);
215
+ const ty = gap + row * (tileH + gap);
216
+ ctx.drawImage(stage.canvas, 0, 0, stage.width, stage.height, tx, ty, tileW, tileH);
217
+ ctx.strokeStyle = "rgba(255, 255, 255, 0.14)";
218
+ ctx.lineWidth = 1;
219
+ ctx.strokeRect(tx + .5, ty + .5, tileW - 1, tileH - 1);
220
+ if (options.labels !== false) {
221
+ const snap = stage.game.clock.snapshot();
222
+ const label = `#${String(snap.frameSeq).padStart(3, "0")} · ${snap.simTimeMs}ms`;
223
+ ctx.fillStyle = "rgba(13, 16, 23, 0.82)";
224
+ ctx.fillRect(tx + 8, ty + 8, 126, 22);
225
+ ctx.fillStyle = "#e2e8f0";
226
+ ctx.font = "bold 11px monospace";
227
+ ctx.fillText(label, tx + 14, ty + 23);
228
+ }
229
+ }
230
+ let png = null;
231
+ if (typeof sheet.toBuffer === "function") {
232
+ const raw = sheet.toBuffer("image/png");
233
+ png = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
234
+ }
235
+ return {
236
+ width: sheetW,
237
+ height: sheetH,
238
+ canvas: sheet,
239
+ png,
240
+ digests
241
+ };
242
+ }
243
+ /**
244
+ * Deterministic stereo audio timeline mixer for pairing `@holtjs/stage/audio` procedural foley &
245
+ * chiptune cues with 60 FPS headless video renders. Exports ready-to-mux stereo 16-bit `.wav` bytes.
246
+ */
247
+ function createAudioTimeline(options = {}) {
248
+ const sampleRate = Math.max(8e3, Math.round(options.sampleRate ?? 44100));
249
+ const cues = [];
250
+ const addAtMs = (timeMs, monoSamples, cueOpts = {}) => {
251
+ if (!monoSamples || monoSamples.length === 0) return;
252
+ const gain = Math.max(0, cueOpts.gain ?? .75);
253
+ const angle = (Math.max(-1, Math.min(1, cueOpts.pan ?? 0)) + 1) * Math.PI / 4;
254
+ cues.push({
255
+ startSample: Math.max(0, Math.round(Math.max(0, timeMs) / 1e3 * sampleRate)),
256
+ samples: monoSamples,
257
+ gainL: Math.cos(angle) * gain,
258
+ gainR: Math.sin(angle) * gain
259
+ });
260
+ };
261
+ const addAtFrame = (frame, fps, monoSamples, cueOpts) => {
262
+ addAtMs(Math.max(0, frame) / Math.max(1, fps) * 1e3, monoSamples, cueOpts);
263
+ };
264
+ const toStereoPcm16 = (durationMs) => {
265
+ const totalFrames = Math.max(1, Math.ceil(Math.max(1, durationMs) / 1e3 * sampleRate));
266
+ const mixL = new Float32Array(totalFrames);
267
+ const mixR = new Float32Array(totalFrames);
268
+ for (let c = 0; c < cues.length; c++) {
269
+ const cue = cues[c];
270
+ const src = cue.samples;
271
+ const start = cue.startSample;
272
+ if (start >= totalFrames) continue;
273
+ const end = Math.min(totalFrames, start + src.length);
274
+ const gL = cue.gainL;
275
+ const gR = cue.gainR;
276
+ for (let i = start, s = 0; i < end; i++, s++) {
277
+ const v = src[s];
278
+ mixL[i] += v * gL;
279
+ mixR[i] += v * gR;
280
+ }
281
+ }
282
+ const pcm = new Int16Array(totalFrames * 2);
283
+ for (let i = 0; i < totalFrames; i++) {
284
+ const l = Math.tanh(mixL[i]);
285
+ const r = Math.tanh(mixR[i]);
286
+ pcm[i * 2] = Math.max(-32768, Math.min(32767, Math.round(l * 32767)));
287
+ pcm[i * 2 + 1] = Math.max(-32768, Math.min(32767, Math.round(r * 32767)));
288
+ }
289
+ return pcm;
290
+ };
291
+ const toWav = (durationMs) => {
292
+ const pcm = toStereoPcm16(durationMs);
293
+ const numChannels = 2;
294
+ const bitsPerSample = 16;
295
+ const byteRate = sampleRate * numChannels * bitsPerSample / 8;
296
+ const blockAlign = 4;
297
+ const dataBytes = pcm.byteLength;
298
+ const buf = new ArrayBuffer(44 + dataBytes);
299
+ const view = new DataView(buf);
300
+ const writeAscii = (offset, str) => {
301
+ for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
302
+ };
303
+ writeAscii(0, "RIFF");
304
+ view.setUint32(4, 36 + dataBytes, true);
305
+ writeAscii(8, "WAVE");
306
+ writeAscii(12, "fmt ");
307
+ view.setUint32(16, 16, true);
308
+ view.setUint16(20, 1, true);
309
+ view.setUint16(22, numChannels, true);
310
+ view.setUint32(24, sampleRate, true);
311
+ view.setUint32(28, byteRate, true);
312
+ view.setUint16(32, blockAlign, true);
313
+ view.setUint16(34, bitsPerSample, true);
314
+ writeAscii(36, "data");
315
+ view.setUint32(40, dataBytes, true);
316
+ new Uint8Array(buf, 44).set(new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength));
317
+ return new Uint8Array(buf);
318
+ };
319
+ return {
320
+ sampleRate,
321
+ addAtMs,
322
+ addAtFrame,
323
+ toStereoPcm16,
324
+ toWav
325
+ };
326
+ }
327
+ export { createAudioTimeline, createHeadlessStage, renderStoryboard };
package/dist/hit.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ export interface Point2 {
2
+ x: number;
3
+ y: number;
4
+ }
5
+ export interface CircleObstacle {
6
+ readonly x: number;
7
+ readonly y: number;
8
+ readonly r: number;
9
+ }
10
+ export interface RectBounds {
11
+ readonly minX: number;
12
+ readonly minY: number;
13
+ readonly maxX: number;
14
+ readonly maxY: number;
15
+ }
16
+ /**
17
+ * Continuous swept-circle intersection: returns the earliest fraction `t in [0, 1]` along the
18
+ * segment from `(ax, ay)` by `(sx, sy)` where a point touches circle `(cx, cy, radius)`
19
+ * (use `radius = moverRadius + targetRadius` for two circles). Returns `0` if already overlapping
20
+ * at the start, or `-1` if there is no contact. Prevents high-speed projectiles from tunneling.
21
+ */
22
+ export declare function sweptCircleHit(ax: number, ay: number, sx: number, sy: number, cx: number, cy: number, radius: number): number;
23
+ /**
24
+ * First contact fraction `f in [0, 1]` of a rotating radial melee blade (length `reach`, sweeping
25
+ * from `startAngle` across `arcSpan` in direction `dir` = `1` CW or `-1` CCW) against target circle
26
+ * `(targetX, targetY, targetRadius)`. Returns `-1` when missed, `0` when already overlapping at
27
+ * `startAngle` or within `closeSq` of the origin.
28
+ */
29
+ export declare function arcSweepFirstContact(originX: number, originY: number, reach: number, startAngle: number, arcSpan: number, dir: number, closeSq: number, targetX: number, targetY: number, targetRadius: number): number;
30
+ /**
31
+ * True if target circle `(targetX, targetY, targetRadius)` intersects an angular melee slice
32
+ * `[startAngle, startAngle + dir * sliceWidth]` of radius `reach` around `(originX, originY)`
33
+ * (or lies inside `closeSq` close-range tolerance).
34
+ */
35
+ export declare function arcSweepTouches(originX: number, originY: number, reach: number, startAngle: number, sliceWidth: number, dir: number, closeSq: number, targetX: number, targetY: number, targetRadius: number): boolean;
36
+ /** True when two circles overlap (strictly closer than `ar + br`). */
37
+ export declare function circleOverlapsCircle(ax: number, ay: number, ar: number, bx: number, by: number, br: number): boolean;
38
+ /** True when two axis-aligned bounding boxes strictly overlap. */
39
+ export declare function aabbOverlapsAabb(ax0: number, ay0: number, ax1: number, ay1: number, bx0: number, by0: number, bx1: number, by1: number): boolean;
40
+ /** True when circle `(cx, cy, radius)` intersects AABB `[x0, x1] x [y0, y1]`. */
41
+ export declare function circleOverlapsAabb(cx: number, cy: number, radius: number, x0: number, y0: number, x1: number, y1: number): boolean;
42
+ /** Squared distance from point `(px, py)` to line segment `(ax, ay) -> (bx, by)`. */
43
+ export declare function pointToSegmentDistSq(px: number, py: number, ax: number, ay: number, bx: number, by: number): number;
44
+ /** True when line segment `(ax, ay) -> (bx, by)` intersects circle `(cx, cy, radius)`. */
45
+ export declare function segmentHitsCircle(ax: number, ay: number, bx: number, by: number, cx: number, cy: number, radius: number): boolean;
46
+ /** True when capsule `(ax, ay) -> (bx, by)` with radius `capsuleRadius` hits circle `(cx, cy, targetRadius)`. */
47
+ export declare function capsuleHitsCircle(ax: number, ay: number, bx: number, by: number, capsuleRadius: number, cx: number, cy: number, targetRadius: number): boolean;
48
+ /**
49
+ * Push a circle `(pos.x, pos.y, radius)` out of static circle obstacles and optionally clamp inside `bounds`.
50
+ * Uses `Math.sqrt` deterministically so client prediction and server DO agree to the bit.
51
+ */
52
+ export declare function resolveCircleObstacles(pos: Point2, radius: number, obstacles: readonly CircleObstacle[], bounds?: RectBounds, candidateIndices?: ArrayLike<number> | null): void;
53
+ /**
54
+ * Push circle `(pos.x, pos.y, radius)` smoothly out of axis-aligned obstacle `[x0, x1] x [y0, y1]`.
55
+ * Returns `true` if a penetration was resolved.
56
+ */
57
+ export declare function resolveCircleAabb(pos: Point2, radius: number, x0: number, y0: number, x1: number, y1: number): boolean;
58
+ /** Exponential per-tick knockback decay factor (`exp(-dt / tau)`). */
59
+ export declare function knockbackDecay(dt: number, tau?: number): number;
60
+ /** Initial velocity (units/s) whose exponentially-decayed discrete steps sum to `distance`. */
61
+ export declare function knockbackInitialSpeed(distance: number, dt: number, decay: number): number;
62
+ /** Advance knockback velocity one tick in-place and snap tiny residuals below `stopSq` to zero. */
63
+ export declare function stepKnockback(vel: Point2, decay: number, stopSq?: number): boolean;