pngine 4.3.1 → 4.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,395 @@
1
+ // Host texture writes and reflection — the runtime half of
2
+ // `writeTexture(p, name, bytes, opts)` / `getTextures(p)` (plan 04 Task 2).
3
+ //
4
+ // Split out of gpu.js the way gpu-host-write.js was, and for the same reason:
5
+ // gpu.js has a source budget, and the refusal messages and descriptor record do
6
+ // not fit in it. gpu.js keeps the map (`texNames`, beside `bufNames`) and three
7
+ // one-line forwards; the bodies read the dispatcher's state through the same
8
+ // ops bag the extracted dispatchers use (types/gpu-ops.d.ts).
9
+ //
10
+ // Addressing is by the SJON `(texture :name …)` name, from the first commit:
11
+ // raw ids are an emission-order artefact, change when the document is edited,
12
+ // and never appear in a public record. The name → { id, pool, frameWritten }
13
+ // map comes from the payload's texture-name block (header flag bit 7); until it
14
+ // is installed every name is unknown.
15
+ //
16
+ // Two kinds of failure, kept apart on purpose:
17
+ // - A REFUSAL is a fact about the document or the destination: no such name,
18
+ // the frame writes it itself, a bad pool member, no copy-dst, multisampled,
19
+ // 1D, a bad mip/origin/extent/stride/aspect, too little data. It reaches
20
+ // the host through onError as a PngineGPUError with source "write-texture"
21
+ // and makes no queue call.
22
+ // - A malformed MAP or RECORD (bytes that are not bytes, an offset/poolIndex/
23
+ // aspect/size that is not what it must be) is the caller's bug: a TypeError
24
+ // thrown before any entry is applied, so a call is either well-formed or
25
+ // does nothing.
26
+ //
27
+ // The layout arithmetic is NOT here. `calculateWrite` (plan 01) is the one
28
+ // contract the compiler, the static command decoder and this host share; this
29
+ // module only turns the public option shapes into its input and its output into
30
+ // the WebGPU call. The descriptor likewise comes from plan 03's `txd`, kept
31
+ // current by createTexture and the canvas resize rebuild.
32
+
33
+ import { calculateWrite, formatInfo, missingFormatFeature } from "./texture-layout.js";
34
+
35
+ // Same build-flag fallback the sibling modules install (esbuild
36
+ // --define:DEBUG=false strips the debug paths in production).
37
+ if (typeof DEBUG === "undefined") globalThis.DEBUG = false;
38
+
39
+ /** GPUTextureUsage.COPY_DST — what `queue.writeTexture` requires of its target. */
40
+ const COPY_DST = 0x02;
41
+
42
+ /** The aspects the public API and the wire contract share, in wire tag order. */
43
+ /** @type {("all"|"depth-only"|"stencil-only")[]} */
44
+ const ASPECTS = ["all", "depth-only", "stencil-only"];
45
+
46
+ /** Every numeric option is a u32 in the wire/calculator contract. */
47
+ const U32_MAX = 0xffffffff;
48
+
49
+ /**
50
+ * @typedef {object} TextureName
51
+ * @property {number} id - dispatcher id of the pool's first member
52
+ * @property {number} pool - member count: 1 for an ordinary texture, N for `:pool N`
53
+ * @property {boolean} frameWritten - the frame's own queue ops write it every draw
54
+ */
55
+
56
+ /**
57
+ * The public reflection record. Every field is the descriptor's current state;
58
+ * no raw ids are exposed (those are in `TextureName`, host-private).
59
+ *
60
+ * @typedef {object} TextureInfo
61
+ * @property {[number, number, number]} size - current resolved extent
62
+ * @property {"1d"|"2d"|"3d"} dimension
63
+ * @property {string} format - the preferred sentinel already resolved
64
+ * @property {number} mipLevelCount
65
+ * @property {number} arrayDepth - 2D size[2]; otherwise 1
66
+ * @property {number} usage - GPUTextureUsage bits
67
+ * @property {number} sampleCount
68
+ * @property {"explicit"|"canvas"|"image-bitmap"} sizeSource
69
+ * @property {number} pool - 1 or N
70
+ * @property {boolean} frameWritten
71
+ * @property {boolean} writable - at least one host write is currently permitted
72
+ * @property {("all"|"depth-only"|"stencil-only")[]} writableAspects
73
+ */
74
+
75
+ /** @typedef {ArrayBufferView|ArrayBuffer} Bytes */
76
+
77
+ /**
78
+ * The long form of one entry in a draw message's `textures` map. All options
79
+ * are the public `writeTexture` options except `redraw`, which belongs to the
80
+ * pending scheduler, not one write.
81
+ *
82
+ * @typedef {object} HostTextureWrite
83
+ * @property {Bytes} bytes - what to write; a view is written as the window it covers
84
+ * @property {number} [offset=0] - byte offset into the source view
85
+ * @property {number} [bytesPerRow] - absent stays absent at the WebGPU boundary (D26)
86
+ * @property {number} [rowsPerImage] - absent stays absent at the WebGPU boundary (D26)
87
+ * @property {number[]} [origin] - [x, y, z]; length 0-3, missing members 0
88
+ * @property {number} [mipLevel=0]
89
+ * @property {"all"|"depth-only"|"stencil-only"} [aspect="all"]
90
+ * @property {number[]} [size] - [w], [w h] or [w h d]; default remaining extent
91
+ * @property {number|"active"} [poolIndex] - k for base+k, "active" for the coming frame
92
+ */
93
+
94
+ /** @typedef {Record<string, Bytes|HostTextureWrite>} HostTextures */
95
+
96
+ /**
97
+ * WebGPU's BufferSource: a typed array, a DataView, or a bare ArrayBuffer.
98
+ * @param {unknown} b
99
+ * @returns {b is GPUAllowSharedBufferSource}
100
+ */
101
+ function isBytes(b) {
102
+ return ArrayBuffer.isView(b) || b instanceof ArrayBuffer;
103
+ }
104
+
105
+ /** @param {unknown} v @returns {boolean} */
106
+ function isIndex(v) {
107
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= U32_MAX;
108
+ }
109
+
110
+ /** @param {unknown} v @returns {boolean} */
111
+ function isArrayLike(v) {
112
+ return Array.isArray(v) || ArrayBuffer.isView(v);
113
+ }
114
+
115
+ /**
116
+ * D13's source state: a detached buffer has no bytes left to read, and a
117
+ * resizable/growable one could move between this check and the queue copy.
118
+ * Both are refused by name, before the calculator and the queue, rather than
119
+ * read as a short/zero window (EOF) or a stale one.
120
+ * @param {Bytes} bytes
121
+ * @returns {"detached-source"|"resizable-source"|null}
122
+ */
123
+ function sourceState(bytes) {
124
+ const buffer = /** @type {any} */ (ArrayBuffer.isView(bytes) ? bytes.buffer : bytes);
125
+ if (!buffer) return null;
126
+ if (buffer.detached === true) return "detached-source";
127
+ if (buffer.resizable === true || buffer.growable === true) return "resizable-source";
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * Install the name map (a Map or a plain object), replacing the previous one
133
+ * whole — a reload must never inherit the last payload's names.
134
+ * @param {GpuOps} ops
135
+ * @param {Map<string, TextureName>|Record<string, TextureName>} names
136
+ */
137
+ export function setTextureNames(ops, names) {
138
+ ops.texNames.clear();
139
+ for (const [name, r] of names instanceof Map ? names : Object.entries(names)) {
140
+ ops.texNames.set(name, { id: r.id, pool: r.pool || 1, frameWritten: !!r.frameWritten });
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Every named texture that currently exists: the public record, no ids.
146
+ *
147
+ * `writable` means at least one host write is permitted right now: created,
148
+ * copy-dst, one sample, a 2D/3D dimension, not frameWritten, and at least one
149
+ * writable aspect. `writableAspects` describes format/aspect legality alone, so
150
+ * a combined depth/stencil texture advertises its stencil aspect even though a
151
+ * frame may have forbidden the name for this draw.
152
+ *
153
+ * @param {GpuOps} ops
154
+ * @returns {Record<string, TextureInfo>}
155
+ */
156
+ export function listTextures(ops) {
157
+ /** @type {Record<string, TextureInfo>} */
158
+ const out = {};
159
+ for (const [name, { id, pool, frameWritten }] of ops.texNames) {
160
+ const d = ops.txd[id];
161
+ if (!ops.tex[id] || !d) continue;
162
+ /** @type {("all"|"depth-only"|"stencil-only")[]} */
163
+ const writableAspects = [];
164
+ for (const aspect of ASPECTS) {
165
+ if ("ok" in formatInfo(d.format, aspect)) writableAspects.push(aspect);
166
+ }
167
+ const writable =
168
+ !!(d.usage & COPY_DST) &&
169
+ d.sampleCount === 1 &&
170
+ d.dimension !== "1d" &&
171
+ !frameWritten &&
172
+ writableAspects.length > 0;
173
+ out[name] = {
174
+ size: [d.size.width, d.size.height, d.size.depthOrArrayLayers],
175
+ dimension: /** @type {"1d"|"2d"|"3d"} */ (d.dimension),
176
+ format: d.format,
177
+ mipLevelCount: d.mipLevelCount,
178
+ arrayDepth: d.dimension === "2d" ? d.size.depthOrArrayLayers : 1,
179
+ usage: d.usage,
180
+ sampleCount: d.sampleCount,
181
+ sizeSource: /** @type {"explicit"|"canvas"|"image-bitmap"} */ (d.extentSource),
182
+ pool,
183
+ frameWritten,
184
+ writable,
185
+ writableAspects,
186
+ };
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /**
192
+ * One map entry, defaulted and shape-checked, or a TypeError. Runs for every
193
+ * entry BEFORE any write resolves, so a malformed record cannot ride behind a
194
+ * valid one that already reached the queue.
195
+ *
196
+ * @param {string} name
197
+ * @param {Bytes|HostTextureWrite} spec
198
+ */
199
+ function normalize(name, spec) {
200
+ if (name.length === 0) throw new TypeError("writeTexture: texture names must be nonempty strings");
201
+ const w = isBytes(spec) ? { bytes: spec } : /** @type {HostTextureWrite} */ (spec);
202
+ if (!w || !isBytes(w.bytes)) throw new TypeError(`writeTexture '${name}': bytes must be an ArrayBufferView or an ArrayBuffer`);
203
+
204
+ const offset = w.offset ?? 0;
205
+ if (!isIndex(offset)) throw new TypeError(`writeTexture '${name}': offset must be a non-negative u32 integer, got ${offset}`);
206
+ const mipLevel = w.mipLevel ?? 0;
207
+ if (!isIndex(mipLevel)) throw new TypeError(`writeTexture '${name}': mipLevel must be a non-negative u32 integer, got ${mipLevel}`);
208
+ if (w.bytesPerRow !== undefined && !isIndex(w.bytesPerRow)) {
209
+ throw new TypeError(`writeTexture '${name}': bytesPerRow must be a non-negative u32 integer, got ${w.bytesPerRow}`);
210
+ }
211
+ if (w.rowsPerImage !== undefined && !isIndex(w.rowsPerImage)) {
212
+ throw new TypeError(`writeTexture '${name}': rowsPerImage must be a non-negative u32 integer, got ${w.rowsPerImage}`);
213
+ }
214
+
215
+ const aspect = w.aspect ?? "all";
216
+ if (!ASPECTS.includes(/** @type {any} */ (aspect))) throw new TypeError(`writeTexture '${name}': aspect must be one of ${ASPECTS.join(", ")}, got ${aspect}`);
217
+
218
+ const origin = w.origin ?? [];
219
+ if (!isArrayLike(origin) || origin.length > 3) throw new TypeError(`writeTexture '${name}': origin must be an array of 0-3 numbers`);
220
+ const originValues = Array.from(origin);
221
+ for (const v of originValues) {
222
+ if (!isIndex(v)) throw new TypeError(`writeTexture '${name}': origin members must be non-negative u32 integers, got ${v}`);
223
+ }
224
+
225
+ /** @type {{width: number, height?: number, depthOrArrayLayers?: number}|undefined} */
226
+ let size;
227
+ if (w.size !== undefined) {
228
+ if (!isArrayLike(w.size) || w.size.length < 1 || w.size.length > 3) {
229
+ throw new TypeError(`writeTexture '${name}': size must be an array of 1-3 numbers`);
230
+ }
231
+ const values = Array.from(w.size);
232
+ for (const v of values) {
233
+ if (!isIndex(v)) throw new TypeError(`writeTexture '${name}': size members must be non-negative u32 integers, got ${v}`);
234
+ }
235
+ size = { width: values[0] };
236
+ if (values.length > 1) size.height = values[1];
237
+ if (values.length > 2) size.depthOrArrayLayers = values[2];
238
+ }
239
+
240
+ const poolIndex = w.poolIndex;
241
+ if (poolIndex !== undefined && poolIndex !== "active" && !isIndex(poolIndex)) {
242
+ throw new TypeError(`writeTexture '${name}': poolIndex must be a non-negative integer or "active", got ${poolIndex}`);
243
+ }
244
+
245
+ return {
246
+ name,
247
+ bytes: w.bytes,
248
+ offset,
249
+ bytesPerRow: w.bytesPerRow,
250
+ rowsPerImage: w.rowsPerImage,
251
+ mipLevel,
252
+ aspect,
253
+ origin: {
254
+ x: originValues[0] ?? 0,
255
+ y: originValues[1] ?? 0,
256
+ z: originValues[2] ?? 0,
257
+ },
258
+ size,
259
+ poolIndex,
260
+ };
261
+ }
262
+
263
+ /**
264
+ * The member ids one write selects, or the refusal that stops it.
265
+ * @param {string} name
266
+ * @param {TextureName} r
267
+ * @param {number|"active"|undefined} poolIndex
268
+ * @param {number|undefined} counter
269
+ * @returns {number[]|string}
270
+ */
271
+ function members(name, r, poolIndex, counter) {
272
+ const { id, pool } = r;
273
+ if (poolIndex === undefined) return Array.from({ length: pool }, (_, k) => id + k);
274
+ if (poolIndex === "active") {
275
+ if (pool === 1) return [id];
276
+ if (counter === undefined) return `active-counter — '${name}' poolIndex "active" needs getFrameCounter, which this embedded executor predates`;
277
+ return [id + (counter % pool)];
278
+ }
279
+ if (pool === 1) return `not-pooled — '${name}' is not pooled (poolIndex given)`;
280
+ if (poolIndex >= pool) return `pool-index-out-of-range — '${name}' poolIndex ${poolIndex} is out of range for a pool of ${pool}`;
281
+ return [id + poolIndex];
282
+ }
283
+
284
+ /**
285
+ * Put host bytes in textures, by name.
286
+ *
287
+ * Every name is either applied or refused through `ops.reportError` with
288
+ * source "write-texture" — one message per refused member, and a refusal does
289
+ * not stop the names after it. A refused write makes no queue call. The whole
290
+ * map is shape-checked before the first byte moves.
291
+ *
292
+ * The calculator's copy extent is what the queue receives as `size`, but the
293
+ * AUTHOR'S stride presence is preserved: an absent `bytesPerRow`/
294
+ * `rowsPerImage` reaches `queue.writeTexture` as `undefined`, never the
295
+ * calculator's normalized minimum (D26).
296
+ *
297
+ * @param {GpuOps} ops
298
+ * @param {HostTextures} textures - the draw message's `textures` map
299
+ * @param {number} [counter] - the coming frame's counter (`wasm.getFrameCounter()`),
300
+ * read before `frame()`; undefined when the executor has no such export
301
+ * @returns {number} how many queue writes were made (a pool counts once per member)
302
+ * @throws {TypeError} on a malformed map or record
303
+ */
304
+ export function writeTextures(ops, textures, counter) {
305
+ if (!textures || typeof textures !== "object" || Array.isArray(textures)) {
306
+ throw new TypeError("writeTexture: textures must be an object keyed by texture name");
307
+ }
308
+ if (counter !== undefined && !(Number.isInteger(counter) && counter >= 0)) {
309
+ throw new TypeError(`writeTexture: the frame counter must be a non-negative integer, got ${counter}`);
310
+ }
311
+ const writes = Object.entries(textures).map(([name, spec]) => normalize(name, spec));
312
+
313
+ /** @param {string} why */
314
+ const report = (why) => ops.reportError({ message: `writeTexture: ${why}`, source: "write-texture" });
315
+
316
+ let count = 0;
317
+ for (const w of writes) {
318
+ const r = ops.texNames.get(w.name);
319
+ if (!r) {
320
+ report(`unknown-texture — '${w.name}' (see getTextures())`);
321
+ continue;
322
+ }
323
+ if (r.frameWritten) {
324
+ report(`frame-written — '${w.name}' is written by the frame after any host write: use a dedicated texture`);
325
+ continue;
326
+ }
327
+ const source = sourceState(w.bytes);
328
+ if (source) {
329
+ report(`${source} — '${w.name}' has no stable source bytes to copy`);
330
+ continue;
331
+ }
332
+ const selected = members(w.name, r, w.poolIndex, counter);
333
+ if (typeof selected === "string") {
334
+ report(selected);
335
+ continue;
336
+ }
337
+
338
+ // The public option shape -> plan 01's input shape. Absence stays absence:
339
+ // an undefined optional member is not passed as a normalized value.
340
+ const write = {
341
+ offset: w.offset,
342
+ mipLevel: w.mipLevel,
343
+ origin: w.origin,
344
+ aspect: w.aspect,
345
+ bytesPerRow: w.bytesPerRow,
346
+ rowsPerImage: w.rowsPerImage,
347
+ size: w.size,
348
+ };
349
+
350
+ for (const id of selected) {
351
+ const texture = ops.tex[id];
352
+ const descriptor = ops.txd[id];
353
+ if (!texture || !descriptor) {
354
+ report(`missing-texture — '${w.name}' names a texture this payload never created`);
355
+ continue;
356
+ }
357
+ if (descriptor.dimension === "1d") {
358
+ report(`unsupported-dimension — '${w.name}' is 1d; host writes support 2d and 3d textures`);
359
+ continue;
360
+ }
361
+
362
+ // The format implies its device feature on this path too: a device whose
363
+ // rebuild dropped it must not accept a compressed write because the
364
+ // texture object happened to survive.
365
+ const missing = missingFormatFeature(descriptor.format, descriptor.dimension, ops.device.features);
366
+ if (missing !== null) {
367
+ report(`texture '${w.name}' format '${descriptor.format}' requires '${missing}'; this adapter does not support it`);
368
+ continue;
369
+ }
370
+
371
+ const calc = calculateWrite(descriptor, write, w.bytes.byteLength);
372
+ if ("refuse" in calc) {
373
+ const { code, field, actual, limit } = calc.refuse;
374
+ report(`'${w.name}': ${code} — ${field}/${actual}/${limit}`);
375
+ continue;
376
+ }
377
+
378
+ const copy = calc.ok.copyExtent;
379
+ DEBUG && ops.debug() && console.log(`[GPU] writeTexture '${w.name}': tex[${id}] ${copy.width}x${copy.height}x${copy.depthOrArrayLayers}`);
380
+ ops.device.queue.writeTexture(
381
+ {
382
+ texture,
383
+ mipLevel: w.mipLevel,
384
+ origin: [w.origin.x, w.origin.y, w.origin.z],
385
+ aspect: w.aspect,
386
+ },
387
+ /** @type {GPUAllowSharedBufferSource} */ (w.bytes),
388
+ { offset: w.offset, bytesPerRow: w.bytesPerRow, rowsPerImage: w.rowsPerImage },
389
+ [copy.width, copy.height, copy.depthOrArrayLayers],
390
+ );
391
+ count++;
392
+ }
393
+ }
394
+ return count;
395
+ }