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/src/dev.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // PNGine Dev API (full-feature profile)
2
2
 
3
3
  export { pngine, destroy } from "./init.js";
4
- export { draw, play, pause, stop, seek, setFrame, setUniform, setUniforms, getUniforms, restart } from "./anim.js";
4
+ export { draw, play, pause, stop, seek, setFrame, setUniform, setUniforms, getUniforms, getStats, restart } from "./anim.js";
5
5
  export { extractBytecode, detectFormat, isPng, isZip, isPngb } from "./extract.js";
6
6
  export { parsePayload, createExecutor, getExecutorImports, getExecutorVariantName } from "./loader.js";
@@ -42,21 +42,22 @@ export function dispatchQueueCommand(cmd, view, pos, ops) {
42
42
  const { time, cw, ch } = ops.clock();
43
43
  DEBUG && ops.debug() && console.log(`[GPU] writeTimeUniform buf[${id}] time=${time} cw=${cw} ch=${ch}`);
44
44
  if (ops.buf[id]) {
45
- const data = new Float32Array([time, cw, ch, cw / (ch || 1)]);
46
- ops.device.queue.writeBuffer(ops.buf[id], offset, new Uint8Array(data.buffer, 0, Math.min(size, 16)));
45
+ // Staged through the dispatcher's own scratch rather than a fresh
46
+ // Float32Array per write: this runs every frame, once per queue step.
47
+ const s = ops.scratch;
48
+ s.time[0] = time; s.time[1] = cw; s.time[2] = ch; s.time[3] = cw / (ch || 1);
49
+ ops.device.queue.writeBuffer(ops.buf[id], offset, s.timeBytes, 0, Math.min(size, 16));
47
50
  }
48
51
  return pos + 8;
49
52
  }
50
53
  case 0x26: { // write_pointer_uniform
51
54
  const id = view.getUint16(pos, true), offset = view.getUint32(pos + 2, true), size = view.getUint16(pos + 6, true);
52
- const p = ops.pointer();
53
- DEBUG && ops.debug() && console.log(`[GPU] writePointerUniform buf[${id}] x=${p[0]} y=${p[1]}`);
54
- if (ops.buf[id]) {
55
- // 12 floats = 48 bytes; the 12th is padding. Layout is pinned by
56
- // tests/npm/helpers/pointer-layout.js.
57
- const data = new Float32Array([...p, 0]);
58
- ops.device.queue.writeBuffer(ops.buf[id], offset, new Uint8Array(data.buffer, 0, Math.min(size, 48)));
59
- }
55
+ const s = ops.scratch;
56
+ DEBUG && ops.debug() && console.log(`[GPU] writePointerUniform buf[${id}] x=${s.ptr[0]} y=${s.ptr[1]}`);
57
+ // 12 floats = 48 bytes; the 12th is padding. Layout is pinned by
58
+ // tests/npm/helpers/pointer-layout.js. setPointer writes the state
59
+ // straight into this array, so the write copies with no staging at all.
60
+ if (ops.buf[id]) ops.device.queue.writeBuffer(ops.buf[id], offset, s.ptrBytes, 0, Math.min(size, 48));
60
61
  return pos + 8;
61
62
  }
62
63
  case 0x27: { // resolve_query_set
@@ -138,12 +139,20 @@ export function dispatchQueueCommand(cmd, view, pos, ops) {
138
139
  case 0x30: { // init_wasm_module (async)
139
140
  const id = view.getUint16(pos, true), ptr = view.getUint32(pos + 2, true), len = view.getUint32(pos + 6, true);
140
141
  DEBUG && ops.debug() && console.log(`[GPU] init_wasm_module: id=${id}, ptr=${ptr}, len=${len}`);
141
- if (len === 0) return pos + 10;
142
+ // Guarded like the create_* handlers: each occurrence compiles a module
143
+ // AND allocates a fresh WebAssembly.Memory, dropping the previous
144
+ // instance to GC with no way to release it explicitly.
145
+ if (len === 0 || ops.wm[id]) return pos + 10;
142
146
  const bytes = new Uint8Array(ops.mem.buffer, ptr, len).slice();
143
147
  const importedMem = new WebAssembly.Memory({ initial: 1 });
144
148
  const wasmImports = { env: { abort: () => { throw new Error('WASM abort'); }, memory: importedMem } };
145
149
  return WebAssembly.compile(bytes).then(mod =>
146
150
  WebAssembly.instantiate(mod, wasmImports).then(inst => {
151
+ // Same window as 0x0B: a dispatcher released mid-compile has an
152
+ // emptied table, and this instance carries its own
153
+ // WebAssembly.Memory. Nothing to release explicitly — just don't
154
+ // hand it to an array nobody will walk again.
155
+ if (!ops.alive()) return pos + 10;
147
156
  ops.wm[id] = { inst, importedMem };
148
157
  DEBUG && ops.debug() && console.log(`[GPU] init_wasm_module done: id=${id}, exports=`, Object.keys(inst.exports));
149
158
  return pos + 10;
@@ -189,6 +198,15 @@ export function dispatchQueueCommand(cmd, view, pos, ops) {
189
198
  onQueryResult(Array.from(data, v => Number(v)));
190
199
  b.unmap();
191
200
  }).catch((e) => {
201
+ // A throw in the success path above — getMappedRange, or the
202
+ // host's own onQueryResult — lands here with the buffer still
203
+ // MAPPED and unmap() unreached. That is permanent: 0x22 above
204
+ // skips a MAP_READ destination whose mapState isn't 'unmapped',
205
+ // so one bad callback kills readback for the rest of the session
206
+ // and leaves the buffer mapped. Guarded on mapState because a
207
+ // REJECTED mapAsync leaves the buffer unmapped per spec, where
208
+ // an unconditional unmap() would itself throw.
209
+ if (b.mapState === 'mapped') { try { b.unmap(); } catch { /* raced a teardown */ } }
192
210
  // Swallowed, this waits forever: onQueryResult never fires either,
193
211
  // so a failed readback looks exactly like one still in flight.
194
212
  ops.reportError({ message: `query readback failed for buffer ${rb.id}: ${e?.message || e}`, source: "readback" });
@@ -3,6 +3,27 @@
3
3
 
4
4
  import { decodeTextureViewDescriptor } from "./descriptor-decode.js";
5
5
 
6
+ /**
7
+ * A pass-scoped command outside an open pass is a dropped command — and a
8
+ * missing begin_*_pass drops its ENTIRE pass this way, silently (an executor
9
+ * variant without the compute plugin would erase a whole simulation with
10
+ * zero output). Report through the host's onError; worker-core dedupes
11
+ * consecutive identical gpu-error messages, so a persistently broken frame
12
+ * surfaces once, not per-command-per-frame.
13
+ *
14
+ * @param {GpuOps} ops
15
+ * @param {string} opName - WebGPU method name, used verbatim in the report
16
+ */
17
+ function requirePass(ops, opName) {
18
+ const pass = ops.getPass();
19
+ if (!pass) {
20
+ const message = `${opName} with no active pass — command dropped`;
21
+ ops.log(`[GPU] ${message}`);
22
+ ops.reportError({ message, source: "command" });
23
+ }
24
+ return pass;
25
+ }
26
+
6
27
  /**
7
28
  * Dispatch core resource/pass commands.
8
29
  *
@@ -55,6 +76,10 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
55
76
  if (!ops.txv[id] && ops.tex[tid]) {
56
77
  const desc = len ? decodeTextureViewDescriptor(new Uint8Array(ops.mem.buffer, ptr, len)) : {};
57
78
  ops.txv[id] = ops.tex[tid].createView(desc);
79
+ // Remembered, not recomputed: the descriptor bytes live in the command
80
+ // stream, which is rewritten every frame, so by the time a resize needs
81
+ // to rebuild this view they are long gone.
82
+ ops.txs[id] = { tid, desc };
58
83
  }
59
84
  return pos + 12;
60
85
  }
@@ -62,6 +87,11 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
62
87
  const id = view.getUint16(pos, true);
63
88
  const ptr = view.getUint32(pos + 2, true);
64
89
  const len = view.getUint32(pos + 6, true);
90
+ // Guarded like every other create: the wire protocol has no destroy, so
91
+ // overwriting a populated slot would strand the previous object with no
92
+ // way to release it. A repeat create is a no-op, which is what turns a
93
+ // create landing in replayed bytecode from an unbounded leak into noise.
94
+ if (ops.qs[id]) return pos + 10;
65
95
  const d = new Uint8Array(ops.mem.buffer, ptr, len);
66
96
  // Descriptor: [type:u8] [count:u16 LE]
67
97
  const type = d[0] === 1 ? 'timestamp' : 'occlusion';
@@ -80,7 +110,9 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
80
110
  const id = view.getUint16(pos, true);
81
111
  const ptr = view.getUint32(pos + 2, true);
82
112
  const len = view.getUint32(pos + 6, true);
83
- if (len === 0) return pos + 10;
113
+ // Guarded (see 0x09): a decoded bitmap is megabytes of pixel memory, and
114
+ // an overwritten slot loses the only handle that could close() it.
115
+ if (len === 0 || ops.bmp[id]) return pos + 10;
84
116
  // Blob format: [mime_len:u8][mime:bytes][image_data:bytes]
85
117
  const raw = new Uint8Array(ops.mem.buffer, ptr, len);
86
118
  const mimeLen = raw[0];
@@ -88,7 +120,11 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
88
120
  const imageData = raw.slice(1 + mimeLen);
89
121
  const blob = new Blob([imageData], { type: mimeStr });
90
122
  return createImageBitmap(blob).then((bitmap) => {
91
- ops.bmp[id] = bitmap;
123
+ // destroy() may have run during the decode. This closure holds the OLD
124
+ // dispatcher's table, already emptied — writing here strands megabytes
125
+ // of pixel memory whose only explicit release is the close() below.
126
+ if (!ops.alive()) bitmap.close();
127
+ else ops.bmp[id] = bitmap;
92
128
  return pos + 10;
93
129
  });
94
130
  }
@@ -96,6 +132,7 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
96
132
  const id = view.getUint16(pos, true);
97
133
  const ptr = view.getUint32(pos + 2, true);
98
134
  const len = view.getUint32(pos + 6, true);
135
+ if (ops.ppl[id]) return pos + 10; // guarded (see 0x09)
99
136
  const desc = JSON.parse(ops.rs(ptr, len));
100
137
  ops.ppl[id] = ops.device.createPipelineLayout({ bindGroupLayouts: desc.bindGroupLayouts.map((i) => ops.bgl[i]) });
101
138
  return pos + 10;
@@ -104,6 +141,7 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
104
141
  const id = view.getUint16(pos, true);
105
142
  const ptr = view.getUint32(pos + 2, true);
106
143
  const len = view.getUint32(pos + 6, true);
144
+ if (ops.bun[id]) return pos + 10; // guarded (see 0x09)
107
145
  const d = new Uint8Array(ops.mem.buffer, ptr, len);
108
146
  const dv = new DataView(d.buffer, d.byteOffset, d.byteLength);
109
147
  let off = 0;
@@ -183,53 +221,73 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
183
221
  const pipId = view.getUint16(pos, true);
184
222
  ops.curPip = pipId;
185
223
  ops.log(`[GPU] setPipeline(${pipId})`);
186
- ops.getPass()?.setPipeline(ops.pip[pipId]);
224
+ requirePass(ops, "setPipeline")?.setPipeline(ops.pip[pipId]);
187
225
  return pos + 2;
188
226
  }
189
227
  case 0x13: { // set_bind_group
190
228
  const gi = view.getUint8(pos);
191
229
  const bgId = view.getUint16(pos + 1, true);
192
230
  let group = ops.bg[bgId];
193
- // Recreate bind group if it was created for a different pipeline's auto-layout
231
+ // A bind group built against `layout: "auto"` belongs to the pipeline
232
+ // whose layout produced it; binding it under a different pipeline is
233
+ // invalid, so it has to be rebuilt for the bound one.
234
+ //
235
+ // CACHED PER (bind group, pipeline). This used to store the rebuilt group
236
+ // in a local and never write it back, and never update d.layoutId — so
237
+ // the condition stayed true and every frame that bound the group made a
238
+ // fresh GPUBindGroup, none of them released. A single write-back slot
239
+ // would not do either: a payload alternating two pipelines over one group
240
+ // needs both, and one slot would thrash every frame.
241
+ // Only AUTO-layout groups need this. A group built from an explicitly
242
+ // authored (bind-group-layout …) — layoutId carries BGL_TAG (0x8000) — is
243
+ // already usable with every pipeline built from that layout, and rebuilding
244
+ // it under `curPip`'s auto layout would swap the authored layout for the
245
+ // derived one: the exact substitution the explicit form exists to prevent,
246
+ // and one WebGPU rejects if the pipeline has an explicit layout. §339.
194
247
  const d = ops.bgd[bgId];
195
- if (d && ops.curPip >= 0 && d.layoutId !== ops.curPip) {
248
+ if (d && ops.curPip >= 0 && (d.layoutId & 0x8000) === 0 && d.layoutId !== ops.curPip) {
196
249
  const p = ops.pip[ops.curPip];
197
250
  if (p) {
198
- group = ops.device.createBindGroup({ layout: p.getBindGroupLayout(d.gi), entries: ops.buildBindGroupEntries(d.entries) });
199
- ops.log(`[GPU] setBindGroup(${gi}, ${bgId}) recreated for pipeline ${ops.curPip}`);
251
+ const cache = d.alt ??= new Map();
252
+ group = cache.get(ops.curPip);
253
+ if (!group) {
254
+ group = ops.device.createBindGroup({ layout: p.getBindGroupLayout(d.gi), entries: ops.buildBindGroupEntries(d.entries) });
255
+ cache.set(ops.curPip, group);
256
+ ops.log(`[GPU] setBindGroup(${gi}, ${bgId}) recreated for pipeline ${ops.curPip}`);
257
+ }
200
258
  }
201
259
  }
202
260
  ops.log(`[GPU] setBindGroup(${gi}, ${bgId}) pass=${ops.getPass() ? 'valid' : 'NULL'} bg[${bgId}]=${group ? 'exists' : 'MISSING'}`);
203
- ops.getPass()?.setBindGroup(gi, group);
261
+ requirePass(ops, "setBindGroup")?.setBindGroup(gi, group);
204
262
  return pos + 3;
205
263
  }
206
264
  case 0x14: { // set_vertex_buffer
207
- ops.getPass()?.setVertexBuffer(view.getUint8(pos), ops.buf[view.getUint16(pos + 1, true)]);
265
+ requirePass(ops, "setVertexBuffer")?.setVertexBuffer(view.getUint8(pos), ops.buf[view.getUint16(pos + 1, true)]);
208
266
  return pos + 3;
209
267
  }
210
268
  case 0x15: { // draw
211
269
  const vc = view.getUint32(pos, true);
212
270
  const ic = view.getUint32(pos + 4, true);
213
271
  ops.log(`[GPU] draw(${vc}, ${ic}) pass=${ops.getPass() ? 'valid' : 'NULL'}`);
214
- ops.getPass()?.draw(vc, ic, view.getUint32(pos + 8, true), view.getUint32(pos + 12, true));
272
+ requirePass(ops, "draw")?.draw(vc, ic, view.getUint32(pos + 8, true), view.getUint32(pos + 12, true));
215
273
  return pos + 16;
216
274
  }
217
275
  case 0x16: { // draw_indexed
218
- ops.getPass()?.drawIndexed(view.getUint32(pos, true), view.getUint32(pos + 4, true), view.getUint32(pos + 8, true), view.getInt32(pos + 12, true), view.getUint32(pos + 16, true));
276
+ requirePass(ops, "drawIndexed")?.drawIndexed(view.getUint32(pos, true), view.getUint32(pos + 4, true), view.getUint32(pos + 8, true), view.getInt32(pos + 12, true), view.getUint32(pos + 16, true));
219
277
  return pos + 20;
220
278
  }
221
279
  case 0x17: { // end_pass
222
280
  ops.log("[GPU] endPass");
223
- ops.getPass()?.end();
281
+ requirePass(ops, "endPass")?.end();
224
282
  ops.setPass(null);
225
283
  return pos;
226
284
  }
227
285
  case 0x18: { // dispatch
228
- ops.getPass()?.dispatchWorkgroups(view.getUint32(pos, true), view.getUint32(pos + 4, true), view.getUint32(pos + 8, true));
286
+ requirePass(ops, "dispatchWorkgroups")?.dispatchWorkgroups(view.getUint32(pos, true), view.getUint32(pos + 4, true), view.getUint32(pos + 8, true));
229
287
  return pos + 12;
230
288
  }
231
289
  case 0x19: { // set_index_buffer
232
- ops.getPass()?.setIndexBuffer(ops.buf[view.getUint16(pos, true)], view.getUint8(pos + 2) === 1 ? "uint32" : "uint16");
290
+ requirePass(ops, "setIndexBuffer")?.setIndexBuffer(ops.buf[view.getUint16(pos, true)], view.getUint8(pos + 2) === 1 ? "uint32" : "uint16");
233
291
  return pos + 3;
234
292
  }
235
293
  case 0x1A: { // execute_bundles
@@ -239,7 +297,7 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
239
297
  const bid = view.getUint16(pos + 1 + i * 2, true);
240
298
  if (ops.bun[bid]) bundles.push(ops.bun[bid]);
241
299
  }
242
- if (bundles.length > 0) ops.getPass()?.executeBundles(bundles);
300
+ if (bundles.length > 0) requirePass(ops, "executeBundles")?.executeBundles(bundles);
243
301
  return pos + 1 + count * 2;
244
302
  }
245
303
  case 0x1B: { // begin_render_pass_mrt
@@ -0,0 +1,57 @@
1
+ // Live-resource accounting for a command dispatcher.
2
+ //
3
+ // The instrument a long-running session needs: exact counts of the GPU objects
4
+ // the runtime is holding right now, independent of logs, DEBUG defines and GC
5
+ // timing. Heap size cannot answer "did 600 frames strand anything" — a GPU
6
+ // object is a few bytes of JS wrapper over driver memory the heap never sees —
7
+ // and forcing GC before every sample only tells you what was collectable, not
8
+ // what the runtime still believes it owns.
9
+ //
10
+ // Counts are DERIVED from the resource tables rather than accumulated at each
11
+ // create site. That is deliberate: a create site the instrumentation missed
12
+ // would report a leak as zero, which is the one failure mode a leak instrument
13
+ // must not have. Walking the tables cannot miss a resource that is in a table,
14
+ // and a resource that is in no table is not retained by the dispatcher at all.
15
+ //
16
+ // Cost is O(total ids) per call, and it is called per stats request — never per
17
+ // frame.
18
+
19
+ /**
20
+ * Populated slots per table. The tables are sparse arrays indexed by resource
21
+ * id, so holes read as undefined and are skipped.
22
+ *
23
+ * @param {Record<string, ArrayLike<unknown>>} tables
24
+ * @returns {{live: Record<string, number>, total: number}}
25
+ */
26
+ export function countLive(tables) {
27
+ /** @type {Record<string, number>} */
28
+ const live = {};
29
+ let total = 0;
30
+ for (const kind in tables) {
31
+ const table = tables[kind];
32
+ let n = 0;
33
+ for (let i = 0; i < table.length; i++) if (table[i]) n++;
34
+ live[kind] = n;
35
+ total += n;
36
+ }
37
+ return { live, total };
38
+ }
39
+
40
+ /**
41
+ * GPUBindGroups alive beyond the ones in `bg`: set_bind_group caches a rebuilt
42
+ * group per (bind group, pipeline) when a group is bound under a pipeline other
43
+ * than the one whose auto-layout produced it. Those are real, retained
44
+ * GPUBindGroups that appear in no table — the exact shape of the leak that made
45
+ * this instrument worth having (register A1) — so a count that ignored them
46
+ * would report flat while the runtime grew.
47
+ *
48
+ * @param {ArrayLike<{alt?: Map<number, unknown>|null}>} bgd
49
+ */
50
+ export function countCachedBindGroups(bgd) {
51
+ let n = 0;
52
+ for (let i = 0; i < bgd.length; i++) {
53
+ const alt = bgd[i]?.alt;
54
+ if (alt) n += alt.size;
55
+ }
56
+ return n;
57
+ }