ugly-game 0.15.26 → 0.15.28

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.
@@ -129,6 +129,17 @@ export interface AtlasLayout {
129
129
  * wrapping to an unrelated texture.
130
130
  */
131
131
  export declare function packFaceMats(m: readonly number[]): [number, number];
132
+ /**
133
+ * Bytes one instance occupies in the instance storage buffer.
134
+ *
135
+ * EXPORTED BECAUSE THE CALLER HAS TO SIZE `requiredLimits` WITH IT. A device built by a plain
136
+ * `requestDevice()` gets WebGPU's DEFAULT limits — 256 MiB `maxBufferSize`, 128 MiB
137
+ * `maxStorageBufferBindingSize` — no matter what the adapter advertises, so a consumer that wants a
138
+ * capacity past ~1.67 M instances must request the higher limit at device creation or the allocation
139
+ * is rejected. Working that out requires this number, and a caller that hardcodes 80 is one struct
140
+ * change away from being quietly wrong.
141
+ */
142
+ export declare const INSTANCE_BYTES: number;
132
143
  /**
133
144
  * One rigid transform over a contiguous run of instances — see `GpuShadowRenderer.setBodyTransforms`.
134
145
  * `first`/`count` are INSTANCE SLOTS in the buffer, matching what `updateInstanceRange` wrote.
@@ -456,6 +467,45 @@ export declare function carveFace(mask: number, corner: readonly [number, number
456
467
  export declare function bevelClass(mask: number, bevel: number, concave: number,
457
468
  /** Subdivision — the section boundaries move with it. See buildBevelCube on the shadowing. */
458
469
  BEVEL_SEG?: number): number;
