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.
- package/LICENSE +121 -0
- package/README.md +20 -10
- package/dist/core.mjs +4 -4
- package/dist/dev.d.ts +16 -0
- package/dist/dev.mjs +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.mjs +1 -0
- package/dist/mini-no-audio.mjs +1 -1
- package/dist/mini.mjs +1 -1
- package/dist/viewer.d.ts +16 -0
- package/dist/viewer.mjs +1 -1
- package/package.json +17 -9
- package/schema/pngine.sjon +64 -24
- package/src/anim.js +78 -13
- package/src/dev.js +1 -1
- package/src/gpu-queue-commands.js +29 -11
- package/src/gpu-resource-pass-commands.js +73 -15
- package/src/gpu-stats.js +57 -0
- package/src/gpu.js +195 -28
- package/src/init-core.js +112 -26
- package/src/init.js +41 -24
- package/src/mini.js +189 -93
- package/src/viewer-init.js +20 -18
- package/src/viewer.js +1 -1
- package/src/worker-core.js +115 -2
- package/src/worker-prefetch.js +14 -1
- package/src/worker-viewer.js +0 -1
- package/wasm/pngine-compiler.wasm +0 -0
- package/wasm/pngine.wasm +0 -0
package/src/gpu.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import { dispatchResourcePassCommand } from "./gpu-resource-pass-commands.js";
|
|
13
13
|
import { dispatchQueueCommand } from "./gpu-queue-commands.js";
|
|
14
|
+
import { countCachedBindGroups, countLive } from "./gpu-stats.js";
|
|
14
15
|
import { uniformToTypedArray } from "./uniform-convert.js";
|
|
15
16
|
import { decodeTextureFormat } from "./enums.js";
|
|
16
17
|
import {
|
|
@@ -53,6 +54,13 @@ export function requiredFeaturesFor(adapter) {
|
|
|
53
54
|
return out;
|
|
54
55
|
}
|
|
55
56
|
|
|
57
|
+
// One decoder for the process, not one per string read. A TextDecoder carries
|
|
58
|
+
// native decoding state and is stateless between decode() calls with no
|
|
59
|
+
// `stream: true`, so a fresh one per read bought nothing — and rs() is on the
|
|
60
|
+
// frame path (call_wasm_func reads its function name every frame), which made
|
|
61
|
+
// it the only per-frame allocation in the corpus that was not a few bytes.
|
|
62
|
+
const DECODER = new TextDecoder();
|
|
63
|
+
|
|
56
64
|
// Build flag - esbuild replaces DEBUG with false in production (--define:DEBUG=false)
|
|
57
65
|
// For dev: Vite provides DEBUG=true via define config
|
|
58
66
|
// Fallback for Worker contexts where Vite's define doesn't reach
|
|
@@ -280,17 +288,44 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
280
288
|
// which is the honest answer to "how far did the clock move".
|
|
281
289
|
let tdelta = 0;
|
|
282
290
|
let cw = 0, ch = 0; // canvas width/height
|
|
283
|
-
|
|
284
|
-
|
|
291
|
+
// Staging for the two built-in uniform writes, allocated once per dispatcher.
|
|
292
|
+
//
|
|
293
|
+
// Both used to build `new Float32Array([…])` per write — 60 allocations a
|
|
294
|
+
// second each, whose whole purpose was to be copied by writeBuffer and
|
|
295
|
+
// dropped, and multiplied by however many queue steps a frame runs (the step
|
|
296
|
+
// list is uncapped). mini already avoided this on one of the two arms (§310);
|
|
297
|
+
// this is the same move on both, one tier up.
|
|
298
|
+
//
|
|
299
|
+
// `.ptr` doubles as the pointer STATE — setPointer writes into it directly, so
|
|
300
|
+
// there is no per-frame copy either. Index 11 is the layout's padding float
|
|
301
|
+
// and stays 0 (pinned by tests/npm/helpers/pointer-layout.js).
|
|
302
|
+
//
|
|
303
|
+
// The byte views exist so the queue write can be BYTE-counted: writeBuffer's
|
|
304
|
+
// 5-argument form measures dataOffset/size in ELEMENTS of the array it is
|
|
305
|
+
// handed, and the sizes on the wire are byte counts.
|
|
306
|
+
const timeAB = new ArrayBuffer(16); // pngine-inputs: time, w, h, aspect
|
|
307
|
+
const ptrAB = new ArrayBuffer(48); // pointer-inputs: 11 floats + padding
|
|
308
|
+
const scratch = {
|
|
309
|
+
time: new Float32Array(timeAB), timeBytes: new Uint8Array(timeAB),
|
|
310
|
+
ptr: new Float32Array(ptrAB), ptrBytes: new Uint8Array(ptrAB),
|
|
311
|
+
};
|
|
285
312
|
let enc = null; // command encoder
|
|
286
313
|
let pass = null; // current pass
|
|
287
314
|
let dbg = false; // debug flag
|
|
288
315
|
let curPip = -1; // current pipeline ID (for bind group layout recreation)
|
|
316
|
+
// Cleared by destroy(). Read by the execute loop and by the two async create
|
|
317
|
+
// handlers, both of which can resume after this dispatcher was released.
|
|
318
|
+
let alive = true;
|
|
289
319
|
|
|
290
320
|
// Resource tables - arrays indexed by ID (more minifiable than Maps)
|
|
291
321
|
const buf = []; // buffers
|
|
292
322
|
const tex = []; // textures
|
|
293
|
-
const txv = []; // texture views
|
|
323
|
+
const txv = []; // texture views, explicit — (texture-view …), rt 4
|
|
324
|
+
const dfv = []; // texture views, default — createView(), cached per texture id
|
|
325
|
+
// What each explicit view was made from: {tid, desc}. Kept because a view
|
|
326
|
+
// outlives nothing — when resizeCanvasBound destroys and recreates its source
|
|
327
|
+
// texture, the only way to rebuild the view is to still know how it was made.
|
|
328
|
+
const txs = [];
|
|
294
329
|
const smp = []; // samplers
|
|
295
330
|
const shd = []; // shaders
|
|
296
331
|
const pip = []; // pipelines
|
|
@@ -301,6 +336,9 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
301
336
|
const wm = []; // wasm modules
|
|
302
337
|
const wcr = []; // wasm call results
|
|
303
338
|
const bgd = []; // bind group descriptors (for recreation)
|
|
339
|
+
// create_bind_group's layout_id id-space tag; mirrors
|
|
340
|
+
// src/types/opcodes.zig BIND_GROUP_LAYOUT_TAG. Set ⇒ standalone bgl id.
|
|
341
|
+
const BGL_TAG = 0x8000;
|
|
304
342
|
const txd = []; // texture descriptors
|
|
305
343
|
const bun = []; // render bundles
|
|
306
344
|
const qs = []; // query sets
|
|
@@ -319,7 +357,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
319
357
|
// Helper: read string from WASM memory
|
|
320
358
|
function rs(ptr, len) {
|
|
321
359
|
if (len === 0) return "";
|
|
322
|
-
return
|
|
360
|
+
return DECODER.decode(new Uint8Array(mem.buffer, ptr, len));
|
|
323
361
|
}
|
|
324
362
|
|
|
325
363
|
// A create-resource command arrived with an empty descriptor payload — a
|
|
@@ -467,7 +505,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
467
505
|
txd[id] = { format: desc.format, usage: desc.usage, canvasBound,
|
|
468
506
|
dimension: desc.dimension, sampleCount: desc.sampleCount, depth: desc.size[2] };
|
|
469
507
|
DEBUG && dbg && console.log(`[GPU] createTexture(${id}) ${desc.size[0]}x${desc.size[1]} ${desc.format} usage=0x${desc.usage.toString(16)}${canvasBound ? ' [canvas]' : ''}`);
|
|
470
|
-
|
|
508
|
+
installTexture(id, scoped("createTexture", id, () => device.createTexture(desc)));
|
|
471
509
|
}
|
|
472
510
|
|
|
473
511
|
function createSampler(id, ptr, len) {
|
|
@@ -482,11 +520,62 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
482
520
|
if (bg[id]) return;
|
|
483
521
|
if (len === 0) return emptyDescriptor("createBindGroup", id);
|
|
484
522
|
const { gi, entries } = decodeBindGroupData(new Uint8Array(mem.buffer, ptr, len));
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
523
|
+
// `alt` caches the auto-layout rebuilds set_bind_group makes when this
|
|
524
|
+
// group is bound under a pipeline other than `layoutId`, keyed by pipeline
|
|
525
|
+
// id. Filled lazily there; invalidated by resizeCanvasBound below, whose
|
|
526
|
+
// rebuilt textures would otherwise leave every cached entry holding a view
|
|
527
|
+
// of a destroyed texture. An explicit-BGL group never rebuilds (see below),
|
|
528
|
+
// so its `alt` stays null.
|
|
529
|
+
bgd[id] = { layoutId, gi, entries, alt: null };
|
|
530
|
+
DEBUG && dbg && console.log(`[GPU] createBindGroup(${id}) layoutId=${fmtLayoutId(layoutId)} entries=[${entries.map(e => `{b=${e.binding} rt=${e.rt} rid=${e.rid}}`).join(',')}]`);
|
|
531
|
+
const layout = resolveBindGroupLayout(layoutId, gi);
|
|
532
|
+
if (!layout) return;
|
|
533
|
+
bg[id] = scoped("createBindGroup", id, () => device.createBindGroup({ layout, entries: buildBindGroupEntries(entries) }));
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// `layout_id` names one of two id spaces, discriminated by BGL_TAG: tagged is a
|
|
537
|
+
// standalone (bind-group-layout …) id, untagged is the id of the pipeline whose
|
|
538
|
+
// auto-derived layout the group targets. Both are numbered from 0, so the tag is
|
|
539
|
+
// the only thing separating them.
|
|
540
|
+
//
|
|
541
|
+
// The spaces do NOT fall back to each other. WebGPU makes an auto-derived layout
|
|
542
|
+
// exclusive to its own pipeline, and an explicitly created layout incompatible
|
|
543
|
+
// with any auto-layout pipeline — so resolving one as the other does not produce
|
|
544
|
+
// a merely different layout, it produces a bind group the driver rejects at draw
|
|
545
|
+
// time. Returning undefined (→ no bind group) is the honest outcome. §339.
|
|
546
|
+
function resolveBindGroupLayout(layoutId, gi) {
|
|
547
|
+
if (layoutId & BGL_TAG) return bgl[layoutId & ~BGL_TAG];
|
|
548
|
+
return pip[layoutId]?.getBindGroupLayout(gi);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function fmtLayoutId(layoutId) {
|
|
552
|
+
return (layoutId & BGL_TAG) ? `bgl:${layoutId & ~BGL_TAG}` : `pipeline:${layoutId}`;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// Install a texture and its default view together, so `dfv[id]` exists for
|
|
556
|
+
// exactly the ids `tex[id]` does. The two call sites are the only places a
|
|
557
|
+
// texture enters a table: createTexture and the resize rebuild.
|
|
558
|
+
//
|
|
559
|
+
// Why the view is cached at all: every attachment and every rt-1 bind-group
|
|
560
|
+
// entry used to mint a fresh `createView()` at the point of use, which for an
|
|
561
|
+
// attachment is once per pass per FRAME — 99 views per frame across the
|
|
562
|
+
// example corpus, none released (the wire protocol has no destroy for a view,
|
|
563
|
+
// and WebGPU offers none either; they go when the GC reaches the wrapper).
|
|
564
|
+
// Collectable, so not growth — but invisible to BOTH leak instruments, which
|
|
565
|
+
// is what made it worth fixing rather than documenting (LEAK-07-A, §351).
|
|
566
|
+
//
|
|
567
|
+
// Why eagerly rather than lazily: a lazy fill happens on the first pass that
|
|
568
|
+
// needs the view, i.e. inside frame 0, and a create inside a frame is exactly
|
|
569
|
+
// what the frame-purity gate exists to forbid. Creating it here keeps the
|
|
570
|
+
// gate's allowlist honest instead of carving out an exception for the fill.
|
|
571
|
+
//
|
|
572
|
+
// NOT used for the swap-chain texture: getCurrentTexture() returns a DIFFERENT
|
|
573
|
+
// GPUTexture each frame, so a cached view of it would point a pass at a stale
|
|
574
|
+
// image. That one createView stays per-frame, and is the only one the
|
|
575
|
+
// frame-purity allowlist admits.
|
|
576
|
+
function installTexture(id, texture) {
|
|
577
|
+
tex[id] = texture;
|
|
578
|
+
dfv[id] = texture.createView();
|
|
490
579
|
}
|
|
491
580
|
|
|
492
581
|
// Map decoded bind-group entries (rt 0=buffer, 1=texture default-view,
|
|
@@ -497,7 +586,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
497
586
|
return entries.map(e => {
|
|
498
587
|
const entry = { binding: e.binding };
|
|
499
588
|
if (e.rt === 0) { entry.resource = { buffer: buf[e.rid] }; if (e.offset) entry.resource.offset = e.offset; if (e.size) entry.resource.size = e.size; }
|
|
500
|
-
else if (e.rt === 1) entry.resource =
|
|
589
|
+
else if (e.rt === 1) entry.resource = dfv[e.rid];
|
|
501
590
|
else if (e.rt === 2) entry.resource = smp[e.rid];
|
|
502
591
|
else if (e.rt === 4) entry.resource = txv[e.rid]; // pre-created (texture-view …)
|
|
503
592
|
return entry;
|
|
@@ -517,7 +606,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
517
606
|
if (depthId !== 0xffff && tex[depthId]) {
|
|
518
607
|
const pds = pendingDepthStencilOps;
|
|
519
608
|
const pcv = pendingClearValues;
|
|
520
|
-
const dsa = { view:
|
|
609
|
+
const dsa = { view: dfv[depthId], depthLoadOp: pds ? pds.dl : "clear", depthStoreOp: pds ? pds.ds : "store", depthClearValue: pcv ? pcv.depth : 1.0 };
|
|
521
610
|
if (txd[depthId]?.format?.includes("stencil")) { dsa.stencilLoadOp = pds ? pds.sl : "clear"; dsa.stencilStoreOp = pds ? pds.ss : "store"; dsa.stencilClearValue = pcv ? pcv.stencil : 0; }
|
|
522
611
|
pd.depthStencilAttachment = dsa;
|
|
523
612
|
pendingDepthStencilOps = null;
|
|
@@ -541,11 +630,11 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
541
630
|
const canvasTex = targetCtx.getCurrentTexture();
|
|
542
631
|
cv = canvasTex.createView();
|
|
543
632
|
} else {
|
|
544
|
-
cv =
|
|
633
|
+
cv = dfv[colorId];
|
|
545
634
|
}
|
|
546
635
|
const att = colorAttachment(cv, loadOp, storeOp, cr, cg, cb, ca);
|
|
547
636
|
if (resolveId !== undefined && resolveId !== 0xffff) {
|
|
548
|
-
att.resolveTarget = (resolveId === CANVAS) ? targetCtx.getCurrentTexture().createView() :
|
|
637
|
+
att.resolveTarget = (resolveId === CANVAS) ? targetCtx.getCurrentTexture().createView() : dfv[resolveId];
|
|
549
638
|
}
|
|
550
639
|
pd = { colorAttachments: [att] };
|
|
551
640
|
}
|
|
@@ -557,7 +646,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
557
646
|
if (!enc) enc = device.createCommandEncoder();
|
|
558
647
|
const CANVAS = 0xfffe;
|
|
559
648
|
const colorAttachments = attachments.map(a => {
|
|
560
|
-
const cv = (a.tid === CANVAS) ? targetCtx.getCurrentTexture().createView() :
|
|
649
|
+
const cv = (a.tid === CANVAS) ? targetCtx.getCurrentTexture().createView() : dfv[a.tid];
|
|
561
650
|
return colorAttachment(cv, a.load, a.store, a.r, a.g, a.b, a.a);
|
|
562
651
|
});
|
|
563
652
|
DEBUG && dbg && console.log(`[GPU] beginRenderPassMRT count=${attachments.length} depth=${depthId}`);
|
|
@@ -587,6 +676,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
587
676
|
createComputePipeline,
|
|
588
677
|
createBindGroup,
|
|
589
678
|
txv,
|
|
679
|
+
txs,
|
|
590
680
|
tex,
|
|
591
681
|
bgl,
|
|
592
682
|
device,
|
|
@@ -639,11 +729,12 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
639
729
|
return e;
|
|
640
730
|
},
|
|
641
731
|
clock: () => ({ time, cw, ch }),
|
|
642
|
-
|
|
732
|
+
scratch,
|
|
643
733
|
decodeWasmArgs: (ab) => decodeWasmArgs(ab, { cw, ch, time, tdelta }),
|
|
644
734
|
getOnQueryResult: () => onQueryResult,
|
|
645
735
|
debug: () => dbg,
|
|
646
736
|
reportError: (e) => { onError && onError(e); },
|
|
737
|
+
alive: () => alive,
|
|
647
738
|
};
|
|
648
739
|
|
|
649
740
|
// Main dispatch - inline command constants for minification
|
|
@@ -664,8 +755,33 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
664
755
|
return UNKNOWN_CMD;
|
|
665
756
|
}
|
|
666
757
|
|
|
758
|
+
// Command buffers executed since this dispatcher was built. The denominator
|
|
759
|
+
// for "resources per frame" in a soak — a live count that is flat over 10
|
|
760
|
+
// buffers and flat over 600 are very different statements.
|
|
761
|
+
let executed = 0;
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Live GPU objects this dispatcher holds, by kind. See gpu-stats.js for why
|
|
765
|
+
* these are derived from the tables rather than counted at each create.
|
|
766
|
+
*/
|
|
767
|
+
function getStats() {
|
|
768
|
+
const { live, total } = countLive({
|
|
769
|
+
// Two view tables, counted apart: `txv` is an authored resource
|
|
770
|
+
// ((texture-view …), bound as rt 4), `dfv` is the dispatcher's own
|
|
771
|
+
// per-texture default-view cache. Merging them would hide which side grew.
|
|
772
|
+
buffer: buf, texture: tex, textureView: txv, defaultView: dfv,
|
|
773
|
+
sampler: smp, shader: shd,
|
|
774
|
+
pipeline: pip, bindGroup: bg, bindGroupLayout: bgl, pipelineLayout: ppl,
|
|
775
|
+
imageBitmap: bmp, wasmModule: wm, renderBundle: bun, querySet: qs,
|
|
776
|
+
});
|
|
777
|
+
const cachedBindGroups = countCachedBindGroups(bgd);
|
|
778
|
+
live.bindGroup += cachedBindGroups;
|
|
779
|
+
return { live, total: total + cachedBindGroups, cachedBindGroups, executed };
|
|
780
|
+
}
|
|
781
|
+
|
|
667
782
|
// Execute command buffer
|
|
668
783
|
async function execute(ptr) {
|
|
784
|
+
executed++;
|
|
669
785
|
let view = new DataView(mem.buffer);
|
|
670
786
|
const totalLen = view.getUint32(ptr, true);
|
|
671
787
|
const cmdCount = view.getUint16(ptr + 4, true);
|
|
@@ -684,6 +800,11 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
684
800
|
}
|
|
685
801
|
if (result instanceof Promise) {
|
|
686
802
|
pos = await result;
|
|
803
|
+
// destroy() is synchronous and can run during an async command (0x0B
|
|
804
|
+
// decode, 0x30 compile). Past this point the loop reads `mem`, which
|
|
805
|
+
// destroy() drops (a TypeError), and every create it reaches lands in a
|
|
806
|
+
// table already emptied (a leak).
|
|
807
|
+
if (!alive) break;
|
|
687
808
|
view = new DataView(mem.buffer);
|
|
688
809
|
} else {
|
|
689
810
|
pos = result;
|
|
@@ -691,16 +812,44 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
691
812
|
}
|
|
692
813
|
}
|
|
693
814
|
|
|
694
|
-
//
|
|
815
|
+
// Release everything this dispatcher holds.
|
|
816
|
+
//
|
|
817
|
+
// Runs on every payload reload (worker-core.js loadBytecode) — in an editor,
|
|
818
|
+
// that is once per compile — and on teardown. The reload path then builds a
|
|
819
|
+
// FRESH dispatcher, so the tables below become garbage wholesale either way;
|
|
820
|
+
// what this function buys is DETERMINISTIC release, which for GPU-backed
|
|
821
|
+
// objects is the difference between freeing driver memory now and freeing it
|
|
822
|
+
// whenever the JS wrapper happens to be collected.
|
|
823
|
+
//
|
|
824
|
+
// Three kinds carry an explicit release and so must appear here: GPUBuffer
|
|
825
|
+
// and GPUTexture (destroy), GPUQuerySet (destroy), and ImageBitmap (close —
|
|
826
|
+
// a decoded bitmap is megabytes of pixel memory). GPURenderBundle, shader
|
|
827
|
+
// modules, pipelines and layouts have no release method; truncating their
|
|
828
|
+
// tables just drops the references.
|
|
695
829
|
function destroy() {
|
|
830
|
+
alive = false;
|
|
696
831
|
buf.forEach(b => b?.destroy?.());
|
|
697
832
|
tex.forEach(t => t?.destroy?.());
|
|
698
|
-
|
|
833
|
+
qs.forEach(q => q?.destroy?.());
|
|
834
|
+
bmp.forEach(b => b?.close?.());
|
|
835
|
+
buf.length = tex.length = txv.length = dfv.length = smp.length = shd.length = pip.length = 0;
|
|
699
836
|
bg.length = bgl.length = ppl.length = bmp.length = wm.length = 0;
|
|
700
|
-
wcr.length = bgd.length = txd.length = bufUsage.length = 0;
|
|
837
|
+
wcr.length = bgd.length = txd.length = txs.length = bufUsage.length = 0;
|
|
838
|
+
qs.length = bun.length = 0;
|
|
701
839
|
curPip = -1;
|
|
702
840
|
pendingReadbacks.length = 0;
|
|
703
|
-
|
|
841
|
+
pendingOcclusionQS = pendingTimestampWrites = null;
|
|
842
|
+
pendingDepthStencilOps = pendingClearValues = null;
|
|
843
|
+
// The remaining closure state. Moot while a destroyed dispatcher is
|
|
844
|
+
// immediately replaced, but handleDestroy now keeps the worker alive
|
|
845
|
+
// between the device teardown and the terminate — so a dispatcher can
|
|
846
|
+
// genuinely outlive its device, and `mem` in particular pins the executor's
|
|
847
|
+
// whole WASM memory.
|
|
848
|
+
onQueryResult = onError = onShaderError = null;
|
|
849
|
+
uniformMap = null;
|
|
850
|
+
mem = null;
|
|
851
|
+
targetCtx = null;
|
|
852
|
+
enc = pass = null;
|
|
704
853
|
}
|
|
705
854
|
|
|
706
855
|
// Uniform table: Map<string, {bufferId, offset, size, type, elemCount}>
|
|
@@ -784,19 +933,36 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
784
933
|
tex[id].destroy?.();
|
|
785
934
|
const desc = { size: [w || 1, h || 1, d.depth || 1], format: d.format, usage: d.usage, sampleCount: d.sampleCount || 1 };
|
|
786
935
|
if (d.dimension) desc.dimension = d.dimension;
|
|
787
|
-
|
|
936
|
+
installTexture(id, device.createTexture(desc));
|
|
937
|
+
}
|
|
938
|
+
// Explicit (texture-view …) resources of a recreated texture, remade from
|
|
939
|
+
// their recorded source. Must run BEFORE the bind-group loop below, which
|
|
940
|
+
// reads txv. Skipped for views of ordinary textures: those textures were
|
|
941
|
+
// not touched, so their views are still valid.
|
|
942
|
+
for (let id = 0; id < txv.length; id++) {
|
|
943
|
+
const s = txs[id];
|
|
944
|
+
if (!s || !txd[s.tid]?.canvasBound || !tex[s.tid]) continue;
|
|
945
|
+
txv[id] = tex[s.tid].createView(s.desc);
|
|
788
946
|
}
|
|
789
947
|
// Bind groups that referenced a recreated texture still hold a stale view.
|
|
790
|
-
// Rebuild any bind group
|
|
791
|
-
//
|
|
948
|
+
// Rebuild any bind group with an entry pointing at a canvas-bound texture,
|
|
949
|
+
// by its default view (rt 1) or through an explicit one (rt 4). Missing the
|
|
950
|
+
// rt-4 half left the group binding a view of a texture whose memory this
|
|
951
|
+
// function had just freed — bounded, and permanently broken (LEAK-07-B).
|
|
792
952
|
for (let id = 0; id < bg.length; id++) {
|
|
793
953
|
const d = bgd[id];
|
|
794
954
|
if (!d) continue;
|
|
795
|
-
const needsRebuild = d.entries.some(e => e.rt === 1
|
|
955
|
+
const needsRebuild = d.entries.some(e => e.rt === 1
|
|
956
|
+
? txd[e.rid]?.canvasBound
|
|
957
|
+
: e.rt === 4 && txd[txs[e.rid]?.tid]?.canvasBound);
|
|
796
958
|
if (!needsRebuild) continue;
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
959
|
+
// Drop the per-pipeline auto-layout cache too: its entries hold views of
|
|
960
|
+
// the textures just destroyed above, and set_bind_group would keep
|
|
961
|
+
// handing them out. They rebuild lazily on the next bind.
|
|
962
|
+
d.alt = null;
|
|
963
|
+
const layout = resolveBindGroupLayout(d.layoutId, d.gi);
|
|
964
|
+
if (!layout) continue;
|
|
965
|
+
bg[id] = device.createBindGroup({ layout, entries: buildBindGroupEntries(d.entries) });
|
|
800
966
|
}
|
|
801
967
|
}
|
|
802
968
|
|
|
@@ -805,7 +971,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
805
971
|
setDebug(v) { dbg = v; },
|
|
806
972
|
setMemory(m) { mem = m; },
|
|
807
973
|
setTime(t) { tdelta = t - time; time = t; },
|
|
808
|
-
setPointer(s) {
|
|
974
|
+
setPointer(s) { scratch.ptr.set(s); },
|
|
809
975
|
setCanvasSize(w, h) { cw = w; ch = h; },
|
|
810
976
|
resizeCanvasBound,
|
|
811
977
|
setRenderTargetContext(c) { targetCtx = c || ctx; },
|
|
@@ -815,6 +981,7 @@ export function createCommandDispatcher(device, ctx) {
|
|
|
815
981
|
setUniformTable,
|
|
816
982
|
setUniform,
|
|
817
983
|
setUniforms,
|
|
984
|
+
getStats,
|
|
818
985
|
execute,
|
|
819
986
|
destroy,
|
|
820
987
|
};
|
package/src/init-core.js
CHANGED
|
@@ -22,6 +22,15 @@ import { workerErrorFromMessage } from "./worker-errors.js";
|
|
|
22
22
|
//
|
|
23
23
|
// Errors arriving before the handshake settles (a shader that fails to compile
|
|
24
24
|
// during init) still reach options.onError; they are not init failures.
|
|
25
|
+
//
|
|
26
|
+
// Routing is handed over AT THE RESOLVE, not by the caller afterwards, and that
|
|
27
|
+
// is load-bearing rather than tidy. `ready` resolves this promise but both
|
|
28
|
+
// profiles then await the audio phase — extractAudio, then createAudioPlayer,
|
|
29
|
+
// where a sointu module renders the entire song during instantiation. Leaving
|
|
30
|
+
// these handlers installed across that window meant a worker error in it hit
|
|
31
|
+
// fail(): terminate the worker, then reject a promise that has already settled,
|
|
32
|
+
// which is a silent no-op. The host got a "ready" instance with a dead worker,
|
|
33
|
+
// no error delivered, and a 250ms ack timeout on every later destroy().
|
|
25
34
|
export function awaitWorkerReady(worker, initMessage, transfer, options) {
|
|
26
35
|
return new Promise((resolve, reject) => {
|
|
27
36
|
let timeout = null;
|
|
@@ -35,6 +44,7 @@ export function awaitWorkerReady(worker, initMessage, transfer, options) {
|
|
|
35
44
|
worker.onmessage = (e) => {
|
|
36
45
|
if (e.data.type === "ready") {
|
|
37
46
|
clearTimeout(timeout);
|
|
47
|
+
routeWorkerMessages(worker, options);
|
|
38
48
|
resolve(e.data);
|
|
39
49
|
} else if (e.data.type === "error") {
|
|
40
50
|
fail(new Error(e.data.message));
|
|
@@ -50,7 +60,9 @@ export function awaitWorkerReady(worker, initMessage, transfer, options) {
|
|
|
50
60
|
}
|
|
51
61
|
|
|
52
62
|
// Install the post-init routing: worker messages → options.onError /
|
|
53
|
-
// options.onQueryResult.
|
|
63
|
+
// options.onQueryResult. Called by awaitWorkerReady the instant `ready`
|
|
64
|
+
// arrives, so there is no window in which neither this nor the init handshake
|
|
65
|
+
// owns the worker's messages.
|
|
54
66
|
//
|
|
55
67
|
// Repointing `onerror` is the load-bearing part. awaitWorkerReady aimed it at
|
|
56
68
|
// the init promise's reject; leaving it there means every worker exception
|
|
@@ -71,11 +83,22 @@ export function routeWorkerMessages(worker, options) {
|
|
|
71
83
|
|
|
72
84
|
// Attach pointer / keyboard / wheel tracking to `canvas`, filling a
|
|
73
85
|
// Float32Array(12) the worker reads as pointer-inputs. Must be called before
|
|
74
|
-
// canvas.transferControlToOffscreen(). Returns the buffer plus
|
|
75
|
-
//
|
|
86
|
+
// canvas.transferControlToOffscreen(). Returns the buffer plus a `detach()`
|
|
87
|
+
// that removes every listener installed here.
|
|
88
|
+
//
|
|
89
|
+
// All seven listeners register through ONE AbortController, and that is
|
|
90
|
+
// structural rather than tidy. Five of them (the canvas pointer/wheel handlers)
|
|
91
|
+
// are anonymous: no reference is kept, so removeEventListener has nothing to be
|
|
92
|
+
// passed and they were simply unremovable. Each closes over `ptr` and `canvas`,
|
|
93
|
+
// so a host that retains the element — an SPA that pools canvases, a framework
|
|
94
|
+
// that keeps a ref — kept the whole instance's pointer state alive with it. A
|
|
95
|
+
// signal detaches them without giving every closure a name.
|
|
96
|
+
//
|
|
76
97
|
// Layout: x, y, clickX, clickY, dx, dy, buttons, pressure, modifiers, scrollX, scrollY, _pad
|
|
77
98
|
export function attachPointerTracking(canvas) {
|
|
78
99
|
const ptr = new Float32Array(12);
|
|
100
|
+
const ac = new AbortController();
|
|
101
|
+
const signal = ac.signal;
|
|
79
102
|
let lastPX = 0, lastPY = 0;
|
|
80
103
|
// Modifier bitmask: 1=Shift, 2=Ctrl, 4=Alt, 8=Meta, 16=Space
|
|
81
104
|
let mods = 0;
|
|
@@ -83,10 +106,8 @@ export function attachPointerTracking(canvas) {
|
|
|
83
106
|
mods = (e.shiftKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.altKey ? 4 : 0) | (e.metaKey ? 8 : 0) | (mods & 16);
|
|
84
107
|
ptr[8] = mods;
|
|
85
108
|
};
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
document.addEventListener("keydown", onKeyDown);
|
|
89
|
-
document.addEventListener("keyup", onKeyUp);
|
|
109
|
+
document.addEventListener("keydown", (e) => { if (e.code === "Space") { mods |= 16; ptr[8] = mods; } }, { signal });
|
|
110
|
+
document.addEventListener("keyup", (e) => { if (e.code === "Space") { mods &= ~16; ptr[8] = mods; } }, { signal });
|
|
90
111
|
canvas.addEventListener("pointerdown", (e) => {
|
|
91
112
|
const r = canvas.getBoundingClientRect();
|
|
92
113
|
const nx = (e.clientX - r.left) / r.width;
|
|
@@ -95,8 +116,11 @@ export function attachPointerTracking(canvas) {
|
|
|
95
116
|
ptr[6] = e.buttons; ptr[7] = e.pressure || 0.5;
|
|
96
117
|
updateMods(e);
|
|
97
118
|
lastPX = nx; lastPY = ny;
|
|
119
|
+
// Not released explicitly: the spec auto-releases capture on pointerup and
|
|
120
|
+
// pointercancel, so there is nothing left to hold after the gesture ends
|
|
121
|
+
// (leak register C6 — verified, non-issue).
|
|
98
122
|
canvas.setPointerCapture(e.pointerId);
|
|
99
|
-
});
|
|
123
|
+
}, { signal });
|
|
100
124
|
canvas.addEventListener("pointermove", (e) => {
|
|
101
125
|
const r = canvas.getBoundingClientRect();
|
|
102
126
|
const nx = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));
|
|
@@ -106,23 +130,23 @@ export function attachPointerTracking(canvas) {
|
|
|
106
130
|
ptr[6] = e.buttons; ptr[7] = e.pressure || (e.buttons ? 0.5 : 0);
|
|
107
131
|
updateMods(e);
|
|
108
132
|
lastPX = nx; lastPY = ny;
|
|
109
|
-
}, { passive: true });
|
|
133
|
+
}, { passive: true, signal });
|
|
110
134
|
canvas.addEventListener("pointerup", () => {
|
|
111
135
|
ptr[2] = -Math.abs(ptr[2]); ptr[3] = -Math.abs(ptr[3]);
|
|
112
136
|
ptr[6] = 0; ptr[7] = 0;
|
|
113
|
-
});
|
|
137
|
+
}, { signal });
|
|
114
138
|
canvas.addEventListener("pointercancel", () => {
|
|
115
139
|
ptr[2] = -Math.abs(ptr[2]); ptr[3] = -Math.abs(ptr[3]);
|
|
116
140
|
ptr[6] = 0; ptr[7] = 0;
|
|
117
|
-
});
|
|
141
|
+
}, { signal });
|
|
118
142
|
canvas.addEventListener("wheel", (e) => {
|
|
119
143
|
e.preventDefault();
|
|
120
144
|
ptr[9] += Math.sign(e.deltaX);
|
|
121
145
|
ptr[10] += Math.sign(e.deltaY);
|
|
122
146
|
mods = (e.shiftKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.altKey ? 4 : 0) | (e.metaKey ? 8 : 0) | (mods & 16);
|
|
123
147
|
ptr[8] = mods;
|
|
124
|
-
}, { passive: false });
|
|
125
|
-
return { pointer: ptr,
|
|
148
|
+
}, { passive: false, signal });
|
|
149
|
+
return { pointer: ptr, detach: () => ac.abort() };
|
|
126
150
|
}
|
|
127
151
|
|
|
128
152
|
// Size the canvas backing store for HiDPI, before transferControlToOffscreen.
|
|
@@ -221,31 +245,41 @@ export function attachAutoResize(canvas, worker, seedW, seedH, onSize) {
|
|
|
221
245
|
*/
|
|
222
246
|
|
|
223
247
|
// Create the Pngine POJO with read-only getters over `internal`.
|
|
248
|
+
//
|
|
249
|
+
// Every getter reads through `internal`, which destroy() empties in place. That
|
|
250
|
+
// is the only thing that actually releases the instance: `p._ = null` does not,
|
|
251
|
+
// because these closures capture the `internal` PARAMETER, not the `_` property
|
|
252
|
+
// — so a host holding a destroyed handle used to keep the terminated Worker,
|
|
253
|
+
// the canvas, the audio player and the pointer buffer reachable through it.
|
|
254
|
+
//
|
|
255
|
+
// Post-destroy reads answer null/0 rather than throwing (Decision #3): it
|
|
256
|
+
// matches the POJO feel of the rest of the surface, and a teardown path that
|
|
257
|
+
// reads `p.time` one last time should not explode.
|
|
224
258
|
export function createPngine(internal) {
|
|
225
259
|
return {
|
|
226
260
|
get width() {
|
|
227
|
-
return internal.width;
|
|
261
|
+
return internal.width ?? 0;
|
|
228
262
|
},
|
|
229
263
|
get height() {
|
|
230
|
-
return internal.height;
|
|
264
|
+
return internal.height ?? 0;
|
|
231
265
|
},
|
|
232
266
|
get isPlaying() {
|
|
233
|
-
return internal.pb
|
|
267
|
+
return internal.pb?.playing ?? false;
|
|
234
268
|
},
|
|
235
269
|
get time() {
|
|
236
|
-
return internal.pb
|
|
270
|
+
return internal.pb?.time ?? 0;
|
|
237
271
|
},
|
|
238
272
|
get frameCount() {
|
|
239
|
-
return internal.frameCount;
|
|
273
|
+
return internal.frameCount ?? 0;
|
|
240
274
|
},
|
|
241
275
|
get animation() {
|
|
242
276
|
return internal.animation;
|
|
243
277
|
},
|
|
244
278
|
get currentScene() {
|
|
245
|
-
return internal.pb
|
|
279
|
+
return internal.pb?.scene ?? null;
|
|
246
280
|
},
|
|
247
281
|
get currentFrame() {
|
|
248
|
-
return internal.pb
|
|
282
|
+
return internal.pb?.frame ?? null;
|
|
249
283
|
},
|
|
250
284
|
get duration() {
|
|
251
285
|
// Animation duration in seconds, or 0 if no animation
|
|
@@ -260,8 +294,23 @@ export function createPngine(internal) {
|
|
|
260
294
|
};
|
|
261
295
|
}
|
|
262
296
|
|
|
263
|
-
//
|
|
264
|
-
//
|
|
297
|
+
// How long destroy() waits for the worker to acknowledge before terminating it
|
|
298
|
+
// anyway. A wedged or already-dead agent must never strand the thread.
|
|
299
|
+
const DESTROY_ACK_TIMEOUT_MS = 250;
|
|
300
|
+
|
|
301
|
+
// Destroy a pngine instance: stop the RAF loop, tear down audio, detach every
|
|
302
|
+
// listener, let the worker release its GPU device, and terminate it.
|
|
303
|
+
//
|
|
304
|
+
// The worker teardown is ACKNOWLEDGED, not fire-and-forget. This used to post
|
|
305
|
+
// `destroy` and call terminate() on the very next line — and terminate()
|
|
306
|
+
// discards messages that have not been delivered yet, so worker-core's
|
|
307
|
+
// handleDestroy (gpu.destroy() + device.destroy()) was dead code on the normal
|
|
308
|
+
// path. Every GPU resource an instance owned was left for the browser to
|
|
309
|
+
// reclaim whenever it got round to collecting the worker agent, which in a
|
|
310
|
+
// churning SPA means many devices' worth of GPU memory outliving their players.
|
|
311
|
+
//
|
|
312
|
+
// destroy() stays synchronous — the terminate just happens on the ack, or on a
|
|
313
|
+
// timer if none arrives.
|
|
265
314
|
export function destroy(p) {
|
|
266
315
|
const i = p._;
|
|
267
316
|
if (!i) return p;
|
|
@@ -269,10 +318,47 @@ export function destroy(p) {
|
|
|
269
318
|
if (i.animationId) cancelAnimationFrame(i.animationId);
|
|
270
319
|
if (i.disconnectResize) i.disconnectResize();
|
|
271
320
|
if (i.audio) i.audio.destroy();
|
|
272
|
-
if (i.
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
321
|
+
if (i.detachListeners) i.detachListeners();
|
|
322
|
+
// Settle every in-flight worker request (anim.js workerRequest) with its
|
|
323
|
+
// fallback: no reply can arrive once we terminate, and an unsettled promise
|
|
324
|
+
// retains the awaiting caller's whole continuation.
|
|
325
|
+
if (i.pendingRequests) {
|
|
326
|
+
for (const abandon of [...i.pendingRequests]) abandon();
|
|
327
|
+
i.pendingRequests = null;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const worker = i.worker;
|
|
331
|
+
if (worker) {
|
|
332
|
+
let done = false;
|
|
333
|
+
const finish = () => {
|
|
334
|
+
if (done) return;
|
|
335
|
+
done = true;
|
|
336
|
+
clearTimeout(timer);
|
|
337
|
+
worker.terminate();
|
|
338
|
+
};
|
|
339
|
+
const timer = setTimeout(finish, DESTROY_ACK_TIMEOUT_MS);
|
|
340
|
+
// Replaces routeWorkerMessages' handler: nothing else this instance could
|
|
341
|
+
// report still has anywhere to go.
|
|
342
|
+
worker.onmessage = (e) => { if (e.data?.type === "destroyed") finish(); };
|
|
343
|
+
worker.onerror = finish;
|
|
344
|
+
worker.postMessage({ type: "destroy" });
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Empty the bag the getters read through — this is what actually releases the
|
|
348
|
+
// instance, however long the host holds `p`.
|
|
349
|
+
i.worker = null;
|
|
350
|
+
i.canvas = null;
|
|
351
|
+
i.audio = null;
|
|
352
|
+
i.pointer = null;
|
|
353
|
+
i.animation = null;
|
|
354
|
+
i.pb = null;
|
|
355
|
+
i.detachListeners = null;
|
|
356
|
+
i.disconnectResize = null;
|
|
357
|
+
i.animationId = null;
|
|
358
|
+
i.ready = false;
|
|
359
|
+
i.width = 0;
|
|
360
|
+
i.height = 0;
|
|
361
|
+
i.frameCount = 0;
|
|
276
362
|
|
|
277
363
|
p._ = null;
|
|
278
364
|
return p;
|