pngine 2.0.0 → 2.2.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.
@@ -55,6 +55,8 @@ export const MSG = {
55
55
  DESTROY: "destroy",
56
56
  SET_UNIFORM: "setUniform",
57
57
  GET_UNIFORMS: "getUniforms",
58
+ GET_STATS: "getStats",
59
+ STATS: "stats",
58
60
  RESIZE: "resize",
59
61
  READY: "ready",
60
62
  ERROR: "error",
@@ -65,6 +67,9 @@ export const MSG = {
65
67
  RESTART: "restart",
66
68
  DEVICE_LOST: "device-lost",
67
69
  DEVICE_RESTORED: "device-restored",
70
+ // Posted once handleDestroy has released the device. The host terminates on
71
+ // it (init-core.js destroy()), which is what keeps handleDestroy reachable.
72
+ DESTROYED: "destroyed",
68
73
  };
69
74
 
70
75
  const NO_EMBEDDED_EXECUTOR_ERROR =
@@ -483,8 +488,18 @@ export function createWorkerHandlers(env, opts = {}) {
483
488
  gpu?.resizeCanvasBound?.(data.width, data.height);
484
489
  }
485
490
 
491
+ // Release everything this worker owns and tell the host it may terminate us.
492
+ //
493
+ // The ack is what makes this run at all: destroy() used to post `destroy` and
494
+ // terminate on the very next line, which discards the undelivered message —
495
+ // so this function was dead code on the normal path and the GPUDevice was
496
+ // left to the browser's reclamation of the worker agent. Now the host waits
497
+ // for MSG.DESTROYED (or a 250ms fallback), which also means the nulling below
498
+ // is load-bearing rather than ceremony: between the ack and the terminate
499
+ // this worker genuinely outlives its device.
486
500
  function handleDestroy() {
487
501
  moduleLoaded = false;
502
+ initialized = false;
488
503
  uniformMap = null;
489
504
  prefetch?.destroy();
490
505
  gpu?.destroy();
@@ -492,7 +507,20 @@ export function createWorkerHandlers(env, opts = {}) {
492
507
  device.destroy();
493
508
  device = null;
494
509
  }
495
- initialized = false;
510
+ // Drop the big retained references: the executor's WASM memory (its .bss
511
+ // arrays are the executor's entire state), the last payload, and the
512
+ // canvas/context pair holding the OffscreenCanvas.
513
+ gpu = null;
514
+ wasm = null;
515
+ memory = null;
516
+ lastBytecode = null;
517
+ context = null;
518
+ canvas = null;
519
+ prefetch = null;
520
+ // The lock's tail retains the last render closure (canvas, dims) on a
521
+ // worker that the destroy ack deliberately lets outlive its device.
522
+ renderLock = Promise.resolve();
523
+ post({ type: MSG.DESTROYED });
496
524
  }
497
525
 
498
526
  // Set a uniform value without triggering a draw.
@@ -526,6 +554,27 @@ export function createWorkerHandlers(env, opts = {}) {
526
554
  post({ type: MSG.UNIFORMS, uniforms });
527
555
  }
528
556
 
557
+ // Report live GPU-resource counts + the executor's WASM memory size.
558
+ //
559
+ // The instrument for a long-running session: everything else the host can see
560
+ // (heap size, frame rate) is downstream of GC timing, while these are what
561
+ // the runtime believes it still owns. Two properties are worth asserting in a
562
+ // soak, and both are stated here rather than inferred:
563
+ // • `gpu.live.*` flat across frames — the runtime creates nothing per frame.
564
+ // • `wasmBytes` constant — the shipped executor has NO allocator (its state
565
+ // is static .bss arrays, and nothing in src/ calls @wasmMemoryGrow), so a
566
+ // growing WASM memory is itself a bug signal, not normal churn.
567
+ function handleGetStats() {
568
+ post({
569
+ type: MSG.STATS,
570
+ gpu: gpu?.getStats?.() ?? null,
571
+ wasmBytes: memory?.buffer?.byteLength ?? 0,
572
+ frameCount,
573
+ moduleLoaded,
574
+ deviceLost,
575
+ });
576
+ }
577
+
529
578
  // WASM imports for the shared wasmUrl executor path (dev only).
530
579
  function getWasmImports() {
531
580
  return {
@@ -558,7 +607,7 @@ export function createWorkerHandlers(env, opts = {}) {
558
607
  }
559
608
  }
560
609
 
561
- async function dispatch(message) {
610
+ async function dispatchOne(message) {
562
611
  const { type, ...data } = message;
563
612
  try {
564
613
  switch (type) {
@@ -583,6 +632,9 @@ export function createWorkerHandlers(env, opts = {}) {
583
632
  case MSG.GET_UNIFORMS:
584
633
  handleGetUniforms();
585
634
  break;
635
+ case MSG.GET_STATS:
636
+ handleGetStats();
637
+ break;
586
638
  case MSG.RESIZE:
587
639
  handleResize(data);
588
640
  break;
@@ -595,12 +647,73 @@ export function createWorkerHandlers(env, opts = {}) {
595
647
  }
596
648
  }
597
649
 
650
+ // One message at a time.
651
+ //
652
+ // Each Worker message is delivered as its own task, and both entries wire
653
+ // `onmessage = (e) => dispatch(e.data)` — so two handler BODIES overlap
654
+ // whenever the first is suspended when the second arrives. The window is
655
+ // narrower than "any two messages" and worth naming precisely: a chain of
656
+ // awaits that all settle as microtasks finishes before the next task is even
657
+ // delivered, so overlap needs a genuinely async step. gpu.execute() has two
658
+ // (create_image_bitmap 0x0B, init_wasm_module 0x30), which means any payload
659
+ // carrying a `(texture … :data …)` suspends its load across tasks — where the
660
+ // editor's compile-per-keystroke meets its own rAF draw loop.
661
+ //
662
+ // Overlap is not a scheduling nicety there. `load` runs
663
+ // `gpu.destroy(); wireDispatcher()` underneath a suspended `await
664
+ // gpu.execute()`, and the resumed execute keeps driving the dispatcher just
665
+ // released — creating GPU objects into tables nothing will walk again. The
666
+ // mirror case is quieter and worse: a second load arriving while the first
667
+ // holds `moduleLoaded` false skips the reset branch entirely and inherits a
668
+ // LIVE dispatcher's tables, so the payload it replaced is never released at
669
+ // all. `withRenderLock` serializes only draw-vs-prefetch and cannot see any
670
+ // of this.
671
+ //
672
+ // FIFO, and the chain never rejects — dispatchOne reports its own errors —
673
+ // mirroring withRenderLock's shape.
674
+ let chain = Promise.resolve();
675
+ // Superseded rAF draws are dropped rather than rendered back-to-back once the
676
+ // stall clears: a frame whose time has already been overtaken is work nobody
677
+ // will see. A draw carrying `uniforms` is NEVER dropped — that state is
678
+ // host-supplied (anim.js draw(p, {uniforms})) and the next frame does not
679
+ // re-send it, so collapsing it would silently lose a write.
680
+ let queuedDraws = 0;
681
+ function dispatch(message) {
682
+ const supersedable = message.type === MSG.DRAW && !message.uniforms;
683
+ if (supersedable) queuedDraws++;
684
+ const run = () => {
685
+ if (supersedable && --queuedDraws > 0) return;
686
+ return dispatchOne(message);
687
+ };
688
+ const done = chain.then(run, run);
689
+ chain = done.then(
690
+ () => {},
691
+ () => {},
692
+ );
693
+ return done;
694
+ }
695
+
598
696
  // Build the prefetch capability now that the spine it layers over exists.
599
697
  if (makePrefetch) {
600
698
  prefetch = makePrefetch({
601
699
  env,
602
700
  post,
603
701
  render,
702
+ // Thumbnails must be side-effect-free: wasm.frame() advances the
703
+ // executor's frame_counter, which IS the ping-pong pool phase, so an
704
+ // odd number of thumbnail renders between live frames would invert
705
+ // every pooled binding. Save/restore the counter around the render;
706
+ // executors older than the additive setFrameCounter export keep the
707
+ // historical drift (`wasm` is read at call time — it is null while
708
+ // this capability is being built).
709
+ renderEphemeral: async (t, w, h) => {
710
+ const save = typeof wasm?.setFrameCounter === "function" ? wasm.getFrameCounter() : undefined;
711
+ try {
712
+ await render(t, w, h);
713
+ } finally {
714
+ if (save !== undefined) wasm.setFrameCounter(save);
715
+ }
716
+ },
604
717
  getCanvas: () => canvas,
605
718
  getGpu: () => gpu,
606
719
  loaded: () => moduleLoaded,
@@ -16,6 +16,16 @@
16
16
  // withRenderLock(fn) — serializes fn against handleDraw's live render, so a
17
17
  // live 'draw' can never share the offscreen render
18
18
  // target a still-in-flight prefetch render left active
19
+ //
20
+ // OWNERSHIP CONTRACT — `{type: "thumbnail", index, bitmap}`:
21
+ // the ImageBitmap is TRANSFERRED, so the worker gives up its only reference the
22
+ // moment it posts. The HOST owns it from there and MUST call `bitmap.close()`
23
+ // once it has drawn or uploaded it. An ImageBitmap holds decoded pixel memory
24
+ // that no GC pressure reliably reclaims on its own, and a scrubbing timeline
25
+ // emits one per thumb block — so a host that only drops the reference
26
+ // accumulates megabytes for the length of the session. This is the one
27
+ // lifetime rule the engine cannot enforce for its consumer; it is stated here
28
+ // because this file defines the message.
19
29
 
20
30
  export function createPrefetch(host) {
21
31
  const { env, post } = host;
@@ -154,7 +164,10 @@ export function createPrefetch(host) {
154
164
  // live frame does. null/absent leaves the shader's own defaults.
155
165
  if (uniforms) gpu.setUniforms(uniforms);
156
166
  const centerTime = Math.min((idx + 0.5) * thumbSecondsPerBlock, thumbMaxTime);
157
- await host.render(centerTime, prefetchCanvas.width, prefetchCanvas.height);
167
+ // renderEphemeral restores the executor frame counter afterwards
168
+ // (thumbnails must not shift ping-pong pool phase); fall back for
169
+ // hosts built before it existed.
170
+ await (host.renderEphemeral ?? host.render)(centerTime, prefetchCanvas.width, prefetchCanvas.height);
158
171
  } finally {
159
172
  gpu.setRenderTargetContext(null);
160
173
  }
@@ -8,7 +8,6 @@ import { browserEnv, createWorkerHandlers } from "./worker-core.js";
8
8
  const { dispatch } = createWorkerHandlers(browserEnv(), {
9
9
  allowWasmUrl: false,
10
10
  selfRecover: true,
11
- prefetch: false,
12
11
  });
13
12
 
14
13
  onmessage = (e) => dispatch(e.data);
Binary file
package/wasm/pngine.wasm CHANGED
Binary file