ugly-game 0.15.30 → 0.15.32

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.
@@ -1,3 +1,7 @@
1
+ /** One cube instance: world position, per-axis scale, a hue (< 0 ⇒ neutral ground), and an optional
2
+ * emissive flag (> 0 ⇒ the cube self-glows at full brightness, bypassing sun/shadow/AO — used for the
3
+ * place ghost, destroy marker, projectiles, and sparkles so effect cubes read as distinct from terrain). */
4
+ import { type Plane } from './mat4';
1
5
  import { type ProbeGrid } from './giProbes';
2
6
  export interface CubeInstance {
3
7
  x: number;
@@ -560,6 +564,40 @@ export declare const FACE_DIRS: readonly (readonly [number, number, number])[];
560
564
  * never needs expressing — a cube with no visible face is dropped by the mesher and never reaches
561
565
  * the buffer at all.
562
566
  */
567
+ /**
568
+ * THE VOLUME A DIRECTIONAL LIGHT'S SHADOW PASS SHOULD CULL AGAINST — which is NOT the box it renders
569
+ * with, and conflating the two is what makes the sun draw the whole world.
570
+ *
571
+ * A shadow caster only matters if it can darken a pixel the camera can actually see. That set is the
572
+ * camera frustum SWEPT TOWARD THE LIGHT: every point which, followed along the light's travel
573
+ * direction, eventually lands inside the camera's view. Everything else casts onto geometry nobody is
574
+ * looking at.
575
+ *
576
+ * The ortho box the map is rendered through cannot serve as that test. It is fitted to the SPHERE
577
+ * enclosing the camera frustum — deliberately, because a sphere is rotation invariant and that is
578
+ * what stops the shadow map shimmering as you turn — and a sphere's bounding cube is many times the
579
+ * frustum's own volume. Measured in all-mine-sky at N=512: a 0.32 G-unit³ frustum inside a 7.28 G
580
+ * unit³ cube, 22.7x, on a world only 512 units across. Every resident instance was inside it from
581
+ * every camera angle, and `lightVisible` sat at 2.09 M against the camera's 348 K.
582
+ *
583
+ * ⚠️ THE RULE IS EXACT, NOT AN APPROXIMATION OF ONE. Sweeping a convex volume along a direction `d`
584
+ * turns each bounding half-space `n·p + w >= 0` into either itself or the whole of space: substituting
585
+ * `p = r - t·d` gives `n·r + w >= t(n·d)`, and if `n·d <= 0` some `t >= 0` always satisfies it. So a
586
+ * plane survives the sweep exactly when its inward normal points along the sweep, and the others stop
587
+ * constraining anything. The intersection of the survivors contains the swept hull, so the test is
588
+ * conservative — it can keep a caster that does not matter, never drop one that does.
589
+ *
590
+ * Sanity, with the sun overhead: the frustum's BOTTOM plane is kept and its TOP plane is dropped.
591
+ * Geometry above you casts down into view; geometry below you cannot.
592
+ *
593
+ * ⚠️ WHAT THIS DOES NOT COVER: a receiver outside the camera frustum whose shadow is still seen —
594
+ * through a mirror, or a reflection pass that samples the same map. Those need the reflected frustum
595
+ * swept in as well, or this pass left uncalled for them.
596
+ *
597
+ * @param camVP the CAMERA's view-projection, not the light's
598
+ * @param sunTravel the direction light TRAVELS (from the sun outward), matching `frame`'s `sunDir`
599
+ */
600
+ export declare function casterPlanes(camVP: ArrayLike<number>, sunTravel: readonly [number, number, number]): Plane[];
563
601
  export declare const FACE_MASK_ALL = 63;
564
602
  /** Is face `d` drawn? Bit d set ⇒ yes. 0 is the unknown sentinel ⇒ every face. */
565
603
  export declare function faceExposed(faceMask: number, d: number): boolean;
@@ -638,6 +676,9 @@ export declare class GpuShadowRenderer {
638
676
  private giGridBuf;
639
677
  private giProbeBuf;
640
678
  private count;
679
+ /** Ranges `clearInstanceRange` has been asked to blank, flushed into the next frame's encoder. */
680
+ private pendingClears;
681
+ private clearedTotal;
641
682
  private cam;
642
683
  /**
643
684
  * Scratch for the per-cascade copy of `cam`, with that cascade's matrix parked at `lightVP[0]`.
@@ -675,6 +716,7 @@ export declare class GpuShadowRenderer {
675
716
  private eye;
676
717
  private bevel;
677
718
  private faceCull;
719
+ private casterCull;
678
720
  private fillet;
679
721
  private alphaPipe;
680
722
  private alphaBGL;
@@ -837,6 +879,17 @@ export declare class GpuShadowRenderer {
837
879
  * ⚠️ AND IT IS IGNORED WHILE A BEVEL IS SET. See `frame()` — the two are mutually exclusive.
838
880
  */
839
881
  setFaceCull(on: boolean): void;
882
+ /**
883
+ * Cull shadow casters against the camera frustum swept toward the sun, instead of against the
884
+ * cascade's own ortho box. See `casterPlanes` for why those are different volumes.
885
+ *
886
+ * ⚠️ IT CHANGES NO PIXEL, WHICH IS ALSO WHY IT NEEDS TO BE A TOGGLE. A change that is supposed to
887
+ * be invisible cannot be verified by looking at it — the A/B is `readCullStats().lightVisible` and
888
+ * the frame time, and both need the OFF case measured on the same machine in the same session.
889
+ * Off by default: a caller whose shadows are sampled by something other than the camera (a mirror,
890
+ * a reflection pass) must opt in knowingly.
891
+ */
892
+ setShadowCasterCull(on: boolean): void;
840
893
  setAtlas(tex: GPUTexture, layout: AtlasLayout): void;
841
894
  /** Static scene: sizes the buffer to exactly these instances. */
842
895
  setScene(instances: CubeInstance[]): void;
@@ -899,6 +952,31 @@ export declare class GpuShadowRenderer {
899
952
  */
900
953
  updateInstanceRaw(src: Float32Array<ArrayBuffer>, first: number): void;
901
954
  updateInstanceRange(instances: CubeInstance[], first: number): void;
955
+ /**
956
+ * BLANK A RANGE OF SLOTS ON THE GPU — the free() half of managing this buffer as an arena.
957
+ *
958
+ * A caller that allocates and releases sub-ranges (one chunk of a voxel world per allocation, say)
959
+ * has to blank what it releases: the cull walks `[0, count)` and does not know which slots the
960
+ * caller still considers live, so a stale range keeps drawing. Doing that with `updateInstanceRange`
961
+ * means shipping zeros over the bus — measured on all-mine-sky's chunk ladder, blanking was 47 % of
962
+ * ALL instance-buffer write traffic under a churning LOD ladder, and none of it was geometry.
963
+ *
964
+ * `clearBuffer` is a GPU-local fill: no staging, no upload bandwidth, no per-instance JavaScript.
965
+ * The clears queue here and flush at the top of the next `frame()`, because a clear needs a command
966
+ * encoder and callers free from wherever their streaming happens to land.
967
+ *
968
+ * ⚠️ IT WRITES ZEROS, AND ZERO SCALE IS WHAT MAKES THAT SAFE. `clearBuffer` cannot write a sentinel
969
+ * position, so a blanked instance sits at the ORIGIN — inside most frustums. The cull rejects
970
+ * nonpositive extent for exactly this reason; without that test this method would be a way to fill
971
+ * the visible list with degenerate cubes rather than a way to free space.
972
+ *
973
+ * ⚠️ IT DOES NOT MOVE `count`. Freeing the tail should also lower the draw count, but only the
974
+ * caller knows whether the tail is now free — call `setInstanceCount` as well when it is.
975
+ */
976
+ clearInstanceRange(first: number, n: number): void;
977
+ /** Instances blanked by `clearInstanceRange` since the counter was last read. The fragmentation and
978
+ * write-cost readout a caller managing this buffer as an arena needs, and cheap enough to leave on. */
979
+ get clearedInstances(): number;
902
980
  /** How many instances the cull + draw passes consider, whatever is in the buffer past that. Pairs with
903
981
  * `updateInstanceRange`: shrinking the dynamic tail is a count change, not an upload. */
904
982
  setInstanceCount(n: number): void;
package/dist/gpuShadow.js CHANGED
@@ -1111,6 +1111,50 @@ export const FACE_DIRS = [
1111
1111
  * never needs expressing — a cube with no visible face is dropped by the mesher and never reaches
1112
1112
  * the buffer at all.
1113
1113
  */
1114
+ /**
1115
+ * THE VOLUME A DIRECTIONAL LIGHT'S SHADOW PASS SHOULD CULL AGAINST — which is NOT the box it renders
1116
+ * with, and conflating the two is what makes the sun draw the whole world.
1117
+ *
1118
+ * A shadow caster only matters if it can darken a pixel the camera can actually see. That set is the
1119
+ * camera frustum SWEPT TOWARD THE LIGHT: every point which, followed along the light's travel
1120
+ * direction, eventually lands inside the camera's view. Everything else casts onto geometry nobody is
1121
+ * looking at.
1122
+ *
1123
+ * The ortho box the map is rendered through cannot serve as that test. It is fitted to the SPHERE
1124
+ * enclosing the camera frustum — deliberately, because a sphere is rotation invariant and that is
1125
+ * what stops the shadow map shimmering as you turn — and a sphere's bounding cube is many times the
1126
+ * frustum's own volume. Measured in all-mine-sky at N=512: a 0.32 G-unit³ frustum inside a 7.28 G
1127
+ * unit³ cube, 22.7x, on a world only 512 units across. Every resident instance was inside it from
1128
+ * every camera angle, and `lightVisible` sat at 2.09 M against the camera's 348 K.
1129
+ *
1130
+ * ⚠️ THE RULE IS EXACT, NOT AN APPROXIMATION OF ONE. Sweeping a convex volume along a direction `d`
1131
+ * turns each bounding half-space `n·p + w >= 0` into either itself or the whole of space: substituting
1132
+ * `p = r - t·d` gives `n·r + w >= t(n·d)`, and if `n·d <= 0` some `t >= 0` always satisfies it. So a
1133
+ * plane survives the sweep exactly when its inward normal points along the sweep, and the others stop
1134
+ * constraining anything. The intersection of the survivors contains the swept hull, so the test is
1135
+ * conservative — it can keep a caster that does not matter, never drop one that does.
1136
+ *
1137
+ * Sanity, with the sun overhead: the frustum's BOTTOM plane is kept and its TOP plane is dropped.
1138
+ * Geometry above you casts down into view; geometry below you cannot.
1139
+ *
1140
+ * ⚠️ WHAT THIS DOES NOT COVER: a receiver outside the camera frustum whose shadow is still seen —
1141
+ * through a mirror, or a reflection pass that samples the same map. Those need the reflected frustum
1142
+ * swept in as well, or this pass left uncalled for them.
1143
+ *
1144
+ * @param camVP the CAMERA's view-projection, not the light's
1145
+ * @param sunTravel the direction light TRAVELS (from the sun outward), matching `frame`'s `sunDir`
1146
+ */
1147
+ export function casterPlanes(camVP, sunTravel) {
1148
+ // Toward the light is the opposite of the way it travels — that is the direction a caster has to be
1149
+ // displaced along to reach the frustum it shadows.
1150
+ const len = Math.hypot(sunTravel[0], sunTravel[1], sunTravel[2]) || 1;
1151
+ const dx = -sunTravel[0] / len, dy = -sunTravel[1] / len, dz = -sunTravel[2] / len;
1152
+ // ⚠️ `[0,0,0,1]` IS THE VACUOUS PLANE, and it has to be one the shader cannot reject on. The cull
1153
+ // rejects when `dot(n, c) + w < -e` for a non-negative extent `e`; with a zero normal that reads
1154
+ // `1 < -e`, which is false for every instance. A large `w` with a real normal would also work and
1155
+ // would still cost a dot product per instance for nothing.
1156
+ return frustumPlanes(camVP).map((pl) => pl[0] * dx + pl[1] * dy + pl[2] * dz > 1e-6 ? pl : [0, 0, 0, 1]);
1157
+ }
1114
1158
  export const FACE_MASK_ALL = 0b111111;
1115
1159
  /** Is face `d` drawn? Bit d set ⇒ yes. 0 is the unknown sentinel ⇒ every face. */
1116
1160
  export function faceExposed(faceMask, d) {
@@ -2197,6 +2241,15 @@ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
2197
2241
  let i = gid.x;
2198
2242
  if (i >= u32(cc.cnt.x)) { return; }
2199
2243
  let inst = insts[i];
2244
+ // ── A FREED SLOT IS A ZEROED SLOT ────────────────────────────────────────────────────────────────
2245
+ //
2246
+ // The instance buffer is an ARENA when the caller manages it as one: clearInstanceRange blanks a
2247
+ // freed range on the GPU, and clearBuffer can only write zeros. A zero-scale box is a POINT, and a
2248
+ // point at the origin is inside most frustums — so without this test a freed slot survives the cull,
2249
+ // takes a visible-list entry and an indirect instance, and rasterises a degenerate cube every frame
2250
+ // for as long as it stays free. Rejecting nonpositive extent is also just correct: a box with no
2251
+ // width draws nothing, so nothing that was ever visible is lost here.
2252
+ if (inst.scl.x <= 0.0 || inst.scl.y <= 0.0 || inst.scl.z <= 0.0) { return; }
2200
2253
  // The cull pass indexes the instance buffer DIRECTLY, so its instance index is already global.
2201
2254
  let bd = bodyOf(i);
2202
2255
  let c = bd.pos.xyz + qr(bd.rot, inst.pos.xyz);
@@ -2944,6 +2997,9 @@ export class GpuShadowRenderer {
2944
2997
  giGridBuf;
2945
2998
  giProbeBuf;
2946
2999
  count = 0;
3000
+ /** Ranges `clearInstanceRange` has been asked to blank, flushed into the next frame's encoder. */
3001
+ pendingClears = [];
3002
+ clearedTotal = 0;
2947
3003
  // camVP(16) + lightVP[MAX_CASCADES](16 each) + sun + sunCol + tint + atlas + up + csm + eye
2948
3004
  cam = new Float32Array(16 + MAX_CASCADES * 16 + 7 * 4);
2949
3005
  /**
@@ -2982,6 +3038,7 @@ export class GpuShadowRenderer {
2982
3038
  eye = new Float32Array(3);
2983
3039
  bevel = 0; // see setBevel — 0 keeps the sharp cube exactly, and draws only 36 vertices
2984
3040
  faceCull = false; // see setFaceCull — off is today's all-six-faces cube, bit for bit
3041
+ casterCull = false; // see setShadowCasterCull — off culls casters against the ortho box
2985
3042
  fillet = 0; // the CONCAVE radius, set separately so the two halves can be judged apart
2986
3043
  alphaPipe;
2987
3044
  alphaBGL; // kept so the overlay buffer can grow and rebind on demand
@@ -3668,6 +3725,19 @@ export class GpuShadowRenderer {
3668
3725
  setFaceCull(on) {
3669
3726
  this.faceCull = on;
3670
3727
  }
3728
+ /**
3729
+ * Cull shadow casters against the camera frustum swept toward the sun, instead of against the
3730
+ * cascade's own ortho box. See `casterPlanes` for why those are different volumes.
3731
+ *
3732
+ * ⚠️ IT CHANGES NO PIXEL, WHICH IS ALSO WHY IT NEEDS TO BE A TOGGLE. A change that is supposed to
3733
+ * be invisible cannot be verified by looking at it — the A/B is `readCullStats().lightVisible` and
3734
+ * the frame time, and both need the OFF case measured on the same machine in the same session.
3735
+ * Off by default: a caller whose shadows are sampled by something other than the camera (a mirror,
3736
+ * a reflection pass) must opt in knowingly.
3737
+ */
3738
+ setShadowCasterCull(on) {
3739
+ this.casterCull = on;
3740
+ }
3671
3741
  setAtlas(tex, layout) {
3672
3742
  this.atlasView = tex.createView({ dimension: '2d-array' });
3673
3743
  const ids = Object.keys(layout.tiles).map(Number);
@@ -3739,6 +3809,9 @@ export class GpuShadowRenderer {
3739
3809
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
3740
3810
  });
3741
3811
  this.count = 0;
3812
+ // ⚠️ THE OLD BUFFER IS GONE, SO ITS PENDING CLEARS ARE MEANINGLESS — and worse than meaningless:
3813
+ // they name offsets in a buffer that no longer exists, and the fresh one is already zeroed.
3814
+ this.pendingClears.length = 0;
3742
3815
  this.makeBindGroups();
3743
3816
  }
3744
3817
  updateInstances(instances) {
@@ -3813,6 +3886,48 @@ export class GpuShadowRenderer {
3813
3886
  if (first + n > this.count)
3814
3887
  this.count = first + n;
3815
3888
  }
3889
+ /**
3890
+ * BLANK A RANGE OF SLOTS ON THE GPU — the free() half of managing this buffer as an arena.
3891
+ *
3892
+ * A caller that allocates and releases sub-ranges (one chunk of a voxel world per allocation, say)
3893
+ * has to blank what it releases: the cull walks `[0, count)` and does not know which slots the
3894
+ * caller still considers live, so a stale range keeps drawing. Doing that with `updateInstanceRange`
3895
+ * means shipping zeros over the bus — measured on all-mine-sky's chunk ladder, blanking was 47 % of
3896
+ * ALL instance-buffer write traffic under a churning LOD ladder, and none of it was geometry.
3897
+ *
3898
+ * `clearBuffer` is a GPU-local fill: no staging, no upload bandwidth, no per-instance JavaScript.
3899
+ * The clears queue here and flush at the top of the next `frame()`, because a clear needs a command
3900
+ * encoder and callers free from wherever their streaming happens to land.
3901
+ *
3902
+ * ⚠️ IT WRITES ZEROS, AND ZERO SCALE IS WHAT MAKES THAT SAFE. `clearBuffer` cannot write a sentinel
3903
+ * position, so a blanked instance sits at the ORIGIN — inside most frustums. The cull rejects
3904
+ * nonpositive extent for exactly this reason; without that test this method would be a way to fill
3905
+ * the visible list with degenerate cubes rather than a way to free space.
3906
+ *
3907
+ * ⚠️ IT DOES NOT MOVE `count`. Freeing the tail should also lower the draw count, but only the
3908
+ * caller knows whether the tail is now free — call `setInstanceCount` as well when it is.
3909
+ */
3910
+ clearInstanceRange(first, n) {
3911
+ const capN = (this.scratch.length / INST_F) | 0;
3912
+ if (first < 0 || first >= capN)
3913
+ return;
3914
+ const count = Math.min(n, capN - first);
3915
+ if (count <= 0)
3916
+ return;
3917
+ // Merge into the previous pending clear when they touch — a coarsening pass frees many adjacent
3918
+ // entries in one go, and one encoder call per entry is pure overhead for the same bytes.
3919
+ const n0 = this.pendingClears.length;
3920
+ const last = n0 > 0 ? this.pendingClears[n0 - 1] : undefined;
3921
+ if (last !== undefined && last.first + last.n === first)
3922
+ last.n += count;
3923
+ else
3924
+ this.pendingClears.push({ first, n: count });
3925
+ }
3926
+ /** Instances blanked by `clearInstanceRange` since the counter was last read. The fragmentation and
3927
+ * write-cost readout a caller managing this buffer as an arena needs, and cheap enough to leave on. */
3928
+ get clearedInstances() {
3929
+ return this.clearedTotal;
3930
+ }
3816
3931
  /** How many instances the cull + draw passes consider, whatever is in the buffer past that. Pairs with
3817
3932
  * `updateInstanceRange`: shrinking the dynamic tail is a count change, not an upload. */
3818
3933
  setInstanceCount(n) {
@@ -3912,8 +4027,16 @@ export class GpuShadowRenderer {
3912
4027
  mp.end();
3913
4028
  }
3914
4029
  /** Write a frustum's cull uniform: 6 planes + count + this frustum's VP + occlusion params (occ on the camera pass). */
3915
- writeCull(buf, vp, occlude, bucket = 0) {
3916
- const planes = frustumPlanes(vp);
4030
+ writeCull(buf, vp, occlude, bucket = 0,
4031
+ /**
4032
+ * Cull against THESE planes instead of the ones `vp` implies.
4033
+ *
4034
+ * The shadow pass is the reason this exists: what it RENDERS with and what it should CULL with
4035
+ * are not the same volume, and using one for both is what makes a directional light draw the
4036
+ * whole world. See `casterPlanes`.
4037
+ */
4038
+ planesOverride) {
4039
+ const planes = planesOverride ?? frustumPlanes(vp);
3917
4040
  const u = new Float32Array(52); // planes[24] + cnt[4] + camVP[16] + occ[4] + lod[4]
3918
4041
  for (let p = 0; p < 6; p++) {
3919
4042
  u[p * 4] = planes[p][0];
@@ -4034,6 +4157,17 @@ export class GpuShadowRenderer {
4034
4157
  * occluder that wants to cull per cascade has to be handed every cascade matrix up front, here.
4035
4158
  */
4036
4159
  extraShadowCull, up = [0, 1, 0], linearOut = false) {
4160
+ // ⚠️ FREES FIRST, BEFORE ANYTHING READS THE BUFFER THIS FRAME. `clearInstanceRange` queues rather
4161
+ // than encodes, because a caller frees where its streaming lands and has no encoder there; this is
4162
+ // the first point in the frame that has one, and it is ahead of the cull that would otherwise read
4163
+ // the stale slots.
4164
+ if (this.pendingClears.length > 0) {
4165
+ for (const c of this.pendingClears) {
4166
+ enc.clearBuffer(this.instBuf, c.first * INST_F * 4, c.n * INST_F * 4);
4167
+ this.clearedTotal += c.n;
4168
+ }
4169
+ this.pendingClears.length = 0;
4170
+ }
4037
4171
  // One matrix or many — a single Float32Array is the 1-cascade case and stays byte-identical.
4038
4172
  const mats = Array.isArray(lightVP) ? lightVP : [lightVP];
4039
4173
  const nc = Math.max(1, Math.min(MAX_CASCADES, mats.length));
@@ -4116,8 +4250,13 @@ export class GpuShadowRenderer {
4116
4250
  for (const a of this.lightArgs)
4117
4251
  this.device.queue.writeBuffer(a, 0, lightReset);
4118
4252
  this.writeCull(this.camCull, camVP, occludeNow, camBevel ? 1 : faceCull ? 2 : 0);
4253
+ // ⚠️ THE CASCADES RENDER THROUGH `mats[i]` AND CULL AGAINST SOMETHING ELSE. That is the whole
4254
+ // point: the ortho box is sized for shadow-map STABILITY (see `casterPlanes`), not for deciding
4255
+ // who casts, and using it for both is what had the sun submitting six times the camera's geometry
4256
+ // every frame. The matrix handed to the draw is untouched, so nothing that still casts moves.
4257
+ const casters = this.casterCull ? casterPlanes(camVP, sunDir) : undefined;
4119
4258
  for (let i = 0; i < nc; i++)
4120
- this.writeCull(this.lightCull[i], mats[i], false);
4259
+ this.writeCull(this.lightCull[i], mats[i], false, 0, casters);
4121
4260
  // ⚠️ THE PASS OPENS FOR EITHER REASON. It used to be gated on `this.count > 0` alone, which is
4122
4261
  // right for the cube cull and wrong for a caller's: a scene with no cubes but a forest of props
4123
4262
  // still needs somewhere to dispatch. Gating on both keeps the empty-scene case free.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.30",
3
+ "version": "0.15.32",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {