@holtjs/stage 0.10.1 → 0.10.3

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/CHANGELOG.md CHANGED
@@ -6,6 +6,21 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.10.3] - 2026-12-04
10
+
11
+ ### Added & Optimized
12
+ - **Automatic Atlas Frame-Slice Cache in `Renderer2D` & `mountChunkedTilemap` (`src/renderer-2d.ts`, `src/tilemap.ts`)**:
13
+ - Added an O(1) `Frame`-keyed, `TextureSource.version`-coherent, `64 MB` LRU-bounded sub-canvas slice cache (`getFrameSlice`) in `Renderer2D` across `ImageObject` / `SpriteObject` (cropped, uncropped, and tinted), `BlitterObject`, `InstancedBatchObject`, `TileSpriteObject`, and `NineSliceObject`, plus tile-slice caching in `mountChunkedTilemap` (`chunkCache: true`) and early `Frame.empty` skipping before Canvas2D state saves.
14
+ - Eliminates the `@napi-rs/canvas` large-source `drawImage` cliff (`4096×2467` `Canvas` or `Image` taking ~`0.4 ms/draw`), accelerating `550`-sprite headless frames by **~20–70×** (`~240 ms` -> `~2–11 ms` in `game.step()`) out of the box with zero user-code wrappers.
15
+ - **Turnkey `rawvideo` RGBA8888 FFmpeg Pipe Encoder (`@holtjs/stage/headless`, `src/headless.ts`)**:
16
+ - Added `encodeVideoWithFfmpeg(stage, options)`, `stage.encodeVideo(options)`, and `buildFfmpegRawVideoArgs(options)` for Node.js and Bun, streaming `stage.toRgba()` directly into `ffmpeg -f rawvideo -pix_fmt rgba` with `drain` backpressure handling and optional `AudioTimeline` / `.wav` muxing (eliminating ~`33 ms/frame` per-frame JPEG/PNG `image2pipe` CPU encoding).
17
+
18
+ ## [0.10.2] - 2026-12-04
19
+
20
+ ### Fixed
21
+ - **2x/3x Retina HiDPI `scrollFactor !== 1` Camera Matrix Parity (`Camera.matrixForScrollFactor`, `src/camera.ts`, `src/renderer-gl.ts`, `src/renderer-webgpu.ts`, `src/renderer-2d.ts`, `src/lighting.ts`, `src/headless.ts`)**:
22
+ - Subtracted the `configureHiDpi` base offset `sx0 = ox / dpr - ox` before multiplying by `scrollFactorX/Y` across WebGL2, WebGPU, Canvas2D, and `Lighting2DSystem`, keeping `scrollFactor(0)` HUD / `mountStage25D` layers anchored at `(0, 0)` on Retina screens, and updated `HeadlessStage.toRgba` / `toRgbaInto` to read dynamic backing dimensions.
23
+
9
24
  ## [0.10.1] - 2026-12-04
10
25
 
11
26
  ### Added & Fixed
@@ -155,6 +155,12 @@ declare class Camera {
155
155
  stepFollow(deltaMs: number): void;
156
156
  /** Recompute `worldView` and world->canvas `matrixCombined`. */
157
157
  syncMetrics(): void;
158
+ /**
159
+ * Compute the world/HUD -> backing-canvas transform matrix for a root node with `(scrollFactorX, scrollFactorY)`,
160
+ * honoring `configureHiDpi()` (`this.dpr`) so `scrollFactor = 0` HUDs, `mountStage25D.root`, and lightmap overlays
161
+ * remain anchored at logical `(0, 0)..(viewportW, viewportH)` on 2x/3x Retina displays.
162
+ */
163
+ matrixForScrollFactor(sfX: number, sfY: number, out: Matrix2D): Matrix2D;
158
164
  }
159
165
  type DisplayObjectType = 'Image' | 'Sprite' | 'NineSlice' | 'TileSprite' | 'Rectangle' | 'Panel' | 'MsdfIcon' | 'Text' | 'Graphics' | 'Blitter' | 'InstancedBatch' | 'ShapeBatch' | 'Container' | 'CustomPass';
160
166
  type SceneHostLike = Scene;
@@ -1122,6 +1128,9 @@ declare class Renderer2D extends EventEmitter {
1122
1128
  private tintCanvas;
1123
1129
  private tintCtx;
1124
1130
  private readonly tintCache;
1131
+ private static readonly MAX_SLICE_BYTES;
1132
+ private readonly sliceCache;
1133
+ private sliceBytes;
1125
1134
  private readonly maskWorldMat;
1126
1135
  private readonly rootScrollMat;
1127
1136
  private readonly matPool;
@@ -1149,8 +1158,10 @@ declare class Renderer2D extends EventEmitter {
1149
1158
  msdfDraws: number;
1150
1159
  pixelAaIcons: number;
1151
1160
  pixelAaDraws: number;
1161
+ frameSlices: number;
1152
1162
  };
1153
1163
  resize(width: number, height: number): void;
1164
+ private getFrameSlice;
1154
1165
  private getTintedSource;
1155
1166
  private isOffscreen;
1156
1167
  private mulMat;
@@ -1,6 +1,6 @@
1
1
  import { _ as rgbToCss, a as EventEmitter, c as Scale, h as packColorAbgr, l as Scenes, m as createMatrix2D, o as FilterMode, p as WHITE_RGB, r as BlendModes, u as TintModes } from "./types-CXsCvp1p.js";
2
2
  import { AnimationManager } from "./anims.js";
3
- import { i as Camera, r as Renderer2D, t as RendererWebGpu } from "./renderer-webgpu-BZ3J971y.js";
3
+ import { i as Camera, r as Renderer2D, t as RendererWebGpu } from "./renderer-webgpu-CHJxmCvR.js";
4
4
  import { c as InstancedBatchObject, d as PanelObject, f as RectangleObject, g as TileSpriteObject, h as TextObject, i as DisplayList, l as MsdfIconObject, m as SpriteObject, n as Container, o as Graphics, p as ShapeBatchObject, r as CustomPassObject, s as ImageObject, t as BlitterObject, u as NineSliceObject } from "./display-DU4edtH-.js";
5
5
  import { TweenManager } from "./tween.js";
6
6
  import { StageKernel } from "./kernel.js";
@@ -4107,21 +4107,7 @@ var RendererGl = class extends EventEmitter {
4107
4107
  let baseMat = parentMat;
4108
4108
  if (!baseMat) {
4109
4109
  if (obj.scrollFactorX === 1 && obj.scrollFactorY === 1) baseMat = camera.matrixCombined;
4110
- else {
4111
- const z = camera.zoom || 1;
4112
- const ox = camera.width * camera.originX;
4113
- const oy = camera.height * camera.originY;
4114
- const sx = camera.roundPixels ? Math.round(camera.scrollX) : camera.scrollX;
4115
- const sy = camera.roundPixels ? Math.round(camera.scrollY) : camera.scrollY;
4116
- const sm = this.sfMat;
4117
- sm.a = z;
4118
- sm.b = 0;
4119
- sm.c = 0;
4120
- sm.d = z;
4121
- sm.tx = (-sx * obj.scrollFactorX - ox) * z + ox + camera.x;
4122
- sm.ty = (-sy * obj.scrollFactorY - oy) * z + oy + camera.y;
4123
- baseMat = sm;
4124
- }
4110
+ else baseMat = camera.matrixForScrollFactor(obj.scrollFactorX, obj.scrollFactorY, this.sfMat);
4125
4111
  }
4126
4112
  let m;
4127
4113
  if (obj.x === 0 && obj.y === 0 && obj.scaleX === 1 && obj.scaleY === 1 && obj.rotation === 0 && obj.skewX === 0 && obj.skewY === 0) m = baseMat;
@@ -1,4 +1,4 @@
1
- import { E as StagePlugin, L as SceneDigestOptions, N as SceneDigest, f as SceneInput, n as EngineClockSnapshot, r as Game, u as Scene } from "./game-B7w2sF5C.js";
1
+ import { E as StagePlugin, L as SceneDigestOptions, N as SceneDigest, f as SceneInput, n as EngineClockSnapshot, r as Game, u as Scene } from "./game-CytDvQt9.js";
2
2
  /** Minimal Canvas2D surface compatible with `@napi-rs/canvas`, `node-canvas`, and browser `<canvas>`. */
3
3
  export interface HeadlessCanvasLike {
4
4
  width: number;
@@ -93,6 +93,8 @@ export interface HeadlessStage {
93
93
  digest(options?: SceneDigestOptions): SceneDigest;
94
94
  /** Step and stream raw RGBA frames (e.g. into `ffmpeg`) at deterministic `fps`. */
95
95
  recordFrames(options: RecordFramesOptions): Promise<EngineClockSnapshot>;
96
+ /** Stream deterministic raw RGBA8888 frames directly into `ffmpeg` (`-f rawvideo -pix_fmt rgba`, zero per-frame PNG/JPEG encode) and optional `.wav` audio. */
97
+ encodeVideo(options: EncodeVideoWithFfmpegOptions): Promise<EncodeVideoResult>;
96
98
  /** Destroy the headless stage and release resources. */
97
99
  destroy(): void;
98
100
  }
@@ -155,4 +157,77 @@ export interface AudioTimeline {
155
157
  * Deterministic stereo audio timeline mixer for pairing `@holtjs/stage/audio` procedural foley &
156
158
  * chiptune cues with 60 FPS headless video renders. Exports ready-to-mux stereo 16-bit `.wav` bytes.
157
159
  */
158
- export declare function createAudioTimeline(options?: AudioTimelineOptions): AudioTimeline;
160
+ export declare function createAudioTimeline(options?: AudioTimelineOptions): AudioTimeline;
161
+ export interface FfmpegRawVideoArgsOptions {
162
+ readonly width: number;
163
+ readonly height: number;
164
+ readonly fps: number;
165
+ readonly outputPath: string;
166
+ /** Optional path to a `.wav` audio file (e.g. written from `AudioTimeline.toWav()`). */
167
+ readonly audioWavPath?: string;
168
+ /** Video codec (default `'libx264'`). */
169
+ readonly videoCodec?: string;
170
+ /** Encoder preset (default `'veryfast'`). */
171
+ readonly preset?: string;
172
+ /** Constant Rate Factor quality `0..51` (default `19`). */
173
+ readonly crf?: number;
174
+ /** Output pixel format for universal player compatibility (default `'yuv420p'`). */
175
+ readonly outputPixelFormat?: string;
176
+ /** Audio codec when `audioWavPath` is supplied (default `'aac'`). */
177
+ readonly audioCodec?: string;
178
+ /** Audio bitrate when `audioWavPath` is supplied (default `'160k'`). */
179
+ readonly audioBitrate?: string;
180
+ /** Extra CLI flags appended before `-movflags +faststart <outputPath>`. */
181
+ readonly extraArgs?: readonly string[];
182
+ }
183
+ export interface EncodeVideoWithFfmpegOptions {
184
+ /** Destination video file path (e.g. `'out.mp4'`). */
185
+ readonly outputPath: string;
186
+ /** Total frames to render (`frames` or `durationMs` required). */
187
+ readonly frames?: number;
188
+ /** Total duration in milliseconds at `stage.fps` (used if `frames` is omitted). */
189
+ readonly durationMs?: number;
190
+ /** Optional `AudioTimeline`, stereo `.wav` `Uint8Array`, or `.wav` file path muxed into the output video. */
191
+ readonly audio?: AudioTimeline | Uint8Array | string;
192
+ /** Custom `ffmpeg` executable path (default `'ffmpeg'`). */
193
+ readonly ffmpegPath?: string;
194
+ /** Video codec (default `'libx264'`). */
195
+ readonly videoCodec?: string;
196
+ /** Encoder preset (default `'veryfast'`). */
197
+ readonly preset?: string;
198
+ /** Constant Rate Factor quality `0..51` (default `19`). */
199
+ readonly crf?: number;
200
+ /** Output pixel format (default `'yuv420p'`). */
201
+ readonly outputPixelFormat?: string;
202
+ /** Audio codec when `audio` is provided (default `'aac'`). */
203
+ readonly audioCodec?: string;
204
+ /** Audio bitrate when `audio` is provided (default `'160k'`). */
205
+ readonly audioBitrate?: string;
206
+ /** Extra CLI flags appended before `-movflags +faststart <outputPath>`. */
207
+ readonly extraArgs?: readonly string[];
208
+ /** Capture a zero-PII `SceneDigest` every N frames (`0` = disabled; default `0`). */
209
+ readonly digestEvery?: number;
210
+ readonly digestOptions?: SceneDigestOptions;
211
+ /** Optional per-frame hook invoked after stepping each frame before piping raw RGBA8888 to `ffmpeg`. */
212
+ readonly onFrame?: (frame: HeadlessRecordedFrame) => void | Promise<void>;
213
+ }
214
+ export interface EncodeVideoResult {
215
+ readonly outputPath: string;
216
+ readonly frames: number;
217
+ readonly width: number;
218
+ readonly height: number;
219
+ readonly fps: number;
220
+ readonly durationMs: number;
221
+ readonly clock: EngineClockSnapshot;
222
+ readonly digests: SceneDigest[];
223
+ }
224
+ /**
225
+ * Build deterministic `ffmpeg` CLI arguments that consume raw `RGBA8888` frames from `stdin` (`pipe:0`),
226
+ * bypassing per-frame PNG/JPEG `image2pipe` CPU encoding overhead (~33 ms/frame saved at 1280x720!).
227
+ */
228
+ export declare function buildFfmpegRawVideoArgs(options: FfmpegRawVideoArgsOptions): string[];
229
+ /**
230
+ * Step a `HeadlessStage` in Node.js or Bun and stream raw `RGBA8888` frames (`-f rawvideo -pix_fmt rgba`)
231
+ * directly into `ffmpeg` stdin with backpressure handling and optional stereo `.wav` audio muxing.
232
+ */
233
+ export declare function encodeVideoWithFfmpeg(stage: HeadlessStage, options: EncodeVideoWithFfmpegOptions): Promise<EncodeVideoResult>;
package/dist/headless.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./types-CXsCvp1p.js";
2
- import { n as Game } from "./game-CnGm5bly.js";
2
+ import { n as Game } from "./game-D-rfAnoA.js";
3
3
  import { buildSceneDigest } from "./trace.js";
4
4
  // src/headless.ts
5
5
  function createVirtualDomHost(createCanvas, width, height) {
@@ -123,29 +123,33 @@ function createHeadlessStage(options) {
123
123
  return game.clock.snapshot();
124
124
  };
125
125
  const toRgbaInto = (out) => {
126
- const byteLen = width * height * 4;
126
+ const cw = rootCanvas.width || width;
127
+ const ch = rootCanvas.height || height;
128
+ const byteLen = cw * ch * 4;
127
129
  const dst = out && out.byteLength >= byteLen ? out : new Uint8Array(byteLen);
128
130
  if (game.renderer.type === 2 && game.renderer.gl) {
129
131
  const gl = game.renderer.gl;
130
- gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, dst);
132
+ gl.readPixels(0, 0, cw, ch, gl.RGBA, gl.UNSIGNED_BYTE, dst);
131
133
  return dst;
132
134
  }
133
135
  const ctx = rootCanvas.getContext("2d");
134
136
  if (!ctx) throw new Error("HeadlessStage.toRgbaInto: 2D context unavailable");
135
- const img = ctx.getImageData(0, 0, width, height);
137
+ const img = ctx.getImageData(0, 0, cw, ch);
136
138
  dst.set(img.data.subarray(0, byteLen));
137
139
  return dst;
138
140
  };
139
141
  const toRgba = () => {
142
+ const cw = rootCanvas.width || width;
143
+ const ch = rootCanvas.height || height;
140
144
  if (game.renderer.type === 2 && game.renderer.gl) {
141
145
  const gl = game.renderer.gl;
142
- const out = new Uint8Array(width * height * 4);
143
- gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, out);
146
+ const out = new Uint8Array(cw * ch * 4);
147
+ gl.readPixels(0, 0, cw, ch, gl.RGBA, gl.UNSIGNED_BYTE, out);
144
148
  return out;
145
149
  }
146
150
  const ctx = rootCanvas.getContext("2d");
147
151
  if (!ctx) throw new Error("HeadlessStage.toRgba: 2D context unavailable");
148
- const img = ctx.getImageData(0, 0, width, height);
152
+ const img = ctx.getImageData(0, 0, cw, ch);
149
153
  return new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength);
150
154
  };
151
155
  const toPng = () => {
@@ -159,24 +163,25 @@ function createHeadlessStage(options) {
159
163
  const recordFrames = async (recOpts) => {
160
164
  const totalFrames = recOpts.frames !== void 0 ? Math.max(1, Math.floor(recOpts.frames)) : Math.max(1, Math.round((recOpts.durationMs ?? 1e3) / 1e3 * fps));
161
165
  const digestEvery = Math.max(0, Math.floor(recOpts.digestEvery ?? 0));
162
- const sharedRgba = recOpts.reuseFrameBuffer ? new Uint8Array(width * height * 4) : null;
166
+ let sharedRgba = recOpts.reuseFrameBuffer ? new Uint8Array((rootCanvas.width || width) * (rootCanvas.height || height) * 4) : null;
163
167
  for (let i = 0; i < totalFrames; i++) {
164
168
  if (i > 0 || game.clock.frameSeq === 0) {
165
169
  simCursorMs += dt;
166
170
  game.step(simCursorMs, dt);
167
171
  }
168
172
  const snapDigest = digestEvery > 0 && i % digestEvery === 0 ? digest(recOpts.digestOptions) : void 0;
173
+ if (sharedRgba) sharedRgba = toRgbaInto(sharedRgba);
169
174
  await recOpts.onFrame({
170
175
  index: i,
171
176
  frameSeq: game.clock.frameSeq,
172
177
  simTimeMs: Math.round(simCursorMs),
173
- rgba: sharedRgba ? toRgbaInto(sharedRgba) : toRgba(),
178
+ rgba: sharedRgba ?? toRgba(),
174
179
  digest: snapDigest
175
180
  });
176
181
  }
177
182
  return game.clock.snapshot();
178
183
  };
179
- return {
184
+ const self = {
180
185
  game,
181
186
  scene: primaryScene,
182
187
  canvas: rootCanvas,
@@ -225,8 +230,10 @@ function createHeadlessStage(options) {
225
230
  toPng,
226
231
  digest,
227
232
  recordFrames,
233
+ encodeVideo: (encOpts) => encodeVideoWithFfmpeg(self, encOpts),
228
234
  destroy: () => game.destroy(false)
229
235
  };
236
+ return self;
230
237
  }
231
238
  /**
232
239
  * Step a `HeadlessStage` across target keyframes and composite a single multi-panel
@@ -369,4 +376,199 @@ function createAudioTimeline(options = {}) {
369
376
  toWav
370
377
  };
371
378
  }
372
- export { createAudioTimeline, createHeadlessStage, renderStoryboard };
379
+ /**
380
+ * Build deterministic `ffmpeg` CLI arguments that consume raw `RGBA8888` frames from `stdin` (`pipe:0`),
381
+ * bypassing per-frame PNG/JPEG `image2pipe` CPU encoding overhead (~33 ms/frame saved at 1280x720!).
382
+ */
383
+ function buildFfmpegRawVideoArgs(options) {
384
+ const w = Math.max(1, Math.round(options.width));
385
+ const h = Math.max(1, Math.round(options.height));
386
+ const fps = Math.max(1, Math.round(options.fps));
387
+ const args = [
388
+ "-y",
389
+ "-f",
390
+ "rawvideo",
391
+ "-pix_fmt",
392
+ "rgba",
393
+ "-s",
394
+ `${w}x${h}`,
395
+ "-r",
396
+ String(fps),
397
+ "-i",
398
+ "pipe:0"
399
+ ];
400
+ if (options.audioWavPath) args.push("-i", options.audioWavPath);
401
+ args.push("-c:v", options.videoCodec ?? "libx264", "-preset", options.preset ?? "veryfast", "-crf", String(options.crf ?? 19), "-pix_fmt", options.outputPixelFormat ?? "yuv420p");
402
+ if (options.audioWavPath) args.push("-c:a", options.audioCodec ?? "aac", "-b:a", options.audioBitrate ?? "160k", "-shortest");
403
+ if (options.extraArgs && options.extraArgs.length > 0) args.push(...options.extraArgs);
404
+ args.push("-movflags", "+faststart", options.outputPath);
405
+ return args;
406
+ }
407
+ const dynamicImportModule = (specifier) => import(
408
+ /* @vite-ignore */
409
+ specifier
410
+ );
411
+ /**
412
+ * Step a `HeadlessStage` in Node.js or Bun and stream raw `RGBA8888` frames (`-f rawvideo -pix_fmt rgba`)
413
+ * directly into `ffmpeg` stdin with backpressure handling and optional stereo `.wav` audio muxing.
414
+ */
415
+ async function encodeVideoWithFfmpeg(stage, options) {
416
+ const [cp, fs, os, path] = await Promise.all([
417
+ dynamicImportModule("node:child_process"),
418
+ dynamicImportModule("node:fs"),
419
+ dynamicImportModule("node:os"),
420
+ dynamicImportModule("node:path")
421
+ ]);
422
+ const totalFrames = options.frames !== void 0 ? Math.max(1, Math.floor(options.frames)) : Math.max(1, Math.round((options.durationMs ?? 1e3) / 1e3 * stage.fps));
423
+ const durationMs = totalFrames / stage.fps * 1e3;
424
+ const cw = stage.canvas.width || stage.width;
425
+ const ch = stage.canvas.height || stage.height;
426
+ let tempWavPath = null;
427
+ let audioWavPath;
428
+ if (typeof options.audio === "string") audioWavPath = options.audio;
429
+ else if (options.audio) {
430
+ const wavBytes = options.audio instanceof Uint8Array ? options.audio : options.audio.toWav(durationMs);
431
+ tempWavPath = path.join(os.tmpdir(), `holt-stage-audio-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.wav`);
432
+ fs.writeFileSync(tempWavPath, wavBytes);
433
+ audioWavPath = tempWavPath;
434
+ }
435
+ const ffArgs = buildFfmpegRawVideoArgs({
436
+ width: cw,
437
+ height: ch,
438
+ fps: stage.fps,
439
+ outputPath: options.outputPath,
440
+ audioWavPath,
441
+ videoCodec: options.videoCodec,
442
+ preset: options.preset,
443
+ crf: options.crf,
444
+ outputPixelFormat: options.outputPixelFormat,
445
+ audioCodec: options.audioCodec,
446
+ audioBitrate: options.audioBitrate,
447
+ extraArgs: options.extraArgs
448
+ });
449
+ const ffmpegBin = options.ffmpegPath ?? "ffmpeg";
450
+ const ff = cp.spawn(ffmpegBin, ffArgs, { stdio: [
451
+ "pipe",
452
+ "ignore",
453
+ "pipe"
454
+ ] });
455
+ let stderrLog = "";
456
+ let spawnError = null;
457
+ let stdinError = null;
458
+ let closed = false;
459
+ let closedCode = null;
460
+ ff.stderr.on("data", (chunk) => {
461
+ stderrLog += chunk.toString();
462
+ });
463
+ ff.on("error", (err) => {
464
+ spawnError = err;
465
+ });
466
+ ff.stdin.on("error", (err) => {
467
+ stdinError = err;
468
+ });
469
+ const closePromise = new Promise((resolve) => {
470
+ ff.on("close", (code) => {
471
+ closed = true;
472
+ closedCode = code;
473
+ resolve(code);
474
+ });
475
+ ff.on("error", () => {
476
+ closed = true;
477
+ resolve(null);
478
+ });
479
+ });
480
+ const digests = [];
481
+ try {
482
+ await new Promise((resolve, reject) => {
483
+ if (spawnError) {
484
+ reject(spawnError);
485
+ return;
486
+ }
487
+ const onSpawn = () => {
488
+ ff.removeListener("error", onErr);
489
+ resolve();
490
+ };
491
+ const onErr = (err) => {
492
+ ff.removeListener("spawn", onSpawn);
493
+ reject(err);
494
+ };
495
+ ff.once("spawn", onSpawn);
496
+ ff.once("error", onErr);
497
+ });
498
+ const waitDrainOrExit = () => new Promise((resolve, reject) => {
499
+ if (spawnError) {
500
+ reject(spawnError);
501
+ return;
502
+ }
503
+ if (stdinError) {
504
+ reject(stdinError);
505
+ return;
506
+ }
507
+ if (closed) {
508
+ reject(/* @__PURE__ */ new Error(`encodeVideoWithFfmpeg: ffmpeg exited early with code ${String(closedCode)}:\n${stderrLog}`));
509
+ return;
510
+ }
511
+ const cleanup = () => {
512
+ ff.stdin.removeListener("drain", onDrain);
513
+ ff.stdin.removeListener("error", onPipeErr);
514
+ ff.removeListener("error", onProcErr);
515
+ ff.removeListener("close", onProcClose);
516
+ };
517
+ const onDrain = () => {
518
+ cleanup();
519
+ resolve();
520
+ };
521
+ const onPipeErr = (err) => {
522
+ cleanup();
523
+ reject(err);
524
+ };
525
+ const onProcErr = (err) => {
526
+ cleanup();
527
+ reject(err);
528
+ };
529
+ const onProcClose = (code) => {
530
+ cleanup();
531
+ reject(/* @__PURE__ */ new Error(`encodeVideoWithFfmpeg: ffmpeg exited early with code ${String(code)}:\n${stderrLog}`));
532
+ };
533
+ ff.stdin.once("drain", onDrain);
534
+ ff.stdin.on("error", onPipeErr);
535
+ ff.once("error", onProcErr);
536
+ ff.once("close", onProcClose);
537
+ });
538
+ const clock = await stage.recordFrames({
539
+ frames: totalFrames,
540
+ digestEvery: options.digestEvery,
541
+ digestOptions: options.digestOptions,
542
+ onFrame: async (frame) => {
543
+ if (frame.digest) digests.push(frame.digest);
544
+ if (options.onFrame) await options.onFrame(frame);
545
+ if (spawnError) throw spawnError;
546
+ if (stdinError) throw stdinError;
547
+ if (closed) throw new Error(`encodeVideoWithFfmpeg: ffmpeg exited early with code ${String(closedCode)}:\n${stderrLog}`);
548
+ if (!ff.stdin.write(frame.rgba)) await waitDrainOrExit();
549
+ }
550
+ });
551
+ ff.stdin.end();
552
+ const exitCode = await closePromise;
553
+ if (spawnError) throw spawnError;
554
+ if (exitCode !== 0) throw new Error(`encodeVideoWithFfmpeg: ffmpeg exited with code ${String(exitCode)}:\n${stderrLog}`);
555
+ return {
556
+ outputPath: options.outputPath,
557
+ frames: totalFrames,
558
+ width: cw,
559
+ height: ch,
560
+ fps: stage.fps,
561
+ durationMs,
562
+ clock,
563
+ digests
564
+ };
565
+ } finally {
566
+ try {
567
+ ff.stdin.end();
568
+ } catch {}
569
+ if (tempWavPath) try {
570
+ fs.rmSync(tempWavPath, { force: true });
571
+ } catch {}
572
+ }
573
+ }
574
+ export { buildFfmpegRawVideoArgs, createAudioTimeline, createHeadlessStage, encodeVideoWithFfmpeg, renderStoryboard };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as WebGpuBootstrapResult, A as createInputRecorder, At as NineSliceObject, B as SceneDigestSurfaceEntry, Bt as SpriteAnimEventListener, C as RecordedInputEntry, Ct as EquipmentBinding, D as TimelineClickOptions, Dt as InstancedColumns, E as StagePlugin, Et as InstancedBatchObject, F as SceneDigestEngineSandbox, Ft as RectangleObject, G as InputConfig, Gt as TextStyleConfig, H as SceneDigestSurfaces, Ht as SpritePlayOptions, I as SceneDigestNode, It as SceneHostLike, J as Pointer, Jt as CameraFollowOptions, K as InputPlugin, Kt as TileSpriteObject, L as SceneDigestOptions, Lt as ShapeBatchColumns, M as createInputTimeline, Mt as PanelOpenSide, N as SceneDigest, Nt as PanelStyleConfig, O as TimelineDragOptions, Ot as MsdfIconConfig, P as SceneDigestActiveFocus, Pt as RectClipMask, Q as RequestWebGpuOptions, R as SceneDigestOverlayStats, Rt as ShapeBatchObject, S as InputTimelinePlugin, St as DisplaySemantics, T as StageKernel, Tt as ImageObject, U as buildSceneDigest, Ut as SyncAttachmentOptions, V as SceneDigestSurfaceSource, Vt as SpriteObject, W as sanitizeTrackToken, Wt as TextObject, X as RendererWebGpu, Xt as HiDpiScaleLike, Y as PointerSample, Yt as HiDpiConfigureOptions, Z as RendererWebGpuOptions, _ as ActionMap, _t as CustomPassOptions, a as GameLoop, at as RendererGlOptions, b as InputTargetSpec, bt as DisplayObject, c as LoaderPlugin, ct as StageRenderTarget, d as SceneCtor, dt as BlitterObject, et as WebGpuCanvasContextLike, f as SceneInput, ft as Bob$1, g as ViewportFitResult, gt as CustomPassObject, h as StageRenderer, ht as CustomPassCallback, i as GameConfig$1, it as RendererGl, j as createInputReplay, jt as PanelObject, k as TimelineKeyOptions, kt as MsdfIconObject, l as ScaleManager, lt as AnchorPose2D, m as SceneManager, mt as ContainerFiltersShim, n as EngineClockSnapshot, nt as requestWebGpuDevice, o as GameObjectFactory, ot as RendererStats, p as SceneLifecycleStats, pt as Container, q as KeyboardPlugin, qt as Camera, r as Game, rt as Renderer2D, s as JsonCache, st as Stage2DCustomImageHandler, t as EngineClock, tt as WebGpuDeviceLike, u as Scene, ut as BindEquipmentOptions, v as InputProvider, vt as DirectionalPlayOptions, w as StageInputEvent, wt as Graphics, x as InputTimelineOptions, xt as DisplayObjectType, y as InputRecorderPlugin, yt as DisplayList, z as SceneDigestSandbox, zt as ShapeBatchStyleDefaults } from "./game-B7w2sF5C.js";
1
+ import { $ as WebGpuBootstrapResult, A as createInputRecorder, At as NineSliceObject, B as SceneDigestSurfaceEntry, Bt as SpriteAnimEventListener, C as RecordedInputEntry, Ct as EquipmentBinding, D as TimelineClickOptions, Dt as InstancedColumns, E as StagePlugin, Et as InstancedBatchObject, F as SceneDigestEngineSandbox, Ft as RectangleObject, G as InputConfig, Gt as TextStyleConfig, H as SceneDigestSurfaces, Ht as SpritePlayOptions, I as SceneDigestNode, It as SceneHostLike, J as Pointer, Jt as CameraFollowOptions, K as InputPlugin, Kt as TileSpriteObject, L as SceneDigestOptions, Lt as ShapeBatchColumns, M as createInputTimeline, Mt as PanelOpenSide, N as SceneDigest, Nt as PanelStyleConfig, O as TimelineDragOptions, Ot as MsdfIconConfig, P as SceneDigestActiveFocus, Pt as RectClipMask, Q as RequestWebGpuOptions, R as SceneDigestOverlayStats, Rt as ShapeBatchObject, S as InputTimelinePlugin, St as DisplaySemantics, T as StageKernel, Tt as ImageObject, U as buildSceneDigest, Ut as SyncAttachmentOptions, V as SceneDigestSurfaceSource, Vt as SpriteObject, W as sanitizeTrackToken, Wt as TextObject, X as RendererWebGpu, Xt as HiDpiScaleLike, Y as PointerSample, Yt as HiDpiConfigureOptions, Z as RendererWebGpuOptions, _ as ActionMap, _t as CustomPassOptions, a as GameLoop, at as RendererGlOptions, b as InputTargetSpec, bt as DisplayObject, c as LoaderPlugin, ct as StageRenderTarget, d as SceneCtor, dt as BlitterObject, et as WebGpuCanvasContextLike, f as SceneInput, ft as Bob$1, g as ViewportFitResult, gt as CustomPassObject, h as StageRenderer, ht as CustomPassCallback, i as GameConfig$1, it as RendererGl, j as createInputReplay, jt as PanelObject, k as TimelineKeyOptions, kt as MsdfIconObject, l as ScaleManager, lt as AnchorPose2D, m as SceneManager, mt as ContainerFiltersShim, n as EngineClockSnapshot, nt as requestWebGpuDevice, o as GameObjectFactory, ot as RendererStats, p as SceneLifecycleStats, pt as Container, q as KeyboardPlugin, qt as Camera, r as Game, rt as Renderer2D, s as JsonCache, st as Stage2DCustomImageHandler, t as EngineClock, tt as WebGpuDeviceLike, u as Scene, ut as BindEquipmentOptions, v as InputProvider, vt as DirectionalPlayOptions, w as StageInputEvent, wt as Graphics, x as InputTimelineOptions, xt as DisplayObjectType, y as InputRecorderPlugin, yt as DisplayList, z as SceneDigestSandbox, zt as ShapeBatchStyleDefaults } from "./game-CytDvQt9.js";
2
2
  import { A as FilterModeValue, B as WEBGL, C as AUTO, D as CANVAS, E as BlendModes, F as Scale, G as packColorAbgr, H as WHITE_RGB, I as ScaleMode, K as parseColor, L as Scenes, M as Matrix2D, N as Rect2D, O as EventEmitter, P as RgbaColor, R as TintMode, S as TextureSource, T as BlendMode, U as WorldView2D, V as WEBGPU, W as createMatrix2D, _ as SpriteSheetConfig, a as AtlasClipRule, b as TextureImageSource, c as GenerateFrameNamesConfig, d as AtlasJsonLike, f as CanvasTexture, g as GlTextureHost, h as FrameExtraMeta, i as AtlasAutoAnimOptions, j as HEX_MASK, k as FilterMode, l as GenerateFrameNumbersConfig, m as FrameAnchorTuple, n as AnimationFrameInput, o as CompiledAnimationFrame, p as Frame, q as rgbToCss, r as AnimationManager, s as DirectionalAnimGroup, t as AnimationConfig, u as StageAnimation, v as Texture, w as BLACK_RGB, x as TextureManager, y as TextureImageOptions, z as TintModes } from "./anims-D9N8w6IM.js";
3
3
  import { FlexAlign, FlexContainerSpec, FlexDir, FlexItemRect, FlexItemSpec, FlexJustify, FlexPadding, FlexResult, WrapContainerSpec, WrapItemRect, WrapItemSpec, WrapJustify, WrapResult, computeFlexLayout, computeWrapLayout, resolvePadding } from "./flex.js";
4
4
  import { a as SpringHandle, c as TweenManager, i as Easings, l as TweenOptions, n as EasingFn, o as SpringOptions, r as EasingName, s as TweenHandle, t as DisposableOwner, u as TweenStats } from "./tween-BiF1FUvc.js";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { _ as rgbToCss, a as EventEmitter, c as Scale, d as WEBGL, f as WEBGPU, g as parseColor, h as packColorAbgr, i as CANVAS, l as Scenes, m as createMatrix2D, n as BLACK_RGB, o as FilterMode, p as WHITE_RGB, r as BlendModes, s as HEX_MASK, t as AUTO, u as TintModes } from "./types-CXsCvp1p.js";
2
- import { _ as CanvasTexture, a as JsonCache, b as TextureManager, c as Scene, d as KeyboardPlugin, f as Pointer, g as SdfPanelBatcher, h as MsdfIconBatcher, i as GameObjectFactory, l as SceneManager, m as PixelAaBatcher, n as Game, o as LoaderPlugin, p as RendererGl, r as GameLoop, s as ScaleManager, t as EngineClock, u as InputPlugin, v as Frame, x as TextureSource, y as Texture } from "./game-CnGm5bly.js";
2
+ import { _ as CanvasTexture, a as JsonCache, b as TextureManager, c as Scene, d as KeyboardPlugin, f as Pointer, g as SdfPanelBatcher, h as MsdfIconBatcher, i as GameObjectFactory, l as SceneManager, m as PixelAaBatcher, n as Game, o as LoaderPlugin, p as RendererGl, r as GameLoop, s as ScaleManager, t as EngineClock, u as InputPlugin, v as Frame, x as TextureSource, y as Texture } from "./game-D-rfAnoA.js";
3
3
  import { AnimationManager } from "./anims.js";
4
- import { i as Camera, n as requestWebGpuDevice, r as Renderer2D, t as RendererWebGpu } from "./renderer-webgpu-BZ3J971y.js";
4
+ import { i as Camera, n as requestWebGpuDevice, r as Renderer2D, t as RendererWebGpu } from "./renderer-webgpu-CHJxmCvR.js";
5
5
  import { a as DisplayObject, c as InstancedBatchObject, d as PanelObject, f as RectangleObject, g as TileSpriteObject, h as TextObject, i as DisplayList, l as MsdfIconObject, m as SpriteObject, n as Container, o as Graphics, p as ShapeBatchObject, r as CustomPassObject, s as ImageObject, t as BlitterObject, u as NineSliceObject } from "./display-DU4edtH-.js";
6
6
  import { ActionMap, StageKernel, createInputRecorder, createInputReplay, createInputTimeline } from "./kernel.js";
7
7
  import { buildSceneDigest, sanitizeTrackToken } from "./trace.js";
@@ -1,4 +1,4 @@
1
- import { J as Pointer, jt as PanelObject, pt as Container, u as Scene } from "./game-B7w2sF5C.js";
1
+ import { J as Pointer, jt as PanelObject, pt as Container, u as Scene } from "./game-CytDvQt9.js";
2
2
  export type VirtualJoystickMode = 'floating' | 'fixed';
3
3
  export interface JoystickVector {
4
4
  /** Normalized X axis in [-1, 1] after deadzone remapping. */
package/dist/kernel.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as createInputRecorder, C as RecordedInputEntry, D as TimelineClickOptions, E as StagePlugin, M as createInputTimeline, O as TimelineDragOptions, S as InputTimelinePlugin, T as StageKernel, _ as ActionMap, b as InputTargetSpec, j as createInputReplay, k as TimelineKeyOptions, v as InputProvider, w as StageInputEvent, x as InputTimelineOptions, y as InputRecorderPlugin } from "./game-B7w2sF5C.js";
1
+ import { A as createInputRecorder, C as RecordedInputEntry, D as TimelineClickOptions, E as StagePlugin, M as createInputTimeline, O as TimelineDragOptions, S as InputTimelinePlugin, T as StageKernel, _ as ActionMap, b as InputTargetSpec, j as createInputReplay, k as TimelineKeyOptions, v as InputProvider, w as StageInputEvent, x as InputTimelineOptions, y as InputRecorderPlugin } from "./game-CytDvQt9.js";
2
2
  export { ActionMap, InputProvider, InputRecorderPlugin, InputTargetSpec, InputTimelineOptions, InputTimelinePlugin, RecordedInputEntry, StageInputEvent, StageKernel, StagePlugin, TimelineClickOptions, TimelineDragOptions, TimelineKeyOptions, createInputRecorder, createInputReplay, createInputTimeline };
@@ -1,4 +1,4 @@
1
- import { It as SceneHostLike, Tt as ImageObject, bt as DisplayObject, gt as CustomPassObject, pt as Container } from "./game-B7w2sF5C.js";
1
+ import { It as SceneHostLike, Tt as ImageObject, bt as DisplayObject, gt as CustomPassObject, pt as Container } from "./game-CytDvQt9.js";
2
2
  export type DayPhase = 'day' | 'dusk' | 'night';
3
3
  export interface DayNightConfig {
4
4
  dayLengthMs?: number;
package/dist/lighting.js CHANGED
@@ -303,15 +303,16 @@ function computeNodeScreenMatrix(node, scene, out) {
303
303
  break;
304
304
  }
305
305
  const cam = scene.cameras.main;
306
+ const invDpr = cam.dpr > 0 && cam.dpr !== 1 ? 1 / cam.dpr : 1;
306
307
  if (sfX === 1 && sfY === 1) {
307
308
  cam.syncMetrics();
308
309
  const cm = cam.matrixCombined;
309
- const na = cm.a * out.a + cm.c * out.b;
310
- const nb = cm.b * out.a + cm.d * out.b;
311
- const nc = cm.a * out.c + cm.c * out.d;
312
- const nd = cm.b * out.c + cm.d * out.d;
313
- const ntx = cm.a * out.tx + cm.c * out.ty + cm.tx;
314
- const nty = cm.b * out.tx + cm.d * out.ty + cm.ty;
310
+ const na = (cm.a * out.a + cm.c * out.b) * invDpr;
311
+ const nb = (cm.b * out.a + cm.d * out.b) * invDpr;
312
+ const nc = (cm.a * out.c + cm.c * out.d) * invDpr;
313
+ const nd = (cm.b * out.c + cm.d * out.d) * invDpr;
314
+ const ntx = (cm.a * out.tx + cm.c * out.ty + cm.tx) * invDpr;
315
+ const nty = (cm.b * out.tx + cm.d * out.ty + cm.ty) * invDpr;
315
316
  out.a = na;
316
317
  out.b = nb;
317
318
  out.c = nc;
@@ -319,19 +320,14 @@ function computeNodeScreenMatrix(node, scene, out) {
319
320
  out.tx = ntx;
320
321
  out.ty = nty;
321
322
  } else if (sfX !== 0 || sfY !== 0) {
322
- const z = cam.zoom || 1;
323
- const ox = cam.width * cam.originX;
324
- const oy = cam.height * cam.originY;
325
- const sx = cam.roundPixels ? Math.round(cam.scrollX) : cam.scrollX;
326
- const sy = cam.roundPixels ? Math.round(cam.scrollY) : cam.scrollY;
327
- const tx = (-sx * sfX - ox) * z + ox + cam.x;
328
- const ty = (-sy * sfY - oy) * z + oy + cam.y;
329
- out.a *= z;
330
- out.b *= z;
331
- out.c *= z;
332
- out.d *= z;
333
- out.tx = out.tx * z + tx;
334
- out.ty = out.ty * z + ty;
323
+ const sm = createMatrix2D();
324
+ cam.matrixForScrollFactor(sfX, sfY, sm);
325
+ out.a = out.a * sm.a * invDpr;
326
+ out.b = out.b * sm.d * invDpr;
327
+ out.c = out.c * sm.a * invDpr;
328
+ out.d = out.d * sm.d * invDpr;
329
+ out.tx = (out.tx * sm.a + sm.tx) * invDpr;
330
+ out.ty = (out.ty * sm.d + sm.ty) * invDpr;
335
331
  }
336
332
  out.scaleX = Math.hypot(out.a, out.b);
337
333
  out.scaleY = Math.hypot(out.c, out.d);
@@ -1,4 +1,4 @@
1
- import { It as SceneHostLike, bt as DisplayObject, pt as Container } from "./game-B7w2sF5C.js";
1
+ import { It as SceneHostLike, bt as DisplayObject, pt as Container } from "./game-CytDvQt9.js";
2
2
  export interface Camera25DConfig {
3
3
  viewportWidth: number;
4
4
  viewportHeight: number;
@@ -306,6 +306,32 @@ var Camera = class {
306
306
  m.scaleX = z;
307
307
  m.scaleY = z;
308
308
  }
309
+ /**
310
+ * Compute the world/HUD -> backing-canvas transform matrix for a root node with `(scrollFactorX, scrollFactorY)`,
311
+ * honoring `configureHiDpi()` (`this.dpr`) so `scrollFactor = 0` HUDs, `mountStage25D.root`, and lightmap overlays
312
+ * remain anchored at logical `(0, 0)..(viewportW, viewportH)` on 2x/3x Retina displays.
313
+ */
314
+ matrixForScrollFactor(sfX, sfY, out) {
315
+ const z = this.zoom || 1;
316
+ const dpr = this.dpr > 0 ? this.dpr : 1;
317
+ const ox = this.width * this.originX;
318
+ const oy = this.height * this.originY;
319
+ const sx = this.roundPixels ? Math.round(this.scrollX) : this.scrollX;
320
+ const sy = this.roundPixels ? Math.round(this.scrollY) : this.scrollY;
321
+ const sx0 = dpr !== 1 ? ox / dpr - ox : 0;
322
+ const sy0 = dpr !== 1 ? oy / dpr - oy : 0;
323
+ const effSx = (sx - sx0) * sfX + sx0;
324
+ const effSy = (sy - sy0) * sfY + sy0;
325
+ out.a = z;
326
+ out.b = 0;
327
+ out.c = 0;
328
+ out.d = z;
329
+ out.tx = (-effSx - ox) * z + ox + this.x;
330
+ out.ty = (-effSy - oy) * z + oy + this.y;
331
+ out.scaleX = z;
332
+ out.scaleY = z;
333
+ return out;
334
+ }
309
335
  };
310
336
  // src/renderer-2d.ts
311
337
  function addPerCornerRoundedRectSubpath(ctx, x, y, w, h, tl, tr, br, bl) {
@@ -364,6 +390,9 @@ var Renderer2D = class Renderer2D extends EventEmitter {
364
390
  tintCanvas = null;
365
391
  tintCtx = null;
366
392
  tintCache = /* @__PURE__ */ new Map();
393
+ static MAX_SLICE_BYTES = 67108864;
394
+ sliceCache = /* @__PURE__ */ new Map();
395
+ sliceBytes = 0;
367
396
  maskWorldMat = createMatrix2D();
368
397
  rootScrollMat = createMatrix2D();
369
398
  matPool = Array.from({ length: 16 }, () => createMatrix2D());
@@ -388,7 +417,8 @@ var Renderer2D = class Renderer2D extends EventEmitter {
388
417
  msdfIcons: 0,
389
418
  msdfDraws: 0,
390
419
  pixelAaIcons: 0,
391
- pixelAaDraws: 0
420
+ pixelAaDraws: 0,
421
+ frameSlices: 0
392
422
  };
393
423
  constructor(canvas, width, height, existingCtx) {
394
424
  super();
@@ -411,13 +441,68 @@ var Renderer2D = class Renderer2D extends EventEmitter {
411
441
  this.canvas.width = w;
412
442
  this.canvas.height = h;
413
443
  }
414
- getTintedSource(img, sx, sy, sw, sh, rgb, fill, texSource) {
444
+ getFrameSlice(frame) {
445
+ const src = frame.source;
446
+ if (!src || src.isRenderTarget) return null;
447
+ const cw = frame.cutWidth;
448
+ const ch = frame.cutHeight;
449
+ const cx = frame.cutX;
450
+ const cy = frame.cutY;
451
+ if (cw <= 0 || ch <= 0 || cw > 1024 || ch > 1024) return null;
452
+ if ((cx | 0) !== cx || (cy | 0) !== cy || (cw | 0) !== cw || (ch | 0) !== ch) return null;
453
+ const atlasArea = src.width * src.height;
454
+ const frameArea = cw * ch;
455
+ if (atlasArea <= 262144 || atlasArea < frameArea * 4) return null;
456
+ const hit = this.sliceCache.get(frame);
457
+ if (hit && hit.ver === src.version && hit.cx === cx && hit.cy === cy && hit.cw === cw && hit.ch === ch) {
458
+ if (this.sliceBytes > Renderer2D.MAX_SLICE_BYTES * .75) {
459
+ this.sliceCache.delete(frame);
460
+ this.sliceCache.set(frame, hit);
461
+ }
462
+ return hit.canvas;
463
+ }
464
+ const rawImg = src.image;
465
+ if ("complete" in rawImg && !rawImg.complete) return null;
466
+ const doc = this.canvas?.ownerDocument ?? (typeof document !== "undefined" ? document : null);
467
+ if (!doc) return null;
468
+ if (hit) {
469
+ this.sliceBytes -= hit.bytes;
470
+ this.sliceCache.delete(frame);
471
+ }
472
+ const bytes = frameArea * 4;
473
+ while (this.sliceBytes + bytes > Renderer2D.MAX_SLICE_BYTES && this.sliceCache.size > 0) {
474
+ const oldestKey = this.sliceCache.keys().next().value;
475
+ if (oldestKey === void 0) break;
476
+ const oldest = this.sliceCache.get(oldestKey);
477
+ if (oldest) this.sliceBytes -= oldest.bytes;
478
+ this.sliceCache.delete(oldestKey);
479
+ }
480
+ const slice = doc.createElement("canvas");
481
+ slice.width = cw;
482
+ slice.height = ch;
483
+ const sctx = slice.getContext("2d");
484
+ if (!sctx) return null;
485
+ sctx.imageSmoothingEnabled = false;
486
+ sctx.drawImage(rawImg, cx, cy, cw, ch, 0, 0, cw, ch);
487
+ this.sliceCache.set(frame, {
488
+ canvas: slice,
489
+ ver: src.version,
490
+ cx,
491
+ cy,
492
+ cw,
493
+ ch,
494
+ bytes
495
+ });
496
+ this.sliceBytes += bytes;
497
+ return slice;
498
+ }
499
+ getTintedSource(img, sx, sy, sw, sh, rgb, fill, texSource, keySx = sx, keySy = sy) {
415
500
  const iw = Math.max(1, Math.ceil(sw));
416
501
  const ih = Math.max(1, Math.ceil(sh));
417
502
  const doc = this.canvas.ownerDocument ?? (typeof document !== "undefined" ? document : null);
418
503
  if (!doc) return null;
419
504
  if (texSource && !texSource.isRenderTarget && iw <= 512 && ih <= 512) {
420
- const cacheKey = `${texSource.id}:${texSource.version}:${sx},${sy},${sw},${sh}:${rgb}:${fill ? 1 : 0}`;
505
+ const cacheKey = `${texSource.id}:${texSource.version}:${keySx},${keySy},${sw},${sh}:${rgb}:${fill ? 1 : 0}`;
421
506
  const hit = this.tintCache.get(cacheKey);
422
507
  if (hit) {
423
508
  this.tintCache.delete(cacheKey);
@@ -516,10 +601,15 @@ var Renderer2D = class Renderer2D extends EventEmitter {
516
601
  }
517
602
  renderImage(img, ctx, m) {
518
603
  const frame = img.frame;
519
- if (!frame || frame.width <= 0 || frame.height <= 0) return;
520
- const srcImg = frame.source.image;
604
+ if (!frame || frame.empty || frame.width <= 0 || frame.height <= 0) return;
605
+ const sliced = this.getFrameSlice(frame);
606
+ const srcImg = sliced ?? frame.source.image;
521
607
  const ox = img.displayOriginX, oy = img.displayOriginY;
522
- let sx = frame.cutX, sy = frame.cutY, sw = frame.cutWidth, sh = frame.cutHeight;
608
+ let sx = sliced ? 0 : frame.cutX;
609
+ let sy = sliced ? 0 : frame.cutY;
610
+ let keySx = frame.cutX;
611
+ let keySy = frame.cutY;
612
+ let sw = frame.cutWidth, sh = frame.cutHeight;
523
613
  let dx = -ox, dy = -oy, dw = img.width, dh = img.height;
524
614
  if (img.isCropped) {
525
615
  const rx = Math.max(0, Math.min(frame.width, img.cropX));
@@ -529,6 +619,8 @@ var Renderer2D = class Renderer2D extends EventEmitter {
529
619
  if (rw <= 0 || rh <= 0) return;
530
620
  sx += rx;
531
621
  sy += ry;
622
+ keySx += rx;
623
+ keySy += ry;
532
624
  sw = rw;
533
625
  sh = rh;
534
626
  dx = -ox + rx;
@@ -548,7 +640,7 @@ var Renderer2D = class Renderer2D extends EventEmitter {
548
640
  ctx.scale(img.flipX ? -1 : 1, img.flipY ? -1 : 1);
549
641
  }
550
642
  if (img.isTinted && (img.tint !== 0xffffff || img.tintMode === TintModes.FILL)) {
551
- const tinted = this.getTintedSource(srcImg, sx, sy, sw, sh, img.tint, img.tintMode === TintModes.FILL, frame.source);
643
+ const tinted = this.getTintedSource(srcImg, sx, sy, sw, sh, img.tint, img.tintMode === TintModes.FILL, frame.source, keySx, keySy);
552
644
  if (tinted) {
553
645
  ctx.drawImage(tinted, 0, 0, Math.ceil(sw), Math.ceil(sh), dx, dy, dw, dh);
554
646
  this.curDrawCalls++;
@@ -564,8 +656,11 @@ var Renderer2D = class Renderer2D extends EventEmitter {
564
656
  }
565
657
  renderNineSlice(ns, ctx) {
566
658
  const frame = ns.frame;
567
- if (!frame || frame.width <= 0 || frame.height <= 0 || ns.width <= 0 || ns.height <= 0) return;
568
- const srcImg = frame.source.image;
659
+ if (!frame || frame.empty || frame.width <= 0 || frame.height <= 0 || ns.width <= 0 || ns.height <= 0) return;
660
+ const sliced = this.getFrameSlice(frame);
661
+ const srcImg = sliced ?? frame.source.image;
662
+ const baseX = sliced ? 0 : frame.cutX;
663
+ const baseY = sliced ? 0 : frame.cutY;
569
664
  ctx.imageSmoothingEnabled = frame.source.filterMode !== FilterMode.NEAREST;
570
665
  const w = ns.width, h = ns.height;
571
666
  const ox = ns.displayOriginX, oy = ns.displayOriginY;
@@ -581,16 +676,16 @@ var Renderer2D = class Renderer2D extends EventEmitter {
581
676
  B *= s;
582
677
  }
583
678
  const sxs = [
584
- frame.cutX,
585
- frame.cutX + ns.leftWidth,
586
- frame.cutX + frame.cutWidth - ns.rightWidth,
587
- frame.cutX + frame.cutWidth
679
+ baseX,
680
+ baseX + ns.leftWidth,
681
+ baseX + frame.cutWidth - ns.rightWidth,
682
+ baseX + frame.cutWidth
588
683
  ];
589
684
  const sys = [
590
- frame.cutY,
591
- frame.cutY + ns.topHeight,
592
- frame.cutY + frame.cutHeight - ns.bottomHeight,
593
- frame.cutY + frame.cutHeight
685
+ baseY,
686
+ baseY + ns.topHeight,
687
+ baseY + frame.cutHeight - ns.bottomHeight,
688
+ baseY + frame.cutHeight
594
689
  ];
595
690
  const dxs = [
596
691
  -ox,
@@ -623,17 +718,19 @@ var Renderer2D = class Renderer2D extends EventEmitter {
623
718
  }
624
719
  renderTileSprite(ts, ctx) {
625
720
  const frame = ts.frame;
626
- if (!frame || frame.width <= 0 || frame.height <= 0 || ts.width <= 0 || ts.height <= 0) return;
627
- const srcImg = frame.source.image;
721
+ if (!frame || frame.empty || frame.width <= 0 || frame.height <= 0 || ts.width <= 0 || ts.height <= 0) return;
722
+ const sliced = this.getFrameSlice(frame);
723
+ const srcImg = sliced ?? frame.source.image;
628
724
  ctx.imageSmoothingEnabled = frame.source.filterMode !== FilterMode.NEAREST;
629
725
  const ox = ts.displayOriginX, oy = ts.displayOriginY;
630
726
  const fw = frame.width, fh = frame.height;
631
727
  const offX = (ts.tilePositionX % fw + fw) % fw;
632
728
  const offY = (ts.tilePositionY % fh + fh) % fh;
633
729
  let drawSrc = srcImg;
634
- let baseSx = frame.cutX, baseSy = frame.cutY;
730
+ let baseSx = sliced ? 0 : frame.cutX;
731
+ let baseSy = sliced ? 0 : frame.cutY;
635
732
  if (ts.isTinted && ts.tint !== 0xffffff) {
636
- const tinted = this.getTintedSource(srcImg, frame.cutX, frame.cutY, frame.cutWidth, frame.cutHeight, ts.tint, false, frame.source);
733
+ const tinted = this.getTintedSource(srcImg, baseSx, baseSy, frame.cutWidth, frame.cutHeight, ts.tint, false, frame.source, frame.cutX, frame.cutY);
637
734
  if (tinted) {
638
735
  drawSrc = tinted;
639
736
  baseSx = 0;
@@ -1149,7 +1246,7 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1149
1246
  const baseAlpha = ctx.globalAlpha;
1150
1247
  const n = Math.min(cols.count, batch.maxCount, cols.x.length, cols.y.length);
1151
1248
  let vis = 0;
1152
- let lastTintImg = null;
1249
+ let lastTintSrcId = -1;
1153
1250
  let lastCutX = -1, lastCutY = -1, lastCutW = -1, lastCutH = -1, lastRgb = -1;
1154
1251
  let cachedTinted = null;
1155
1252
  for (let i = 0; i < n; i++) {
@@ -1157,7 +1254,7 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1157
1254
  const a = baseAlpha * (cols.alpha ? cols.alpha[s] : 1);
1158
1255
  if (a <= 0) continue;
1159
1256
  const fr = cols.frameIndex ? batch.texture.get(cols.frameIndex[s]) : batch.defaultFrame;
1160
- if (!fr || fr.width <= 0 || fr.height <= 0) continue;
1257
+ if (!fr || fr.empty || fr.width <= 0 || fr.height <= 0) continue;
1161
1258
  const sx = cols.scaleX ? cols.scaleX[s] : 1;
1162
1259
  const sy = cols.scaleY ? cols.scaleY[s] : sx;
1163
1260
  const rot = cols.rotation ? cols.rotation[s] : 0;
@@ -1166,7 +1263,10 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1166
1263
  const py = cols.y[s];
1167
1264
  const dx = -fr.width * batch.originX;
1168
1265
  const dy = -fr.height * batch.originY;
1169
- const srcImg = fr.source.image;
1266
+ const sliced = this.getFrameSlice(fr);
1267
+ const srcImg = sliced ?? fr.source.image;
1268
+ const drawSx = sliced ? 0 : fr.cutX;
1269
+ const drawSy = sliced ? 0 : fr.cutY;
1170
1270
  ctx.save();
1171
1271
  ctx.globalAlpha = a;
1172
1272
  ctx.imageSmoothingEnabled = fr.source.filterMode !== FilterMode.NEAREST;
@@ -1174,9 +1274,9 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1174
1274
  if (rot !== 0) ctx.rotate(rot);
1175
1275
  if (sx !== 1 || sy !== 1) ctx.scale(sx, sy);
1176
1276
  if (rgb !== 0xffffff && fr.cutWidth > 0 && fr.cutHeight > 0) {
1177
- if (srcImg !== lastTintImg || fr.cutX !== lastCutX || fr.cutY !== lastCutY || fr.cutWidth !== lastCutW || fr.cutHeight !== lastCutH || rgb !== lastRgb) {
1178
- cachedTinted = this.getTintedSource(srcImg, fr.cutX, fr.cutY, fr.cutWidth, fr.cutHeight, rgb, false, fr.source);
1179
- lastTintImg = srcImg;
1277
+ if (fr.source.id !== lastTintSrcId || fr.cutX !== lastCutX || fr.cutY !== lastCutY || fr.cutWidth !== lastCutW || fr.cutHeight !== lastCutH || rgb !== lastRgb) {
1278
+ cachedTinted = this.getTintedSource(srcImg, drawSx, drawSy, fr.cutWidth, fr.cutHeight, rgb, false, fr.source, fr.cutX, fr.cutY);
1279
+ lastTintSrcId = fr.source.id;
1180
1280
  lastCutX = fr.cutX;
1181
1281
  lastCutY = fr.cutY;
1182
1282
  lastCutW = fr.cutWidth;
@@ -1190,7 +1290,7 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1190
1290
  continue;
1191
1291
  }
1192
1292
  }
1193
- ctx.drawImage(srcImg, fr.cutX, fr.cutY, fr.cutWidth, fr.cutHeight, dx, dy, fr.width, fr.height);
1293
+ ctx.drawImage(srcImg, drawSx, drawSy, fr.cutWidth, fr.cutHeight, dx, dy, fr.width, fr.height);
1194
1294
  ctx.restore();
1195
1295
  vis++;
1196
1296
  }
@@ -1361,13 +1461,15 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1361
1461
  const bob = list[i];
1362
1462
  if (!bob.visible || bob.alpha <= 0) continue;
1363
1463
  const frame = bob.frame;
1464
+ if (!frame || frame.empty) continue;
1364
1465
  if (this.isOffscreen(m, bob.x, bob.y, bob.x + frame.width, bob.y + frame.height)) {
1365
1466
  this.curCulled++;
1366
1467
  continue;
1367
1468
  }
1469
+ const sliced = this.getFrameSlice(frame);
1368
1470
  ctx.imageSmoothingEnabled = frame.source.filterMode !== FilterMode.NEAREST;
1369
1471
  ctx.globalAlpha = baseAlpha * bob.alpha;
1370
- ctx.drawImage(frame.source.image, frame.cutX, frame.cutY, frame.cutWidth, frame.cutHeight, bob.x, bob.y, frame.width, frame.height);
1472
+ ctx.drawImage(sliced ?? frame.source.image, sliced ? 0 : frame.cutX, sliced ? 0 : frame.cutY, frame.cutWidth, frame.cutHeight, bob.x, bob.y, frame.width, frame.height);
1371
1473
  vis++;
1372
1474
  }
1373
1475
  ctx.globalAlpha = baseAlpha;
@@ -1382,25 +1484,12 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1382
1484
  let baseMat;
1383
1485
  if (parentMat === null) {
1384
1486
  if (obj.scrollFactorX === 1 && obj.scrollFactorY === 1) baseMat = camera.matrixCombined;
1385
- else {
1386
- const z = camera.zoom || 1;
1387
- const ox = camera.width * camera.originX;
1388
- const oy = camera.height * camera.originY;
1389
- const sx = camera.roundPixels ? Math.round(camera.scrollX) : camera.scrollX;
1390
- const sy = camera.roundPixels ? Math.round(camera.scrollY) : camera.scrollY;
1391
- const rm = this.rootScrollMat;
1392
- rm.a = z;
1393
- rm.b = 0;
1394
- rm.c = 0;
1395
- rm.d = z;
1396
- rm.tx = (-sx * obj.scrollFactorX - ox) * z + ox + camera.x;
1397
- rm.ty = (-sy * obj.scrollFactorY - oy) * z + oy + camera.y;
1398
- baseMat = rm;
1399
- }
1487
+ else baseMat = camera.matrixForScrollFactor(obj.scrollFactorX, obj.scrollFactorY, this.rootScrollMat);
1400
1488
  } else baseMat = parentMat;
1401
1489
  while (depth >= this.matPool.length) this.matPool.push(createMatrix2D());
1402
1490
  const m = this.mulMat(baseMat, obj.x, obj.y, obj.scaleX, obj.scaleY, obj.rotation, this.matPool[depth], obj.skewX, obj.skewY);
1403
1491
  const t = obj.type;
1492
+ if ((t === "Image" || t === "Sprite") && obj.frame?.empty) return;
1404
1493
  if (t === "Image" || t === "Sprite" || t === "NineSlice" || t === "TileSprite" || t === "Rectangle" || t === "Panel") {
1405
1494
  const ox = obj.displayOriginX;
1406
1495
  const oy = obj.displayOriginY;
@@ -1525,10 +1614,13 @@ var Renderer2D = class Renderer2D extends EventEmitter {
1525
1614
  this.lastStats.sdfDraws = this.curSdfPanels > 0 ? 1 : 0;
1526
1615
  this.lastStats.msdfIcons = this.curMsdfIcons;
1527
1616
  this.lastStats.msdfDraws = this.curMsdfIcons > 0 ? 1 : 0;
1617
+ this.lastStats.frameSlices = this.sliceCache.size;
1528
1618
  }
1529
1619
  destroy() {
1530
1620
  this.removeAllListeners();
1531
1621
  this.tintCache.clear();
1622
+ this.sliceCache.clear();
1623
+ this.sliceBytes = 0;
1532
1624
  this.tintCanvas = null;
1533
1625
  this.tintCtx = null;
1534
1626
  }
@@ -2501,21 +2593,7 @@ var RendererWebGpu = class extends EventEmitter {
2501
2593
  let baseMat = parentMat;
2502
2594
  if (!baseMat) {
2503
2595
  if (obj.scrollFactorX === 1 && obj.scrollFactorY === 1) baseMat = camera.matrixCombined;
2504
- else {
2505
- const z = camera.zoom || 1;
2506
- const ox = camera.width * camera.originX;
2507
- const oy = camera.height * camera.originY;
2508
- const sx = camera.roundPixels ? Math.round(camera.scrollX) : camera.scrollX;
2509
- const sy = camera.roundPixels ? Math.round(camera.scrollY) : camera.scrollY;
2510
- const sm = this.sfMat;
2511
- sm.a = z;
2512
- sm.b = 0;
2513
- sm.c = 0;
2514
- sm.d = z;
2515
- sm.tx = (-sx * obj.scrollFactorX - ox) * z + ox + camera.x;
2516
- sm.ty = (-sy * obj.scrollFactorY - oy) * z + oy + camera.y;
2517
- baseMat = sm;
2518
- }
2596
+ else baseMat = camera.matrixForScrollFactor(obj.scrollFactorX, obj.scrollFactorY, this.sfMat);
2519
2597
  }
2520
2598
  let m;
2521
2599
  if (obj.x === 0 && obj.y === 0 && obj.scaleX === 1 && obj.scaleY === 1 && obj.rotation === 0 && obj.skewX === 0 && obj.skewY === 0) m = baseMat;
@@ -1,2 +1,2 @@
1
- import { $ as WebGpuBootstrapResult, Q as RequestWebGpuOptions, X as RendererWebGpu, Z as RendererWebGpuOptions, et as WebGpuCanvasContextLike, nt as requestWebGpuDevice, tt as WebGpuDeviceLike } from "./game-B7w2sF5C.js";
1
+ import { $ as WebGpuBootstrapResult, Q as RequestWebGpuOptions, X as RendererWebGpu, Z as RendererWebGpuOptions, et as WebGpuCanvasContextLike, nt as requestWebGpuDevice, tt as WebGpuDeviceLike } from "./game-CytDvQt9.js";
2
2
  export { RendererWebGpu, RendererWebGpuOptions, RequestWebGpuOptions, WebGpuBootstrapResult, WebGpuCanvasContextLike, WebGpuDeviceLike, requestWebGpuDevice };
@@ -1 +1 @@
1
- export { t as RendererWebGpu, n as requestWebGpuDevice } from "./renderer-webgpu-BZ3J971y.js";
1
+ export { t as RendererWebGpu, n as requestWebGpuDevice } from "./renderer-webgpu-CHJxmCvR.js";
package/dist/rig2d.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { T as BlendMode } from "./anims-D9N8w6IM.js";
2
- import { It as SceneHostLike, Tt as ImageObject, pt as Container, wt as Graphics } from "./game-B7w2sF5C.js";
2
+ import { It as SceneHostLike, Tt as ImageObject, pt as Container, wt as Graphics } from "./game-CytDvQt9.js";
3
3
  export type RigCurveKind = 'linear' | 'step' | 'smoothstep' | 'outBack';
4
4
  export interface RigBoneDef {
5
5
  name: string;
package/dist/tilemap.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { It as SceneHostLike, dt as BlitterObject, pt as Container } from "./game-B7w2sF5C.js";
1
+ import { It as SceneHostLike, dt as BlitterObject, pt as Container } from "./game-CytDvQt9.js";
2
2
  /** Pack signed 16-bit chunk coordinates `[-32768..32767]` into a single 32-bit integer Map key (zero string allocation). */
3
3
  export declare function packChunkKey(cx: number, cy: number): number;
4
4
  export declare function unpackChunkX(key: number): number;
package/dist/tilemap.js CHANGED
@@ -508,6 +508,32 @@ function mountChunkedTilemap(scene, map, atlas, opts = {}) {
508
508
  const chunkPx = cs * ts;
509
509
  const halfTs = ts * .5;
510
510
  let totalBobs = 0;
511
+ const tileSlices = useChunkCache ? layers.map(() => new Array(16)) : [];
512
+ const getTileSlice = (li, mask, fr) => {
513
+ const row = tileSlices[li];
514
+ if (!row || !doc) return null;
515
+ const cached = row[mask];
516
+ if (cached !== void 0) return cached;
517
+ const src = fr.source;
518
+ const cw = fr.cutWidth;
519
+ const ch = fr.cutHeight;
520
+ if (!src || cw <= 0 || ch <= 0 || src.width * src.height <= Math.max(262144, cw * ch * 4)) {
521
+ row[mask] = null;
522
+ return null;
523
+ }
524
+ const sc = doc.createElement("canvas");
525
+ sc.width = cw;
526
+ sc.height = ch;
527
+ const sctx = sc.getContext("2d");
528
+ if (!sctx) {
529
+ row[mask] = null;
530
+ return null;
531
+ }
532
+ sctx.imageSmoothingEnabled = false;
533
+ sctx.drawImage(src.image ?? atlas.canvas, fr.cutX, fr.cutY, cw, ch, 0, 0, cw, ch);
534
+ row[mask] = sc;
535
+ return sc;
536
+ };
511
537
  const evictChunkEntry = (entry) => {
512
538
  if (entry.chunkImage) {
513
539
  entry.chunkImage.destroy();
@@ -544,7 +570,9 @@ function mountChunkedTilemap(scene, map, atlas, opts = {}) {
544
570
  const mask = map.sampleDualGridMask(vx, vy, layers[li].matches);
545
571
  if (mask === 0) continue;
546
572
  const fr = frameTable[li][mask];
547
- cctx.drawImage(srcImg, fr.cutX, fr.cutY, fr.cutWidth, fr.cutHeight, dx, dy, ts, ts);
573
+ const tileSlice = getTileSlice(li, mask, fr);
574
+ if (tileSlice) cctx.drawImage(tileSlice, 0, 0, fr.cutWidth, fr.cutHeight, dx, dy, ts, ts);
575
+ else cctx.drawImage(srcImg, fr.cutX, fr.cutY, fr.cutWidth, fr.cutHeight, dx, dy, ts, ts);
548
576
  bobCount++;
549
577
  }
550
578
  }
package/dist/trace.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as SceneDigestSurfaceEntry, F as SceneDigestEngineSandbox, H as SceneDigestSurfaces, I as SceneDigestNode, L as SceneDigestOptions, N as SceneDigest, P as SceneDigestActiveFocus, R as SceneDigestOverlayStats, U as buildSceneDigest, V as SceneDigestSurfaceSource, W as sanitizeTrackToken, z as SceneDigestSandbox } from "./game-B7w2sF5C.js";
1
+ import { B as SceneDigestSurfaceEntry, F as SceneDigestEngineSandbox, H as SceneDigestSurfaces, I as SceneDigestNode, L as SceneDigestOptions, N as SceneDigest, P as SceneDigestActiveFocus, R as SceneDigestOverlayStats, U as buildSceneDigest, V as SceneDigestSurfaceSource, W as sanitizeTrackToken, z as SceneDigestSandbox } from "./game-CytDvQt9.js";
2
2
  export { SceneDigest, SceneDigestActiveFocus, SceneDigestEngineSandbox, SceneDigestNode, SceneDigestOptions, SceneDigestOverlayStats, SceneDigestSandbox, SceneDigestSurfaceEntry, SceneDigestSurfaceSource, SceneDigestSurfaces, buildSceneDigest, sanitizeTrackToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holtjs/stage",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
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.",