ugly-game 0.14.34 → 0.15.1

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.
@@ -46,6 +46,18 @@ export interface CrowdAssets {
46
46
  lods: CrowdLod[];
47
47
  /** `targets[targetId]` — that target's gathers, at most one per rung. */
48
48
  targets: CrowdTarget[][];
49
+ /**
50
+ * First target id belonging to the FACE, if this kit has per-frame face channels.
51
+ *
52
+ * Targets from here up are lifted out of the CPU-baked `mergeTargets` path and made GPU-resident,
53
+ * driven by a per-frame weight row (see `enableFaceRig`). They must be the LAST ids and
54
+ * contiguous, which is how the cook lays them out.
55
+ *
56
+ * ⚠️ OMITTED ⇒ NO FACE RIG, and the renderer behaves exactly as it did before this existed. That
57
+ * default is deliberate: every kit cooked without face channels keeps working untouched, and a
58
+ * caller that forgets this gets today's cost rather than a broken face.
59
+ */
60
+ faceFirst?: number;
49
61
  boneCount: number;
50
62
  /** Shared skin atlas. The CALLER owns and uploads it; this renderer never decodes anything. */
51
63
  skin: GPUTexture;
@@ -248,6 +260,81 @@ export interface MergedMorph {
248
260
  delta: Float32Array;
249
261
  count: number;
250
262
  }
263
+ /**
264
+ * Split the target library at `faceFirst` — body below, face at and above.
265
+ *
266
+ * The face channels are cooked LAST and contiguous (ids 662..708 in the shipped human kit), so
267
+ * separating them is a range check rather than an index table. The body half keeps the CPU-baked
268
+ * `mergeTargets` path; the face half becomes GPU-resident and is driven by a per-frame weight row.
269
+ *
270
+ * ⚠️ THE FACE HALF IS RE-INDEXED FROM 0, deliberately. A weight row is 47 floats indexed 0..46; if
271
+ * the face half kept its shipped ids every lookup would need the offset subtracted at exactly the
272
+ * right place, and getting it wrong produces a face that moves nothing while every counter stays
273
+ * healthy.
274
+ */
275
+ export declare function splitFaceTargets(targets: CrowdTarget[][], faceFirst: number): {
276
+ body: CrowdTarget[][];
277
+ face: CrowdTarget[][];
278
+ };
279
+ /** One rung's face targets, transposed so each VERTEX names the channels that move it. */
280
+ export interface FaceCsr {
281
+ /** Ascending vertex ids this rung's face channels touch. */
282
+ verts: Uint32Array;
283
+ /** CSR row offsets into `chan`/`delta`; length `verts.length + 1`. */
284
+ offset: Uint32Array;
285
+ /** Channel index 0..channelCount-1, one per entry. */
286
+ chan: Uint32Array;
287
+ /** `4·n` vec4-padded deltas, in the same order as `chan`. */
288
+ delta: Float32Array;
289
+ }
290
+ /**
291
+ * Transpose the face targets into CSR keyed by VERTEX, once per rung at load.
292
+ *
293
+ * ⚠️ THIS TRANSPOSE IS WHY THE PER-FRAME PASS IS RACE-FREE, and it is the same problem
294
+ * `mergeTargets` solves a different way. One thread per (channel, entry) doing `pos += delta*w` is
295
+ * a data race the moment two channels name the same vertex — and for a face that is the common
296
+ * case, not an edge case: `mouth-open` and `mouth-pursing` overlap almost entirely on the lips.
297
+ * `mergeTargets` escapes it by collapsing on the CPU, but that bakes the weights in, so it must
298
+ * re-run whenever a weight moves — exactly what a per-frame face cannot afford. Transposing keeps
299
+ * the weights out of the data: each vertex appears ONCE, one thread owns it, and the weights are
300
+ * looked up per entry inside that thread.
301
+ *
302
+ * ⚠️ Gathers are FILTERED by `g.lod`, not indexed by it — the same convention `mergeTargets` uses.
303
+ * A target may have several gathers or none at a given rung.
304
+ */
305
+ export declare function buildFaceCsr(face: CrowdTarget[][], lod: number, channelCount: number): FaceCsr;
306
+ /** The face channel set: 34 MakeHuman expression units, with the mouth units split left/right. */
307
+ export declare const FACE_CHANNEL_COUNT = 47;
308
+ /**
309
+ * Weight-row stride in FLOATS.
310
+ *
311
+ * ⚠️ 48, not 47. The WGSL indexes a row as `weights[row * FACE_ROW_FLOATS + chan]`, and a stride
312
+ * that is not a multiple of 4 puts consecutive rows on unaligned vec4 boundaries. The wasted float
313
+ * costs 4 bytes per face; getting it wrong reads every face's weights one channel out of phase,
314
+ * which renders as a face making almost-right shapes.
315
+ */
316
+ export declare const FACE_ROW_FLOATS = 48;
317
+ /** The face pass's 16-byte uniform, written in one place so CPU and WGSL cannot disagree. */
318
+ export declare function faceParams(faceCount: number, vertCount: number, channelCount: number): Uint32Array;
319
+ /** Bytes for `rows` weight rows at the padded stride. */
320
+ export declare function faceBufferBytes(rows: number): number;
321
+ /**
322
+ * ⚠️ REJECTS rather than padding or truncating. A 46-float array shifts every channel by one, which
323
+ * renders as a face making the wrong shapes — indistinguishable from a bad viseme table, and
324
+ * therefore debugged in the wrong repo.
325
+ */
326
+ export declare function checkFaceWeights(w: Float32Array): void;
327
+ /**
328
+ * The CPU oracle for the face pass: `out[v] = rest[v] + Σ w[chan]·delta` over one face's CSR.
329
+ *
330
+ * This is the specification the WGSL is checked against on the WebGPU harness, which is why it is a
331
+ * plain function with its own tests rather than the same formula trusted twice.
332
+ *
333
+ * ⚠️ READS `rest`, WRITES `out`, and they must be different buffers. That separation is the whole
334
+ * idempotence argument: recomputing the absolute position from the pristine slot every frame means
335
+ * running the pass twice changes nothing, where accumulating in place drifts.
336
+ */
337
+ export declare function applyFaceCsr(csr: FaceCsr, weights: Float32Array, row: number, rest: Float32Array, out: Float32Array): void;
251
338
  /**
252
339
  * Collapse every weighted target at `lod` into ONE sparse (vertex, delta) list, on the CPU.
253
340
  *
@@ -575,6 +662,29 @@ export declare const CROWD_PIPELINE_STATE: {
575
662
  };
576
663
  /** Floats in the draw pass's scene uniform. See `frame` for the field-by-field layout. */
577
664
  export declare const CROWD_U_FLOATS: number;
665
+ /**
666
+ * THE PER-FRAME FACE PASS. Two entry points, both one thread per (animated face, face vertex).
667
+ *
668
+ * ⚠️ ONE THREAD PER VERTEX, NOT PER DELTA ENTRY — the same correctness argument mergeTargets makes
669
+ * for the body. Two face channels routinely move the same lip vertex, so a per-entry thread doing
670
+ * a read-modify-write is a data race, and f32 atomics are not in core WGSL. buildFaceCsr is what
671
+ * makes each vertex the property of exactly one thread.
672
+ *
673
+ * ⚠️ READS srcSlot, WRITES dstSlot. Recomputing the absolute position from the pristine
674
+ * body-morphed slot every frame is what makes the pass idempotent; accumulating in place drifts,
675
+ * and a drifting face reads as a rig bug rather than as a missing reset.
676
+ *
677
+ * ⚠️ THE WEIGHT ROW COMES FROM faceTable[f].z, not from f. Faces are grouped by rung for dispatch, so
678
+ * f is a position within this rung's group; using it as the weight row directly would hand a face
679
+ * whichever mouth happened to be at that index.
680
+ *
681
+ * ⚠️ srcSlot, dstSlot AND the weight row SHARE ONE vec4u BUFFER, and that is a hard requirement, not
682
+ * tidiness. WebGPU's default maxStorageBuffersPerShaderStage is 8, and MORPH above already uses
683
+ * exactly 8 — three separate per-face tables put faceMorph at 9, which fails pipeline creation on
684
+ * any adapter reporting the default limit. That failure is a BLACK SCREEN at runtime, and no
685
+ * headless test can see it: demo/cli/faceWgsl.check.mts is what caught it.
686
+ */
687
+ export declare const FACE_WGSL = "\nstruct FP { faceCount: u32, vertCount: u32, channelCount: u32, pad: u32 };\n@group(0) @binding(0) var<storage,read_write> rest: array<vec4f>;\n@group(0) @binding(1) var<storage,read_write> restN: array<vec4f>;\n@group(0) @binding(2) var<storage,read> fVerts: array<u32>;\n@group(0) @binding(3) var<storage,read> fOffset: array<u32>;\n@group(0) @binding(4) var<storage,read> fChan: array<u32>;\n@group(0) @binding(5) var<storage,read> fDelta: array<vec4f>;\n@group(0) @binding(6) var<storage,read> weights: array<f32>;\n// x = source (pristine) slot, y = destination (animated) slot, z = weight row, w = unused.\n@group(0) @binding(7) var<storage,read> faceTable: array<vec4u>;\n@group(0) @binding(8) var<storage,read> adjOffset: array<u32>;\n@group(0) @binding(9) var<storage,read> adjTri: array<u32>;\n@group(0) @binding(10) var<storage,read> idx: array<u32>;\n@group(0) @binding(11) var<uniform> p: FP;\n\n// PASS A \u2014 position. Every face at this rung shares the same vertex list, so ONE dispatch covers\n// all of them: thread -> (face within the group, vertex within the face).\n@compute @workgroup_size(64) fn faceMorph(@builtin(global_invocation_id) g: vec3u) {\n if (g.x >= p.faceCount * p.vertCount) { return; }\n let f = g.x / p.vertCount;\n let i = g.x % p.vertCount;\n let v = fVerts[i];\n let tbl = faceTable[f];\n var q = rest[tbl.x + v].xyz;\n let row = tbl.z * 48u;\n let a = fOffset[i];\n let b = fOffset[i + 1u];\n for (var k = a; k < b; k = k + 1u) {\n q = q + fDelta[k].xyz * weights[row + fChan[k]];\n }\n rest[tbl.y + v] = vec4f(q, 1.0);\n}\n\n// PASS B \u2014 normals over the face subset only, area-weighted exactly like the body's PASS 3. A\n// SEPARATE dispatch, so every position PASS A moved is visible before any normal reads it.\n@compute @workgroup_size(64) fn faceNormals(@builtin(global_invocation_id) g: vec3u) {\n if (g.x >= p.faceCount * p.vertCount) { return; }\n let f = g.x / p.vertCount;\n let i = g.x % p.vertCount;\n let v = fVerts[i];\n let s = faceTable[f].y;\n var n = vec3f(0.0, 0.0, 0.0);\n let a = adjOffset[v];\n let b = adjOffset[v + 1u];\n for (var k = a; k < b; k = k + 1u) {\n let t = adjTri[k] * 3u;\n let p0 = rest[s + idx[t]].xyz;\n let p1 = rest[s + idx[t + 1u]].xyz;\n let p2 = rest[s + idx[t + 2u]].xyz;\n n = n + cross(p1 - p0, p2 - p0);\n }\n let len = length(n);\n restN[s + v] = vec4f(select(vec3f(0.0, 1.0, 0.0), n / len, len > 1e-12), 0.0);\n}";
578
688
  /** The four vertex pools. rest/restN are morph output; def/defN are the per-frame skin output. */
579
689
  export interface CrowdPools {
580
690
  rest: GPUBuffer;
@@ -597,6 +707,29 @@ export declare class GpuCrowdRenderer {
597
707
  */
598
708
  private morphBGL;
599
709
  private morphLayout;
710
+ private facePipe;
711
+ private faceNormalPipe;
712
+ private faceParamBuf;
713
+ /**
714
+ * The coarsest rung that still gets a face rig. **LOD0 is the finest**, so a character is rigged
715
+ * when `rung <= faceRigLod`; the default 1 rigs LOD0 and LOD1 and skips LOD2/LOD3.
716
+ *
717
+ * ⚠️ A CALLER SHOULD DRIVE ITS AUDIO THRESHOLD FROM THE SAME SIGNAL. A face moving silently, and a
718
+ * voice arriving from a frozen face, are both worse than either being off.
719
+ */
720
+ faceRigLod: number;
721
+ /** Per-rung CSR of the face channels, built once in `setAssets`. Null where a rung has none. */
722
+ private faceCsr;
723
+ /** Per-rung GPU copies of that CSR, plus the two bind groups (one per face pipeline). */
724
+ private faceLod;
725
+ /** slot → its weight row, rung and destination slot. Only rigged characters appear. */
726
+ private rigged;
727
+ /** Rows handed out so far; a freed row is reused rather than compacted (see `disableFaceRig`). */
728
+ private faceRows;
729
+ private wCpu;
730
+ private wBuf;
731
+ private faceTableBuf;
732
+ private faceTableCpu;
600
733
  /** The per-frame skin pass. One dispatch per BUCKET, selected by a dynamic uniform offset. */
601
734
  private skinPipe;
602
735
  private skinBGL;
@@ -695,6 +828,14 @@ export declare class GpuCrowdRenderer {
695
828
  * per-character or per-frame; a character is a slot plus a record, and that is the whole point.
696
829
  */
697
830
  setAssets(a: CrowdAssets): void;
831
+ /**
832
+ * Transpose this kit's face channels once per rung and upload them.
833
+ *
834
+ * ⚠️ ONCE, AT LOAD. The transpose is the thing that makes the per-frame pass race-free, and it
835
+ * depends only on the geometry — not on any weight — so paying for it per frame would be paying
836
+ * repeatedly for an answer that never changes.
837
+ */
838
+ private buildFaceLods;
698
839
  /**
699
840
  * Group 2 — the two atlases and the scene copy.
700
841
  *
@@ -737,6 +878,46 @@ export declare class GpuCrowdRenderer {
737
878
  * problem, and is a silent corruption if faked before then.
738
879
  */
739
880
  morph(slot: number, lod: number, weights: Float32Array): void;
881
+ /** Grow the weight and face-table buffers to hold `rows`, and rebuild the bind groups on them. */
882
+ private allocFaceBuffers;
883
+ /** One bind group per face pipeline — see the `layout: 'auto'` note in the constructor. */
884
+ private buildFaceBindGroups;
885
+ /**
886
+ * Turn on per-frame face animation for `slot`, drawing into `dstSlot`.
887
+ *
888
+ * ⚠️ `dstSlot` STARTS AS A COPY of `slot`, positions AND normals. Only face vertices are rewritten
889
+ * per frame; every other vertex is correct from this copy and never touched again. Skipping the
890
+ * copy leaves whatever the pool last held there, which draws as a head animating on a stranger's
891
+ * body.
892
+ *
893
+ * ⚠️ THE CALLER MUST POINT THE INSTANCE RECORD AT `dstSlot`, not at `slot`. `slot` stays pristine
894
+ * precisely so the pass can recompute from it, so a record still naming `slot` shows a face that
895
+ * never moves — with every counter healthy.
896
+ *
897
+ * Re-entrant: called again with a different rung it re-copies, because the face vertex set differs
898
+ * per rung. Beyond `faceRigLod` it disables instead, so a caller can drive it straight from the
899
+ * character's current rung each frame without branching.
900
+ */
901
+ enableFaceRig(slot: number, lod: number, dstSlot: number): void;
902
+ /** Stop dispatching for this slot — it costs exactly what it cost before the rig existed. */
903
+ disableFaceRig(slot: number): void;
904
+ /**
905
+ * Write one face's 47 channel weights. Cheap enough for every rigged face every frame.
906
+ *
907
+ * ⚠️ A console.error PLUS a no-op when the slot has no rig — never silence. A silently dropped
908
+ * write gives a still face with healthy counters, which reads as a broken driver in the app.
909
+ */
910
+ setFaceWeights(slot: number, w: Float32Array): void;
911
+ /** How many faces are currently rigged — for a caller's HUD and for the benchmark. */
912
+ get faceRigCount(): number;
913
+ /**
914
+ * Run both face passes for every rigged face. Call once per frame, before `frame()`.
915
+ *
916
+ * ⚠️ ONE DISPATCH PAIR PER RUNG, never one per face. Faces at a rung share the same vertex list,
917
+ * which is the whole reason the CSR is per rung rather than per character; at fifty faces, a
918
+ * dispatch each would cost more in launches than the work being launched.
919
+ */
920
+ faceFrame(): void;
740
921
  /**
741
922
  * Upload this frame's instance records and their per-LOD buckets.
742
923
  *
@@ -288,6 +288,135 @@ export function makeMergeScratch(vertCount) {
288
288
  dirty: new Uint8Array(vertCount),
289
289
  };
290
290
  }
291
+ /**
292
+ * Split the target library at `faceFirst` — body below, face at and above.
293
+ *
294
+ * The face channels are cooked LAST and contiguous (ids 662..708 in the shipped human kit), so
295
+ * separating them is a range check rather than an index table. The body half keeps the CPU-baked
296
+ * `mergeTargets` path; the face half becomes GPU-resident and is driven by a per-frame weight row.
297
+ *
298
+ * ⚠️ THE FACE HALF IS RE-INDEXED FROM 0, deliberately. A weight row is 47 floats indexed 0..46; if
299
+ * the face half kept its shipped ids every lookup would need the offset subtracted at exactly the
300
+ * right place, and getting it wrong produces a face that moves nothing while every counter stays
301
+ * healthy.
302
+ */
303
+ export function splitFaceTargets(targets, faceFirst) {
304
+ const cut = Math.max(0, Math.min(faceFirst, targets.length));
305
+ return { body: targets.slice(0, cut), face: targets.slice(cut) };
306
+ }
307
+ /**
308
+ * Transpose the face targets into CSR keyed by VERTEX, once per rung at load.
309
+ *
310
+ * ⚠️ THIS TRANSPOSE IS WHY THE PER-FRAME PASS IS RACE-FREE, and it is the same problem
311
+ * `mergeTargets` solves a different way. One thread per (channel, entry) doing `pos += delta*w` is
312
+ * a data race the moment two channels name the same vertex — and for a face that is the common
313
+ * case, not an edge case: `mouth-open` and `mouth-pursing` overlap almost entirely on the lips.
314
+ * `mergeTargets` escapes it by collapsing on the CPU, but that bakes the weights in, so it must
315
+ * re-run whenever a weight moves — exactly what a per-frame face cannot afford. Transposing keeps
316
+ * the weights out of the data: each vertex appears ONCE, one thread owns it, and the weights are
317
+ * looked up per entry inside that thread.
318
+ *
319
+ * ⚠️ Gathers are FILTERED by `g.lod`, not indexed by it — the same convention `mergeTargets` uses.
320
+ * A target may have several gathers or none at a given rung.
321
+ */
322
+ export function buildFaceCsr(face, lod, channelCount) {
323
+ const byVert = new Map();
324
+ for (let c = 0; c < Math.min(channelCount, face.length); c++) {
325
+ const gathers = maybe(face, c);
326
+ if (!gathers)
327
+ continue;
328
+ for (const g of gathers) {
329
+ if (g.lod !== lod)
330
+ continue;
331
+ for (let e = 0; e < g.index.length; e++) {
332
+ const v = g.index[e];
333
+ const row = byVert.get(v) ?? [];
334
+ row.push({
335
+ chan: c,
336
+ d: [g.delta[e * 3], g.delta[e * 3 + 1], g.delta[e * 3 + 2]],
337
+ });
338
+ byVert.set(v, row);
339
+ }
340
+ }
341
+ }
342
+ const verts = new Uint32Array([...byVert.keys()].sort((a, b) => a - b));
343
+ const offset = new Uint32Array(verts.length + 1);
344
+ let n = 0;
345
+ for (let i = 0; i < verts.length; i++) {
346
+ offset[i] = n;
347
+ n += byVert.get(verts[i]).length;
348
+ }
349
+ offset[verts.length] = n;
350
+ const chan = new Uint32Array(n);
351
+ const delta = new Float32Array(n * 4);
352
+ let k = 0;
353
+ for (const v of verts) {
354
+ for (const e of byVert.get(v)) {
355
+ chan[k] = e.chan;
356
+ delta[k * 4] = e.d[0];
357
+ delta[k * 4 + 1] = e.d[1];
358
+ delta[k * 4 + 2] = e.d[2];
359
+ k++;
360
+ }
361
+ }
362
+ return { verts, offset, chan, delta };
363
+ }
364
+ /** The face channel set: 34 MakeHuman expression units, with the mouth units split left/right. */
365
+ export const FACE_CHANNEL_COUNT = 47;
366
+ /**
367
+ * Weight-row stride in FLOATS.
368
+ *
369
+ * ⚠️ 48, not 47. The WGSL indexes a row as `weights[row * FACE_ROW_FLOATS + chan]`, and a stride
370
+ * that is not a multiple of 4 puts consecutive rows on unaligned vec4 boundaries. The wasted float
371
+ * costs 4 bytes per face; getting it wrong reads every face's weights one channel out of phase,
372
+ * which renders as a face making almost-right shapes.
373
+ */
374
+ export const FACE_ROW_FLOATS = 48;
375
+ /** The face pass's 16-byte uniform, written in one place so CPU and WGSL cannot disagree. */
376
+ export function faceParams(faceCount, vertCount, channelCount) {
377
+ return new Uint32Array([faceCount, vertCount, channelCount, 0]);
378
+ }
379
+ /** Bytes for `rows` weight rows at the padded stride. */
380
+ export function faceBufferBytes(rows) {
381
+ return rows * FACE_ROW_FLOATS * 4;
382
+ }
383
+ /**
384
+ * ⚠️ REJECTS rather than padding or truncating. A 46-float array shifts every channel by one, which
385
+ * renders as a face making the wrong shapes — indistinguishable from a bad viseme table, and
386
+ * therefore debugged in the wrong repo.
387
+ */
388
+ export function checkFaceWeights(w) {
389
+ if (w.length !== FACE_CHANNEL_COUNT)
390
+ throw new Error(`setFaceWeights: expected ${FACE_CHANNEL_COUNT} channels, got ${w.length}`);
391
+ }
392
+ /**
393
+ * The CPU oracle for the face pass: `out[v] = rest[v] + Σ w[chan]·delta` over one face's CSR.
394
+ *
395
+ * This is the specification the WGSL is checked against on the WebGPU harness, which is why it is a
396
+ * plain function with its own tests rather than the same formula trusted twice.
397
+ *
398
+ * ⚠️ READS `rest`, WRITES `out`, and they must be different buffers. That separation is the whole
399
+ * idempotence argument: recomputing the absolute position from the pristine slot every frame means
400
+ * running the pass twice changes nothing, where accumulating in place drifts.
401
+ */
402
+ export function applyFaceCsr(csr, weights, row, rest, out) {
403
+ const base = row * FACE_ROW_FLOATS;
404
+ for (let i = 0; i < csr.verts.length; i++) {
405
+ const v = csr.verts[i];
406
+ let x = rest[v * 4], y = rest[v * 4 + 1], z = rest[v * 4 + 2];
407
+ for (let k = csr.offset[i]; k < csr.offset[i + 1]; k++) {
408
+ const w = weights[base + csr.chan[k]] ?? 0;
409
+ if (w === 0)
410
+ continue;
411
+ x += csr.delta[k * 4] * w;
412
+ y += csr.delta[k * 4 + 1] * w;
413
+ z += csr.delta[k * 4 + 2] * w;
414
+ }
415
+ out[v * 4] = x;
416
+ out[v * 4 + 1] = y;
417
+ out[v * 4 + 2] = z;
418
+ }
419
+ }
291
420
  /**
292
421
  * Collapse every weighted target at `lod` into ONE sparse (vertex, delta) list, on the CPU.
293
422
  *
@@ -705,6 +834,83 @@ export const CROWD_U_FLOATS = 40 + 16 * MAX_CASCADES;
705
834
  // ⚠️ NO BACKTICKS ANYWHERE BELOW, including inside WGSL comments — this is a JS template literal
706
835
  // and one stray backtick terminates the shader string and fails the build a hundred lines away.
707
836
  // ─────────────────────────────────────────────────────────────────────────────
837
+ /**
838
+ * THE PER-FRAME FACE PASS. Two entry points, both one thread per (animated face, face vertex).
839
+ *
840
+ * ⚠️ ONE THREAD PER VERTEX, NOT PER DELTA ENTRY — the same correctness argument mergeTargets makes
841
+ * for the body. Two face channels routinely move the same lip vertex, so a per-entry thread doing
842
+ * a read-modify-write is a data race, and f32 atomics are not in core WGSL. buildFaceCsr is what
843
+ * makes each vertex the property of exactly one thread.
844
+ *
845
+ * ⚠️ READS srcSlot, WRITES dstSlot. Recomputing the absolute position from the pristine
846
+ * body-morphed slot every frame is what makes the pass idempotent; accumulating in place drifts,
847
+ * and a drifting face reads as a rig bug rather than as a missing reset.
848
+ *
849
+ * ⚠️ THE WEIGHT ROW COMES FROM faceTable[f].z, not from f. Faces are grouped by rung for dispatch, so
850
+ * f is a position within this rung's group; using it as the weight row directly would hand a face
851
+ * whichever mouth happened to be at that index.
852
+ *
853
+ * ⚠️ srcSlot, dstSlot AND the weight row SHARE ONE vec4u BUFFER, and that is a hard requirement, not
854
+ * tidiness. WebGPU's default maxStorageBuffersPerShaderStage is 8, and MORPH above already uses
855
+ * exactly 8 — three separate per-face tables put faceMorph at 9, which fails pipeline creation on
856
+ * any adapter reporting the default limit. That failure is a BLACK SCREEN at runtime, and no
857
+ * headless test can see it: demo/cli/faceWgsl.check.mts is what caught it.
858
+ */
859
+ export const FACE_WGSL = /* wgsl */ `
860
+ struct FP { faceCount: u32, vertCount: u32, channelCount: u32, pad: u32 };
861
+ @group(0) @binding(0) var<storage,read_write> rest: array<vec4f>;
862
+ @group(0) @binding(1) var<storage,read_write> restN: array<vec4f>;
863
+ @group(0) @binding(2) var<storage,read> fVerts: array<u32>;
864
+ @group(0) @binding(3) var<storage,read> fOffset: array<u32>;
865
+ @group(0) @binding(4) var<storage,read> fChan: array<u32>;
866
+ @group(0) @binding(5) var<storage,read> fDelta: array<vec4f>;
867
+ @group(0) @binding(6) var<storage,read> weights: array<f32>;
868
+ // x = source (pristine) slot, y = destination (animated) slot, z = weight row, w = unused.
869
+ @group(0) @binding(7) var<storage,read> faceTable: array<vec4u>;
870
+ @group(0) @binding(8) var<storage,read> adjOffset: array<u32>;
871
+ @group(0) @binding(9) var<storage,read> adjTri: array<u32>;
872
+ @group(0) @binding(10) var<storage,read> idx: array<u32>;
873
+ @group(0) @binding(11) var<uniform> p: FP;
874
+
875
+ // PASS A — position. Every face at this rung shares the same vertex list, so ONE dispatch covers
876
+ // all of them: thread -> (face within the group, vertex within the face).
877
+ @compute @workgroup_size(64) fn faceMorph(@builtin(global_invocation_id) g: vec3u) {
878
+ if (g.x >= p.faceCount * p.vertCount) { return; }
879
+ let f = g.x / p.vertCount;
880
+ let i = g.x % p.vertCount;
881
+ let v = fVerts[i];
882
+ let tbl = faceTable[f];
883
+ var q = rest[tbl.x + v].xyz;
884
+ let row = tbl.z * ${FACE_ROW_FLOATS}u;
885
+ let a = fOffset[i];
886
+ let b = fOffset[i + 1u];
887
+ for (var k = a; k < b; k = k + 1u) {
888
+ q = q + fDelta[k].xyz * weights[row + fChan[k]];
889
+ }
890
+ rest[tbl.y + v] = vec4f(q, 1.0);
891
+ }
892
+
893
+ // PASS B — normals over the face subset only, area-weighted exactly like the body's PASS 3. A
894
+ // SEPARATE dispatch, so every position PASS A moved is visible before any normal reads it.
895
+ @compute @workgroup_size(64) fn faceNormals(@builtin(global_invocation_id) g: vec3u) {
896
+ if (g.x >= p.faceCount * p.vertCount) { return; }
897
+ let f = g.x / p.vertCount;
898
+ let i = g.x % p.vertCount;
899
+ let v = fVerts[i];
900
+ let s = faceTable[f].y;
901
+ var n = vec3f(0.0, 0.0, 0.0);
902
+ let a = adjOffset[v];
903
+ let b = adjOffset[v + 1u];
904
+ for (var k = a; k < b; k = k + 1u) {
905
+ let t = adjTri[k] * 3u;
906
+ let p0 = rest[s + idx[t]].xyz;
907
+ let p1 = rest[s + idx[t + 1u]].xyz;
908
+ let p2 = rest[s + idx[t + 2u]].xyz;
909
+ n = n + cross(p1 - p0, p2 - p0);
910
+ }
911
+ let len = length(n);
912
+ restN[s + v] = vec4f(select(vec3f(0.0, 1.0, 0.0), n / len, len > 1e-12), 0.0);
913
+ }`;
708
914
  const MORPH = /* wgsl */ `
709
915
  struct P { slot: u32, vertCount: u32, entryCount: u32, pad: u32 };
710
916
  @group(0) @binding(0) var<storage,read> basePos: array<vec4f>;
@@ -1264,6 +1470,30 @@ export class GpuCrowdRenderer {
1264
1470
  */
1265
1471
  morphBGL;
1266
1472
  morphLayout;
1473
+ // ── the per-frame face rig ───────────────────────────────────────────────────────────────────
1474
+ facePipe;
1475
+ faceNormalPipe;
1476
+ faceParamBuf;
1477
+ /**
1478
+ * The coarsest rung that still gets a face rig. **LOD0 is the finest**, so a character is rigged
1479
+ * when `rung <= faceRigLod`; the default 1 rigs LOD0 and LOD1 and skips LOD2/LOD3.
1480
+ *
1481
+ * ⚠️ A CALLER SHOULD DRIVE ITS AUDIO THRESHOLD FROM THE SAME SIGNAL. A face moving silently, and a
1482
+ * voice arriving from a frozen face, are both worse than either being off.
1483
+ */
1484
+ faceRigLod = 1;
1485
+ /** Per-rung CSR of the face channels, built once in `setAssets`. Null where a rung has none. */
1486
+ faceCsr = [];
1487
+ /** Per-rung GPU copies of that CSR, plus the two bind groups (one per face pipeline). */
1488
+ faceLod = [];
1489
+ /** slot → its weight row, rung and destination slot. Only rigged characters appear. */
1490
+ rigged = new Map();
1491
+ /** Rows handed out so far; a freed row is reused rather than compacted (see `disableFaceRig`). */
1492
+ faceRows = 0;
1493
+ wCpu = new Float32Array(0);
1494
+ wBuf = null;
1495
+ faceTableBuf = null;
1496
+ faceTableCpu = new Uint32Array(0);
1267
1497
  /** The per-frame skin pass. One dispatch per BUCKET, selected by a dynamic uniform offset. */
1268
1498
  skinPipe;
1269
1499
  skinBGL;
@@ -1355,6 +1585,26 @@ export class GpuCrowdRenderer {
1355
1585
  this.morphPipe = pipe('base');
1356
1586
  this.addPipe = pipe('addMorph');
1357
1587
  this.normalPipe = pipe('normals');
1588
+ // ⚠️ `layout: 'auto'` HERE, and it is the opposite choice from the three pipelines above — for a
1589
+ // reason that only applies to this shader. An explicit shared layout must declare EVERY binding
1590
+ // the module has, and the per-stage storage-buffer limit applies to the LAYOUT, not to what an
1591
+ // entry point uses: all 11 declared storage buffers would count, against a default limit of 8.
1592
+ // An auto layout is derived per pipeline from what that entry point statically references — 7
1593
+ // each — so each stays inside the limit. The cost is one bind group per pipeline instead of one
1594
+ // shared, which `faceBg` below carries.
1595
+ const fsm = device.createShaderModule({ code: FACE_WGSL });
1596
+ this.facePipe = device.createComputePipeline({
1597
+ layout: 'auto',
1598
+ compute: { module: fsm, entryPoint: 'faceMorph' },
1599
+ });
1600
+ this.faceNormalPipe = device.createComputePipeline({
1601
+ layout: 'auto',
1602
+ compute: { module: fsm, entryPoint: 'faceNormals' },
1603
+ });
1604
+ this.faceParamBuf = device.createBuffer({
1605
+ size: 16,
1606
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1607
+ });
1358
1608
  this.paramBuf = device.createBuffer({
1359
1609
  size: 16,
1360
1610
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
@@ -1482,8 +1732,12 @@ export class GpuCrowdRenderer {
1482
1732
  usage: U.STORAGE | U.COPY_SRC | extra,
1483
1733
  });
1484
1734
  this.pools = {
1485
- rest: pool(0),
1486
- restN: pool(0),
1735
+ // ⚠️ COPY_DST on rest/restN is what `enableFaceRig` needs: seeding an animated slot is a
1736
+ // buffer copy INTO the pool, and a pool created write-only-by-shader refuses it outright
1737
+ // ("usage doesn't include BufferUsage::CopyDst"). def/defN are pure skin-pass output and
1738
+ // stay as they were.
1739
+ rest: pool(U.COPY_DST),
1740
+ restN: pool(U.COPY_DST),
1487
1741
  def: pool(U.VERTEX),
1488
1742
  defN: pool(U.VERTEX),
1489
1743
  };
@@ -1558,8 +1812,47 @@ export class GpuCrowdRenderer {
1558
1812
  this.skinArrayView = a.skin.createView({ dimension: '2d-array' });
1559
1813
  this.buildMatBG(this.dummySceneView);
1560
1814
  this.rebuildLodBindGroups();
1815
+ this.buildFaceLods(a);
1561
1816
  this.frameBGDirty = true;
1562
1817
  }
1818
+ /**
1819
+ * Transpose this kit's face channels once per rung and upload them.
1820
+ *
1821
+ * ⚠️ ONCE, AT LOAD. The transpose is the thing that makes the per-frame pass race-free, and it
1822
+ * depends only on the geometry — not on any weight — so paying for it per frame would be paying
1823
+ * repeatedly for an answer that never changes.
1824
+ */
1825
+ buildFaceLods(a) {
1826
+ const dev = this.device, U = GPUBufferUsage;
1827
+ if (a.faceFirst === undefined) {
1828
+ this.faceCsr = [];
1829
+ this.faceLod = [];
1830
+ return;
1831
+ }
1832
+ const { face } = splitFaceTargets(a.targets, a.faceFirst);
1833
+ this.faceCsr = a.lods.map((_, lod) => face.length ? buildFaceCsr(face, lod, FACE_CHANNEL_COUNT) : null);
1834
+ const store = (src) => {
1835
+ const b = dev.createBuffer({
1836
+ size: Math.max(src.byteLength, 4),
1837
+ usage: U.STORAGE | U.COPY_DST,
1838
+ });
1839
+ dev.queue.writeBuffer(b, 0, src);
1840
+ return b;
1841
+ };
1842
+ this.faceLod = this.faceCsr.map((csr) => csr?.verts.length
1843
+ ? {
1844
+ verts: store(csr.verts),
1845
+ offset: store(csr.offset),
1846
+ chan: store(csr.chan),
1847
+ delta: store(csr.delta),
1848
+ vertCount: csr.verts.length,
1849
+ morphBg: null,
1850
+ normalBg: null,
1851
+ }
1852
+ : null);
1853
+ // A first allocation so the bind groups have real buffers to point at; it grows on demand.
1854
+ this.allocFaceBuffers(Math.max(1, this.wCpu.length / FACE_ROW_FLOATS));
1855
+ }
1563
1856
  /**
1564
1857
  * Group 2 — the two atlases and the scene copy.
1565
1858
  *
@@ -1687,6 +1980,25 @@ export class GpuCrowdRenderer {
1687
1980
  l.adjTri.destroy();
1688
1981
  }
1689
1982
  this.lodGpu = [];
1983
+ // The face rig belongs to the KIT: its CSR is that kit's geometry and its rows name that kit's
1984
+ // slots. Both are meaningless against the next one, so a rig does not survive a swap.
1985
+ for (const f of this.faceLod)
1986
+ if (f) {
1987
+ f.verts.destroy();
1988
+ f.offset.destroy();
1989
+ f.chan.destroy();
1990
+ f.delta.destroy();
1991
+ }
1992
+ this.faceLod = [];
1993
+ this.faceCsr = [];
1994
+ this.rigged.clear();
1995
+ this.faceRows = 0;
1996
+ this.wBuf?.destroy();
1997
+ this.wBuf = null;
1998
+ this.faceTableBuf?.destroy();
1999
+ this.faceTableBuf = null;
2000
+ this.wCpu = new Float32Array(0);
2001
+ this.faceTableCpu = new Uint32Array(0);
1690
2002
  if (this.pools) {
1691
2003
  this.pools.rest.destroy();
1692
2004
  this.pools.restN.destroy();
@@ -1771,6 +2083,189 @@ export class GpuCrowdRenderer {
1771
2083
  cp.end();
1772
2084
  dev.queue.submit([enc.finish()]);
1773
2085
  }
2086
+ // ── the per-frame face rig ───────────────────────────────────────────────────────────────────
2087
+ /** Grow the weight and face-table buffers to hold `rows`, and rebuild the bind groups on them. */
2088
+ allocFaceBuffers(rows) {
2089
+ this.wCpu = new Float32Array(rows * FACE_ROW_FLOATS);
2090
+ this.faceTableCpu = new Uint32Array(rows * 4);
2091
+ this.wBuf?.destroy();
2092
+ this.faceTableBuf?.destroy();
2093
+ this.wBuf = this.device.createBuffer({
2094
+ size: faceBufferBytes(rows),
2095
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
2096
+ });
2097
+ this.faceTableBuf = this.device.createBuffer({
2098
+ size: rows * 16,
2099
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
2100
+ });
2101
+ for (const f of this.faceLod)
2102
+ if (f)
2103
+ this.buildFaceBindGroups(f);
2104
+ }
2105
+ /** One bind group per face pipeline — see the `layout: 'auto'` note in the constructor. */
2106
+ buildFaceBindGroups(f) {
2107
+ const p = this.pools;
2108
+ const l = this.faceLod.indexOf(f);
2109
+ const g = maybe(this.lodGpu, l);
2110
+ if (!p || !g || !this.wBuf || !this.faceTableBuf)
2111
+ return;
2112
+ f.morphBg = this.device.createBindGroup({
2113
+ layout: this.facePipe.getBindGroupLayout(0),
2114
+ entries: [
2115
+ { binding: 0, resource: { buffer: p.rest } },
2116
+ { binding: 2, resource: { buffer: f.verts } },
2117
+ { binding: 3, resource: { buffer: f.offset } },
2118
+ { binding: 4, resource: { buffer: f.chan } },
2119
+ { binding: 5, resource: { buffer: f.delta } },
2120
+ { binding: 6, resource: { buffer: this.wBuf } },
2121
+ { binding: 7, resource: { buffer: this.faceTableBuf } },
2122
+ { binding: 11, resource: { buffer: this.faceParamBuf } },
2123
+ ],
2124
+ });
2125
+ f.normalBg = this.device.createBindGroup({
2126
+ layout: this.faceNormalPipe.getBindGroupLayout(0),
2127
+ entries: [
2128
+ { binding: 0, resource: { buffer: p.rest } },
2129
+ { binding: 1, resource: { buffer: p.restN } },
2130
+ { binding: 2, resource: { buffer: f.verts } },
2131
+ { binding: 7, resource: { buffer: this.faceTableBuf } },
2132
+ { binding: 8, resource: { buffer: g.adjOffset } },
2133
+ { binding: 9, resource: { buffer: g.adjTri } },
2134
+ { binding: 10, resource: { buffer: g.idx } },
2135
+ { binding: 11, resource: { buffer: this.faceParamBuf } },
2136
+ ],
2137
+ });
2138
+ }
2139
+ /**
2140
+ * Turn on per-frame face animation for `slot`, drawing into `dstSlot`.
2141
+ *
2142
+ * ⚠️ `dstSlot` STARTS AS A COPY of `slot`, positions AND normals. Only face vertices are rewritten
2143
+ * per frame; every other vertex is correct from this copy and never touched again. Skipping the
2144
+ * copy leaves whatever the pool last held there, which draws as a head animating on a stranger's
2145
+ * body.
2146
+ *
2147
+ * ⚠️ THE CALLER MUST POINT THE INSTANCE RECORD AT `dstSlot`, not at `slot`. `slot` stays pristine
2148
+ * precisely so the pass can recompute from it, so a record still naming `slot` shows a face that
2149
+ * never moves — with every counter healthy.
2150
+ *
2151
+ * Re-entrant: called again with a different rung it re-copies, because the face vertex set differs
2152
+ * per rung. Beyond `faceRigLod` it disables instead, so a caller can drive it straight from the
2153
+ * character's current rung each frame without branching.
2154
+ */
2155
+ enableFaceRig(slot, lod, dstSlot) {
2156
+ if (lod > this.faceRigLod) {
2157
+ this.disableFaceRig(slot);
2158
+ return;
2159
+ }
2160
+ const csr = maybe(this.faceCsr, lod);
2161
+ const l = maybe(this.lodGpu, lod);
2162
+ const pools = this.pools;
2163
+ if (!csr?.verts.length)
2164
+ throw new Error(`enableFaceRig: LOD ${lod} has no face targets`);
2165
+ if (!l || !pools)
2166
+ throw new Error(`enableFaceRig: LOD ${lod} has no assets`);
2167
+ const prev = this.rigged.get(slot);
2168
+ const row = prev?.row ?? this.faceRows++;
2169
+ this.rigged.set(slot, { row, lod, dst: dstSlot });
2170
+ if ((row + 1) * FACE_ROW_FLOATS > this.wCpu.length)
2171
+ this.allocFaceBuffers(growCapacity(row + 1, this.wCpu.length / FACE_ROW_FLOATS));
2172
+ const bytes = l.plan.slotVerts * 16; // the pools are arrays of vec4
2173
+ // ⚠️ VIA A STAGING BUFFER, because WebGPU REFUSES copyBufferToBuffer when the source and the
2174
+ // destination are the SAME buffer — even for ranges that provably do not overlap. ("Source and
2175
+ // destination are the same buffer.") Both slots live in the one rest pool, so the copy has to
2176
+ // hop out and back. One-time, at enable, so it costs nothing per frame.
2177
+ const staging = this.device.createBuffer({
2178
+ size: bytes,
2179
+ usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
2180
+ });
2181
+ const enc = this.device.createCommandEncoder();
2182
+ // Copies are ordered within an encoder and each names two DIFFERENT buffers, so reusing one
2183
+ // staging buffer for both pools is sequencing, not a race.
2184
+ enc.copyBufferToBuffer(pools.rest, slot * 16, staging, 0, bytes);
2185
+ enc.copyBufferToBuffer(staging, 0, pools.rest, dstSlot * 16, bytes);
2186
+ enc.copyBufferToBuffer(pools.restN, slot * 16, staging, 0, bytes);
2187
+ enc.copyBufferToBuffer(staging, 0, pools.restN, dstSlot * 16, bytes);
2188
+ this.device.queue.submit([enc.finish()]);
2189
+ staging.destroy();
2190
+ }
2191
+ /** Stop dispatching for this slot — it costs exactly what it cost before the rig existed. */
2192
+ disableFaceRig(slot) {
2193
+ const r = this.rigged.get(slot);
2194
+ if (!r)
2195
+ return;
2196
+ this.rigged.delete(slot);
2197
+ this.wCpu.fill(0, r.row * FACE_ROW_FLOATS, (r.row + 1) * FACE_ROW_FLOATS);
2198
+ // ⚠️ ROWS ARE NOT COMPACTED. Renumbering would move every live face's row mid-frame, and a
2199
+ // renumbered row is a face wearing someone else's mouth. A freed row is simply left for reuse.
2200
+ }
2201
+ /**
2202
+ * Write one face's 47 channel weights. Cheap enough for every rigged face every frame.
2203
+ *
2204
+ * ⚠️ A console.error PLUS a no-op when the slot has no rig — never silence. A silently dropped
2205
+ * write gives a still face with healthy counters, which reads as a broken driver in the app.
2206
+ */
2207
+ setFaceWeights(slot, w) {
2208
+ checkFaceWeights(w);
2209
+ const r = this.rigged.get(slot);
2210
+ if (!r) {
2211
+ console.error(`[crowd] setFaceWeights: slot ${slot} has no face rig — call enableFaceRig first`);
2212
+ return;
2213
+ }
2214
+ this.wCpu.set(w, r.row * FACE_ROW_FLOATS);
2215
+ }
2216
+ /** How many faces are currently rigged — for a caller's HUD and for the benchmark. */
2217
+ get faceRigCount() {
2218
+ return this.rigged.size;
2219
+ }
2220
+ /**
2221
+ * Run both face passes for every rigged face. Call once per frame, before `frame()`.
2222
+ *
2223
+ * ⚠️ ONE DISPATCH PAIR PER RUNG, never one per face. Faces at a rung share the same vertex list,
2224
+ * which is the whole reason the CSR is per rung rather than per character; at fifty faces, a
2225
+ * dispatch each would cost more in launches than the work being launched.
2226
+ */
2227
+ faceFrame() {
2228
+ if (!this.rigged.size || !this.wBuf || !this.faceTableBuf)
2229
+ return;
2230
+ const dev = this.device;
2231
+ dev.queue.writeBuffer(this.wBuf, 0, this.wCpu);
2232
+ const byRung = new Map();
2233
+ for (const [src, r] of this.rigged) {
2234
+ const g = byRung.get(r.lod) ?? [];
2235
+ g.push({ row: r.row, dst: r.dst, src });
2236
+ byRung.set(r.lod, g);
2237
+ }
2238
+ for (const [lod, group] of byRung) {
2239
+ const f = maybe(this.faceLod, lod);
2240
+ if (!f?.morphBg || !f.normalBg)
2241
+ continue;
2242
+ // ⚠️ `f` in the shader indexes THIS TABLE, not the weight buffer — hence the row in .z. The
2243
+ // table is rewritten per rung, so it is packed by position within the group.
2244
+ const tbl = this.faceTableCpu;
2245
+ for (const [i, e] of group.entries()) {
2246
+ tbl[i * 4] = e.src;
2247
+ tbl[i * 4 + 1] = e.dst;
2248
+ tbl[i * 4 + 2] = e.row;
2249
+ tbl[i * 4 + 3] = 0;
2250
+ }
2251
+ dev.queue.writeBuffer(this.faceTableBuf, 0, tbl, 0, group.length * 4);
2252
+ dev.queue.writeBuffer(this.faceParamBuf, 0, faceParams(group.length, f.vertCount, FACE_CHANNEL_COUNT));
2253
+ const threads = group.length * f.vertCount;
2254
+ const enc = dev.createCommandEncoder();
2255
+ const cp = enc.beginComputePass();
2256
+ cp.setPipeline(this.facePipe);
2257
+ cp.setBindGroup(0, f.morphBg);
2258
+ cp.dispatchWorkgroups(Math.ceil(threads / 64));
2259
+ cp.setPipeline(this.faceNormalPipe);
2260
+ cp.setBindGroup(0, f.normalBg);
2261
+ cp.dispatchWorkgroups(Math.ceil(threads / 64));
2262
+ cp.end();
2263
+ // ⚠️ SUBMITTED PER RUNG, because the params uniform and the face table are rewritten between
2264
+ // rungs. Recording both rungs into one encoder would have the second rung's uniform apply to
2265
+ // the first — the classic "one buffer, two dispatches" aliasing bug.
2266
+ dev.queue.submit([enc.finish()]);
2267
+ }
2268
+ }
1774
2269
  /**
1775
2270
  * Upload this frame's instance records and their per-LOD buckets.
1776
2271
  *
@@ -24,6 +24,35 @@ export interface CubeInstance {
24
24
  */
25
25
  decalPos?: number;
26
26
  decalKind?: number;
27
+ /**
28
+ * NEIGHBOUR OCCUPANCY, 27 bits — which of the 26 cells around this one are solid.
29
+ *
30
+ * Bit `(dx+1) + (dy+1)*3 + (dz+1)*9` for the neighbour at offset (dx,dy,dz) ∈ {−1,0,1}³. Bit 13
31
+ * is this cell itself and is ignored. Feeding this lets the vertex shader compute real per-corner
32
+ * ambient occlusion — the dark that collects where two surfaces meet — which is the cue that
33
+ * stops a field of identical blocks from reading as one flat sheet.
34
+ *
35
+ * ⚠️ 0 MEANS UNKNOWN, NOT "NOTHING AROUND ME". A caller that never sets this gets AO of exactly
36
+ * 1.0 and is byte-identical to a build before corner AO existed. That matters because 0 is also
37
+ * the honest encoding of "floating in mid-air", and a renderer that treated the two alike would
38
+ * darken every corner of every cube in every game that has not opted in. The sentinel costs the
39
+ * ability to distinguish a genuinely isolated block, which needs no AO anyway.
40
+ *
41
+ * ⚠️ AND IT IS 27 BITS, WHICH AN f32 CANNOT HOLD. Floats are exact only to 2^24, so `fill()`
42
+ * splits this across two slots. Keep it a plain JS number here — a double holds it exactly — and
43
+ * let the packing be the renderer's problem.
44
+ */
45
+ occ?: number;
46
+ /**
47
+ * PER-BLOCK ALBEDO JITTER, signed, roughly ±0.1. Multiplies the base colour, so a large field of
48
+ * one material stops reading as a single painted sheet.
49
+ *
50
+ * ⚠️ COMPUTED BY THE CALLER, NOT HASHED FROM WORLD POSITION IN THE SHADER, and that is not a
51
+ * stylistic choice. Under a floating origin the world coordinate handed to the shader is REBASED,
52
+ * so a position hash would re-roll every block the instant the origin moved — the whole landscape
53
+ * visibly re-patterning as you walk. The caller knows the stable coordinate; the shader does not.
54
+ */
55
+ jitter?: number;
27
56
  }
28
57
  /** Atlas layout: which ARRAY LAYER a material's top/side/bottom faces sample.
29
58
  *
package/dist/gpuShadow.js CHANGED
@@ -23,8 +23,18 @@ const SHADOW_SIZE = 2048;
23
23
  // one sample, and the selection loop terminates immediately. That keeps the five demo pages and
24
24
  // AMS's existing props/doors/skin path unmoved until each opts in.
25
25
  const MAX_CASCADES = 4;
26
+ // How dark a fully-enclosed corner goes. 0.55 is a real crease without inking the world black; the
27
+ // term is a MULTIPLY on the lit result, so this is the floor the deepest corner reaches.
28
+ const AO_MIN = 0.55;
26
29
  const CULL_WG = 64; // compute-cull workgroup size
27
- const INST_F = 16; // floats per instance: pos.xyz+hue, scl.xyz+emissive, rot quat, aux (tile,up,_,_)
30
+ // Floats per instance: pos.xyz+hue, scl.xyz+emissive, rot quat, aux (tile, up, decalPos, decalKind),
31
+ // aux2 (occLo, occHi, jitter, _).
32
+ //
33
+ // ⚠️ 20, NOT 17, AND THE PADDING IS NOT WASTE. `Inst` is read as a `array<Inst>` of vec4s, so WGSL
34
+ // rounds the struct's stride up to a multiple of 16 bytes: one more float would cost a whole vec4
35
+ // anyway. Spending the other two on a spare slot is free, and the last time this buffer grew it was
36
+ // for the contact decal, which had to widen it for exactly the same reason.
37
+ const INST_F = 20;
28
38
  const OVERLAY_CAP = 512; // max translucent overlay cubes per frame (the place ghost + headroom)
29
39
  // Build the 36-vertex cube (6 faces × 2 tris) in JS and inject as WGSL const arrays —
30
40
  // bulletproof + readable vs. bit-twiddling from vertex_index. cullMode is 'none', so winding
@@ -72,7 +82,7 @@ struct Cam {
72
82
  csm: vec4<f32>, // x = active cascade count · y = crossfade band in uv units
73
83
  eye: vec4<f32>, // xyz = camera position in world space (material relief + specular); w unused
74
84
  };
75
- struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32> }; // pos.w = hue (<0 ⇒ ground) · scl.w = emissive/alpha · rot = quaternion · aux.x = atlas tile (<0 ⇒ hue) · aux.y = up-face code · aux.z/aux.w = CONTACT DECAL (0,0 = none; see setAtlasAO/CubeInstance.decal*)
85
+ struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> }; // pos.w = hue (<0 ⇒ ground) · scl.w = emissive/alpha · rot = quaternion · aux.x = atlas tile (<0 ⇒ hue) · aux.y = up-face code · aux.z/aux.w = CONTACT DECAL (0,0 = none) · aux2.xy = 27-bit NEIGHBOUR OCCUPANCY split 14/13 (0,0 = unknown ⇒ no corner AO) · aux2.z = per-block albedo jitter · aux2.w spare
76
86
  @group(0) @binding(0) var<uniform> cam: Cam;
77
87
  @group(0) @binding(1) var<storage, read> insts: array<Inst>;
78
88
 
@@ -81,6 +91,51 @@ const CUBE_NRM = array<vec3<f32>, 36>(${CUBE.nrm});
81
91
 
82
92
  fn qrot(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> { let t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); }
83
93
  fn worldOf(inst: Inst, vi: u32) -> vec3<f32> { return inst.pos.xyz + qrot(inst.rot, CUBE_POS[vi] * inst.scl.xyz); }
94
+
95
+ // ── PER-CORNER AMBIENT OCCLUSION ────────────────────────────────────────────────────────────────
96
+ //
97
+ // The dark that collects where two surfaces meet: the inside of a step, the base of a wall, the
98
+ // corner of a pit. A voxel world has that geometry everywhere and no cue for it, so a hillside of
99
+ // identical blocks reads as one painted sheet. blockShade() below darkens every block's rim by the
100
+ // same amount whatever is beside it, which draws the GRID but says nothing about SHAPE — an inside
101
+ // corner and open ground come out identical.
102
+ //
103
+ // This is the classic voxel solution and it is strictly better than the screen-space pass it
104
+ // replaces: it reads actual neighbour occupancy instead of estimating a normal from neighbouring
105
+ // depth, so it cannot invent shading from a coarse mesh's faceting, it costs nothing per frame
106
+ // (three bit tests per vertex, then the rasterizer interpolates for free), and it can only ever
107
+ // touch geometry whose caller supplied a mask.
108
+ //
109
+ // occAt reads one neighbour out of the 27-bit mask; the index is the same
110
+ // (dx+1) + (dy+1)*3 + (dz+1)*9 the caller packed with.
111
+ fn occAt(mask: u32, o: vec3<f32>) -> f32 {
112
+ let idx = u32((o.x + 1.0) + (o.y + 1.0) * 3.0 + (o.z + 1.0) * 9.0);
113
+ return f32((mask >> idx) & 1u);
114
+ }
115
+ // Vertex AO for cube vertex vi, in [AO_MIN, 1]. Every cube vertex sits at a CORNER, so CUBE_POS is
116
+ // (±0.5,±0.5,±0.5) and its sign gives the two in-plane directions once the face axis is masked off.
117
+ fn cornerAO(mask: u32, vi: u32) -> f32 {
118
+ if (mask == 0u) { return 1.0; } // unknown ⇒ no AO, see CubeInstance.occ
119
+ let n = CUBE_NRM[vi];
120
+ let ip = sign(CUBE_POS[vi]) * (vec3(1.0, 1.0, 1.0) - abs(n));
121
+ var a1 = vec3(0.0, 0.0, 0.0);
122
+ var a2 = vec3(0.0, 0.0, 0.0);
123
+ if (abs(n.x) > 0.5) { a1 = vec3(0.0, ip.y, 0.0); a2 = vec3(0.0, 0.0, ip.z); }
124
+ else if (abs(n.y) > 0.5) { a1 = vec3(ip.x, 0.0, 0.0); a2 = vec3(0.0, 0.0, ip.z); }
125
+ else { a1 = vec3(ip.x, 0.0, 0.0); a2 = vec3(0.0, ip.y, 0.0); }
126
+ // The three cells that can shade this corner, all one step OUT along the face normal: the two
127
+ // edge neighbours and the one diagonally between them.
128
+ let s1 = occAt(mask, n + a1);
129
+ let s2 = occAt(mask, n + a2);
130
+ let sc = occAt(mask, n + a1 + a2);
131
+ // ⚠️ TWO TOUCHING SIDES IS THE DARKEST CASE, DARKER THAN THE SUM SUGGESTS. When both edges are
132
+ // solid the corner is enclosed whatever the diagonal does — and the diagonal is not even visible
133
+ // from there. Falling through to 3 − (s1+s2+sc) would light an enclosed corner more brightly when
134
+ // the cell diagonally behind it happens to be air, which is backwards.
135
+ var lvl = 3.0 - (s1 + s2 + sc);
136
+ if (s1 > 0.5 && s2 > 0.5) { lvl = 0.0; }
137
+ return mix(${AO_MIN}, 1.0, lvl / 3.0);
138
+ }
84
139
  fn hsv(hh: f32) -> vec3<f32> {
85
140
  let h = fract(hh) * 6.0;
86
141
  let x = 1.0 - abs((h % 2.0) - 1.0);
@@ -110,7 +165,12 @@ fn hsv(hh: f32) -> vec3<f32> {
110
165
  // geometry. occ.x toggles it (camera pass only; the shadow pass never occludes — an off-screen occluder still
111
166
  // casts a shadow into view). occ.yz = hiz dims, occ.w = pixels/texel.
112
167
  const CULL_WGSL = /* wgsl */ `
113
- struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32> };
168
+ // ⚠️ THE SAME STRIDE AS THE DRAW PASSES' Inst, and it has to be kept that way BY HAND — this is a
169
+ // second declaration of one buffer's layout, not a shared one. The cull pass only reads pos/scl/rot,
170
+ // so a stale copy still compiles and still runs; it just indexes every instance past the first at
171
+ // the wrong offset, and the symptom is cubes winking out of existence at the edge of view rather
172
+ // than anything that looks like a struct mismatch.
173
+ struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> };
114
174
  struct Args { vc: u32, ic: atomic<u32>, fv: u32, fi: u32 };
115
175
  struct CullCam {
116
176
  planes: array<vec4<f32>, 6>, cnt: vec4<f32>, // cnt.x = instance count
@@ -230,7 +290,10 @@ struct GiGrid { org: vec4<f32>, dim: vec4<f32> };
230
290
  @group(0) @binding(9) var<storage, read> probes: array<vec4<f32>>;
231
291
  ${GI_WGSL}
232
292
 
233
- struct VOut { @builtin(position) clip: vec4<f32>, @location(0) world: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) hue: f32, @location(3) emis: f32, @location(4) blk: vec3<f32>, @location(5) objN: vec3<f32>, @location(6) tile: f32, @location(7) upc: f32, @location(8) @interpolate(flat) decal: vec2<f32> };
293
+ // vao is deliberately NOT flat: per-corner AO is computed once per vertex and the rasterizer's
294
+ // interpolation across the quad IS the gradient — that smooth ramp into a crease is the whole
295
+ // effect, and it costs nothing.
296
+ struct VOut { @builtin(position) clip: vec4<f32>, @location(0) world: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) hue: f32, @location(3) emis: f32, @location(4) blk: vec3<f32>, @location(5) objN: vec3<f32>, @location(6) tile: f32, @location(7) upc: f32, @location(8) @interpolate(flat) decal: vec2<f32>, @location(9) vao: f32, @location(10) @interpolate(flat) jit: f32 };
234
297
 
235
298
  fn faceVec(code: f32) -> vec3<f32> {
236
299
  let c = i32(code);
@@ -254,6 +317,10 @@ fn faceVec(code: f32) -> vec3<f32> {
254
317
  o.blk = (CUBE_POS[vi] + vec3(0.5, 0.5, 0.5)) * inst.scl.xyz;
255
318
  o.objN = CUBE_NRM[vi];
256
319
  o.tile = inst.aux.x; o.upc = inst.aux.y; o.decal = inst.aux.zw;
320
+ // The 27-bit occupancy mask, reassembled from the 14/13 split fill() had to make because an f32
321
+ // is exact only to 2^24.
322
+ o.vao = cornerAO(u32(inst.aux2.x) | (u32(inst.aux2.y) << 14u), vi);
323
+ o.jit = inst.aux2.z;
257
324
  return o;
258
325
  }
259
326
 
@@ -471,6 +538,13 @@ fn fixedFill(N: vec3<f32>, up: vec3<f32>) -> f32 {
471
538
  // grass; pulling blue down hardest is what makes the eye call it earth rather than shadow. Still a
472
539
  // MULTIPLY, so the atlas grain and the planet tint survive and no per-biome palette is needed.
473
540
  base = base * mix(vec3(1.0), vec3(0.72, 0.52, 0.34), soil);
541
+ // PER-BLOCK VALUE JITTER. A hillside is thousands of instances of one material, and one material
542
+ // is one colour, so it reads as a painted sheet no matter how well it is lit. A few percent of
543
+ // variation block to block breaks that up at no cost — the eye stops seeing a surface and starts
544
+ // seeing blocks. MULTIPLICATIVE and signed, so it darkens and lightens about the material's own
545
+ // colour rather than pushing the whole field one way, and so it survives on textured and flat-hue
546
+ // blocks alike. 0 when the caller supplies none, which is exactly the old behaviour.
547
+ base = base * (1.0 + i.jit);
474
548
  // per-block edge AO makes each voxel visible on FLAT-hue cubes, but reads as a hard GRID over textures — so the
475
549
  // atlas path dropped it ENTIRELY, which left textured terrain with no per-voxel AO at all: only SSAO, which
476
550
  // resolves a pixel or two of crease and nothing at the metre scale. The result is a surface that reads as a slab,
@@ -481,7 +555,13 @@ fn fixedFill(N: vec3<f32>, up: vec3<f32>) -> f32 {
481
555
  // Around 0.35, EDGE_DARK 0.6 yields a floor of 0.86: enough that a cube reads as a cube, far short of the inked
482
556
  // grid the full term draws. (No backticks in here: this is inside a JS template literal.)
483
557
  let bs = blockShade(fx, fz);
484
- let ao = select(bs, mix(1.0, bs, cam.atlas.y), cam.atlas.x > 0.5 && i.tile >= 0.0) * contact;
558
+ // ⚠️ CORNER AO MULTIPLIES IN ON TOP OF blockShade RATHER THAN REPLACING IT, because the two say
559
+ // different things and a voxel world wants both. blockShade is an OUTLINE — it marks where one
560
+ // block ends and the next begins, identically everywhere, which is what keeps a flat field
561
+ // legible as blocks. i.vao is SHAPE — it darkens only where neighbours actually enclose this
562
+ // corner. Dropping the outline for the shape term would make flat ground read smooth again;
563
+ // dropping the shape term is what left the world reading as a slab in the first place.
564
+ let ao = select(bs, mix(1.0, bs, cam.atlas.y), cam.atlas.x > 0.5 && i.tile >= 0.0) * contact * i.vao;
485
565
  // LIGHTING = fixed directional FILL (always on, reads 3D shape in the dark) + the sun KEY (primary, shadowed).
486
566
  // cam.sun.w is the fill/ambient brightness knob; the fill's directional term (0.5..1.35) keeps every face's
487
567
  // orientation legible day or night, while the sun adds bright, shadow-casting key light on top during the day.
@@ -1034,6 +1114,14 @@ export class GpuShadowRenderer {
1034
1114
  scratch[o + 13] = c.up ?? 1;
1035
1115
  scratch[o + 14] = c.decalPos ?? 0;
1036
1116
  scratch[o + 15] = c.decalKind ?? 0; // aux: atlas tile id, up-face code, contact decal (0 = none)
1117
+ // aux2. The 27-bit occupancy mask SPLIT 14/13 because an f32 is only exact to 2^24 — packing
1118
+ // it whole would silently round the high bits and shade corners off neighbours that are not
1119
+ // there. Both halves are 0 when `occ` is absent, which is the "unknown ⇒ no AO" sentinel.
1120
+ const occ = c.occ ?? 0;
1121
+ scratch[o + 16] = occ & 0x3fff;
1122
+ scratch[o + 17] = (occ / 0x4000) | 0;
1123
+ scratch[o + 18] = c.jitter ?? 0;
1124
+ scratch[o + 19] = 0; // spare
1037
1125
  }
1038
1126
  }
1039
1127
  makeBindGroups() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.14.34",
3
+ "version": "0.15.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -15,14 +15,6 @@
15
15
  "files": [
16
16
  "dist"
17
17
  ],
18
- "scripts": {
19
- "preinstall": "npx only-allow pnpm",
20
- "build": "tsc -p tsconfig.json && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/",
21
- "lint": "ugly-app lint",
22
- "lint:fix": "ugly-app lint --fix",
23
- "pretty": "prettier --write .",
24
- "prepublishOnly": "pnpm run pretty && ugly-app lint && tsc -p tsconfig.json && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/"
25
- },
26
18
  "dependencies": {
27
19
  "meshoptimizer": "^1.2.0"
28
20
  },
@@ -35,5 +27,12 @@
35
27
  "@webgpu/types": "^0.1.40",
36
28
  "prettier": "^3.9.5",
37
29
  "ugly-app": "^0.1.841"
30
+ },
31
+ "scripts": {
32
+ "preinstall": "npx only-allow pnpm",
33
+ "build": "tsc -p tsconfig.json && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/",
34
+ "lint": "ugly-app lint",
35
+ "lint:fix": "ugly-app lint --fix",
36
+ "pretty": "prettier --write ."
38
37
  }
39
- }
38
+ }