470
+ /**
471
+ * ── FACE CULLING ────────────────────────────────────────────────────────────────────────────────
472
+ *
473
+ * A surface voxel draws all six of its faces today — 36 vertices — and on a heightfield five of them
474
+ * are buried in solid rock. Measured at N=256 in all-mine-sky, terrain is 61 % of the frame (14.6 ms
475
+ * of 24.1) while being only ~17 % of its triangles, so the cost tracks VERTEX COUNT rather than
476
+ * triangle count, and five sixths of that vertex count is invisible.
477
+ *
478
+ * This drops the buried faces. It needs the neighbour mask instances already carry for AO, so it is
479
+ * free on the GPU and NOT free in the mesher — computing `occ` is the trade the caller opts into.
480
+ *
481
+ * ⚠️ THE FACE ORDER IS buildCube's, AND IT IS LOAD-BEARING. Vertices 0..35 are six faces of six
482
+ * corners in the order +X, −X, +Y, −Y, +Z, −Z, so vertex `vi` belongs to face `vi / 6`. The remap
483
+ * below rewrites `vi` to the vi/6-th EXPOSED face, which only works because that layout is a flat
484
+ * face-major array. See buildCube's "FACE QUADS ARE EMITTED FIRST" note.
485
+ *
486
+ * ⚠️ AND IT IS MUTUALLY EXCLUSIVE WITH THE BEVEL. A beveled cube's bands, facets and fillets span
487
+ * the EDGE BETWEEN two faces, so "drop face 3" is not a well-defined operation on it — the geometry
488
+ * that rounds an edge belongs to neither face alone. `frame()` ignores face culling whenever a bevel
489
+ * is set rather than silently producing holes.
490
+ */
491
+ export declare const FACE_DIRS: readonly (readonly [number, number, number])[];
492
+ /** Is face `d` open to air? A SET bit means the neighbour is SOLID — see occAt. */
493
+ export declare function faceExposed(mask: number, d: number): boolean;
494
+ /** How many faces this instance actually has to draw. mask 0 is the "unknown" sentinel ⇒ all six. */
495
+ export declare function exposedFaceCount(mask: number): number;
496
+ /**
497
+ * Vertex counts for the three face-cull buckets, and the classifier that picks one.
498
+ *
499
+ * ⚠️ SAME ASYMMETRY AS bevelClass: TOO HIGH ONLY WASTES WORK, TOO LOW DELETES GEOMETRY. A bucket
500
+ * whose count is above the instance's need draws degenerate (centre-collapsed) triangles; one below
501
+ * it silently drops a visible face. `faceCull.test.mts` holds the boundary.
502
+ *
503
+ * 6 / 18 / 36 rather than an even split because the distribution is not even: on a heightfield the
504
+ * overwhelming majority of surface voxels expose exactly ONE face, so the cheapest bucket is worth
505
+ * making as cheap as it can be — a 6x cut for the common case.
506
+ */
507
+ export declare const FACE_CULL_BUCKET_VERTS: readonly number[];
508
+ export declare function faceCullClass(mask: number): number;
459
509
  export declare function bevelVertex(corner: readonly [number, number, number], home: readonly [number, number, number], mask: number, bevel: number, role?: number, axis?: readonly [number, number, number],
460
510
  /** The CONCAVE radius. Separate from `bevel` (the convex one) so the two halves of the rounding
461
511
  * can be turned up, down and off independently — the only way to tell which one a defect is in.
@@ -549,6 +599,7 @@ export declare class GpuShadowRenderer {
549
599
  private matCutoff;
550
600
  private eye;
551
601
  private bevel;
602
+ private faceCull;
552
603
  private fillet;
553
604
  private alphaPipe;
554
605
  private alphaBGL;
@@ -684,16 +735,50 @@ export declare class GpuShadowRenderer {
684
735
  * without a mask (`occ` absent ⇒ 0, the "unknown" sentinel) is never beveled, which is why the far
685
736
  * field, sky-body shells, ships, creatures and props stay sharp with no work on their part.
686
737
  *
687
- * ⚠️ NOT FREE WHILE IT IS ON. A non-zero amount draws 132 vertices per instance instead of 36 in
688
- * the CAMERA pass — for every instance, beveled or not, because they all ride one indirect draw.
689
- * The shadow pass keeps the sharp cube either way. At 0 the vertex count drops back to 36, so
690
- * leaving this alone costs exactly what it cost before the feature existed.
738
+ * ⚠️ NOT FREE WHILE IT IS ON, AND THE OLD "132 VERTICES" NUMBER HERE IS DEAD. A non-zero amount
739
+ * moves the CAMERA pass off the 36-vertex sharp cube and onto three bucketed indirect draws of
740
+ * 180 / 420 / 588 vertices — 60, 140 and 196 triangles — with `bevelClass` sorting each instance
741
+ * into the cheapest bucket that still contains all of its geometry. On a terrain heightfield that
742
+ * puts ~45 % in the first bucket and ~9 % in the last, so the mean is ~9x the sharp cube rather
743
+ * than the 16x the worst bucket would suggest. The shadow pass keeps the sharp cube either way.
744
+ * At 0 all three buckets collapse back to 36, so leaving this alone costs exactly what it cost
745
+ * before the feature existed — and that is what an unrelated lab measuring triangle counts is
746
+ * actually drawing, which is worth knowing before attributing a frame to "beveled cubes".
691
747
  */
692
748
  setBevel(amount: number, concave?: number): void;
749
+ /**
750
+ * DRAW ONLY THE FACES THAT ARE OPEN TO AIR, per instance, from the `occ` neighbour mask.
751
+ *
752
+ * A surface voxel costs 36 vertices today and needs 6 of them on a flat heightfield: the other
753
+ * five faces are buried in solid rock and rasterize to nothing. With this on the cull pass sorts
754
+ * instances into 6 / 18 / 36-vertex buckets by how many faces are actually exposed.
755
+ *
756
+ * ⚠️ IT NEEDS A REAL `occ` MASK AND SILENTLY DOES NOTHING WITHOUT ONE. `occ` absent ⇒ 0 ⇒ the
757
+ * "unknown" sentinel ⇒ all six faces, exactly as today — which is the safe direction, and also
758
+ * means a caller who turns this on without teaching their mesher to fill `occ` will measure no
759
+ * change and conclude the feature does not work. Computing that mask is not free; it is the
760
+ * trade.
761
+ *
762
+ * ⚠️ AND IT IS IGNORED WHILE A BEVEL IS SET. See `frame()` — the two are mutually exclusive.
763
+ */
764
+ setFaceCull(on: boolean): void;
693
765
  setAtlas(tex: GPUTexture, layout: AtlasLayout): void;
694
766
  /** Static scene: sizes the buffer to exactly these instances. */
695
767
  setScene(instances: CubeInstance[]): void;
696
- /** Dynamic scene: pre-allocate for `cap` instances; call updateInstances() each frame. */
768
+ /**
769
+ * Dynamic scene: pre-allocate for `cap` instances; call updateInstances() each frame.
770
+ *
771
+ * ⚠️ THIS THROWS RATHER THAN LETTING THE DEVICE REJECT THE BUFFER, because the rejection is
772
+ * COMPLETELY SILENT and costs days. `createBuffer` past a device limit does not throw — it returns
773
+ * an INVALID buffer, and the failure only surfaces as `[Invalid Buffer] is invalid due to a
774
+ * previous error` on an `onuncapturederror` handler that most apps never install. Every bind group
775
+ * built from it is invalid, every pass using them is a no-op, and the symptom is a black frame with
776
+ * correct geometry, a full instance buffer, and zero visible instances in EVERY frustum at once.
777
+ * That is indistinguishable by inspection from a cull bug, a camera bug, or a matrix bug, and it
778
+ * was mistaken for all three before anyone thought to compare `device.limits` against the size.
779
+ *
780
+ * The limits are checkable up front and the message names the fix, so it is checked up front.
781
+ */
697
782
  setCapacity(cap: number): void;
698
783
  updateInstances(instances: CubeInstance[]): void;
699
784
  /**
package/dist/gpuShadow.js CHANGED
@@ -59,6 +59,17 @@ export function packFaceMats(m) {
59
59
  // anyway. Spending the other two on a spare slot is free, and the last time this buffer grew it was
60
60
  // for the contact decal, which had to widen it for exactly the same reason.
61
61
  const INST_F = 20;
62
+ /**
63
+ * Bytes one instance occupies in the instance storage buffer.
64
+ *
65
+ * EXPORTED BECAUSE THE CALLER HAS TO SIZE `requiredLimits` WITH IT. A device built by a plain
66
+ * `requestDevice()` gets WebGPU's DEFAULT limits — 256 MiB `maxBufferSize`, 128 MiB
67
+ * `maxStorageBufferBindingSize` — no matter what the adapter advertises, so a consumer that wants a
68
+ * capacity past ~1.67 M instances must request the higher limit at device creation or the allocation
69
+ * is rejected. Working that out requires this number, and a caller that hardcodes 80 is one struct
70
+ * change away from being quietly wrong.
71
+ */
72
+ export const INSTANCE_BYTES = INST_F * 4;
62
73
  const OVERLAY_CAP = 512; // max translucent overlay cubes per frame (the place ghost + headroom)
63
74
  /** Rigid-body table: `bodies[0]` is the header, so this is bodies + 1. See `struct Body` in the WGSL. */
64
75
  export const MAX_BODIES = 32;
@@ -283,8 +294,9 @@ export const ROLE_BASE = 8; // where ONE convex edge lands among TWO concave one
283
294
  // that touch still meet exactly as they did before this existed.
284
295
  //
285
296
  // FREE WHEN UNKNOWN — occ == 0 (every non-terrain caller: the far field, sky bodies, the ship,
286
- // creatures, props, the place ghost) makes every gate false, so all 132 vertices land on the 8
287
- // sharp corners and the geometry is identical to buildCube()'s.
297
+ // creatures, props, the place ghost) makes every gate false, so all BEVEL_VERTS land on the 8
298
+ // sharp corners and the geometry is identical to buildCube()'s. (It said "132" while the cube was
299
+ // a chamfer only; the fillet, carve and base sections have taken it to 588 since.)
288
300
  //
289
301
  // ⚠️ FACE QUADS ARE EMITTED FIRST, AND THAT ORDERING IS LOAD-BEARING. Vertices 0..35 are byte-for-
290
302
  // byte buildCube()'s cube, which is what lets the camera pass draw 36 instead of 132 whenever the
@@ -1011,6 +1023,67 @@ BEVEL_SEG = bevelSegDefault) {
1011
1023
  return S.facets;
1012
1024
  return S.fans;
1013
1025
  }
1026
+ /**
1027
+ * ── FACE CULLING ────────────────────────────────────────────────────────────────────────────────
1028
+ *
1029
+ * A surface voxel draws all six of its faces today — 36 vertices — and on a heightfield five of them
1030
+ * are buried in solid rock. Measured at N=256 in all-mine-sky, terrain is 61 % of the frame (14.6 ms
1031
+ * of 24.1) while being only ~17 % of its triangles, so the cost tracks VERTEX COUNT rather than
1032
+ * triangle count, and five sixths of that vertex count is invisible.
1033
+ *
1034
+ * This drops the buried faces. It needs the neighbour mask instances already carry for AO, so it is
1035
+ * free on the GPU and NOT free in the mesher — computing `occ` is the trade the caller opts into.
1036
+ *
1037
+ * ⚠️ THE FACE ORDER IS buildCube's, AND IT IS LOAD-BEARING. Vertices 0..35 are six faces of six
1038
+ * corners in the order +X, −X, +Y, −Y, +Z, −Z, so vertex `vi` belongs to face `vi / 6`. The remap
1039
+ * below rewrites `vi` to the vi/6-th EXPOSED face, which only works because that layout is a flat
1040
+ * face-major array. See buildCube's "FACE QUADS ARE EMITTED FIRST" note.
1041
+ *
1042
+ * ⚠️ AND IT IS MUTUALLY EXCLUSIVE WITH THE BEVEL. A beveled cube's bands, facets and fillets span
1043
+ * the EDGE BETWEEN two faces, so "drop face 3" is not a well-defined operation on it — the geometry
1044
+ * that rounds an edge belongs to neither face alone. `frame()` ignores face culling whenever a bevel
1045
+ * is set rather than silently producing holes.
1046
+ */
1047
+ export const FACE_DIRS = [
1048
+ [1, 0, 0],
1049
+ [-1, 0, 0],
1050
+ [0, 1, 0],
1051
+ [0, -1, 0],
1052
+ [0, 0, 1],
1053
+ [0, 0, -1],
1054
+ ];
1055
+ /** Is face `d` open to air? A SET bit means the neighbour is SOLID — see occAt. */
1056
+ export function faceExposed(mask, d) {
1057
+ const o = FACE_DIRS[d];
1058
+ const idx = o[0] + 1 + (o[1] + 1) * 3 + (o[2] + 1) * 9;
1059
+ return ((mask >>> idx) & 1) === 0;
1060
+ }
1061
+ /** How many faces this instance actually has to draw. mask 0 is the "unknown" sentinel ⇒ all six. */
1062
+ export function exposedFaceCount(mask) {
1063
+ if (mask === 0)
1064
+ return 6;
1065
+ let n = 0;
1066
+ for (let d = 0; d < 6; d++)
1067
+ if (faceExposed(mask, d))
1068
+ n++;
1069
+ return n;
1070
+ }
1071
+ /**
1072
+ * Vertex counts for the three face-cull buckets, and the classifier that picks one.
1073
+ *
1074
+ * ⚠️ SAME ASYMMETRY AS bevelClass: TOO HIGH ONLY WASTES WORK, TOO LOW DELETES GEOMETRY. A bucket
1075
+ * whose count is above the instance's need draws degenerate (centre-collapsed) triangles; one below
1076
+ * it silently drops a visible face. `faceCull.test.mts` holds the boundary.
1077
+ *
1078
+ * 6 / 18 / 36 rather than an even split because the distribution is not even: on a heightfield the
1079
+ * overwhelming majority of surface voxels expose exactly ONE face, so the cheapest bucket is worth
1080
+ * making as cheap as it can be — a 6x cut for the common case.
1081
+ */
1082
+ export const FACE_CULL_BUCKET_VERTS = [6, 18, 36];
1083
+ export function faceCullClass(mask) {
1084
+ const n = exposedFaceCount(mask);
1085
+ return n <= 1 ? 6 : n <= 3 ? 18 : 36;
1086
+ }
1014
1087
  // THE RIM TURN IS GONE, AND ITS ABSENCE IS THE POINT. rimTurn() clipped a face's corner and grew a
1015
1088
  // one-axis facet wherever a surface had an L-shaped bite taken out of it — a pit's rim turning a
1016
1089
  // corner. That configuration is a CONCAVE corner, and concave corners are now FILLED rather than
@@ -1511,6 +1584,39 @@ fn occAt(mask: u32, o: vec3<f32>) -> f32 {
1511
1584
  let idx = u32((o.x + 1.0) + (o.y + 1.0) * 3.0 + (o.z + 1.0) * 9.0);
1512
1585
  return f32((mask >> idx) & 1u);
1513
1586
  }
1587
+ // ── FACE CULLING ────────────────────────────────────────────────────────────────────────────────
1588
+ // Mirrors faceExposed / exposedFaceCount / faceCullRemap in TS — ONE source, spliced into both the
1589
+ // draw and cull shaders, so there is no third copy. See the FACE CULLING block above buildCube.
1590
+ const FACE_N = array<vec3<f32>, 6>(
1591
+ vec3(1.0, 0.0, 0.0), vec3(-1.0, 0.0, 0.0),
1592
+ vec3(0.0, 1.0, 0.0), vec3(0.0, -1.0, 0.0),
1593
+ vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, -1.0),
1594
+ );
1595
+ fn faceExposedW(mask: u32, d: u32) -> bool {
1596
+ return occAt(mask, FACE_N[d]) < 0.5; // a SET bit is a SOLID neighbour
1597
+ }
1598
+ fn exposedFaceCountW(mask: u32) -> u32 {
1599
+ if (mask == 0u) { return 6u; } // unknown ⇒ draw everything, same sentinel as the bevel
1600
+ var n = 0u;
1601
+ for (var d = 0u; d < 6u; d = d + 1u) { if (faceExposedW(mask, d)) { n = n + 1u; } }
1602
+ return n;
1603
+ }
1604
+ // Rewrite a sharp-cube vertex index onto the (vi / 6)-th EXPOSED face, keeping its corner. Returns
1605
+ // 0xffffffff when this slot has no face left — the draw's bucket is sized for the WORST instance in
1606
+ // it, so most instances have slots to spare and the vertex shader collapses those to a point.
1607
+ fn faceCullRemap(mask: u32, vi: u32) -> u32 {
1608
+ let slot = vi / 6u;
1609
+ let corner = vi % 6u;
1610
+ var seen = 0u;
1611
+ for (var d = 0u; d < 6u; d = d + 1u) {
1612
+ if (faceExposedW(mask, d)) {
1613
+ if (seen == slot) { return d * 6u + corner; }
1614
+ seen = seen + 1u;
1615
+ }
1616
+ }
1617
+ return 0xffffffffu;
1618
+ }
1619
+
1514
1620
  // ── ROUNDED EDGES ───────────────────────────────────────────────────────────────────────────────
1515
1621
  // Is the edge between faces a and b exposed to air or water — and so beveled? The two faces AND
1516
1622
  // the cell diagonally between them must all be clear.
@@ -2082,11 +2188,26 @@ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
2082
2188
  // ${V} vertices — see CULL_BUCKETS.
2083
2189
  //
2084
2190
  // ⚠️ ROUNDING UP IS FREE; ROUNDING DOWN DELETES TRIANGLES. bevelClass.test.mts is what holds that.
2191
+ // cc.lod.y SELECTS THE BUCKETING MODE: 0 none, 1 bevel sections, 2 exposed faces. One dial rather
2192
+ // than two flags because the modes are mutually exclusive — a beveled cube cannot drop a face,
2193
+ // since the geometry that rounds an edge belongs to two of them and to neither alone.
2194
+ //
2195
+ // ⚠️ TEST 2 BEFORE 1. Written as ascending thresholds the bevel branch swallows mode 2 (2 is also
2196
+ // greater than 0.5), and face culling silently runs the bevel classifier instead — which returns
2197
+ // section counts, so the buckets would be sized 180/420/588 for a 36-vertex cube.
2198
+ //
2199
+ // ⚠️ ROUNDING UP IS FREE; ROUNDING DOWN DELETES TRIANGLES. bevelClass.test.mts and
2200
+ // faceCull.test.mts are what hold that, one per mode.
2085
2201
  var b = 0u;
2086
2202
  if (cc.lod.y > 0.5) {
2087
2203
  let mask = select(u32(inst.aux2.x) | (u32(inst.aux2.y) << 14u), 0u, inst.aux.x < -1.5);
2088
- let cls = bevelClass(mask, cc.lod.z, cc.lod.w);
2089
- if (cls > ${S.fillet}u) { b = 2u; } else if (cls > ${S.fans}u) { b = 1u; }
2204
+ if (cc.lod.y > 1.5) {
2205
+ let n = exposedFaceCountW(mask);
2206
+ if (n > 3u) { b = 2u; } else if (n > 1u) { b = 1u; }
2207
+ } else {
2208
+ let cls = bevelClass(mask, cc.lod.z, cc.lod.w);
2209
+ if (cls > ${S.fillet}u) { b = 2u; } else if (cls > ${S.fans}u) { b = 1u; }
2210
+ }
2090
2211
  }
2091
2212
  let slot = atomicAdd(&args[b].ic, 1u);
2092
2213
  visible[b * u32(cc.lod.x) + slot] = i;
@@ -2193,33 +2314,54 @@ fn faceVec(code: f32) -> vec3<f32> {
2193
2314
  // THE BEVELED CUBE. cam.eye.w is the bevel amount; at 0 — every caller that has not opted in —
2194
2315
  // bevelPos returns the sharp corner and this is buildCube()'s geometry exactly. The draw is only
2195
2316
  // 36 vertices long in that case anyway (see the indirect args), so the tail is never even reached.
2196
- let sharp = BEV_CORNER[vi];
2317
+ // ── FACE CULLING: REWRITE THE VERTEX INDEX ONTO AN EXPOSED FACE ──────────────────────────────
2318
+ //
2319
+ // cam.csm.w is the switch. Gated on the bevel being OFF as well, because the bevel's bands and
2320
+ // facets span the edge BETWEEN two faces and cannot be assigned to either — frame() already
2321
+ // refuses to combine them, and repeating the condition here means a caller who reaches past it
2322
+ // gets today's cube rather than a cube with holes in it.
2323
+ //
2324
+ // ⚠️ vv, NOT vi, FROM HERE DOWN. Every table lookup — corner, home, role, axis — has to use
2325
+ // the rewritten index or the position comes from one face and its normal from another.
2326
+ var vv = vi;
2327
+ var faceless = false; // this slot has no exposed face left → collapse it below
2328
+ if (cam.csm.w > 0.5 && cam.eye.w <= 0.0 && cam.csm.z <= 0.0 && mask != 0u) {
2329
+ let r = faceCullRemap(mask, vi);
2330
+ if (r == 0xffffffffu) { faceless = true; } else { vv = r; }
2331
+ }
2332
+ let sharp = BEV_CORNER[vv];
2197
2333
  // ⚠️ THE CORNER CARVE TAKES ITS home FROM THE MASK, not from the table. Its three vertices belong
2198
2334
  // to whichever of the three faces at that corner is the EXPOSED one, and the table cannot know
2199
2335
  // which — so BEV_HOME holds a placeholder and carveFace() resolves it here, before anything reads
2200
2336
  // it. Left as the placeholder it would texture a patch on a grass top with the dirt SIDE tile at
2201
2337
  // every notch corner, which is the "doesn't match the surrounding textures" report all over again.
2202
2338
  // All three vertices resolve the SAME face, so objN stays flat and the patch keeps one tile.
2203
- var home = BEV_HOME[vi];
2339
+ var home = BEV_HOME[vv];
2204
2340
  // ⚠️ RESOLVED ONCE, USED TWICE. Both of these are needed again further down for the SHADING
2205
2341
  // normal, and each walks up to 27 neighbours of the mask through branchy per-axis loops — the
2206
2342
  // most expensive thing this shader does. Computing them a second time down there cost the carve
2207
2343
  // and base sections about a third of their time (tools/bevelBench.mjs).
2208
2344
  var cf = vec3(0.0, 0.0, 0.0);
2209
2345
  var gb = vec3(0.0, 0.0, 0.0);
2210
- if (BEV_ROLE[vi] == ${ROLE_CARVE}.0) { cf = carveFace(mask, sharp); }
2211
- if (BEV_ROLE[vi] == ${ROLE_BASE}.0) { gb = baseOwner(mask, sharp); }
2212
- if (BEV_ROLE[vi] == ${ROLE_CARVE}.0) {
2346
+ if (BEV_ROLE[vv] == ${ROLE_CARVE}.0) { cf = carveFace(mask, sharp); }
2347
+ if (BEV_ROLE[vv] == ${ROLE_BASE}.0) { gb = baseOwner(mask, sharp); }
2348
+ if (BEV_ROLE[vv] == ${ROLE_CARVE}.0) {
2213
2349
  if (length(cf) > 0.5) { home = cf; }
2214
2350
  }
2215
2351
  // ⚠️ AND THE BASE PATCH TOO. It belongs to the FLAT SURFACE it grows out of, whose outward normal
2216
2352
  // is -g, and the table cannot know which axis that is. Left as the placeholder it shipped as black
2217
2353
  // wedges once already.
2218
- if (BEV_ROLE[vi] == ${ROLE_BASE}.0) {
2354
+ if (BEV_ROLE[vv] == ${ROLE_BASE}.0) {
2219
2355
  if (length(gb) > 0.5) { home = -gb; } // the TEXTURE is the flat surface's; the NORMAL is below
2220
2356
  }
2221
2357
 
2222
- let local = bevelPos(mask, sharp, home, cam.eye.w, BEV_ROLE[vi], BEV_AXIS[vi], cam.csm.z);
2358
+ // ⚠️ COLLAPSED TO THE CENTRE, NOT DISCARDED. A face-cull bucket is sized for the WORST instance
2359
+ // in it — a 3-face bucket still runs 18 vertices for a 2-face cube — so the spare slots have to
2360
+ // go somewhere harmless. Putting all six of a slot's corners on the cube centre makes its two
2361
+ // triangles zero-area, which the rasterizer drops for free and which cannot show a seam. There is
2362
+ // no discard available in a vertex shader, and clipping them out by w would cost more.
2363
+ var local = bevelPos(mask, sharp, home, cam.eye.w, BEV_ROLE[vv], BEV_AXIS[vv], cam.csm.z);
2364
+ if (faceless) { local = vec3(0.0, 0.0, 0.0); }
2223
2365
  let world = bodyPos(bd, inst.pos.xyz + qrot(inst.rot, local * inst.scl.xyz));
2224
2366
  var o: VOut;
2225
2367
  o.clip = cam.camVP * vec4(world, 1.0);
@@ -2237,9 +2379,9 @@ fn faceVec(code: f32) -> vec3<f32> {
2237
2379
  // ⚠️ THE FILLET'S NORMAL SWEEPS THE ARC. At the foot it is the face's own normal and at the crest
2238
2380
  // the bisector — which is what one flat quad's two rows used to carry. Subdivided, every row in
2239
2381
  // between needs its own or the strip is a curve shaded as a fan of flat facets.
2240
- if (BEV_ROLE[vi] == ${ROLE_FMID}.0 || BEV_ROLE[vi] == ${ROLE_FRIM}.0) {
2241
- let fa3 = filletArc(BEV_AXIS[vi], ${seg}.0);
2242
- shade = normalize(home * fa3.y - sign(BEV_AXIS[vi]) * fa3.x);
2382
+ if (BEV_ROLE[vv] == ${ROLE_FMID}.0 || BEV_ROLE[vv] == ${ROLE_FRIM}.0) {
2383
+ let fa3 = filletArc(BEV_AXIS[vv], ${seg}.0);
2384
+ shade = normalize(home * fa3.y - sign(BEV_AXIS[vv]) * fa3.x);
2243
2385
  }
2244
2386
  // ⚠️ A BAND'S NORMAL SWEEPS ACROSS THE STRIP. That sweep is the only reason a flat 45° chamfer
2245
2387
  // reads as a cylinder — the geometry is a plane and the shading is a curve. It used to happen for
@@ -2257,7 +2399,7 @@ fn faceVec(code: f32) -> vec3<f32> {
2257
2399
  // the line that declares it — WGSL use-before-declaration, the shader failed to compile, the
2258
2400
  // pipeline never built and the screen went black. bevelParity.spec.ts could not see it: it
2259
2401
  // compiles COMMON_WGSL into a COMPUTE shader and never builds the vertex stage at all.
2260
- if (BEV_ROLE[vi] == ${ROLE_BASE}.0) {
2402
+ if (BEV_ROLE[vv] == ${ROLE_BASE}.0) {
2261
2403
  let gb2 = gb; // resolved once at the top; see there
2262
2404
  if (length(gb2) > 0.5) {
2263
2405
  let hb = -gb2;
@@ -2272,7 +2414,7 @@ fn faceVec(code: f32) -> vec3<f32> {
2272
2414
  if (dot(cross(b1, b2), hb) < 0.0) { fa2 = b2; fb2 = b1; }
2273
2415
  // The arc points sweep their normal from one wall to the other, exactly as the band they meet
2274
2416
  // does — a chord's two end normals across a subdivided arc is the flat-shaded facet again.
2275
- let ib = i32(BEV_AXIS[vi].x + 0.5);
2417
+ let ib = i32(BEV_AXIS[vv].x + 0.5);
2276
2418
  if (ib == 1) { shade = normalize(hb + fb2); }
2277
2419
  else if (ib >= 2 && ib <= ${2 + seg}) {
2278
2420
  let tb = (f32(ib - 2) / ${seg}.0) * 1.5707963267948966;
@@ -2282,9 +2424,9 @@ fn faceVec(code: f32) -> vec3<f32> {
2282
2424
  else { shade = hb; }
2283
2425
  }
2284
2426
  }
2285
- if (BEV_ROLE[vi] == ${ROLE_BAND}.0) {
2286
- let pb = sign(BEV_AXIS[vi]);
2287
- let stb = round(max(max(abs(BEV_AXIS[vi].x), abs(BEV_AXIS[vi].y)), abs(BEV_AXIS[vi].z))) - 1.0;
2427
+ if (BEV_ROLE[vv] == ${ROLE_BAND}.0) {
2428
+ let pb = sign(BEV_AXIS[vv]);
2429
+ let stb = round(max(max(abs(BEV_AXIS[vv].x), abs(BEV_AXIS[vv].y)), abs(BEV_AXIS[vv].z))) - 1.0;
2288
2430
  let thb = (stb / ${seg}.0) * 1.5707963267948966;
2289
2431
  shade = normalize(home * cos(thb) + pb * sin(thb));
2290
2432
  }
@@ -2292,7 +2434,7 @@ fn faceVec(code: f32) -> vec3<f32> {
2292
2434
  // TEXTURE, and at one segment those three normals sweeping across one triangle is what made a flat
2293
2435
  // chamfer corner read round. Once the patch is a real octant, the honest normal is the sphere's —
2294
2436
  // the point's own direction from the centre — or the geometry is round and the shading is not.
2295
- if (BEV_ROLE[vi] == ${ROLE_FACET}.0 && cam.eye.w > 0.0) {
2437
+ if (BEV_ROLE[vv] == ${ROLE_FACET}.0 && cam.eye.w > 0.0) {
2296
2438
  let ctr = sharp - sign(sharp) * cam.eye.w;
2297
2439
  let dv = local - ctr;
2298
2440
  if (length(dv) > 1e-5) { shade = normalize(dv); }
@@ -2307,7 +2449,7 @@ fn faceVec(code: f32) -> vec3<f32> {
2307
2449
  // Each vertex takes the normal of the thing it MEETS, so the patch is continuous with its
2308
2450
  // neighbours: the two on the exposed face take that face; the two band ends take the side face
2309
2451
  // their band grows from; the crest takes the bisector, which is what the fillet's own crest uses.
2310
- if (BEV_ROLE[vi] == ${ROLE_CARVE}.0) {
2452
+ if (BEV_ROLE[vv] == ${ROLE_CARVE}.0) {
2311
2453
  if (length(cf) > 0.5) { // resolved once at the top; see there
2312
2454
  let ipc = sign(sharp) * (vec3(1.0, 1.0, 1.0) - abs(cf));
2313
2455
  var e1 = vec3(0.0, 0.0, 0.0);
@@ -2318,7 +2460,7 @@ fn faceVec(code: f32) -> vec3<f32> {
2318
2460
  var fa = e1;
2319
2461
  var fb = e2;
2320
2462
  if (dot(cross(e1, e2), cf) > 0.0) { fa = e2; fb = e1; }
2321
- let ax = BEV_AXIS[vi];
2463
+ let ax = BEV_AXIS[vv];
2322
2464
  // sweep from the exposed face at the rim to the side face the neighbour's band grows out of,
2323
2465
  // which is what makes the patch continuous with what surrounds it instead of a flat facet
2324
2466
  if (ax.z > 0.5) { shade = normalize(fa + fb); }
@@ -2764,6 +2906,7 @@ export class GpuShadowRenderer {
2764
2906
  matCutoff = 28; // world units; parallax fades out before here
2765
2907
  eye = new Float32Array(3);
2766
2908
  bevel = 0; // see setBevel — 0 keeps the sharp cube exactly, and draws only 36 vertices
2909
+ faceCull = false; // see setFaceCull — off is today's all-six-faces cube, bit for bit
2767
2910
  fillet = 0; // the CONCAVE radius, set separately so the two halves can be judged apart
2768
2911
  alphaPipe;
2769
2912
  alphaBGL; // kept so the overlay buffer can grow and rebind on demand
@@ -3406,15 +3549,38 @@ export class GpuShadowRenderer {
3406
3549
  * without a mask (`occ` absent ⇒ 0, the "unknown" sentinel) is never beveled, which is why the far
3407
3550
  * field, sky-body shells, ships, creatures and props stay sharp with no work on their part.
3408
3551
  *
3409
- * ⚠️ NOT FREE WHILE IT IS ON. A non-zero amount draws 132 vertices per instance instead of 36 in
3410
- * the CAMERA pass — for every instance, beveled or not, because they all ride one indirect draw.
3411
- * The shadow pass keeps the sharp cube either way. At 0 the vertex count drops back to 36, so
3412
- * leaving this alone costs exactly what it cost before the feature existed.
3552
+ * ⚠️ NOT FREE WHILE IT IS ON, AND THE OLD "132 VERTICES" NUMBER HERE IS DEAD. A non-zero amount
3553
+ * moves the CAMERA pass off the 36-vertex sharp cube and onto three bucketed indirect draws of
3554
+ * 180 / 420 / 588 vertices — 60, 140 and 196 triangles — with `bevelClass` sorting each instance
3555
+ * into the cheapest bucket that still contains all of its geometry. On a terrain heightfield that
3556
+ * puts ~45 % in the first bucket and ~9 % in the last, so the mean is ~9x the sharp cube rather
3557
+ * than the 16x the worst bucket would suggest. The shadow pass keeps the sharp cube either way.
3558
+ * At 0 all three buckets collapse back to 36, so leaving this alone costs exactly what it cost
3559
+ * before the feature existed — and that is what an unrelated lab measuring triangle counts is
3560
+ * actually drawing, which is worth knowing before attributing a frame to "beveled cubes".
3413
3561
  */
3414
3562
  setBevel(amount, concave = amount) {
3415
3563
  this.bevel = Math.max(0, amount);
3416
3564
  this.fillet = Math.max(0, concave);
3417
3565
  }
3566
+ /**
3567
+ * DRAW ONLY THE FACES THAT ARE OPEN TO AIR, per instance, from the `occ` neighbour mask.
3568
+ *
3569
+ * A surface voxel costs 36 vertices today and needs 6 of them on a flat heightfield: the other
3570
+ * five faces are buried in solid rock and rasterize to nothing. With this on the cull pass sorts
3571
+ * instances into 6 / 18 / 36-vertex buckets by how many faces are actually exposed.
3572
+ *
3573
+ * ⚠️ IT NEEDS A REAL `occ` MASK AND SILENTLY DOES NOTHING WITHOUT ONE. `occ` absent ⇒ 0 ⇒ the
3574
+ * "unknown" sentinel ⇒ all six faces, exactly as today — which is the safe direction, and also
3575
+ * means a caller who turns this on without teaching their mesher to fill `occ` will measure no
3576
+ * change and conclude the feature does not work. Computing that mask is not free; it is the
3577
+ * trade.
3578
+ *
3579
+ * ⚠️ AND IT IS IGNORED WHILE A BEVEL IS SET. See `frame()` — the two are mutually exclusive.
3580
+ */
3581
+ setFaceCull(on) {
3582
+ this.faceCull = on;
3583
+ }
3418
3584
  setAtlas(tex, layout) {
3419
3585
  this.atlasView = tex.createView({ dimension: '2d-array' });
3420
3586
  const ids = Object.keys(layout.tiles).map(Number);
@@ -3451,8 +3617,30 @@ export class GpuShadowRenderer {
3451
3617
  this.device.queue.writeBuffer(this.instBuf, 0, this.scratch);
3452
3618
  this.makeBindGroups();
3453
3619
  }
3454
- /** Dynamic scene: pre-allocate for `cap` instances; call updateInstances() each frame. */
3620
+ /**
3621
+ * Dynamic scene: pre-allocate for `cap` instances; call updateInstances() each frame.
3622
+ *
3623
+ * ⚠️ THIS THROWS RATHER THAN LETTING THE DEVICE REJECT THE BUFFER, because the rejection is
3624
+ * COMPLETELY SILENT and costs days. `createBuffer` past a device limit does not throw — it returns
3625
+ * an INVALID buffer, and the failure only surfaces as `[Invalid Buffer] is invalid due to a
3626
+ * previous error` on an `onuncapturederror` handler that most apps never install. Every bind group
3627
+ * built from it is invalid, every pass using them is a no-op, and the symptom is a black frame with
3628
+ * correct geometry, a full instance buffer, and zero visible instances in EVERY frustum at once.
3629
+ * That is indistinguishable by inspection from a cull bug, a camera bug, or a matrix bug, and it
3630
+ * was mistaken for all three before anyone thought to compare `device.limits` against the size.
3631
+ *
3632
+ * The limits are checkable up front and the message names the fix, so it is checked up front.
3633
+ */
3455
3634
  setCapacity(cap) {
3635
+ const need = Math.max(INST_F * 4, cap * INST_F * 4);
3636
+ const lim = this.device.limits;
3637
+ if (need > lim.maxBufferSize || need > lim.maxStorageBufferBindingSize)
3638
+ throw new Error(`GpuShadowRenderer.setCapacity(${cap}): the instance buffer needs ${(need / 1048576).toFixed(1)} MiB, ` +
3639
+ `past this device's maxBufferSize ${(lim.maxBufferSize / 1048576).toFixed(1)} MiB / ` +
3640
+ `maxStorageBufferBindingSize ${(lim.maxStorageBufferBindingSize / 1048576).toFixed(1)} MiB. ` +
3641
+ `A plain requestDevice() grants WebGPU's DEFAULT limits regardless of what the adapter supports — ` +
3642
+ `pass requiredLimits: { maxBufferSize, maxStorageBufferBindingSize } at device creation, ` +
3643
+ `clamped to adapter.limits, or lower the capacity.`);
3456
3644
  this.cap = cap;
3457
3645
  this.scratch = new Float32Array(cap * INST_F);
3458
3646
  this.sceneReady = true;
@@ -3610,7 +3798,7 @@ export class GpuShadowRenderer {
3610
3798
  mp.end();
3611
3799
  }
3612
3800
  /** Write a frustum's cull uniform: 6 planes + count + this frustum's VP + occlusion params (occ on the camera pass). */
3613
- writeCull(buf, vp, occlude, bucket = false) {
3801
+ writeCull(buf, vp, occlude, bucket = 0) {
3614
3802
  const planes = frustumPlanes(vp);
3615
3803
  const u = new Float32Array(52); // planes[24] + cnt[4] + camVP[16] + occ[4] + lod[4]
3616
3804
  for (let p = 0; p < 6; p++) {
@@ -3629,7 +3817,7 @@ export class GpuShadowRenderer {
3629
3817
  // sort them by, and with bucketing off every survivor lands in bucket 0 — which is the whole
3630
3818
  // list, exactly as before.
3631
3819
  u[48] = this.visStride() / 4;
3632
- u[49] = bucket ? 1 : 0;
3820
+ u[49] = bucket; // 0 none · 1 bevel sections · 2 exposed faces
3633
3821
  u[50] = this.bevel;
3634
3822
  u[51] = this.fillet;
3635
3823
  this.device.queue.writeBuffer(buf, 0, u);
@@ -3767,6 +3955,8 @@ export class GpuShadowRenderer {
3767
3955
  this.cam[S + 25] = this.eye[1];
3768
3956
  this.cam[S + 26] = this.eye[2];
3769
3957
  this.cam[S + 22] = this.fillet; // csm.z — the CONCAVE radius, see setBevel
3958
+ this.cam[S + 23] =
3959
+ this.faceCull && !(this.bevel > 0 || this.fillet > 0) ? 1 : 0; // csm.w — face culling, see setFaceCull
3770
3960
  this.cam[S + 27] = this.bevel; // eye.w — the CONVEX radius, see setBevel
3771
3961
  this.device.queue.writeBuffer(this.camBuf, 0, this.cam);
3772
3962
  // Each cascade's shadow pass reads its OWN copy with that cascade's matrix parked at lightVP[0].
@@ -3782,14 +3972,27 @@ export class GpuShadowRenderer {
3782
3972
  // — main pass vs the camera frustum (+ Hi-Z occlusion), shadow pass vs the light frustum. Each dispatch atomically
3783
3973
  // compacts its survivors into a visible list + counts them in instanceCount, which the matching drawIndirect consumes.
3784
3974
  // ⚠️ TWO RESETS, NOT ONE, AND THE VERTEX COUNTS DIFFER ON PURPOSE. The camera pass draws the
3785
- // beveled cube's 132 vertices only while a bevel is actually set; at 0 it draws the first 36,
3786
- // which buildBevelCube guarantees ARE the sharp cube. The shadow pass always draws 36 — a 6% cut
3787
- // is invisible in a shadow map and there is no reason to quadruple the cascades' vertex work.
3975
+ // beveled cube's bucketed 180/420/588 vertices only while a bevel is actually set; at 0 all
3976
+ // three buckets draw the first 36, which buildBevelCube guarantees ARE the sharp cube. The
3977
+ // shadow pass always draws 36 — a 6% cut is invisible in a shadow map and there is no reason to
3978
+ // multiply the cascades' vertex work.
3979
+ //
3980
+ // ⚠️ SO "HOW MANY TRIANGLES IS A BOX" HAS TWO ANSWERS AND THIS LINE PICKS BETWEEN THEM. A caller
3981
+ // that never sets a bevel — which is every lab but terrain-relief — draws 12 triangles a box,
3982
+ // not the 60–196 the section table implies.
3788
3983
  const camBevel = this.bevel > 0 || this.fillet > 0;
3984
+ // ⚠️ THE BEVEL WINS. Face culling drops whole faces; the bevel's bands and facets span the edge
3985
+ // between two of them and belong to neither, so combining the two would cut geometry that is
3986
+ // still visible. Rather than let a caller ask for both and get holes, a set bevel simply turns
3987
+ // face culling off for that frame — and the VS repeats the same condition so the two cannot
3988
+ // disagree about which mode is live.
3989
+ const faceCull = this.faceCull && !camBevel;
3789
3990
  // With the bevel off there is nothing to classify: one bucket of 36, the other two empty.
3790
3991
  const bucketVerts = camBevel
3791
3992
  ? [this.bev.sec.fans, this.bev.sec.fillet, this.bev.verts]
3792
- : [SHARP_VERTS, SHARP_VERTS, SHARP_VERTS];
3993
+ : faceCull
3994
+ ? [...FACE_CULL_BUCKET_VERTS]
3995
+ : [SHARP_VERTS, SHARP_VERTS, SHARP_VERTS];
3793
3996
  const camReset = new Uint32Array(4 * CULL_BUCKETS);
3794
3997
  for (let b = 0; b < CULL_BUCKETS; b++)
3795
3998
  camReset[b * 4] = bucketVerts[b];
@@ -3798,7 +4001,7 @@ export class GpuShadowRenderer {
3798
4001
  lightReset[0] = SHARP_VERTS;
3799
4002
  for (const a of this.lightArgs)
3800
4003
  this.device.queue.writeBuffer(a, 0, lightReset);
3801
- this.writeCull(this.camCull, camVP, occludeNow, camBevel);
4004
+ this.writeCull(this.camCull, camVP, occludeNow, camBevel ? 1 : faceCull ? 2 : 0);
3802
4005
  for (let i = 0; i < nc; i++)
3803
4006
  this.writeCull(this.lightCull[i], mats[i], false);
3804
4007
  // ⚠️ THE PASS OPENS FOR EITHER REASON. It used to be gated on `this.count > 0` alone, which is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.26",
3
+ "version": "0.15.28",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {