ugly-game 0.15.15 → 0.15.16

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.
@@ -100,6 +100,30 @@ export declare const BEVEL_SEG = 1;
100
100
  /** Vertex counts for the two cube geometries the camera pass can draw. */
101
101
  export declare const SHARP_VERTS = 36;
102
102
  export declare const BEVEL_VERTS: number;
103
+ /**
104
+ * Cumulative section ends, in the order buildBevelCube emits them. A draw with a SMALLER
105
+ * vertexCount stops after a whole section, so these are the only legal truncation points — and the
106
+ * cull pass picks one per instance (see `bevelClass` in MASK_WGSL).
107
+ *
108
+ * ⚠️ DERIVED FROM THE SAME TERMS AS BEVEL_VERTS ON PURPOSE. Written as literals they would be right
109
+ * at BEVEL_SEG = 1 and quietly wrong above it, and "quietly wrong" here means a draw that stops in
110
+ * the middle of a section and takes a third of a triangle with it.
111
+ */
112
+ /**
113
+ * How many vertex-count buckets the camera pass draws, and what each one draws.
114
+ *
115
+ * Three rather than one per class: on a terrain heightfield the five classes fall out 45.1 / 1.0 /
116
+ * 37.0 / 7.5 / 9.4 %, so collapsing 276→420 and 492→588 costs 1.5% of the saving and halves the
117
+ * draws and the memory. A bucket always draws AT LEAST what its instances need.
118
+ */
119
+ export declare const CULL_BUCKETS = 3;
120
+ export declare const SEC_SHARP = 36;
121
+ export declare const SEC_FANS: number;
122
+ export declare const SEC_BANDS: number;
123
+ export declare const SEC_FACETS: number;
124
+ export declare const SEC_FILLET: number;
125
+ export declare const SEC_CARVE: number;
126
+ export declare const SEC_BASE: number;
103
127
  /** What a vertex is, which decides how it is allowed to move. */
104
128
  export declare const ROLE_SHARP = 0;
105
129
  export declare const ROLE_CENTER = 1;
@@ -296,13 +320,43 @@ export declare function carveCorner(mask: number, corner: readonly [number, numb
296
320
  * notch across a FACE, not diagonally, so their own in-plane pair is never both-solid.
297
321
  */
298
322
  export declare function carveFace(mask: number, corner: readonly [number, number, number]): [number, number, number] | null;
323
+ /**
324
+ * How many of the cube's `BEVEL_VERTS` vertices does this neighbourhood actually use?
325
+ *
326
+ * The sections are emitted in a fixed order — sharp | face fans | bands | facets | fillet | carve |
327
+ * base — so a draw with a smaller vertexCount drops whole sections off the END. Every visible cube
328
+ * used to run all 588 regardless: one buried in a hillside 300 blocks away paid exactly what one at
329
+ * your feet paid. On a terrain heightfield 45% of exposed cubes need only the face fans and 9% need
330
+ * everything, so classifying per instance in the CULL pass cuts total vertex work by ~42%.
331
+ *
332
+ * ⚠️ TOO HIGH ONLY WASTES WORK; TOO LOW DELETES GEOMETRY. That asymmetry is the whole risk here, and
333
+ * `bevelClass.test.mts` is what holds it: for a spread of masks it finds the last triangle with any
334
+ * area and asserts it falls inside the class this returns.
335
+ *
336
+ * ⚠️ MIRRORED BY `bevelClass()` IN MASK_WGSL — which is the SAME SOURCE, included into both the draw
337
+ * and cull shaders, precisely so there is no third copy to drift. This TypeScript one exists to be
338
+ * testable against the oracle.
339
+ */
340
+ export declare function bevelClass(mask: number, bevel: number, concave: number): number;
299
341
  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],
300
342
  /** The CONCAVE radius. Separate from `bevel` (the convex one) so the two halves of the rounding
301
343
  * can be turned up, down and off independently — the only way to tell which one a defect is in.
302
344
  * Defaults to the convex radius, which is the "one uniformly rounded solid" the design wants. */
303
345
  concave?: number): [number, number, number];
346
+ /**
347
+ * The 27-bit-mask predicates, shared VERBATIM by the draw passes and the CULL pass.
348
+ *
349
+ * ⚠️ EXTRACTED SO THE CULL PASS CAN ASK THE SAME QUESTIONS THE VERTEX SHADER DOES. bevelClass()
350
+ * decides how many vertices an instance is drawn with; if it ever disagreed with what bevelPos()
351
+ * produces, the cube would silently lose geometry and the terrain would grow holes. It cannot
352
+ * disagree if it is calling these same functions rather than a third hand-written copy — this file
353
+ * has already paid for hand-mirroring twice (bevelVertex/bevelPos, and baseAt's far==0).
354
+ *
355
+ * Pure: no bindings, no textures, so it can be prepended to any shader.
356
+ */
357
+ export declare const MASK_WGSL = "\n// occAt reads one neighbour out of the 27-bit mask; the index is the same\n// (dx+1) + (dy+1)*3 + (dz+1)*9 the caller packed with.\nfn occAt(mask: u32, o: vec3<f32>) -> f32 {\n let idx = u32((o.x + 1.0) + (o.y + 1.0) * 3.0 + (o.z + 1.0) * 9.0);\n return f32((mask >> idx) & 1u);\n}\n// \u2500\u2500 ROUNDED EDGES \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Is the edge between faces a and b exposed to air or water \u2014 and so beveled? The two faces AND\n// the cell diagonally between them must all be clear.\n//\n// \u26A0\uFE0F THE DIAGONAL TERM IS WHAT STOPS A STAIR STEP FROM OPENING A HOLE. Two blocks touching only\n// along a diagonal each see air on both faces at that edge; cutting both back on the two-face test\n// alone leaves a diamond you can see the sky through. Mirrors edgeOpen() in TS \u2014 see bevelVertex.\nfn edgeOpen(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; } // unknown \u21D2 no bevel, see CubeInstance.occ\n return (1.0 - occAt(mask, a)) * (1.0 - occAt(mask, b)) * (1.0 - occAt(mask, a + b));\n}\n// Does the edge between exposed face a and its in-plane neighbour b get a FILLET? From an exposed\n// face two bits classify every edge there is: occ(b) and occ(a+b) give convex / flat / concave /\n// saddle, and the fillet gate is just occ(a+b) \u2014 the cell diagonally across the edge being solid is\n// exactly what makes a groove. The saddle needs no code of its own; from either solid cube's side\n// its near quadrant is an ordinary concave groove. A fillet ADDS material and so can never open a\n// hole. Mirrors edgeFillet() in TS.\n// edgeOpen asked of the cell one step away at off \u2014 is the NEIGHBOUR chamfering this edge? Mirrors\n// edgeOpenAt() in TS.\nfn edgeOpenAt(mask: u32, off: vec3<f32>, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; }\n return (1.0 - occAt(mask, off + a)) * (1.0 - occAt(mask, off + b)) * (1.0 - occAt(mask, off + a + b));\n}\nfn edgeFillet(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; } // unknown \u21D2 no rounding, see CubeInstance.occ\n return (1.0 - occAt(mask, a)) * occAt(mask, a + b);\n}\n// The vertex rule. A vertex's pull along a free axis is INWARD, gated by the edge between its home\n// face and the face on that side. Both primitives that share a vertex resolve the same face/axis\n// pair, so they cannot land in different places \u2014 that is where watertightness comes from, and it\n// is why this takes (corner, home) rather than a vertex index.\n// THE NOTCH \u2014 the exact complement of edgeOpen: both faces SOLID, the diagonal between them AIR.\n// Three blocks in an L around an empty cell: the two with a FACE on it chamfer normally, the third\n// touches it only along one corner edge and keeps a hard arris down the inside of the notch. This is\n// what softens that. Cutting it cannot open a hole \u2014 the wedge is inside this block's own cell and\n// the neighbours' buried faces (drawn, like every face of every instance) close it. Mirrors\n// notchOpen() in TS.\nfn notchOpen(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; }\n return occAt(mask, a) * occAt(mask, b) * (1.0 - occAt(mask, a + b));\n}\n// THE INSIDE CORNER, as the whole EIGHT-CELL configuration around the lattice point: this cube and\n// both in-plane neighbours SOLID with the notch between them AIR, and all four cells in the layer\n// above AIR. The upper layer is not decoration \u2014 it is what says the two neighbours actually chamfer\n// their edges into the notch, and those two chamfers are what the patch's three points land on.\n// Mirrors carveOpen() (and case3(), which is its lower half) in TS; see there for the full statement.\nfn carveOpen(mask: u32, a: vec3<f32>, c: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; }\n if (occAt(mask, a) > 0.5) { return 0.0; } // only an EXPOSED face has a rim to turn\n let ip = sign(c) * (vec3(1.0, 1.0, 1.0) - abs(a)); // the two in-plane directions, signed\n var d1 = vec3(0.0, 0.0, 0.0);\n var d2 = vec3(0.0, 0.0, 0.0);\n if (abs(a.x) > 0.5) { d1 = vec3(0.0, ip.y, 0.0); d2 = vec3(0.0, 0.0, ip.z); }\n else if (abs(a.y) > 0.5) { d1 = vec3(ip.x, 0.0, 0.0); d2 = vec3(0.0, 0.0, ip.z); }\n else { d1 = vec3(ip.x, 0.0, 0.0); d2 = vec3(0.0, ip.y, 0.0); }\n return occAt(mask, d1) * occAt(mask, d2) * (1.0 - occAt(mask, d1 + d2))\n * (1.0 - occAt(mask, d1 + a)) * (1.0 - occAt(mask, d2 + a)) * (1.0 - occAt(mask, d1 + d2 + a));\n}\n// THE SAME INSIDE CORNER, ASKED BY ANY OF THE EIGHT CELLS \u2014 the direction of the all-air layer, or\n// (0,0,0). carveOpen can only be asked by the ONE cube whose exposed face turns the corner; the two\n// neighbours need this, because their shared BURIED faces have to retreat out of the patch's way or\n// they stand in front of it as thin sheets. Both cubes see all eight cells, so they cannot disagree.\n// Mirrors carveCorner() in TS.\nfn carveCorner(mask: u32, c: vec3<f32>) -> vec3<f32> {\n if (mask == 0u) { return vec3(0.0, 0.0, 0.0); }\n let s = sign(c);\n for (var k = 0; k < 3; k = k + 1) {\n var u1 = vec3(0.0, 0.0, 0.0);\n var u2 = vec3(0.0, 0.0, 0.0);\n var hk = vec3(0.0, 0.0, 0.0);\n if (k == 0) { u1 = vec3(0.0, s.y, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(s.x, 0.0, 0.0); }\n else if (k == 1) { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(0.0, s.y, 0.0); }\n else { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, s.y, 0.0); hk = vec3(0.0, 0.0, s.z); }\n // the far layer all air, and this cube's own layer 3 solid of 4 (it is itself the first)\n let farAir = (1.0 - occAt(mask, hk)) * (1.0 - occAt(mask, hk + u1))\n * (1.0 - occAt(mask, hk + u2)) * (1.0 - occAt(mask, hk + u1 + u2));\n let nearSolid = 1.0 + occAt(mask, u1) + occAt(mask, u2) + occAt(mask, u1 + u2);\n if (farAir > 0.5 && abs(nearSolid - 3.0) < 0.5) { return hk; }\n }\n return vec3(0.0, 0.0, 0.0);\n}\n// THE BASE CORNER \u2014 one convex edge among two concave ones, asked by any of the eight cells.\n// Returns the direction of the ALL-SOLID layer, or (0,0,0). Mirrors baseAt() in TS.\nfn baseAt(mask: u32, c: vec3<f32>) -> vec3<f32> {\n if (mask == 0u) { return vec3(0.0, 0.0, 0.0); }\n let s = sign(c);\n for (var k = 0; k < 3; k = k + 1) {\n var u1 = vec3(0.0, 0.0, 0.0);\n var u2 = vec3(0.0, 0.0, 0.0);\n var hk = vec3(0.0, 0.0, 0.0);\n if (k == 0) { u1 = vec3(0.0, s.y, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(s.x, 0.0, 0.0); }\n else if (k == 1) { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(0.0, s.y, 0.0); }\n else { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, s.y, 0.0); hk = vec3(0.0, 0.0, s.z); }\n let far = occAt(mask, hk) + occAt(mask, hk + u1) + occAt(mask, hk + u2) + occAt(mask, hk + u1 + u2);\n let near = 1.0 + occAt(mask, u1) + occAt(mask, u2) + occAt(mask, u1 + u2);\n if (far > 3.5 && near < 1.5) { return hk; }\n // \u26A0\uFE0F far MUST BE EXACTLY ONE, AND THE LOWER BOUND IS WHAT WAS MISSING. near == 4 says this cube\n // sits in a flat surface; far == 1 says exactly one cell above it is solid \u2014 the block whose base\n // this corner is. far == 0 means nothing is standing there at all, so there is no base corner and\n // no patch, but the test read only \"far < 1.5\" and answered yes. Ordinary flat ground therefore\n // claimed a base corner, and its fillet crest retreated a full bevel into a notch.\n // TS baseAt() has always required far === 1; this is the half that drifted, and only\n // tools/bevelParity.mjs could see it \u2014 894 cases, all ROLE_FMID.\n if (near > 3.5 && far > 0.5 && far < 1.5) { return -hk; }\n }\n return vec3(0.0, 0.0, 0.0);\n}\n// \u2026and only the surface cell on the 3D diagonal from the block emits the patch. The flat surface\n// owns it, not the block \u2014 see baseOwner() in TS for why the shading depends on that.\nfn baseOwner(mask: u32, c: vec3<f32>) -> vec3<f32> {\n let g = baseAt(mask, c);\n if (length(g) < 0.5) { return g; }\n if (dot(g, sign(c)) > 0.0) { return vec3(0.0, 0.0, 0.0); }\n if (occAt(mask, sign(c)) < 0.5) { return vec3(0.0, 0.0, 0.0); }\n return g;\n}\n// WHICH of the three faces at this corner is the exposed one the carve fires on \u2014 (0,0,0) if none.\n// At most one can answer (see carveFace() in TS), so this is the corner's whole verdict, and the\n// patch takes its home from it rather than from the table: which face is exposed is something only\n// the mask knows. Mirrors carveFace() in TS.\nfn carveFace(mask: u32, c: vec3<f32>) -> vec3<f32> {\n let fx = vec3(sign(c.x), 0.0, 0.0);\n let fy = vec3(0.0, sign(c.y), 0.0);\n let fz = vec3(0.0, 0.0, sign(c.z));\n if (carveOpen(mask, fx, c) > 0.5) { return fx; }\n if (carveOpen(mask, fy, c) > 0.5) { return fy; }\n if (carveOpen(mask, fz, c) > 0.5) { return fz; }\n return vec3(0.0, 0.0, 0.0);\n}\n// The vertex rule. A vertex's pull along a free axis is INWARD, gated by the CONVEX chamfer (both\n// cells air) or the NOTCH (both solid, diagonal air) \u2014 never both, since they disagree about the\n// home face. See bevelVertex in TS for why nothing here may move a vertex on an EXPOSED face except\n// the convex term: the visible surface is shared with neighbours computing from their own cells, and\n// a one-sided cut tears it.\n// The vertex rule \u2014 see bevelVertex in TS for the full statement of each term.\n\n// HOW MANY VERTICES DOES THIS CUBE ACTUALLY NEED? \u2014 the cull pass's question.\n//\n// buildBevelCube emits in a fixed order: sharp | face fans | bands | facets | fillet | carve | base.\n// So a SMALLER vertexCount drops whole sections off the END, and an instance that provably has no\n// inside corner never has to run the 168 vertices of carve and base. Measured on a terrain\n// heightfield: 45% of exposed cubes need only the face fans, and 9% need all 588.\n//\n// \u26A0\uFE0F THIS MUST NEVER RETURN LESS THAN THE CUBE USES. Too high only wastes work; too low deletes\n// geometry. bevelClass.test.mts checks it against the oracle: for a spread of masks it finds the\n// last triangle with any area and asserts it falls inside the class.\nfn bevelClass(mask: u32, bevel: f32, conc: f32) -> u32 {\n if (mask == 0u || (bevel <= 0.0 && conc <= 0.0)) { return 180u; }\n var anyBase = false;\n var anyCarve = false;\n for (var i = 0u; i < 8u; i++) {\n let c = vec3<f32>(\n select(-0.5, 0.5, (i & 1u) != 0u),\n select(-0.5, 0.5, (i & 2u) != 0u),\n select(-0.5, 0.5, (i & 4u) != 0u));\n if (conc > 0.0 && length(baseOwner(mask, c)) > 0.5) { anyBase = true; }\n if (length(carveFace(mask, c)) > 0.5) { anyCarve = true; }\n }\n if (anyBase) { return 588u; }\n if (anyCarve) { return 492u; }\n var anyFillet = false;\n var anyConvex = false;\n for (var f = 0u; f < 6u; f++) {\n var a = vec3<f32>(0.0, 0.0, 0.0);\n let sgn = select(1.0, -1.0, (f & 1u) != 0u);\n if (f < 2u) { a.x = sgn; } else if (f < 4u) { a.y = sgn; } else { a.z = sgn; }\n for (var g = 0u; g < 6u; g++) {\n var b = vec3<f32>(0.0, 0.0, 0.0);\n let sg2 = select(1.0, -1.0, (g & 1u) != 0u);\n if (g < 2u) { b.x = sg2; } else if (g < 4u) { b.y = sg2; } else { b.z = sg2; }\n if (abs(dot(a, b)) > 0.5) { continue; } // same axis: not an edge\n if (edgeOpen(mask, a, b) > 0.5) { anyConvex = true; }\n if (edgeFillet(mask, a, b) > 0.5) { anyFillet = true; }\n }\n }\n if (anyFillet && conc > 0.0) { return 420u; }\n if (anyConvex && bevel > 0.0) { return 276u; }\n return 180u;\n}\n";
304
358
  export declare const COMMON_WGSL: string;
305
- export declare const CULL_WGSL = "\n// \u26A0\uFE0F THE SAME STRIDE AS THE DRAW PASSES' Inst, and it has to be kept that way BY HAND \u2014 this is a\n// second declaration of one buffer's layout, not a shared one. The cull pass only reads pos/scl/rot,\n// so a stale copy still compiles and still runs; it just indexes every instance past the first at\n// the wrong offset, and the symptom is cubes winking out of existence at the edge of view rather\n// than anything that looks like a struct mismatch.\nstruct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> };\nstruct Args { vc: u32, ic: atomic<u32>, fv: u32, fi: u32 };\nstruct CullCam {\n planes: array<vec4<f32>, 6>, cnt: vec4<f32>, // cnt.x = instance count\n camVP: mat4x4<f32>, occ: vec4<f32>, // occ.x = occlusion on \u00B7 occ.yz = hiz w,h \u00B7 occ.w = downscale\n};\n@group(0) @binding(0) var<storage, read> insts: array<Inst>;\n@group(0) @binding(1) var<storage, read_write> args: Args;\n@group(0) @binding(2) var<storage, read_write> visible: array<u32>;\n@group(0) @binding(3) var<uniform> cc: CullCam;\n@group(0) @binding(4) var hiz: texture_2d<f32>;\nfn qr(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); }\n@compute @workgroup_size(64)\nfn cull(@builtin(global_invocation_id) gid: vec3<u32>) {\n let i = gid.x;\n if (i >= u32(cc.cnt.x)) { return; }\n let inst = insts[i];\n let c = inst.pos.xyz;\n let h = 0.5 * inst.scl.xyz;\n let bx = qr(inst.rot, vec3<f32>(h.x, 0.0, 0.0)); // rotated box semi-axes\n let by = qr(inst.rot, vec3<f32>(0.0, h.y, 0.0));\n let bz = qr(inst.rot, vec3<f32>(0.0, 0.0, h.z));\n for (var p = 0u; p < 6u; p++) {\n let pl = cc.planes[p];\n let e = abs(dot(pl.xyz, bx)) + abs(dot(pl.xyz, by)) + abs(dot(pl.xyz, bz)); // box half-width along the normal\n if (dot(pl.xyz, c) + pl.w < -e) { return; }\n }\n // \u2500\u2500 Hi-Z occlusion (camera pass only) \u2500\u2500\n if (cc.occ.x > 0.5) {\n var mn = vec2<f32>(1e9, 1e9);\n var mx = vec2<f32>(-1e9, -1e9);\n var nearZ = 1e9;\n var ok = true;\n for (var ci = 0u; ci < 8u; ci++) {\n let s = vec3<f32>(select(-1.0, 1.0, (ci & 1u) != 0u), select(-1.0, 1.0, (ci & 2u) != 0u), select(-1.0, 1.0, (ci & 4u) != 0u));\n let corner = c + bx * s.x + by * s.y + bz * s.z;\n let clip = cc.camVP * vec4<f32>(corner, 1.0);\n if (clip.w <= 0.0) { ok = false; break; } // a corner at/behind the eye \u2192 don't occlusion-cull (keep)\n let ndc = clip.xyz / clip.w;\n let uv = ndc.xy * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5, 0.5);\n mn = min(mn, uv); mx = max(mx, uv);\n nearZ = min(nearZ, ndc.z);\n }\n if (ok && nearZ >= 0.0) {\n let dim = vec2<f32>(cc.occ.y, cc.occ.z);\n let t0 = vec2<i32>(floor(clamp(mn, vec2<f32>(0.0), vec2<f32>(1.0)) * dim));\n let t1 = vec2<i32>(floor(clamp(mx, vec2<f32>(0.0), vec2<f32>(1.0)) * dim));\n // only query a bounded footprint; a huge on-screen box just isn't occlusion-tested (kept)\n if (t1.x - t0.x <= 8 && t1.y - t0.y <= 8) {\n // DILATE the query by 2 Hi-Z texels. hiz is LAST frame's depth; under camera motion a cube reprojects by\n // a few source pixels between frames, so a cube sitting at an occluder's silhouette gets tested against\n // stale NEAR depth from where the occluder used to be and is wrongly culled \u2014 it blinks out for a frame\n // (worst on thin/sparse geometry, but a one-frame hole in dense terrain too). Taking MAX over a dilated\n // footprint is strictly MORE conservative (it can only raise farOccluder \u21D2 only ever KEEP more cubes), so it\n // never hides real geometry; it just leaves a couple of deeply-hidden cubes unculled. 2\u00D78px of slack.\n let lim = vec2<i32>(i32(cc.occ.y) - 1, i32(cc.occ.z) - 1);\n let q0 = max(t0 - vec2<i32>(2, 2), vec2<i32>(0, 0));\n let q1 = min(t1 + vec2<i32>(2, 2), lim);\n var farOccluder = 0.0; // MAX over the footprint of the coarse max-depth\n for (var y = q0.y; y <= q1.y; y++) {\n for (var x = q0.x; x <= q1.x; x++) {\n farOccluder = max(farOccluder, textureLoad(hiz, vec2<i32>(x, y), 0).r);\n }\n }\n if (nearZ > farOccluder) { return; } // behind the farthest occluder everywhere \u2192 occluded\n }\n }\n }\n let slot = atomicAdd(&args.ic, 1u);\n visible[slot] = i;\n}\n";
359
+ export declare const CULL_WGSL = "\n\n// occAt reads one neighbour out of the 27-bit mask; the index is the same\n// (dx+1) + (dy+1)*3 + (dz+1)*9 the caller packed with.\nfn occAt(mask: u32, o: vec3<f32>) -> f32 {\n let idx = u32((o.x + 1.0) + (o.y + 1.0) * 3.0 + (o.z + 1.0) * 9.0);\n return f32((mask >> idx) & 1u);\n}\n// \u2500\u2500 ROUNDED EDGES \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Is the edge between faces a and b exposed to air or water \u2014 and so beveled? The two faces AND\n// the cell diagonally between them must all be clear.\n//\n// \u26A0\uFE0F THE DIAGONAL TERM IS WHAT STOPS A STAIR STEP FROM OPENING A HOLE. Two blocks touching only\n// along a diagonal each see air on both faces at that edge; cutting both back on the two-face test\n// alone leaves a diamond you can see the sky through. Mirrors edgeOpen() in TS \u2014 see bevelVertex.\nfn edgeOpen(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; } // unknown \u21D2 no bevel, see CubeInstance.occ\n return (1.0 - occAt(mask, a)) * (1.0 - occAt(mask, b)) * (1.0 - occAt(mask, a + b));\n}\n// Does the edge between exposed face a and its in-plane neighbour b get a FILLET? From an exposed\n// face two bits classify every edge there is: occ(b) and occ(a+b) give convex / flat / concave /\n// saddle, and the fillet gate is just occ(a+b) \u2014 the cell diagonally across the edge being solid is\n// exactly what makes a groove. The saddle needs no code of its own; from either solid cube's side\n// its near quadrant is an ordinary concave groove. A fillet ADDS material and so can never open a\n// hole. Mirrors edgeFillet() in TS.\n// edgeOpen asked of the cell one step away at off \u2014 is the NEIGHBOUR chamfering this edge? Mirrors\n// edgeOpenAt() in TS.\nfn edgeOpenAt(mask: u32, off: vec3<f32>, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; }\n return (1.0 - occAt(mask, off + a)) * (1.0 - occAt(mask, off + b)) * (1.0 - occAt(mask, off + a + b));\n}\nfn edgeFillet(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; } // unknown \u21D2 no rounding, see CubeInstance.occ\n return (1.0 - occAt(mask, a)) * occAt(mask, a + b);\n}\n// The vertex rule. A vertex's pull along a free axis is INWARD, gated by the edge between its home\n// face and the face on that side. Both primitives that share a vertex resolve the same face/axis\n// pair, so they cannot land in different places \u2014 that is where watertightness comes from, and it\n// is why this takes (corner, home) rather than a vertex index.\n// THE NOTCH \u2014 the exact complement of edgeOpen: both faces SOLID, the diagonal between them AIR.\n// Three blocks in an L around an empty cell: the two with a FACE on it chamfer normally, the third\n// touches it only along one corner edge and keeps a hard arris down the inside of the notch. This is\n// what softens that. Cutting it cannot open a hole \u2014 the wedge is inside this block's own cell and\n// the neighbours' buried faces (drawn, like every face of every instance) close it. Mirrors\n// notchOpen() in TS.\nfn notchOpen(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; }\n return occAt(mask, a) * occAt(mask, b) * (1.0 - occAt(mask, a + b));\n}\n// THE INSIDE CORNER, as the whole EIGHT-CELL configuration around the lattice point: this cube and\n// both in-plane neighbours SOLID with the notch between them AIR, and all four cells in the layer\n// above AIR. The upper layer is not decoration \u2014 it is what says the two neighbours actually chamfer\n// their edges into the notch, and those two chamfers are what the patch's three points land on.\n// Mirrors carveOpen() (and case3(), which is its lower half) in TS; see there for the full statement.\nfn carveOpen(mask: u32, a: vec3<f32>, c: vec3<f32>) -> f32 {\n if (mask == 0u) { return 0.0; }\n if (occAt(mask, a) > 0.5) { return 0.0; } // only an EXPOSED face has a rim to turn\n let ip = sign(c) * (vec3(1.0, 1.0, 1.0) - abs(a)); // the two in-plane directions, signed\n var d1 = vec3(0.0, 0.0, 0.0);\n var d2 = vec3(0.0, 0.0, 0.0);\n if (abs(a.x) > 0.5) { d1 = vec3(0.0, ip.y, 0.0); d2 = vec3(0.0, 0.0, ip.z); }\n else if (abs(a.y) > 0.5) { d1 = vec3(ip.x, 0.0, 0.0); d2 = vec3(0.0, 0.0, ip.z); }\n else { d1 = vec3(ip.x, 0.0, 0.0); d2 = vec3(0.0, ip.y, 0.0); }\n return occAt(mask, d1) * occAt(mask, d2) * (1.0 - occAt(mask, d1 + d2))\n * (1.0 - occAt(mask, d1 + a)) * (1.0 - occAt(mask, d2 + a)) * (1.0 - occAt(mask, d1 + d2 + a));\n}\n// THE SAME INSIDE CORNER, ASKED BY ANY OF THE EIGHT CELLS \u2014 the direction of the all-air layer, or\n// (0,0,0). carveOpen can only be asked by the ONE cube whose exposed face turns the corner; the two\n// neighbours need this, because their shared BURIED faces have to retreat out of the patch's way or\n// they stand in front of it as thin sheets. Both cubes see all eight cells, so they cannot disagree.\n// Mirrors carveCorner() in TS.\nfn carveCorner(mask: u32, c: vec3<f32>) -> vec3<f32> {\n if (mask == 0u) { return vec3(0.0, 0.0, 0.0); }\n let s = sign(c);\n for (var k = 0; k < 3; k = k + 1) {\n var u1 = vec3(0.0, 0.0, 0.0);\n var u2 = vec3(0.0, 0.0, 0.0);\n var hk = vec3(0.0, 0.0, 0.0);\n if (k == 0) { u1 = vec3(0.0, s.y, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(s.x, 0.0, 0.0); }\n else if (k == 1) { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(0.0, s.y, 0.0); }\n else { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, s.y, 0.0); hk = vec3(0.0, 0.0, s.z); }\n // the far layer all air, and this cube's own layer 3 solid of 4 (it is itself the first)\n let farAir = (1.0 - occAt(mask, hk)) * (1.0 - occAt(mask, hk + u1))\n * (1.0 - occAt(mask, hk + u2)) * (1.0 - occAt(mask, hk + u1 + u2));\n let nearSolid = 1.0 + occAt(mask, u1) + occAt(mask, u2) + occAt(mask, u1 + u2);\n if (farAir > 0.5 && abs(nearSolid - 3.0) < 0.5) { return hk; }\n }\n return vec3(0.0, 0.0, 0.0);\n}\n// THE BASE CORNER \u2014 one convex edge among two concave ones, asked by any of the eight cells.\n// Returns the direction of the ALL-SOLID layer, or (0,0,0). Mirrors baseAt() in TS.\nfn baseAt(mask: u32, c: vec3<f32>) -> vec3<f32> {\n if (mask == 0u) { return vec3(0.0, 0.0, 0.0); }\n let s = sign(c);\n for (var k = 0; k < 3; k = k + 1) {\n var u1 = vec3(0.0, 0.0, 0.0);\n var u2 = vec3(0.0, 0.0, 0.0);\n var hk = vec3(0.0, 0.0, 0.0);\n if (k == 0) { u1 = vec3(0.0, s.y, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(s.x, 0.0, 0.0); }\n else if (k == 1) { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, 0.0, s.z); hk = vec3(0.0, s.y, 0.0); }\n else { u1 = vec3(s.x, 0.0, 0.0); u2 = vec3(0.0, s.y, 0.0); hk = vec3(0.0, 0.0, s.z); }\n let far = occAt(mask, hk) + occAt(mask, hk + u1) + occAt(mask, hk + u2) + occAt(mask, hk + u1 + u2);\n let near = 1.0 + occAt(mask, u1) + occAt(mask, u2) + occAt(mask, u1 + u2);\n if (far > 3.5 && near < 1.5) { return hk; }\n // \u26A0\uFE0F far MUST BE EXACTLY ONE, AND THE LOWER BOUND IS WHAT WAS MISSING. near == 4 says this cube\n // sits in a flat surface; far == 1 says exactly one cell above it is solid \u2014 the block whose base\n // this corner is. far == 0 means nothing is standing there at all, so there is no base corner and\n // no patch, but the test read only \"far < 1.5\" and answered yes. Ordinary flat ground therefore\n // claimed a base corner, and its fillet crest retreated a full bevel into a notch.\n // TS baseAt() has always required far === 1; this is the half that drifted, and only\n // tools/bevelParity.mjs could see it \u2014 894 cases, all ROLE_FMID.\n if (near > 3.5 && far > 0.5 && far < 1.5) { return -hk; }\n }\n return vec3(0.0, 0.0, 0.0);\n}\n// \u2026and only the surface cell on the 3D diagonal from the block emits the patch. The flat surface\n// owns it, not the block \u2014 see baseOwner() in TS for why the shading depends on that.\nfn baseOwner(mask: u32, c: vec3<f32>) -> vec3<f32> {\n let g = baseAt(mask, c);\n if (length(g) < 0.5) { return g; }\n if (dot(g, sign(c)) > 0.0) { return vec3(0.0, 0.0, 0.0); }\n if (occAt(mask, sign(c)) < 0.5) { return vec3(0.0, 0.0, 0.0); }\n return g;\n}\n// WHICH of the three faces at this corner is the exposed one the carve fires on \u2014 (0,0,0) if none.\n// At most one can answer (see carveFace() in TS), so this is the corner's whole verdict, and the\n// patch takes its home from it rather than from the table: which face is exposed is something only\n// the mask knows. Mirrors carveFace() in TS.\nfn carveFace(mask: u32, c: vec3<f32>) -> vec3<f32> {\n let fx = vec3(sign(c.x), 0.0, 0.0);\n let fy = vec3(0.0, sign(c.y), 0.0);\n let fz = vec3(0.0, 0.0, sign(c.z));\n if (carveOpen(mask, fx, c) > 0.5) { return fx; }\n if (carveOpen(mask, fy, c) > 0.5) { return fy; }\n if (carveOpen(mask, fz, c) > 0.5) { return fz; }\n return vec3(0.0, 0.0, 0.0);\n}\n// The vertex rule. A vertex's pull along a free axis is INWARD, gated by the CONVEX chamfer (both\n// cells air) or the NOTCH (both solid, diagonal air) \u2014 never both, since they disagree about the\n// home face. See bevelVertex in TS for why nothing here may move a vertex on an EXPOSED face except\n// the convex term: the visible surface is shared with neighbours computing from their own cells, and\n// a one-sided cut tears it.\n// The vertex rule \u2014 see bevelVertex in TS for the full statement of each term.\n\n// HOW MANY VERTICES DOES THIS CUBE ACTUALLY NEED? \u2014 the cull pass's question.\n//\n// buildBevelCube emits in a fixed order: sharp | face fans | bands | facets | fillet | carve | base.\n// So a SMALLER vertexCount drops whole sections off the END, and an instance that provably has no\n// inside corner never has to run the 168 vertices of carve and base. Measured on a terrain\n// heightfield: 45% of exposed cubes need only the face fans, and 9% need all 588.\n//\n// \u26A0\uFE0F THIS MUST NEVER RETURN LESS THAN THE CUBE USES. Too high only wastes work; too low deletes\n// geometry. bevelClass.test.mts checks it against the oracle: for a spread of masks it finds the\n// last triangle with any area and asserts it falls inside the class.\nfn bevelClass(mask: u32, bevel: f32, conc: f32) -> u32 {\n if (mask == 0u || (bevel <= 0.0 && conc <= 0.0)) { return 180u; }\n var anyBase = false;\n var anyCarve = false;\n for (var i = 0u; i < 8u; i++) {\n let c = vec3<f32>(\n select(-0.5, 0.5, (i & 1u) != 0u),\n select(-0.5, 0.5, (i & 2u) != 0u),\n select(-0.5, 0.5, (i & 4u) != 0u));\n if (conc > 0.0 && length(baseOwner(mask, c)) > 0.5) { anyBase = true; }\n if (length(carveFace(mask, c)) > 0.5) { anyCarve = true; }\n }\n if (anyBase) { return 588u; }\n if (anyCarve) { return 492u; }\n var anyFillet = false;\n var anyConvex = false;\n for (var f = 0u; f < 6u; f++) {\n var a = vec3<f32>(0.0, 0.0, 0.0);\n let sgn = select(1.0, -1.0, (f & 1u) != 0u);\n if (f < 2u) { a.x = sgn; } else if (f < 4u) { a.y = sgn; } else { a.z = sgn; }\n for (var g = 0u; g < 6u; g++) {\n var b = vec3<f32>(0.0, 0.0, 0.0);\n let sg2 = select(1.0, -1.0, (g & 1u) != 0u);\n if (g < 2u) { b.x = sg2; } else if (g < 4u) { b.y = sg2; } else { b.z = sg2; }\n if (abs(dot(a, b)) > 0.5) { continue; } // same axis: not an edge\n if (edgeOpen(mask, a, b) > 0.5) { anyConvex = true; }\n if (edgeFillet(mask, a, b) > 0.5) { anyFillet = true; }\n }\n }\n if (anyFillet && conc > 0.0) { return 420u; }\n if (anyConvex && bevel > 0.0) { return 276u; }\n return 180u;\n}\n\n// \u26A0\uFE0F THE SAME STRIDE AS THE DRAW PASSES' Inst, and it has to be kept that way BY HAND \u2014 this is a\n// second declaration of one buffer's layout, not a shared one. The cull pass only reads pos/scl/rot,\n// so a stale copy still compiles and still runs; it just indexes every instance past the first at\n// the wrong offset, and the symptom is cubes winking out of existence at the edge of view rather\n// than anything that looks like a struct mismatch.\nstruct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> };\nstruct Args { vc: u32, ic: atomic<u32>, fv: u32, fi: u32 };\nstruct CullCam {\n planes: array<vec4<f32>, 6>, cnt: vec4<f32>, // cnt.x = instance count\n camVP: mat4x4<f32>, occ: vec4<f32>, // occ.x = occlusion on \u00B7 occ.yz = hiz w,h \u00B7 occ.w = downscale\n lod: vec4<f32>, // x = bucket stride in u32s \u00B7 y = bucketing on \u00B7 z = bevel \u00B7 w = fillet\n};\n@group(0) @binding(0) var<storage, read> insts: array<Inst>;\n@group(0) @binding(1) var<storage, read_write> args: array<Args, 3>;\n@group(0) @binding(2) var<storage, read_write> visible: array<u32>;\n@group(0) @binding(3) var<uniform> cc: CullCam;\n@group(0) @binding(4) var hiz: texture_2d<f32>;\nfn qr(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); }\n@compute @workgroup_size(64)\nfn cull(@builtin(global_invocation_id) gid: vec3<u32>) {\n let i = gid.x;\n if (i >= u32(cc.cnt.x)) { return; }\n let inst = insts[i];\n let c = inst.pos.xyz;\n let h = 0.5 * inst.scl.xyz;\n let bx = qr(inst.rot, vec3<f32>(h.x, 0.0, 0.0)); // rotated box semi-axes\n let by = qr(inst.rot, vec3<f32>(0.0, h.y, 0.0));\n let bz = qr(inst.rot, vec3<f32>(0.0, 0.0, h.z));\n for (var p = 0u; p < 6u; p++) {\n let pl = cc.planes[p];\n let e = abs(dot(pl.xyz, bx)) + abs(dot(pl.xyz, by)) + abs(dot(pl.xyz, bz)); // box half-width along the normal\n if (dot(pl.xyz, c) + pl.w < -e) { return; }\n }\n // \u2500\u2500 Hi-Z occlusion (camera pass only) \u2500\u2500\n if (cc.occ.x > 0.5) {\n var mn = vec2<f32>(1e9, 1e9);\n var mx = vec2<f32>(-1e9, -1e9);\n var nearZ = 1e9;\n var ok = true;\n for (var ci = 0u; ci < 8u; ci++) {\n let s = vec3<f32>(select(-1.0, 1.0, (ci & 1u) != 0u), select(-1.0, 1.0, (ci & 2u) != 0u), select(-1.0, 1.0, (ci & 4u) != 0u));\n let corner = c + bx * s.x + by * s.y + bz * s.z;\n let clip = cc.camVP * vec4<f32>(corner, 1.0);\n if (clip.w <= 0.0) { ok = false; break; } // a corner at/behind the eye \u2192 don't occlusion-cull (keep)\n let ndc = clip.xyz / clip.w;\n let uv = ndc.xy * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5, 0.5);\n mn = min(mn, uv); mx = max(mx, uv);\n nearZ = min(nearZ, ndc.z);\n }\n if (ok && nearZ >= 0.0) {\n let dim = vec2<f32>(cc.occ.y, cc.occ.z);\n let t0 = vec2<i32>(floor(clamp(mn, vec2<f32>(0.0), vec2<f32>(1.0)) * dim));\n let t1 = vec2<i32>(floor(clamp(mx, vec2<f32>(0.0), vec2<f32>(1.0)) * dim));\n // only query a bounded footprint; a huge on-screen box just isn't occlusion-tested (kept)\n if (t1.x - t0.x <= 8 && t1.y - t0.y <= 8) {\n // DILATE the query by 2 Hi-Z texels. hiz is LAST frame's depth; under camera motion a cube reprojects by\n // a few source pixels between frames, so a cube sitting at an occluder's silhouette gets tested against\n // stale NEAR depth from where the occluder used to be and is wrongly culled \u2014 it blinks out for a frame\n // (worst on thin/sparse geometry, but a one-frame hole in dense terrain too). Taking MAX over a dilated\n // footprint is strictly MORE conservative (it can only raise farOccluder \u21D2 only ever KEEP more cubes), so it\n // never hides real geometry; it just leaves a couple of deeply-hidden cubes unculled. 2\u00D78px of slack.\n let lim = vec2<i32>(i32(cc.occ.y) - 1, i32(cc.occ.z) - 1);\n let q0 = max(t0 - vec2<i32>(2, 2), vec2<i32>(0, 0));\n let q1 = min(t1 + vec2<i32>(2, 2), lim);\n var farOccluder = 0.0; // MAX over the footprint of the coarse max-depth\n for (var y = q0.y; y <= q1.y; y++) {\n for (var x = q0.x; x <= q1.x; x++) {\n farOccluder = max(farOccluder, textureLoad(hiz, vec2<i32>(x, y), 0).r);\n }\n }\n if (nearZ > farOccluder) { return; } // behind the farthest occluder everywhere \u2192 occluded\n }\n }\n }\n // \u2500\u2500 vertex-count bucket \u2500\u2500\n // Every surviving cube used to run all 588 vertices, whether its neighbourhood used\n // them or not: one buried in a hillside 300 blocks away paid exactly what one at your feet paid.\n // bevelClass reads the same 27-bit mask the vertex shader does, through the same functions, and\n // says which section the geometry actually stops at. Buckets: 180 / 420 /\n // 588 vertices \u2014 see CULL_BUCKETS.\n //\n // \u26A0\uFE0F ROUNDING UP IS FREE; ROUNDING DOWN DELETES TRIANGLES. bevelClass.test.mts is what holds that.\n var b = 0u;\n if (cc.lod.y > 0.5) {\n let mask = u32(inst.aux2.x) | (u32(inst.aux2.y) << 14u);\n let cls = bevelClass(mask, cc.lod.z, cc.lod.w);\n if (cls > 420u) { b = 2u; } else if (cls > 180u) { b = 1u; }\n }\n let slot = atomicAdd(&args[b].ic, 1u);\n visible[b * u32(cc.lod.x) + slot] = i;\n}\n";
306
360
  export declare const HIZ_WGSL = "\n@group(0) @binding(0) var srcDepth: texture_depth_2d;\n@group(0) @binding(1) var dst: texture_storage_2d<r32float, write>;\nstruct P { dim: vec4<u32> }; // dim.xy = dst size, dim.zw = src size\n@group(0) @binding(2) var<uniform> p: P;\n@compute @workgroup_size(8, 8)\nfn build(@builtin(global_invocation_id) gid: vec3<u32>) {\n if (gid.x >= p.dim.x || gid.y >= p.dim.y) { return; }\n let down = 8u;\n var mx = 0.0;\n for (var dy = 0u; dy < down; dy++) {\n for (var dx = 0u; dx < down; dx++) {\n let sx = gid.x * down + dx; let sy = gid.y * down + dy;\n if (sx < p.dim.z && sy < p.dim.w) { mx = max(mx, textureLoad(srcDepth, vec2<i32>(i32(sx), i32(sy)), 0)); }\n }\n }\n textureStore(dst, vec2<i32>(i32(gid.x), i32(gid.y)), vec4<f32>(mx, 0.0, 0.0, 1.0));\n}\n";
307
361
  export declare const SHADOW_WGSL: string;
308
362
  export declare const MAIN_WGSL: string;
@@ -320,7 +374,6 @@ export declare class GpuShadowRenderer {
320
374
  private shadowPipe;
321
375
  private mainPipe;
322
376
  private shadowBGs;
323
- private mainBG;
324
377
  private shadowBGL;
325
378
  private mainBGL;
326
379
  private shadowSampler;
@@ -376,6 +429,7 @@ export declare class GpuShadowRenderer {
376
429
  private cap;
377
430
  private camArgs;
378
431
  private camVis;
432
+ private mainBGs;
379
433
  private camCull;
380
434
  private camCullBG;
381
435
  private lightArgs;
@@ -399,6 +453,9 @@ export declare class GpuShadowRenderer {
399
453
  private hizReady;
400
454
  private occView;
401
455
  constructor(device: GPUDevice, format: GPUTextureFormat);
456
+ /** Bytes per bucket in a visible-index list: the instance capacity, rounded up to the 256-byte
457
+ * alignment a storage-buffer binding offset requires. */
458
+ private visStride;
402
459
  private makeCullBuf;
403
460
  private cullBG;
404
461
  private makeCullResources;
package/dist/gpuShadow.js CHANGED
@@ -98,7 +98,31 @@ export const BEVEL_VERTS = 36 +
98
98
  8 * 3 * BEVEL_SEG * BEVEL_SEG +
99
99
  144 +
100
100
  8 * 3 * (2 * BEVEL_SEG + 1) +
101
- 8 * 12;
101
+ 8 * 3 * (BEVEL_SEG + 3);
102
+ /**
103
+ * Cumulative section ends, in the order buildBevelCube emits them. A draw with a SMALLER
104
+ * vertexCount stops after a whole section, so these are the only legal truncation points — and the
105
+ * cull pass picks one per instance (see `bevelClass` in MASK_WGSL).
106
+ *
107
+ * ⚠️ DERIVED FROM THE SAME TERMS AS BEVEL_VERTS ON PURPOSE. Written as literals they would be right
108
+ * at BEVEL_SEG = 1 and quietly wrong above it, and "quietly wrong" here means a draw that stops in
109
+ * the middle of a section and takes a third of a triangle with it.
110
+ */
111
+ /**
112
+ * How many vertex-count buckets the camera pass draws, and what each one draws.
113
+ *
114
+ * Three rather than one per class: on a terrain heightfield the five classes fall out 45.1 / 1.0 /
115
+ * 37.0 / 7.5 / 9.4 %, so collapsing 276→420 and 492→588 costs 1.5% of the saving and halves the
116
+ * draws and the memory. A bucket always draws AT LEAST what its instances need.
117
+ */
118
+ export const CULL_BUCKETS = 3;
119
+ export const SEC_SHARP = 36;
120
+ export const SEC_FANS = SEC_SHARP + 144;
121
+ export const SEC_BANDS = SEC_FANS + 12 * 6 * BEVEL_SEG;
122
+ export const SEC_FACETS = SEC_BANDS + 8 * 3 * BEVEL_SEG * BEVEL_SEG;
123
+ export const SEC_FILLET = SEC_FACETS + 144;
124
+ export const SEC_CARVE = SEC_FILLET + 8 * 3 * (2 * BEVEL_SEG + 1);
125
+ export const SEC_BASE = BEVEL_VERTS;
102
126
  /** What a vertex is, which decides how it is allowed to move. */
103
127
  export const ROLE_SHARP = 0; // one of the 36 plain quad vertices — only alive when bevel == 0
104
128
  export const ROLE_CENTER = 1; // a face fan's hub; never moves
@@ -432,7 +456,9 @@ function buildBevelCube() {
432
456
  for (const sz of [-0.5, 0.5]) {
433
457
  const c = [sx, sy, sz];
434
458
  const hp = [Math.sign(sx), 0, 0]; // placeholder; the shader resolves it from the mask
435
- for (let i = 1; i <= 4; i++)
459
+ // A fan over 5 + BEVEL_SEG points: the two feet, the two crests, and BEVEL_SEG + 1 along the
460
+ // block's chamfer arc between them. At BEVEL_SEG = 1 that is the original six.
461
+ for (let i = 1; i <= BEVEL_SEG + 3; i++)
436
462
  for (const q of [0, i, i + 1])
437
463
  push([...c], hp, ROLE_BASE, [q, 0, 0]);
438
464
  }
@@ -761,6 +787,68 @@ export function carveFace(mask, corner) {
761
787
  }
762
788
  return null;
763
789
  }
790
+ /**
791
+ * How many of the cube's `BEVEL_VERTS` vertices does this neighbourhood actually use?
792
+ *
793
+ * The sections are emitted in a fixed order — sharp | face fans | bands | facets | fillet | carve |
794
+ * base — so a draw with a smaller vertexCount drops whole sections off the END. Every visible cube
795
+ * used to run all 588 regardless: one buried in a hillside 300 blocks away paid exactly what one at
796
+ * your feet paid. On a terrain heightfield 45% of exposed cubes need only the face fans and 9% need
797
+ * everything, so classifying per instance in the CULL pass cuts total vertex work by ~42%.
798
+ *
799
+ * ⚠️ TOO HIGH ONLY WASTES WORK; TOO LOW DELETES GEOMETRY. That asymmetry is the whole risk here, and
800
+ * `bevelClass.test.mts` is what holds it: for a spread of masks it finds the last triangle with any
801
+ * area and asserts it falls inside the class this returns.
802
+ *
803
+ * ⚠️ MIRRORED BY `bevelClass()` IN MASK_WGSL — which is the SAME SOURCE, included into both the draw
804
+ * and cull shaders, precisely so there is no third copy to drift. This TypeScript one exists to be
805
+ * testable against the oracle.
806
+ */
807
+ export function bevelClass(mask, bevel, concave) {
808
+ if (mask === 0 || (bevel <= 0 && concave <= 0))
809
+ return SEC_FANS;
810
+ const corners = [];
811
+ for (const x of [-0.5, 0.5])
812
+ for (const y of [-0.5, 0.5])
813
+ for (const z of [-0.5, 0.5])
814
+ corners.push([x, y, z]);
815
+ let anyBase = false;
816
+ let anyCarve = false;
817
+ for (const c of corners) {
818
+ if (concave > 0 && baseOwner(mask, c) !== null)
819
+ anyBase = true;
820
+ if (carveFace(mask, c) !== null)
821
+ anyCarve = true;
822
+ }
823
+ if (anyBase)
824
+ return SEC_BASE;
825
+ if (anyCarve)
826
+ return SEC_CARVE;
827
+ const ax = [
828
+ [1, 0, 0],
829
+ [-1, 0, 0],
830
+ [0, 1, 0],
831
+ [0, -1, 0],
832
+ [0, 0, 1],
833
+ [0, 0, -1],
834
+ ];
835
+ let anyFillet = false;
836
+ let anyConvex = false;
837
+ for (const a of ax)
838
+ for (const b of ax) {
839
+ if (Math.abs(a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) > 0.5)
840
+ continue;
841
+ if (edgeOpen(mask, a, b) > 0.5)
842
+ anyConvex = true;
843
+ if (edgeFillet(mask, a, b) > 0.5)
844
+ anyFillet = true;
845
+ }
846
+ if (anyFillet && concave > 0)
847
+ return SEC_FILLET;
848
+ if (anyConvex && bevel > 0)
849
+ return SEC_FACETS;
850
+ return SEC_FANS;
851
+ }
764
852
  // THE RIM TURN IS GONE, AND ITS ABSENCE IS THE POINT. rimTurn() clipped a face's corner and grew a
765
853
  // one-axis facet wherever a surface had an L-shaped bite taken out of it — a pit's rim turning a
766
854
  // corner. That configuration is a CONCAVE corner, and concave corners are now FILLED rather than
@@ -892,16 +980,28 @@ concave = bevel) {
892
980
  ];
893
981
  if (cr[0] * h[0] + cr[1] * h[1] + cr[2] * h[2] < 0)
894
982
  [fa, fb] = [fb, fa];
895
- // (along fa, along fb, along h) per point — see section 7
896
- const T = [
897
- [0, concave, 0],
898
- [-bevel, concave / 2, concave / 2],
899
- [-bevel, 0, concave],
900
- [0, -bevel, concave],
901
- [concave / 2, -bevel, concave / 2],
902
- [concave, 0, 0],
903
- ];
904
- const t = T[Math.round(axis[0])];
983
+ // (along fa, along fb, along h) per point — see section 7.
984
+ // ⚠️ POINTS 2..2+BEVEL_SEG RIDE THE BLOCK'S CHAMFER ARC, they are not two ends of a chord. That
985
+ // side of the patch IS the block's vertical-edge band, at height conc above the surface: same
986
+ // circle, radius bevel, centred where both horizontal axes have pulled in by bevel. At
987
+ // BEVEL_SEG = 1 the arc has two points and this is byte for byte the old six-point patch; above
988
+ // it the band has BEVEL_SEG + 1 and the patch must carry every one of them or the two stop
989
+ // pairing — a block standing on a plane opened 8 band edges and 4 base edges at BEVEL_SEG = 2,
990
+ // and that corner is the one this patch exists for.
991
+ const i0 = Math.round(axis[0]);
992
+ let t;
993
+ if (i0 === 0)
994
+ t = [0, concave, 0];
995
+ else if (i0 === 1)
996
+ t = [-bevel, concave / 2, concave / 2];
997
+ else if (i0 <= 2 + BEVEL_SEG) {
998
+ const th = ((i0 - 2) / BEVEL_SEG) * (Math.PI / 2);
999
+ t = [bevel * (Math.sin(th) - 1), bevel * (Math.cos(th) - 1), concave];
1000
+ }
1001
+ else if (i0 === 3 + BEVEL_SEG)
1002
+ t = [concave / 2, -bevel, concave / 2];
1003
+ else
1004
+ t = [concave, 0, 0];
905
1005
  for (let i = 0; i < 3; i++)
906
1006
  out[i] += fa[i] * t[0] + fb[i] * t[1] + h[i] * t[2];
907
1007
  return out;
@@ -1091,7 +1191,7 @@ concave = bevel) {
1091
1191
  // HAND, and for the whole life of this file nothing checked that they agree — every closure and
1092
1192
  // intersection number came from the TS side, so the shader could drift arbitrarily and the suite
1093
1193
  // stayed green. bevelParity.spec.ts runs THIS source on a real GPU and diffs it against the TS.
1094
- export const COMMON_WGSL = /* wgsl */ `
1194
+ const COMMON_HEAD_WGSL = /* wgsl */ `
1095
1195
  struct Cam {
1096
1196
  camVP: mat4x4<f32>,
1097
1197
  lightVP: array<mat4x4<f32>, ${MAX_CASCADES}>, // CASCADES, tightest first. A 1-cascade caller uses only [0].
@@ -1131,6 +1231,19 @@ fn worldOf(inst: Inst, vi: u32) -> vec3<f32> { return inst.pos.xyz + qrot(inst.r
1131
1231
  // (three bit tests per vertex, then the rasterizer interpolates for free), and it can only ever
1132
1232
  // touch geometry whose caller supplied a mask.
1133
1233
  //
1234
+ `;
1235
+ /**
1236
+ * The 27-bit-mask predicates, shared VERBATIM by the draw passes and the CULL pass.
1237
+ *
1238
+ * ⚠️ EXTRACTED SO THE CULL PASS CAN ASK THE SAME QUESTIONS THE VERTEX SHADER DOES. bevelClass()
1239
+ * decides how many vertices an instance is drawn with; if it ever disagreed with what bevelPos()
1240
+ * produces, the cube would silently lose geometry and the terrain would grow holes. It cannot
1241
+ * disagree if it is calling these same functions rather than a third hand-written copy — this file
1242
+ * has already paid for hand-mirroring twice (bevelVertex/bevelPos, and baseAt's far==0).
1243
+ *
1244
+ * Pure: no bindings, no textures, so it can be prepended to any shader.
1245
+ */
1246
+ export const MASK_WGSL = /* wgsl */ `
1134
1247
  // occAt reads one neighbour out of the 27-bit mask; the index is the same
1135
1248
  // (dx+1) + (dy+1)*3 + (dz+1)*9 the caller packed with.
1136
1249
  fn occAt(mask: u32, o: vec3<f32>) -> f32 {
@@ -1233,7 +1346,14 @@ fn baseAt(mask: u32, c: vec3<f32>) -> vec3<f32> {
1233
1346
  let far = occAt(mask, hk) + occAt(mask, hk + u1) + occAt(mask, hk + u2) + occAt(mask, hk + u1 + u2);
1234
1347
  let near = 1.0 + occAt(mask, u1) + occAt(mask, u2) + occAt(mask, u1 + u2);
1235
1348
  if (far > 3.5 && near < 1.5) { return hk; }
1236
- if (near > 3.5 && far < 1.5) { return -hk; }
1349
+ // ⚠️ far MUST BE EXACTLY ONE, AND THE LOWER BOUND IS WHAT WAS MISSING. near == 4 says this cube
1350
+ // sits in a flat surface; far == 1 says exactly one cell above it is solid — the block whose base
1351
+ // this corner is. far == 0 means nothing is standing there at all, so there is no base corner and
1352
+ // no patch, but the test read only "far < 1.5" and answered yes. Ordinary flat ground therefore
1353
+ // claimed a base corner, and its fillet crest retreated a full bevel into a notch.
1354
+ // TS baseAt() has always required far === 1; this is the half that drifted, and only
1355
+ // tools/bevelParity.mjs could see it — 894 cases, all ROLE_FMID.
1356
+ if (near > 3.5 && far > 0.5 && far < 1.5) { return -hk; }
1237
1357
  }
1238
1358
  return vec3(0.0, 0.0, 0.0);
1239
1359
  }
@@ -1265,6 +1385,52 @@ fn carveFace(mask: u32, c: vec3<f32>) -> vec3<f32> {
1265
1385
  // the convex term: the visible surface is shared with neighbours computing from their own cells, and
1266
1386
  // a one-sided cut tears it.
1267
1387
  // The vertex rule — see bevelVertex in TS for the full statement of each term.
1388
+
1389
+ // HOW MANY VERTICES DOES THIS CUBE ACTUALLY NEED? — the cull pass's question.
1390
+ //
1391
+ // buildBevelCube emits in a fixed order: sharp | face fans | bands | facets | fillet | carve | base.
1392
+ // So a SMALLER vertexCount drops whole sections off the END, and an instance that provably has no
1393
+ // inside corner never has to run the 168 vertices of carve and base. Measured on a terrain
1394
+ // heightfield: 45% of exposed cubes need only the face fans, and 9% need all 588.
1395
+ //
1396
+ // ⚠️ THIS MUST NEVER RETURN LESS THAN THE CUBE USES. Too high only wastes work; too low deletes
1397
+ // geometry. bevelClass.test.mts checks it against the oracle: for a spread of masks it finds the
1398
+ // last triangle with any area and asserts it falls inside the class.
1399
+ fn bevelClass(mask: u32, bevel: f32, conc: f32) -> u32 {
1400
+ if (mask == 0u || (bevel <= 0.0 && conc <= 0.0)) { return ${SEC_FANS}u; }
1401
+ var anyBase = false;
1402
+ var anyCarve = false;
1403
+ for (var i = 0u; i < 8u; i++) {
1404
+ let c = vec3<f32>(
1405
+ select(-0.5, 0.5, (i & 1u) != 0u),
1406
+ select(-0.5, 0.5, (i & 2u) != 0u),
1407
+ select(-0.5, 0.5, (i & 4u) != 0u));
1408
+ if (conc > 0.0 && length(baseOwner(mask, c)) > 0.5) { anyBase = true; }
1409
+ if (length(carveFace(mask, c)) > 0.5) { anyCarve = true; }
1410
+ }
1411
+ if (anyBase) { return ${SEC_BASE}u; }
1412
+ if (anyCarve) { return ${SEC_CARVE}u; }
1413
+ var anyFillet = false;
1414
+ var anyConvex = false;
1415
+ for (var f = 0u; f < 6u; f++) {
1416
+ var a = vec3<f32>(0.0, 0.0, 0.0);
1417
+ let sgn = select(1.0, -1.0, (f & 1u) != 0u);
1418
+ if (f < 2u) { a.x = sgn; } else if (f < 4u) { a.y = sgn; } else { a.z = sgn; }
1419
+ for (var g = 0u; g < 6u; g++) {
1420
+ var b = vec3<f32>(0.0, 0.0, 0.0);
1421
+ let sg2 = select(1.0, -1.0, (g & 1u) != 0u);
1422
+ if (g < 2u) { b.x = sg2; } else if (g < 4u) { b.y = sg2; } else { b.z = sg2; }
1423
+ if (abs(dot(a, b)) > 0.5) { continue; } // same axis: not an edge
1424
+ if (edgeOpen(mask, a, b) > 0.5) { anyConvex = true; }
1425
+ if (edgeFillet(mask, a, b) > 0.5) { anyFillet = true; }
1426
+ }
1427
+ }
1428
+ if (anyFillet && conc > 0.0) { return ${SEC_FILLET}u; }
1429
+ if (anyConvex && bevel > 0.0) { return ${SEC_FACETS}u; }
1430
+ return ${SEC_FANS}u;
1431
+ }
1432
+ `;
1433
+ const COMMON_TAIL_WGSL = /* wgsl */ `
1268
1434
  fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32, role: f32, ax: vec3<f32>, conc: f32) -> vec3<f32> {
1269
1435
  if (role == ${ROLE_SHARP}.0) { return select(c, vec3(0.0, 0.0, 0.0), bevel > 0.0 || conc > 0.0); }
1270
1436
  if (role == ${ROLE_CENTER}.0 || (bevel <= 0.0 && conc <= 0.0) || mask == 0u) { return c; }
@@ -1314,13 +1480,17 @@ fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32, role: f32, ax: ve
1314
1480
  var fa = e1;
1315
1481
  var fb = e2;
1316
1482
  if (dot(cross(e1, e2), hb) < 0.0) { fa = e2; fb = e1; }
1483
+ // Points 2..2+BEVEL_SEG ride the block's chamfer arc — see bevelVertex in TS for why a chord
1484
+ // there stops pairing with the band as soon as the band is subdivided.
1317
1485
  var t = vec3(0.0, 0.0, 0.0);
1318
1486
  let i = i32(ax.x + 0.5);
1319
1487
  if (i == 0) { t = vec3(0.0, conc, 0.0); }
1320
1488
  else if (i == 1) { t = vec3(-bevel, conc * 0.5, conc * 0.5); }
1321
- else if (i == 2) { t = vec3(-bevel, 0.0, conc); }
1322
- else if (i == 3) { t = vec3(0.0, -bevel, conc); }
1323
- else if (i == 4) { t = vec3(conc * 0.5, -bevel, conc * 0.5); }
1489
+ else if (i <= ${2 + BEVEL_SEG}) {
1490
+ let th = (f32(i - 2) / ${BEVEL_SEG}.0) * 1.5707963267948966;
1491
+ t = vec3(bevel * (sin(th) - 1.0), bevel * (cos(th) - 1.0), conc);
1492
+ }
1493
+ else if (i == ${3 + BEVEL_SEG}) { t = vec3(conc * 0.5, -bevel, conc * 0.5); }
1324
1494
  else { t = vec3(conc, 0.0, 0.0); }
1325
1495
  return c + fa * t.x + fb * t.y + hb * t.z;
1326
1496
  }
@@ -1367,6 +1537,27 @@ fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32, role: f32, ax: ve
1367
1537
  }
1368
1538
  let free = vec3(1.0, 1.0, 1.0) - abs(a);
1369
1539
  let s = sign(c);
1540
+ // ⚠️ HOISTED OUT OF THE k LOOP BECAUSE THEY DO NOT DEPEND ON k. carveOpen, carveCorner, baseAt and
1541
+ // baseOwner read only (mask, a, c) — all loop-invariant — but they were called inside the loop, so
1542
+ // a rim vertex that clips on both of its in-plane axes ran each of them TWICE. They are also the
1543
+ // most expensive thing in the file: each walks 8–27 neighbours of the 27-bit mask through branchy
1544
+ // per-axis loops. Measured with tools/bevelBench.mjs, face-fan (RIM) vertices cost 0.97 ns each
1545
+ // against 0.11 for a band vertex, and there are 144 of them on every cube — 29% of the whole
1546
+ // bevel's GPU time in one section.
1547
+ //
1548
+ // The gate is "will ANY iteration ask for it", so this never computes something the loop would
1549
+ // not have: the loop's own guard is abs(axk) > 0.5 on a free axis, hence dot(abs(ax), free).
1550
+ let axFree = dot(abs(ax), free);
1551
+ var rimOpen = 0.0;
1552
+ var rimCorner = vec3(0.0, 0.0, 0.0);
1553
+ var rimBase = vec3(0.0, 0.0, 0.0);
1554
+ if (role == ${ROLE_RIM}.0 && axFree > 0.5) {
1555
+ rimOpen = carveOpen(mask, a, c);
1556
+ rimCorner = carveCorner(mask, c);
1557
+ if (occAt(mask, a) < 0.5) { rimBase = baseOwner(mask, c); }
1558
+ }
1559
+ var fmidBase = vec3(0.0, 0.0, 0.0);
1560
+ if (role == ${ROLE_FMID}.0) { fmidBase = baseAt(mask, c); }
1370
1561
  var d = vec3(0.0, 0.0, 0.0);
1371
1562
  for (var k = 0; k < 3; k = k + 1) {
1372
1563
  var e = vec3(0.0, 0.0, 0.0);
@@ -1405,12 +1596,12 @@ fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32, role: f32, ax: ve
1405
1596
  // because each rim point retreats along its OWN axis to exactly where the neighbour on that
1406
1597
  // side has already put its own rim. Stands or falls with ROLE_CARVE — gate one and you must
1407
1598
  // gate the other. See bevelVertex in TS for why the axis gate is load-bearing.
1408
- pull = max(pull, carveOpen(mask, a, c));
1599
+ pull = max(pull, rimOpen);
1409
1600
  // AND THE BURIED SIDE FACES RETREAT TOO, OR THEY COVER THE PATCH — a face that keeps its square
1410
1601
  // corner at a carved corner leaves a thin sheet standing in the air the carve opened, in front
1411
1602
  // of the geometry the carve exists to show. The clip is the patch's own edge, which lies in
1412
1603
  // this face's plane. See bevelVertex in TS.
1413
- let cc = carveCorner(mask, c);
1604
+ let cc = rimCorner;
1414
1605
  if (length(cc) > 0.5 && occAt(mask, a) > 0.5 && abs(dot(a, cc)) < 0.5) {
1415
1606
  var p2 = 1.0;
1416
1607
  if (abs(dot(e, cc)) > 0.5) { p2 = bevel / (bevel + conc); }
@@ -1420,7 +1611,7 @@ fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32, role: f32, ax: ve
1420
1611
  // A FILLET CREST RETREATS AT A BASE CORNER AND ITS FOOT DOES NOT — the crest is the one line the
1421
1612
  // fillet's two halves share, and they otherwise end at different places along it. See TS.
1422
1613
  if (role == ${ROLE_FMID}.0 && abs(dot(e, ax)) < 0.5) {
1423
- let gb = baseAt(mask, c);
1614
+ let gb = fmidBase;
1424
1615
  if (length(gb) > 0.5 && abs(dot(e, gb)) < 0.5) { pull = max(pull, 1.0); }
1425
1616
  }
1426
1617
  // Max across the radii too: a face gives up its ground ONCE — see bevelVertex in TS.
@@ -1430,7 +1621,7 @@ fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32, role: f32, ax: ve
1430
1621
  // AND THE FLAT SURFACE GIVES UP ITS CORNER, by the CONCAVE radius, on the cell diagonally under
1431
1622
  // the block — the patch's one new side. One axis each. See bevelVertex in TS.
1432
1623
  if (role == ${ROLE_RIM}.0 && abs(axk) > 0.5 && occAt(mask, a) < 0.5) {
1433
- let gb = baseOwner(mask, c);
1624
+ let gb = rimBase;
1434
1625
  if (length(gb) > 0.5 && dot(a, gb) < -0.5) { fp = max(fp, conc); }
1435
1626
  }
1436
1627
  d = d + e * max(pull * bevel, fp);
@@ -1494,7 +1685,9 @@ fn hsv(hh: f32) -> vec3<f32> {
1494
1685
  // the larger region only ever raises the occluder distance, so it strictly keeps more cubes and never hides real
1495
1686
  // geometry. occ.x toggles it (camera pass only; the shadow pass never occludes — an off-screen occluder still
1496
1687
  // casts a shadow into view). occ.yz = hiz dims, occ.w = pixels/texel.
1688
+ export const COMMON_WGSL = COMMON_HEAD_WGSL + MASK_WGSL + COMMON_TAIL_WGSL;
1497
1689
  export const CULL_WGSL = /* wgsl */ `
1690
+ ${MASK_WGSL}
1498
1691
  // ⚠️ THE SAME STRIDE AS THE DRAW PASSES' Inst, and it has to be kept that way BY HAND — this is a
1499
1692
  // second declaration of one buffer's layout, not a shared one. The cull pass only reads pos/scl/rot,
1500
1693
  // so a stale copy still compiles and still runs; it just indexes every instance past the first at
@@ -1505,9 +1698,10 @@ struct Args { vc: u32, ic: atomic<u32>, fv: u32, fi: u32 };
1505
1698
  struct CullCam {
1506
1699
  planes: array<vec4<f32>, 6>, cnt: vec4<f32>, // cnt.x = instance count
1507
1700
  camVP: mat4x4<f32>, occ: vec4<f32>, // occ.x = occlusion on · occ.yz = hiz w,h · occ.w = downscale
1701
+ lod: vec4<f32>, // x = bucket stride in u32s · y = bucketing on · z = bevel · w = fillet
1508
1702
  };
1509
1703
  @group(0) @binding(0) var<storage, read> insts: array<Inst>;
1510
- @group(0) @binding(1) var<storage, read_write> args: Args;
1704
+ @group(0) @binding(1) var<storage, read_write> args: array<Args, ${CULL_BUCKETS}>;
1511
1705
  @group(0) @binding(2) var<storage, read_write> visible: array<u32>;
1512
1706
  @group(0) @binding(3) var<uniform> cc: CullCam;
1513
1707
  @group(0) @binding(4) var hiz: texture_2d<f32>;
@@ -1568,8 +1762,22 @@ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
1568
1762
  }
1569
1763
  }
1570
1764
  }
1571
- let slot = atomicAdd(&args.ic, 1u);
1572
- visible[slot] = i;
1765
+ // ── vertex-count bucket ──
1766
+ // Every surviving cube used to run all ${BEVEL_VERTS} vertices, whether its neighbourhood used
1767
+ // them or not: one buried in a hillside 300 blocks away paid exactly what one at your feet paid.
1768
+ // bevelClass reads the same 27-bit mask the vertex shader does, through the same functions, and
1769
+ // says which section the geometry actually stops at. Buckets: ${SEC_FANS} / ${SEC_FILLET} /
1770
+ // ${BEVEL_VERTS} vertices — see CULL_BUCKETS.
1771
+ //
1772
+ // ⚠️ ROUNDING UP IS FREE; ROUNDING DOWN DELETES TRIANGLES. bevelClass.test.mts is what holds that.
1773
+ var b = 0u;
1774
+ if (cc.lod.y > 0.5) {
1775
+ let mask = u32(inst.aux2.x) | (u32(inst.aux2.y) << 14u);
1776
+ let cls = bevelClass(mask, cc.lod.z, cc.lod.w);
1777
+ if (cls > ${SEC_FILLET}u) { b = 2u; } else if (cls > ${SEC_FANS}u) { b = 1u; }
1778
+ }
1779
+ let slot = atomicAdd(&args[b].ic, 1u);
1780
+ visible[b * u32(cc.lod.x) + slot] = i;
1573
1781
  }
1574
1782
  `;
1575
1783
  // Hi-Z BUILD: max-reduce the previous frame's depth (a sampleable depth texture) into a coarse R32float buffer —
@@ -1657,15 +1865,21 @@ fn faceVec(code: f32) -> vec3<f32> {
1657
1865
  // every notch corner, which is the "doesn't match the surrounding textures" report all over again.
1658
1866
  // All three vertices resolve the SAME face, so objN stays flat and the patch keeps one tile.
1659
1867
  var home = BEV_HOME[vi];
1868
+ // ⚠️ RESOLVED ONCE, USED TWICE. Both of these are needed again further down for the SHADING
1869
+ // normal, and each walks up to 27 neighbours of the mask through branchy per-axis loops — the
1870
+ // most expensive thing this shader does. Computing them a second time down there cost the carve
1871
+ // and base sections about a third of their time (tools/bevelBench.mjs).
1872
+ var cf = vec3(0.0, 0.0, 0.0);
1873
+ var gb = vec3(0.0, 0.0, 0.0);
1874
+ if (BEV_ROLE[vi] == ${ROLE_CARVE}.0) { cf = carveFace(mask, sharp); }
1875
+ if (BEV_ROLE[vi] == ${ROLE_BASE}.0) { gb = baseOwner(mask, sharp); }
1660
1876
  if (BEV_ROLE[vi] == ${ROLE_CARVE}.0) {
1661
- let cf = carveFace(mask, sharp);
1662
1877
  if (length(cf) > 0.5) { home = cf; }
1663
1878
  }
1664
1879
  // ⚠️ AND THE BASE PATCH TOO. It belongs to the FLAT SURFACE it grows out of, whose outward normal
1665
1880
  // is -g, and the table cannot know which axis that is. Left as the placeholder it shipped as black
1666
1881
  // wedges once already.
1667
1882
  if (BEV_ROLE[vi] == ${ROLE_BASE}.0) {
1668
- let gb = baseOwner(mask, sharp);
1669
1883
  if (length(gb) > 0.5) { home = -gb; } // the TEXTURE is the flat surface's; the NORMAL is below
1670
1884
  }
1671
1885
 
@@ -1702,7 +1916,7 @@ fn faceVec(code: f32) -> vec3<f32> {
1702
1916
  // pipeline never built and the screen went black. bevelParity.spec.ts could not see it: it
1703
1917
  // compiles COMMON_WGSL into a COMPUTE shader and never builds the vertex stage at all.
1704
1918
  if (BEV_ROLE[vi] == ${ROLE_BASE}.0) {
1705
- let gb2 = baseOwner(mask, sharp);
1919
+ let gb2 = gb; // resolved once at the top; see there
1706
1920
  if (length(gb2) > 0.5) {
1707
1921
  let hb = -gb2;
1708
1922
  let ipb = -sign(sharp) * (vec3(1.0, 1.0, 1.0) - abs(gb2));
@@ -1714,11 +1928,15 @@ fn faceVec(code: f32) -> vec3<f32> {
1714
1928
  var fa2 = b1;
1715
1929
  var fb2 = b2;
1716
1930
  if (dot(cross(b1, b2), hb) < 0.0) { fa2 = b2; fb2 = b1; }
1931
+ // The arc points sweep their normal from one wall to the other, exactly as the band they meet
1932
+ // does — a chord's two end normals across a subdivided arc is the flat-shaded facet again.
1717
1933
  let ib = i32(BEV_AXIS[vi].x + 0.5);
1718
1934
  if (ib == 1) { shade = normalize(hb + fb2); }
1719
- else if (ib == 2) { shade = fb2; }
1720
- else if (ib == 3) { shade = fa2; }
1721
- else if (ib == 4) { shade = normalize(hb + fa2); }
1935
+ else if (ib >= 2 && ib <= ${2 + BEVEL_SEG}) {
1936
+ let tb = (f32(ib - 2) / ${BEVEL_SEG}.0) * 1.5707963267948966;
1937
+ shade = normalize(fb2 * cos(tb) + fa2 * sin(tb));
1938
+ }
1939
+ else if (ib == ${3 + BEVEL_SEG}) { shade = normalize(hb + fa2); }
1722
1940
  else { shade = hb; }
1723
1941
  }
1724
1942
  }
@@ -1748,8 +1966,7 @@ fn faceVec(code: f32) -> vec3<f32> {
1748
1966
  // neighbours: the two on the exposed face take that face; the two band ends take the side face
1749
1967
  // their band grows from; the crest takes the bisector, which is what the fillet's own crest uses.
1750
1968
  if (BEV_ROLE[vi] == ${ROLE_CARVE}.0) {
1751
- let cf = carveFace(mask, sharp);
1752
- if (length(cf) > 0.5) {
1969
+ if (length(cf) > 0.5) { // resolved once at the top; see there
1753
1970
  let ipc = sign(sharp) * (vec3(1.0, 1.0, 1.0) - abs(cf));
1754
1971
  var e1 = vec3(0.0, 0.0, 0.0);
1755
1972
  var e2 = vec3(0.0, 0.0, 0.0);
@@ -2108,7 +2325,6 @@ export class GpuShadowRenderer {
2108
2325
  shadowPipe;
2109
2326
  mainPipe;
2110
2327
  shadowBGs = [];
2111
- mainBG;
2112
2328
  shadowBGL;
2113
2329
  mainBGL;
2114
2330
  shadowSampler;
@@ -2166,6 +2382,7 @@ export class GpuShadowRenderer {
2166
2382
  cap = 0;
2167
2383
  camArgs;
2168
2384
  camVis;
2385
+ mainBGs = [];
2169
2386
  camCull;
2170
2387
  camCullBG;
2171
2388
  lightArgs = [];
@@ -2451,25 +2668,33 @@ export class GpuShadowRenderer {
2451
2668
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
2452
2669
  });
2453
2670
  }
2671
+ /** Bytes per bucket in a visible-index list: the instance capacity, rounded up to the 256-byte
2672
+ * alignment a storage-buffer binding offset requires. */
2673
+ visStride() {
2674
+ return Math.ceil((Math.max(1, this.cap) * 4) / 256) * 256;
2675
+ }
2454
2676
  // One frustum's cull resources: indirect args (drawIndirect), a compacted visible-index list sized to the
2455
2677
  // instance capacity, and a uniform holding the 6 planes + instance count + camVP + occlusion params.
2456
2678
  makeCullBuf() {
2457
2679
  const d = this.device;
2458
2680
  const args = d.createBuffer({
2459
- size: 4 * 4,
2681
+ size: 4 * 4 * CULL_BUCKETS,
2460
2682
  usage: GPUBufferUsage.STORAGE |
2461
2683
  GPUBufferUsage.INDIRECT |
2462
2684
  GPUBufferUsage.COPY_DST |
2463
2685
  GPUBufferUsage.COPY_SRC,
2464
2686
  });
2687
+ // ⚠️ EACH BUCKET GETS A 256-BYTE-ALIGNED SLICE OF ONE BUFFER, because a storage buffer BINDING
2688
+ // offset must be 256-aligned and the draw passes bind one slice at a time. Packing the buckets
2689
+ // back to back at cap*4 would fail bind-group validation the moment cap is not a multiple of 64.
2465
2690
  const vis = d.createBuffer({
2466
- size: Math.max(1, this.cap) * 4,
2691
+ size: this.visStride() * CULL_BUCKETS,
2467
2692
  usage: GPUBufferUsage.STORAGE,
2468
2693
  });
2469
2694
  const cull = d.createBuffer({
2470
- size: 6 * 16 + 16 + 64 + 16,
2695
+ size: 6 * 16 + 16 + 64 + 16 + 16,
2471
2696
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
2472
- }); // planes+cnt+camVP+occ = 192
2697
+ }); // planes+cnt+camVP+occ+lod = 208
2473
2698
  return { args, vis, cull };
2474
2699
  }
2475
2700
  cullBG(args, vis, cull) {
@@ -2504,7 +2729,7 @@ export class GpuShadowRenderer {
2504
2729
  this.camCullBG = this.cullBG(this.camArgs, this.camVis, this.camCull);
2505
2730
  this.lightCullBG = this.lightArgs.map((a, i) => this.cullBG(a, this.lightVis[i], this.lightCull[i]));
2506
2731
  this.statsBuf = this.device.createBuffer({
2507
- size: 4 * 4 * 2,
2732
+ size: 4 * 4 * (CULL_BUCKETS + 1),
2508
2733
  usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
2509
2734
  });
2510
2735
  }
@@ -2612,21 +2837,28 @@ export class GpuShadowRenderer {
2612
2837
  { binding: 2, resource: { buffer: vis } },
2613
2838
  ],
2614
2839
  }));
2615
- this.mainBG = this.device.createBindGroup({
2840
+ // One per vertex-count bucket: identical except for the slice of the visible list at binding 4.
2841
+ // The pass sets the matching group before each drawIndirect, so vis[instance_index] indexes
2842
+ // from 0 within the bucket and no `indirect-first-instance` feature is needed.
2843
+ const stride = this.visStride();
2844
+ this.mainBGs = Array.from({ length: CULL_BUCKETS }, (_, b) => this.device.createBindGroup({
2616
2845
  layout: this.mainBGL,
2617
2846
  entries: [
2618
2847
  { binding: 0, resource: { buffer: this.camBuf } },
2619
2848
  { binding: 1, resource: { buffer: this.instBuf } },
2620
2849
  { binding: 2, resource: this.shadowArrayView },
2621
2850
  { binding: 3, resource: this.shadowSampler },
2622
- { binding: 4, resource: { buffer: this.camVis } },
2851
+ {
2852
+ binding: 4,
2853
+ resource: { buffer: this.camVis, offset: b * stride, size: stride },
2854
+ },
2623
2855
  { binding: 5, resource: this.atlasView },
2624
2856
  { binding: 6, resource: this.atlasSampler },
2625
2857
  { binding: 7, resource: { buffer: this.tileLayerBuf } },
2626
2858
  { binding: 8, resource: { buffer: this.giGridBuf } },
2627
2859
  { binding: 9, resource: { buffer: this.giProbeBuf } },
2628
2860
  ],
2629
- });
2861
+ }));
2630
2862
  }
2631
2863
  /** Bind a block-texture ARRAY + its material→layer map. Each material's top/side/bottom faces sample
2632
2864
  * distinct array layers; a `CubeInstance.tile` of that material id + its `up`-face code selects the
@@ -2723,7 +2955,10 @@ export class GpuShadowRenderer {
2723
2955
  this.fill(this.scratch, instances, this.count);
2724
2956
  this.sceneReady = true;
2725
2957
  this.instBuf = this.device.createBuffer({
2726
- size: this.scratch.byteLength,
2958
+ // ⚠️ NEVER ZERO. An empty scene — startup, a chunk that unloaded, a caller clearing before a
2959
+ // rebuild — is a legal state, but a zero-sized storage buffer fails bind-group creation
2960
+ // outright ("Binding size for [Buffer] is zero"), and every later frame then draws nothing.
2961
+ size: Math.max(INST_F * 4, this.scratch.byteLength),
2727
2962
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
2728
2963
  });
2729
2964
  this.device.queue.writeBuffer(this.instBuf, 0, this.scratch);
@@ -2735,7 +2970,10 @@ export class GpuShadowRenderer {
2735
2970
  this.scratch = new Float32Array(cap * INST_F);
2736
2971
  this.sceneReady = true;
2737
2972
  this.instBuf = this.device.createBuffer({
2738
- size: this.scratch.byteLength,
2973
+ // ⚠️ NEVER ZERO. An empty scene — startup, a chunk that unloaded, a caller clearing before a
2974
+ // rebuild — is a legal state, but a zero-sized storage buffer fails bind-group creation
2975
+ // outright ("Binding size for [Buffer] is zero"), and every later frame then draws nothing.
2976
+ size: Math.max(INST_F * 4, this.scratch.byteLength),
2739
2977
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
2740
2978
  });
2741
2979
  this.count = 0;
@@ -2853,9 +3091,9 @@ export class GpuShadowRenderer {
2853
3091
  mp.end();
2854
3092
  }
2855
3093
  /** Write a frustum's cull uniform: 6 planes + count + this frustum's VP + occlusion params (occ on the camera pass). */
2856
- writeCull(buf, vp, occlude) {
3094
+ writeCull(buf, vp, occlude, bucket = false) {
2857
3095
  const planes = frustumPlanes(vp);
2858
- const u = new Float32Array(48); // planes[24] + cnt[4] + camVP[16] + occ[4]
3096
+ const u = new Float32Array(52); // planes[24] + cnt[4] + camVP[16] + occ[4] + lod[4]
2859
3097
  for (let p = 0; p < 6; p++) {
2860
3098
  u[p * 4] = planes[p][0];
2861
3099
  u[p * 4 + 1] = planes[p][1];
@@ -2868,6 +3106,13 @@ export class GpuShadowRenderer {
2868
3106
  u[45] = this.hizW;
2869
3107
  u[46] = this.hizH;
2870
3108
  u[47] = HIZ_DOWN;
3109
+ // Only the camera pass buckets. The cascades always draw 36 vertices, so there is nothing to
3110
+ // sort them by, and with bucketing off every survivor lands in bucket 0 — which is the whole
3111
+ // list, exactly as before.
3112
+ u[48] = this.visStride() / 4;
3113
+ u[49] = bucket ? 1 : 0;
3114
+ u[50] = this.bevel;
3115
+ u[51] = this.fillet;
2871
3116
  this.device.queue.writeBuffer(buf, 0, u);
2872
3117
  }
2873
3118
  /**
@@ -2987,12 +3232,20 @@ export class GpuShadowRenderer {
2987
3232
  // beveled cube's 132 vertices only while a bevel is actually set; at 0 it draws the first 36,
2988
3233
  // which buildBevelCube guarantees ARE the sharp cube. The shadow pass always draws 36 — a 6% cut
2989
3234
  // is invisible in a shadow map and there is no reason to quadruple the cascades' vertex work.
2990
- const camVerts = this.bevel > 0 || this.fillet > 0 ? BEVEL_VERTS : SHARP_VERTS;
2991
- this.device.queue.writeBuffer(this.camArgs, 0, new Uint32Array([camVerts, 0, 0, 0]));
2992
- const lightReset = new Uint32Array([SHARP_VERTS, 0, 0, 0]);
3235
+ const camBevel = this.bevel > 0 || this.fillet > 0;
3236
+ // With the bevel off there is nothing to classify: one bucket of 36, the other two empty.
3237
+ const bucketVerts = camBevel
3238
+ ? [SEC_FANS, SEC_FILLET, BEVEL_VERTS]
3239
+ : [SHARP_VERTS, SHARP_VERTS, SHARP_VERTS];
3240
+ const camReset = new Uint32Array(4 * CULL_BUCKETS);
3241
+ for (let b = 0; b < CULL_BUCKETS; b++)
3242
+ camReset[b * 4] = bucketVerts[b];
3243
+ this.device.queue.writeBuffer(this.camArgs, 0, camReset);
3244
+ const lightReset = new Uint32Array(4 * CULL_BUCKETS);
3245
+ lightReset[0] = SHARP_VERTS;
2993
3246
  for (const a of this.lightArgs)
2994
3247
  this.device.queue.writeBuffer(a, 0, lightReset);
2995
- this.writeCull(this.camCull, camVP, occludeNow);
3248
+ this.writeCull(this.camCull, camVP, occludeNow, camBevel);
2996
3249
  for (let i = 0; i < nc; i++)
2997
3250
  this.writeCull(this.lightCull[i], mats[i], false);
2998
3251
  if (this.count > 0) {
@@ -3049,8 +3302,15 @@ export class GpuShadowRenderer {
3049
3302
  },
3050
3303
  });
3051
3304
  mp.setPipeline(this.mainPipe);
3052
- mp.setBindGroup(0, this.mainBG);
3053
- mp.drawIndirect(this.camArgs, 0);
3305
+ // ONE DRAW PER VERTEX-COUNT BUCKET. The cull pass sorted the survivors by how many of the
3306
+ // beveled cube's vertices their neighbourhood actually uses (see bevelClass); each bucket's
3307
+ // indirect args carry its own vertexCount, and each binds its own slice of the visible list —
3308
+ // a slice rather than a firstInstance offset because non-zero firstInstance in drawIndirect
3309
+ // needs the `indirect-first-instance` feature, which this renderer does not request.
3310
+ for (let b = 0; b < CULL_BUCKETS; b++) {
3311
+ mp.setBindGroup(0, this.mainBGs[b]);
3312
+ mp.drawIndirect(this.camArgs, b * 16);
3313
+ }
3054
3314
  if (!this.overlayDeferred && this.overlayCount > 0) {
3055
3315
  mp.setPipeline(this.alphaPipe);
3056
3316
  mp.setBindGroup(0, this.overlayBG);
@@ -3081,16 +3341,22 @@ export class GpuShadowRenderer {
3081
3341
  * safe to call from a live render loop (no per-frame readback cost, no race with the ongoing frames). IR/tests. */
3082
3342
  async readCullStats() {
3083
3343
  const enc = this.device.createCommandEncoder();
3084
- enc.copyBufferToBuffer(this.camArgs, 0, this.statsBuf, 0, 16); // args[1] = instanceCount (the visible count)
3085
- enc.copyBufferToBuffer(this.lightArgs[0], 0, this.statsBuf, 16, 16);
3344
+ // ⚠️ ALL THREE BUCKETS, NOT JUST THE FIRST. The camera pass compacts into one list per
3345
+ // vertex-count bucket, so args[0].ic alone reports whatever fraction happened to be simple —
3346
+ // 45% on ordinary terrain — and every caller that trusts camVisible would silently under-read.
3347
+ enc.copyBufferToBuffer(this.camArgs, 0, this.statsBuf, 0, 16 * CULL_BUCKETS);
3348
+ enc.copyBufferToBuffer(this.lightArgs[0], 0, this.statsBuf, 16 * CULL_BUCKETS, 16);
3086
3349
  this.device.queue.submit([enc.finish()]);
3087
3350
  await this.statsBuf.mapAsync(GPUMapMode.READ);
3088
3351
  const a = new Uint32Array(this.statsBuf.getMappedRange().slice(0));
3089
3352
  this.statsBuf.unmap();
3353
+ let camVisible = 0;
3354
+ for (let b = 0; b < CULL_BUCKETS; b++)
3355
+ camVisible += a[b * 4 + 1];
3090
3356
  this.lastCull = {
3091
3357
  total: this.count,
3092
- camVisible: a[1],
3093
- lightVisible: a[5],
3358
+ camVisible,
3359
+ lightVisible: a[CULL_BUCKETS * 4 + 1],
3094
3360
  };
3095
3361
  return this.lastCull;
3096
3362
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.15",
3
+ "version": "0.15.16",
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
  },
@@ -30,10 +22,20 @@
30
22
  "react": ">=18"
31
23
  },
32
24
  "devDependencies": {
33
- "typescript": "^5.6.0",
34
25
  "@types/react": "^19.0.0",
35
26
  "@webgpu/types": "^0.1.40",
36
27
  "prettier": "^3.9.5",
37
- "ugly-app": "^0.1.841"
28
+ "typescript": "^5.6.0",
29
+ "ugly-app": "^0.1.841",
30
+ "wesl": "0.7.28"
31
+ },
32
+ "scripts": {
33
+ "preinstall": "npx only-allow pnpm",
34
+ "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/",
35
+ "lint": "ugly-app lint",
36
+ "lint:fix": "ugly-app lint --fix",
37
+ "lint:wgsl": "node --experimental-strip-types tools/wgslGuard.mts && node --experimental-strip-types tools/wgslLint.mts",
38
+ "test": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/*.test.mts",
39
+ "pretty": "prettier --write ."
38
40
  }
39
- }
41
+ }