ugly-game 0.15.46 → 0.15.48

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.
@@ -23,6 +23,13 @@ export interface PropWorld {
23
23
  valueLift: number;
24
24
  }
25
25
  export interface PropMesh {
26
+ /** Opt-in metallic/roughness shading. Omitted preserves legacy matte lighting. */
27
+ roughness?: number;
28
+ metalness?: number;
29
+ /** Clear lacquer layer over the base material, 0..1. */
30
+ clearcoat?: number;
31
+ /** Analytic studio/sky reflection strength. Defaults to 1 for PBR materials. */
32
+ reflectionStrength?: number;
26
33
  positions: Float32Array;
27
34
  normals: Float32Array;
28
35
  colors: Float32Array;
@@ -32,7 +32,9 @@ struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>, d3: v
32
32
  // PER-MODEL material. Group 2 is already the per-model group (the albedo lives here), so opacity
33
33
  // rides along rather than needing a fourth group or a dynamic offset. mat.x is alpha, mat.y is the
34
34
  // alpha-test cutoff (0 ⇒ no test, which is every model that predates it).
35
- struct Mat { mat: vec4<f32> };
35
+ // mat = opacity, cutoff, roughness (-1 = legacy), metalness.
36
+ // coat = clearcoat, reflection strength, unused, unused.
37
+ struct Mat { mat: vec4<f32>, coat: vec4<f32> };
36
38
  @group(2) @binding(2) var<uniform> mtl: Mat;
37
39
  @group(1) @binding(0) var shadowMap: texture_depth_2d_array; // the SAME cascaded sun shadow map the terrain cubes sample
38
40
  @group(1) @binding(1) var shadowSamp: sampler_comparison;
@@ -187,6 +189,36 @@ fn hsvShift(c: vec3<f32>, hue: f32, sat: f32, val: f32) -> vec3<f32> {
187
189
  let g = dot(rot, vec3(0.299, 0.587, 0.114));
188
190
  return clamp(mix(vec3(g, g, g), rot, sat) * val, vec3(0.0), vec3(4.0));
189
191
  }
192
+ // Analytic studio/sky environment: view-dependent reflections without a downloaded
193
+ // cubemap. This is an approximate image-based light, not scene ray tracing.
194
+ fn studioEnv(r: vec3<f32>, rough: f32) -> vec3<f32> {
195
+ let horizon = smoothstep(-0.15, 0.45, r.y);
196
+ var c = mix(vec3(0.12, 0.11, 0.09), vec3(0.58, 0.68, 0.80), horizon);
197
+ let width = 0.015 + rough * rough * 0.28;
198
+ let top = smoothstep(0.68 - width, 0.68 + width, r.y);
199
+ let stripA = exp(-pow((r.x - 0.48) / (0.07 + width), 2.0)) * smoothstep(-0.1, 0.3, r.y);
200
+ let stripB = exp(-pow((r.z + 0.38) / (0.045 + width), 2.0)) * smoothstep(0.0, 0.3, r.y);
201
+ c += vec3(1.6, 1.5, 1.35) * top * 0.55;
202
+ c += vec3(2.5, 2.35, 2.1) * (stripA + stripB) * (1.0 - rough * 0.7);
203
+ return c;
204
+ }
205
+ fn fresnel(f0: vec3<f32>, cosTheta: f32) -> vec3<f32> {
206
+ return f0 + (vec3(1.0) - f0) * pow(1.0 - clamp(cosTheta, 0.0, 1.0), 5.0);
207
+ }
208
+ fn ggx(nh: f32, nv: f32, nl: f32, rough: f32) -> f32 {
209
+ let a2 = pow(rough, 4.0);
210
+ let den = nh * nh * (a2 - 1.0) + 1.0;
211
+ let D = a2 / max(3.14159265 * den * den, 0.00001);
212
+ let k = pow(rough + 1.0, 2.0) / 8.0;
213
+ let G = (nv / max(nv * (1.0-k) + k, 0.0001)) * (nl / max(nl * (1.0-k) + k, 0.0001));
214
+ return D * G / max(4.0 * nv * nl, 0.0001);
215
+ }
216
+ fn srgbToLinear(c: vec3<f32>) -> vec3<f32> {
217
+ return select(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), c > vec3(0.04045));
218
+ }
219
+ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
220
+ return select(c * 12.92, 1.055 * pow(max(c, vec3(0.0)), vec3(1.0/2.4)) - 0.055, c > vec3(0.0031308));
221
+ }
190
222
  @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
191
223
  let N = normalize(i.n);
192
224
  let ff = select(1.0, 0.5 + 0.85 * fixedFill(N, u.up.xyz), u.up.w > 0.5); // fixed fill (fall back to flat amb if no up)
@@ -207,8 +239,36 @@ fn hsvShift(c: vec3<f32>, hue: f32, sat: f32, val: f32) -> vec3<f32> {
207
239
  }
208
240
  base = hsvShift(base, u.grade.x, max(u.grade.y, 0.0), max(u.grade.z, 0.0));
209
241
  let spec = u.surf.z;
210
- let lit = base * (u.amb.xyz * ff + d * u.sunCol.xyz * sh * (1.0 + spec * 0.6))
242
+ var lit = base * (u.amb.xyz * ff + d * u.sunCol.xyz * sh * (1.0 + spec * 0.6))
211
243
  + base * u.surf.w; // emissive — bioluminescence on dark worlds
244
+ if (mtl.mat.z >= 0.0) {
245
+ let V = normalize(u.cam.xyz - i.world);
246
+ let L = -normalize(u.sun.xyz);
247
+ let H = normalize(L + V);
248
+ let nv = max(dot(N, V), 0.001);
249
+ let nl = max(dot(N, L), 0.0);
250
+ let nh = max(dot(N, H), 0.0);
251
+ let vh = max(dot(V, H), 0.0);
252
+ let rough = clamp(mtl.mat.z, 0.045, 1.0);
253
+ let metal = clamp(mtl.mat.w, 0.0, 1.0);
254
+ // Vertex/instance tints are display sRGB, while albedo textures use sRGB GPU
255
+ // formats (and arrive decoded). Legacy props keep their historical path.
256
+ let albedo = srgbToLinear(i.c) * tex.rgb;
257
+ let f0 = mix(vec3(0.04), albedo, metal);
258
+ let F = fresnel(f0, vh);
259
+ let kd = (vec3(1.0)-F) * (1.0-metal);
260
+ let direct = (kd * albedo / 3.14159265 + F * ggx(nh,nv,nl,rough)) * u.sunCol.xyz * nl * sh * 2.5;
261
+ let R = reflect(-V,N);
262
+ let env = studioEnv(R,rough) * mtl.coat.y;
263
+ let reflected = env * fresnel(f0,nv) * (1.0-rough*0.6);
264
+ let diffuse = albedo * u.amb.xyz * (0.6 + 0.4*max(N.y,0.0)) * (1.0-metal);
265
+ let coatF = fresnel(vec3(0.04),nv) * mtl.coat.x;
266
+ let coating = studioEnv(R,0.12) * coatF * mtl.coat.y;
267
+ let hdr = (direct + diffuse + reflected) * (vec3(1.0)-coatF) + coating;
268
+ // Smooth highlight compression preserves saturated paint rather than
269
+ // clipping reflected softboxes to a flat white patch.
270
+ lit = linearToSrgb(hdr / (vec3(1.0) + hdr * 0.35));
271
+ }
212
272
  let dist = length(i.world - u.cam.xyz);
213
273
  let f = clamp(1.0 - exp(-dist * u.fog.w), 0.0, 1.0);
214
274
  // mtl.mat.x is the model's opacity, 1 for every model that does not set it — the same constant
@@ -758,10 +818,19 @@ export class GpuPropsRenderer {
758
818
  const alpha = m.alpha ?? 1;
759
819
  const cutout = m.cutout ?? 0;
760
820
  const matBuf = dev.createBuffer({
761
- size: 16,
821
+ size: 32,
762
822
  usage: U.UNIFORM | U.COPY_DST,
763
823
  });
764
- dev.queue.writeBuffer(matBuf, 0, new Float32Array([alpha, cutout, 0, 0]));
824
+ dev.queue.writeBuffer(matBuf, 0, new Float32Array([
825
+ alpha,
826
+ cutout,
827
+ m.roughness ?? -1,
828
+ m.metalness ?? 0,
829
+ m.clearcoat ?? 0,
830
+ m.reflectionStrength ?? 1,
831
+ 0,
832
+ 0,
833
+ ]));
765
834
  return {
766
835
  alpha,
767
836
  cutout,
@@ -118,6 +118,15 @@ export interface SkinCreature {
118
118
  models: Float32Array;
119
119
  };
120
120
  }
121
+ /** Dynamic data for an already installed creature; geometry and textures remain unchanged. */
122
+ export interface SkinCreaturePose {
123
+ palette: Float32Array;
124
+ model: Float32Array;
125
+ mix?: number;
126
+ alpha?: number;
127
+ cutout?: number;
128
+ instances?: SkinCreature['instances'];
129
+ }
121
130
  export declare const MAX_CASCADES = 4;
122
131
  export declare class GpuSkinRenderer {
123
132
  private device;
@@ -145,6 +154,8 @@ export declare class GpuSkinRenderer {
145
154
  /** The explicit group 0/1/2 layouts, shared by both render pipelines. */
146
155
  private drawBGL;
147
156
  private packed;
157
+ private disposed;
158
+ private dummyShadow;
148
159
  private dummyShadowView;
149
160
  private dummyShadowSamp;
150
161
  private shadowBG;
@@ -159,6 +170,17 @@ export declare class GpuSkinRenderer {
159
170
  private texId;
160
171
  constructor(device: GPUDevice, format: GPUTextureFormat);
161
172
  setCreatures(list: SkinCreature[]): void;
173
+ /**
174
+ * Upload a new pose without reinstalling geometry. The list addresses the current
175
+ * installed slots in order. Validate every slot before any GPU write; topology,
176
+ * textures or instance-count changes require setCreatures instead. Existing
177
+ * setCreatures callers retain their full replacement semantics, including arrays
178
+ * whose contents were modified in place.
179
+ */
180
+ updatePoses(list: readonly SkinCreaturePose[]): void;
181
+ /** Release only renderer-owned resources. Caller-supplied textures remain owned by the caller. */
182
+ dispose(): void;
183
+ private assertLive;
162
184
  /** Deform + draw every creature with the shared scene lighting. load=true composites over the world;
163
185
  * otherwise clears to `clear`. sun/sunCol/amb/cam/fog/fogDensity match the terrain & prop renderers. */
164
186
  frame(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView, camVP: Float32Array, sunDir: [number, number, number], sunCol: [number, number, number], amb: [number, number, number], camPos: [number, number, number], fog: [number, number, number], fogDensity: number, clear: [number, number, number], load?: boolean, lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler): void;
@@ -196,6 +196,8 @@ export class GpuSkinRenderer {
196
196
  /** The explicit group 0/1/2 layouts, shared by both render pipelines. */
197
197
  drawBGL;
198
198
  packed = [];
199
+ disposed = false;
200
+ dummyShadow;
199
201
  // shadow-receive (group 1): dummy 1×1 depth map when no sun shadow is supplied (demo path), else the terrain's
200
202
  // shared shadow map. The bind group is cached and rebuilt only when the supplied view/sampler identity changes.
201
203
  dummyShadowView;
@@ -433,6 +435,7 @@ export class GpuSkinRenderer {
433
435
  format: 'depth32float',
434
436
  usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT,
435
437
  });
438
+ this.dummyShadow = dummy;
436
439
  this.dummyShadowView = dummy.createView({ dimension: '2d-array' }); // the binding is an array now
437
440
  this.dummyShadowSamp = device.createSampler({ compare: 'less' });
438
441
  this.whiteTex = device.createTexture({
@@ -450,57 +453,66 @@ export class GpuSkinRenderer {
450
453
  });
451
454
  }
452
455
  setCreatures(list) {
456
+ this.assertLive();
453
457
  const dev = this.device, U = GPUBufferUsage;
454
- for (const p of this.packed)
455
- destroyPackedBuffers(p);
456
- this.packed = list.map((c) => {
457
- const n = c.rest.length / 3;
458
- const rest = new Float32Array(n * 4), restN = new Float32Array(n * 4), joints = new Uint32Array(n * 4), weights = new Float32Array(n * 4);
459
- for (let i = 0; i < n; i++) {
460
- rest[i * 4] = c.rest[i * 3];
461
- rest[i * 4 + 1] = c.rest[i * 3 + 1];
462
- rest[i * 4 + 2] = c.rest[i * 3 + 2];
463
- rest[i * 4 + 3] = 1;
464
- restN[i * 4] = c.normals[i * 3];
465
- restN[i * 4 + 1] = c.normals[i * 3 + 1];
466
- restN[i * 4 + 2] = c.normals[i * 3 + 2];
467
- }
468
- for (let i = 0; i < n * 4; i++) {
469
- joints[i] = c.joints[i];
470
- weights[i] = c.weights[i];
471
- }
472
- const mk = (d, u) => {
473
- const b = dev.createBuffer({ size: d.byteLength, usage: u });
474
- dev.queue.writeBuffer(b, 0, d);
475
- return b;
476
- };
477
- const restB = mk(rest, U.STORAGE | U.COPY_DST), restNB = mk(restN, U.STORAGE | U.COPY_DST), jointsB = mk(joints, U.STORAGE | U.COPY_DST), weightsB = mk(weights, U.STORAGE | U.COPY_DST);
478
- // ⚠️ `| U.STORAGE` so the instanced vertex stage can read them as arrays. Adding a usage to a
479
- // buffer that is still bound the same way on the original path changes nothing about it.
480
- const colB = mk(c.colors, U.VERTEX | U.STORAGE | U.COPY_DST), idxB = mk(c.indices, U.INDEX | U.COPY_DST);
481
- // A zero-filled UV buffer when the caller has none: the white fallback samples to 1 at any
482
- // coordinate, so the attribute still has to EXIST but its contents cannot matter.
483
- const uvB = mk(c.uvs && c.uvs.length >= n * 2 ? c.uvs : new Float32Array(n * 2), U.VERTEX | U.STORAGE | U.COPY_DST);
484
- // ⚠️ NULL when the caller has no `uvs2` — NOT a second buffer holding a copy of `uvs`.
485
- //
486
- // `setCreatures` tears down and rebuilds every buffer on each call and all-mine-sky calls it
487
- // EVERY FRAME for EVERY creature. Allocating this unconditionally charged every caller in the
488
- // game — none of which pass `uvs2` — an extra `createBuffer` plus a `writeBuffer` of the same
489
- // n*2 floats, per creature, per frame, for a buffer whose contents cannot matter: with no
490
- // tint the 1x1 white samples to 1 at any coordinate. The attribute still has to EXIST, so
491
- // slot 4 binds `uvB` instead; WebGPU is happy to see the same GPUBuffer in two vertex slots.
492
- const uv2B = c.uvs2 && c.uvs2.length >= n * 2
493
- ? mk(c.uvs2, U.VERTEX | U.STORAGE | U.COPY_DST)
494
- : null;
495
- const tex = c.tex ?? this.whiteTex;
496
- const tex2 = c.tex2 ?? this.whiteTex;
497
- const tint = c.tint ?? this.whiteTex;
498
- // ⚠️ Keyed on the TRIPLE. Keyed on any subset, two creatures sharing those textures but
499
- // differing in the others would silently share the first one's bind group.
500
- const matKey = `${this.texId(tex)}:${this.texId(tex2)}:${this.texId(tint)}`;
501
- let matBG = this.matBGs.get(matKey);
502
- if (!matBG) {
503
- matBG = dev.createBindGroup({
458
+ // Build a complete replacement before releasing the previous generation. A failed
459
+ // allocation/validation must not leak a partial mesh or invalidate a still drawable one.
460
+ const allocated = [];
461
+ const materialGroups = new Map();
462
+ const createBuffer = (descriptor) => {
463
+ const buffer = dev.createBuffer(descriptor);
464
+ allocated.push(buffer);
465
+ return buffer;
466
+ };
467
+ let next;
468
+ try {
469
+ next = list.map((c) => {
470
+ const n = c.rest.length / 3;
471
+ const rest = new Float32Array(n * 4), restN = new Float32Array(n * 4), joints = new Uint32Array(n * 4), weights = new Float32Array(n * 4);
472
+ for (let i = 0; i < n; i++) {
473
+ rest[i * 4] = c.rest[i * 3];
474
+ rest[i * 4 + 1] = c.rest[i * 3 + 1];
475
+ rest[i * 4 + 2] = c.rest[i * 3 + 2];
476
+ rest[i * 4 + 3] = 1;
477
+ restN[i * 4] = c.normals[i * 3];
478
+ restN[i * 4 + 1] = c.normals[i * 3 + 1];
479
+ restN[i * 4 + 2] = c.normals[i * 3 + 2];
480
+ }
481
+ for (let i = 0; i < n * 4; i++) {
482
+ joints[i] = c.joints[i];
483
+ weights[i] = c.weights[i];
484
+ }
485
+ const mk = (d, u) => {
486
+ const b = createBuffer({ size: d.byteLength, usage: u });
487
+ dev.queue.writeBuffer(b, 0, d);
488
+ return b;
489
+ };
490
+ const restB = mk(rest, U.STORAGE | U.COPY_DST), restNB = mk(restN, U.STORAGE | U.COPY_DST), jointsB = mk(joints, U.STORAGE | U.COPY_DST), weightsB = mk(weights, U.STORAGE | U.COPY_DST);
491
+ // ⚠️ `| U.STORAGE` so the instanced vertex stage can read them as arrays. Adding a usage to a
492
+ // buffer that is still bound the same way on the original path changes nothing about it.
493
+ const colB = mk(c.colors, U.VERTEX | U.STORAGE | U.COPY_DST), idxB = mk(c.indices, U.INDEX | U.COPY_DST);
494
+ // A zero-filled UV buffer when the caller has none: the white fallback samples to 1 at any
495
+ // coordinate, so the attribute still has to EXIST but its contents cannot matter.
496
+ const uvB = mk(c.uvs && c.uvs.length >= n * 2 ? c.uvs : new Float32Array(n * 2), U.VERTEX | U.STORAGE | U.COPY_DST);
497
+ // ⚠️ NULL when the caller has no `uvs2` — NOT a second buffer holding a copy of `uvs`.
498
+ //
499
+ // `setCreatures` tears down and rebuilds every buffer on each call and all-mine-sky calls it
500
+ // EVERY FRAME for EVERY creature. Allocating this unconditionally charged every caller in the
501
+ // game — none of which pass `uvs2` — an extra `createBuffer` plus a `writeBuffer` of the same
502
+ // n*2 floats, per creature, per frame, for a buffer whose contents cannot matter: with no
503
+ // tint the 1x1 white samples to 1 at any coordinate. The attribute still has to EXIST, so
504
+ // slot 4 binds `uvB` instead; WebGPU is happy to see the same GPUBuffer in two vertex slots.
505
+ const uv2B = c.uvs2 && c.uvs2.length >= n * 2
506
+ ? mk(c.uvs2, U.VERTEX | U.STORAGE | U.COPY_DST)
507
+ : null;
508
+ const tex = c.tex ?? this.whiteTex;
509
+ const tex2 = c.tex2 ?? this.whiteTex;
510
+ const tint = c.tint ?? this.whiteTex;
511
+ // ⚠️ Keyed on the TRIPLE. Keyed on any subset, two creatures sharing those textures but
512
+ // differing in the others would silently share the first one's bind group.
513
+ const matKey = `${this.texId(tex)}:${this.texId(tex2)}:${this.texId(tint)}`;
514
+ let matBG = materialGroups.get(matKey) ?? this.matBGs.get(matKey);
515
+ matBG ??= dev.createBindGroup({
504
516
  layout: this.drawBGL[2],
505
517
  entries: [
506
518
  { binding: 0, resource: tex.createView() },
@@ -509,117 +521,181 @@ export class GpuSkinRenderer {
509
521
  { binding: 3, resource: tint.createView() },
510
522
  ],
511
523
  });
512
- this.matBGs.set(matKey, matBG);
513
- }
514
- // ── INSTANCING ────────────────────────────────────────────────────────────────────────────
515
- // `count` of 1 with no `instances` is the original path exactly: one palette, one deformed
516
- // copy, P = [n, n, jointCount], which makes the compute shader's inst and po both zero.
517
- const inst = c.instances;
518
- const count = Math.max(1, inst?.count ?? 1);
519
- const palSrc = inst ? inst.palettes : c.palette;
520
- // ⚠️ DERIVED, NOT ASSUMED. jointCount strides the palette per instance, and getting it wrong
521
- // does not throw — it indexes one character's bones through another's offset, so everybody
522
- // after the first wears somebody else's skeleton. Checked against the array length so a
523
- // caller whose palettes do not divide by count is told, rather than rendered wrongly.
524
- const jointCount = Math.floor(palSrc.length / count / 16);
525
- if (inst && jointCount * count * 16 !== palSrc.length)
526
- throw new Error(`gpuSkin: palettes is ${palSrc.length} floats, which is not count(${count}) x jointCount x 16`);
527
- const palB = dev.createBuffer({
528
- size: palSrc.length * 4,
529
- usage: U.STORAGE | U.COPY_DST,
530
- });
531
- dev.queue.writeBuffer(palB, 0, palSrc);
532
- // ⚠️ STORAGE **and** VERTEX on both paths. The instanced vertex stage reads these as arrays
533
- // while the original binds them as vertex buffers, and declaring both usages on one buffer
534
- // costs nothing — it is the same memory, read two ways.
535
- const defB = dev.createBuffer({
536
- size: n * 16 * count,
537
- usage: U.STORAGE | U.VERTEX,
538
- }), defNB = dev.createBuffer({
539
- size: n * 16 * count,
540
- usage: U.STORAGE | U.VERTEX,
541
- });
542
- const pB = dev.createBuffer({ size: 16, usage: U.UNIFORM | U.COPY_DST });
543
- // P.x total invocations, P.y verts per instance, P.z the palette stride.
544
- dev.queue.writeBuffer(pB, 0, new Uint32Array([n * count, n, jointCount, 0]));
545
- const skinBG = dev.createBindGroup({
546
- layout: this.skinPipe.getBindGroupLayout(0),
547
- entries: [
548
- { binding: 0, resource: { buffer: restB } },
549
- { binding: 1, resource: { buffer: jointsB } },
550
- { binding: 2, resource: { buffer: weightsB } },
551
- { binding: 3, resource: { buffer: palB } },
552
- { binding: 4, resource: { buffer: defB } },
553
- { binding: 5, resource: { buffer: pB } },
554
- { binding: 6, resource: { buffer: restNB } },
555
- { binding: 7, resource: { buffer: defNB } },
556
- ],
557
- });
558
- const uBuf = dev.createBuffer({
559
- size: 96 + 16 * 7 + 64 + 16 + 64 * MAX_CASCADES + 16, // + csm vec4 + cascades + blend vec4
560
- usage: U.UNIFORM | U.COPY_DST,
561
- });
562
- const uBG = dev.createBindGroup({
563
- layout: this.drawBGL[0],
564
- entries: [{ binding: 0, resource: { buffer: uBuf } }],
565
- });
566
- // Group 3 exists only for an instanced creature — the single-instance pipeline never binds it.
567
- let instBG = null;
568
- let instModelB = null;
569
- let instParamB = null;
570
- if (inst) {
571
- instModelB = dev.createBuffer({
572
- size: count * 64,
524
+ // ── INSTANCING ────────────────────────────────────────────────────────────────────────────
525
+ // `count` of 1 with no `instances` is the original path exactly: one palette, one deformed
526
+ // copy, P = [n, n, jointCount], which makes the compute shader's inst and po both zero.
527
+ materialGroups.set(matKey, matBG);
528
+ const inst = c.instances;
529
+ const count = Math.max(1, inst?.count ?? 1);
530
+ const palSrc = inst ? inst.palettes : c.palette;
531
+ // ⚠️ DERIVED, NOT ASSUMED. jointCount strides the palette per instance, and getting it wrong
532
+ // does not throw — it indexes one character's bones through another's offset, so everybody
533
+ // after the first wears somebody else's skeleton. Checked against the array length so a
534
+ // caller whose palettes do not divide by count is told, rather than rendered wrongly.
535
+ const jointCount = Math.floor(palSrc.length / count / 16);
536
+ if (inst && jointCount * count * 16 !== palSrc.length)
537
+ throw new Error(`gpuSkin: palettes is ${palSrc.length} floats, which is not count(${count}) x jointCount x 16`);
538
+ const palB = createBuffer({
539
+ size: palSrc.length * 4,
573
540
  usage: U.STORAGE | U.COPY_DST,
574
541
  });
575
- dev.queue.writeBuffer(instModelB, 0, inst.models);
576
- instParamB = dev.createBuffer({
577
- size: 16,
578
- usage: U.UNIFORM | U.COPY_DST,
542
+ dev.queue.writeBuffer(palB, 0, palSrc);
543
+ // ⚠️ STORAGE **and** VERTEX on both paths. The instanced vertex stage reads these as arrays
544
+ // while the original binds them as vertex buffers, and declaring both usages on one buffer
545
+ // costs nothing — it is the same memory, read two ways.
546
+ const defB = createBuffer({
547
+ size: n * 16 * count,
548
+ usage: U.STORAGE | U.VERTEX,
549
+ }), defNB = createBuffer({
550
+ size: n * 16 * count,
551
+ usage: U.STORAGE | U.VERTEX,
579
552
  });
580
- dev.queue.writeBuffer(instParamB, 0, new Uint32Array([n, 0, 0, 0]));
581
- instBG = dev.createBindGroup({
582
- layout: this.instBGL,
553
+ const pB = createBuffer({ size: 16, usage: U.UNIFORM | U.COPY_DST });
554
+ // P.x total invocations, P.y verts per instance, P.z the palette stride.
555
+ dev.queue.writeBuffer(pB, 0, new Uint32Array([n * count, n, jointCount, 0]));
556
+ const skinBG = dev.createBindGroup({
557
+ layout: this.skinPipe.getBindGroupLayout(0),
583
558
  entries: [
584
- { binding: 0, resource: { buffer: defB } },
585
- { binding: 1, resource: { buffer: defNB } },
586
- { binding: 2, resource: { buffer: colB } },
587
- { binding: 3, resource: { buffer: uvB } },
588
- { binding: 4, resource: { buffer: uv2B ?? uvB } },
589
- { binding: 5, resource: { buffer: instModelB } },
590
- { binding: 6, resource: { buffer: instParamB } },
559
+ { binding: 0, resource: { buffer: restB } },
560
+ { binding: 1, resource: { buffer: jointsB } },
561
+ { binding: 2, resource: { buffer: weightsB } },
562
+ { binding: 3, resource: { buffer: palB } },
563
+ { binding: 4, resource: { buffer: defB } },
564
+ { binding: 5, resource: { buffer: pB } },
565
+ { binding: 6, resource: { buffer: restNB } },
566
+ { binding: 7, resource: { buffer: defNB } },
591
567
  ],
592
568
  });
593
- }
594
- return {
595
- count,
596
- instBG,
597
- instModelB,
598
- instParamB,
599
- restB,
600
- restNB,
601
- jointsB,
602
- weightsB,
603
- defB,
604
- defNB,
605
- colB,
606
- uvB,
607
- uv2B,
608
- matBG,
609
- idxB,
610
- idxCount: c.indices.length,
611
- skinBG,
612
- uBuf,
613
- uBG,
614
- palB,
615
- pB,
616
- n,
617
- model: c.model,
618
- mix: c.mix ?? 0,
619
- alpha: c.alpha ?? 1,
620
- cutout: c.cutout ?? 0,
621
- };
622
- });
569
+ const uBuf = createBuffer({
570
+ size: 96 + 16 * 7 + 64 + 16 + 64 * MAX_CASCADES + 16, // + csm vec4 + cascades + blend vec4
571
+ usage: U.UNIFORM | U.COPY_DST,
572
+ });
573
+ const uBG = dev.createBindGroup({
574
+ layout: this.drawBGL[0],
575
+ entries: [{ binding: 0, resource: { buffer: uBuf } }],
576
+ });
577
+ // Group 3 exists only for an instanced creature — the single-instance pipeline never binds it.
578
+ let instBG = null;
579
+ let instModelB = null;
580
+ let instParamB = null;
581
+ if (inst) {
582
+ instModelB = createBuffer({
583
+ size: count * 64,
584
+ usage: U.STORAGE | U.COPY_DST,
585
+ });
586
+ dev.queue.writeBuffer(instModelB, 0, inst.models);
587
+ instParamB = createBuffer({
588
+ size: 16,
589
+ usage: U.UNIFORM | U.COPY_DST,
590
+ });
591
+ dev.queue.writeBuffer(instParamB, 0, new Uint32Array([n, 0, 0, 0]));
592
+ instBG = dev.createBindGroup({
593
+ layout: this.instBGL,
594
+ entries: [
595
+ { binding: 0, resource: { buffer: defB } },
596
+ { binding: 1, resource: { buffer: defNB } },
597
+ { binding: 2, resource: { buffer: colB } },
598
+ { binding: 3, resource: { buffer: uvB } },
599
+ { binding: 4, resource: { buffer: uv2B ?? uvB } },
600
+ { binding: 5, resource: { buffer: instModelB } },
601
+ { binding: 6, resource: { buffer: instParamB } },
602
+ ],
603
+ });
604
+ }
605
+ return {
606
+ count,
607
+ instBG,
608
+ instModelB,
609
+ instParamB,
610
+ restB,
611
+ restNB,
612
+ jointsB,
613
+ weightsB,
614
+ defB,
615
+ defNB,
616
+ colB,
617
+ uvB,
618
+ uv2B,
619
+ matBG,
620
+ idxB,
621
+ idxCount: c.indices.length,
622
+ skinBG,
623
+ uBuf,
624
+ uBG,
625
+ palB,
626
+ pB,
627
+ n,
628
+ paletteFloats: palSrc.length,
629
+ model: c.model,
630
+ mix: c.mix ?? 0,
631
+ alpha: c.alpha ?? 1,
632
+ cutout: c.cutout ?? 0,
633
+ };
634
+ });
635
+ }
636
+ catch (error) {
637
+ for (const buffer of allocated)
638
+ buffer.destroy();
639
+ throw error;
640
+ }
641
+ for (const packed of this.packed)
642
+ destroyPackedBuffers(packed);
643
+ this.packed = next;
644
+ this.matBGs = materialGroups;
645
+ }
646
+ /**
647
+ * Upload a new pose without reinstalling geometry. The list addresses the current
648
+ * installed slots in order. Validate every slot before any GPU write; topology,
649
+ * textures or instance-count changes require setCreatures instead. Existing
650
+ * setCreatures callers retain their full replacement semantics, including arrays
651
+ * whose contents were modified in place.
652
+ */
653
+ updatePoses(list) {
654
+ this.assertLive();
655
+ if (list.length !== this.packed.length)
656
+ throw new Error('gpuSkin: pose count differs from installed creatures');
657
+ for (let i = 0; i < list.length; i++) {
658
+ const pose = list[i], packed = this.packed[i];
659
+ const instances = pose.instances;
660
+ if (Boolean(instances) !== Boolean(packed.instBG) ||
661
+ (instances && instances.count !== packed.count))
662
+ throw new Error('gpuSkin: pose instance count differs from installed creature');
663
+ if (pose.model.length !== 16 ||
664
+ (instances && instances.models.length !== packed.count * 16))
665
+ throw new Error('gpuSkin: pose model must contain 16 floats per instance');
666
+ if ((instances?.palettes ?? pose.palette).length !== packed.paletteFloats)
667
+ throw new Error('gpuSkin: pose palette differs from installed skeleton');
668
+ }
669
+ for (let i = 0; i < list.length; i++) {
670
+ const pose = list[i], packed = this.packed[i];
671
+ this.device.queue.writeBuffer(packed.palB, 0, (pose.instances?.palettes ??
672
+ pose.palette));
673
+ if (pose.instances && packed.instModelB)
674
+ this.device.queue.writeBuffer(packed.instModelB, 0, pose.instances.models);
675
+ packed.model = pose.model;
676
+ packed.mix = pose.mix ?? 0;
677
+ packed.alpha = pose.alpha ?? 1;
678
+ packed.cutout = pose.cutout ?? 0;
679
+ }
680
+ }
681
+ /** Release only renderer-owned resources. Caller-supplied textures remain owned by the caller. */
682
+ dispose() {
683
+ if (this.disposed)
684
+ return;
685
+ this.disposed = true;
686
+ for (const packed of this.packed)
687
+ destroyPackedBuffers(packed);
688
+ this.packed = [];
689
+ this.matBGs.clear();
690
+ this.shadowBG = null;
691
+ this.lastSV = null;
692
+ this.lastSS = null;
693
+ this.whiteTex.destroy();
694
+ this.dummyShadow.destroy();
695
+ }
696
+ assertLive() {
697
+ if (this.disposed)
698
+ throw new Error('gpuSkin: renderer is disposed');
623
699
  }
624
700
  /** Deform + draw every creature with the shared scene lighting. load=true composites over the world;
625
701
  * otherwise clears to `clear`. sun/sunCol/amb/cam/fog/fogDensity match the terrain & prop renderers. */
@@ -627,6 +703,7 @@ export class GpuSkinRenderer {
627
703
  // Optional sun shadow-receive: pass the terrain's lightVP + shadow-map view + comparison sampler and creatures
628
704
  // sit in the same shadow. Omit all three (the demo path) → no shadowing, byte-identical to before.
629
705
  lightVP, shadowView, shadowSamp) {
706
+ this.assertLive();
630
707
  const receive = !!(lightVP && shadowView && shadowSamp);
631
708
  const mats = lightVP ? (Array.isArray(lightVP) ? lightVP : [lightVP]) : [];
632
709
  const cp = enc.beginComputePass();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.46",
3
+ "version": "0.15.48",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -15,20 +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
- "test": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/*.test.mts",
24
- "test:flight": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/flight*.test.mts",
25
- "test:flight-browser": "playwright test -c playwright.flight.config.ts",
26
- "test:flight-perf": "playwright test -c playwright.flight.config.ts --grep 'CPU and retained-memory'",
27
- "test:types": "tsc -p tsconfig.test.json",
28
- "test:package-types": "node tools/packageTypesSmoke.mjs",
29
- "pretty": "prettier --write .",
30
- "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/"
31
- },
32
18
  "dependencies": {
33
19
  "@webgpu/types": "^0.1.40",
34
20
  "meshoptimizer": "^1.2.0"
@@ -44,5 +30,19 @@
44
30
  "typescript": "^5.6.0",
45
31
  "ugly-app": "^0.1.841",
46
32
  "wesl": "0.7.28"
33
+ },
34
+ "scripts": {
35
+ "preinstall": "npx only-allow pnpm",
36
+ "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/",
37
+ "lint": "ugly-app lint",
38
+ "lint:fix": "ugly-app lint --fix",
39
+ "test": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/*.test.mts && pnpm run test:gpu-skin",
40
+ "test:flight": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/flight*.test.mts",
41
+ "test:flight-browser": "playwright test -c playwright.flight.config.ts",
42
+ "test:flight-perf": "playwright test -c playwright.flight.config.ts --grep 'CPU and retained-memory'",
43
+ "test:types": "tsc -p tsconfig.test.json",
44
+ "test:package-types": "node tools/packageTypesSmoke.mjs",
45
+ "pretty": "prettier --write .",
46
+ "test:gpu-skin": "node --experimental-transform-types --import ./tools/tsResolve.mjs --test src/assets/gpuSkin.test.mts"
47
47
  }
48
- }
48
+ }