ugly-game 0.15.76 → 0.15.77

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.
@@ -141,6 +141,12 @@ export interface PropMesh {
141
141
  normalMap?: GPUTexture;
142
142
  /** Thin-glass transmission [0,1]. Use alpha < 1 and depthWrite false. */
143
143
  transmission?: number;
144
+ /** Optical path in unscaled model units. With a frame's copyable scene
145
+ * texture, bend its real pixels through this thickness. Requires a blended
146
+ * transmissive surface. Without a snapshot, thin-glass blending is used. */
147
+ glassThickness?: number;
148
+ /** Dielectric index used for bending and Fresnel coverage. Defaults to 1.5. */
149
+ glassIOR?: number;
144
150
  /** Display-referred albedo render texture, bypassing lighting/tone mapping. */
145
151
  unlit?: boolean;
146
152
  /**
@@ -309,7 +315,16 @@ export interface PropInstance {
309
315
  }
310
316
  export declare class GpuPropsRenderer {
311
317
  private device;
318
+ private format;
312
319
  private inspection;
320
+ private glassInstances;
321
+ private glassVP;
322
+ private snapshots;
323
+ /** Number of source pixels copied by the most recent scene and late passes. */
324
+ readonly glassCopyPixels: {
325
+ scene: number;
326
+ presentation: number;
327
+ };
313
328
  private srgbTarget;
314
329
  private presentation?;
315
330
  private sceneCounts;
@@ -487,9 +502,12 @@ export declare class GpuPropsRenderer {
487
502
  * a single shared uniform written once per cascade during encoding does not work — see `lightBufs`.
488
503
  */
489
504
  shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array, cascade?: number): void;
490
- 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, up?: [number, number, number], lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler, channel?: PropInspectionChannel): void;
505
+ 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, up?: [number, number, number], lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler, channel?: PropInspectionChannel, sceneTexture?: GPUTexture): void;
491
506
  /** Draw over the presented compositor result, testing its final depth.
492
507
  * Reuses the same uploaded instances, material bindings and frame uniforms. */
493
- framePresentation(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView): void;
508
+ framePresentation(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView, sceneTexture?: GPUTexture): void;
494
509
  private encodeColor;
510
+ /** Release renderer-owned backdrop storage on teardown or after a resize. */
511
+ releaseGlassSnapshots(): void;
512
+ private colorPass;
495
513
  }
@@ -6,6 +6,7 @@
6
6
  // ─────────────────────────────────────────────────────────────────────────────
7
7
  // The cull reuses the SAME plane extraction the rest of the engine uses. A second, local copy of
8
8
  // Gribb-Hartmann is exactly how a cull ends up disagreeing with the projection it is culling for.
9
+ import { glassBounds, glassCopyRegion, } from './propGlass.js';
9
10
  import { WET_RIND_WGSL } from './wetRind.js';
10
11
  export { WET_RIND_WGSL } from './wetRind.js';
11
12
  import { INTERIOR_LIGHT_WGSL } from './interiorLight.js';
@@ -62,7 +63,8 @@ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32
62
63
  // Renderer-wide linear HDR equirect (PropLook.environment). A 1×1 dummy when unset, and then never
63
64
  // sampled: look.z and look.w are forced to 0 on the CPU without it.
64
65
  @group(1) @binding(2) var sceneEnvTex: texture_2d<f32>;
65
- struct VO { @builtin(position) pos: vec4<f32>, @location(0) world: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: vec3<f32>, @location(3) l: vec3<f32>, @location(4) uv: vec2<f32> ${split ? ', @location(6) clipDistance: f32' : ''} ${inspect ? ', @location(5) @interpolate(linear) bary:vec3<f32>' : ''} };
66
+ @group(1) @binding(3) var transmittedScene: texture_2d<f32>;
67
+ struct VO { @builtin(position) pos: vec4<f32>, @location(0) world: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: vec3<f32>, @location(3) l: vec3<f32>, @location(4) uv: vec2<f32>, @location(7) glassScale:f32 ${split ? ', @location(6) clipDistance: f32' : ''} ${inspect ? ', @location(5) @interpolate(linear) bary:vec3<f32>' : ''} };
66
68
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
67
69
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
68
70
  // in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
@@ -135,7 +137,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
135
137
  world = sway(lp, world, upv, sc * inst.d2.w);
136
138
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
137
139
  ${split ? 'o.clipDistance = dot(world,vec3(m[0].w,m[1].w,m[2].w))+inst.d3.w;' : ''}
138
- o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
140
+ o.glassScale = sc; o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
139
141
  ${inspect ? 'o.bary = vec3<f32>(f32(vi%3u==0u),f32(vi%3u==1u),f32(vi%3u==2u));' : ''}
140
142
  return o;
141
143
  }
@@ -374,7 +376,10 @@ fn effectiveAO(orm:vec3<f32>) -> f32 { return select(1.0,orm.r,mtl.maps.y>0.5);
374
376
  fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
375
377
  if (mtl.optics.x <= 0.0) { return mtl.mat.x; }
376
378
  let nv = clamp(abs(dot(n,normalize(u.cam.xyz-world))),0.0,1.0);
377
- let F = 0.04 + 0.96*pow(1.0-nv,5.0);
379
+ let eta = max(1.0,mtl.medium.z);
380
+ let r = (eta-1.0)/(eta+1.0);
381
+ let f0 = select(0.04,r*r,mtl.medium.w>0.0);
382
+ let F = f0 + (1.0-f0)*pow(1.0-nv,5.0);
378
383
  return clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
379
384
  }
380
385
  ${THIN_TISSUE_WGSL}
@@ -552,7 +557,23 @@ fn shade(i: VO) -> vec4<f32> {
552
557
  }
553
558
  @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
554
559
  let color = shade(i);
555
- return ${transfer ? 'vec4(encodePropPresentation(color.rgb),color.a)' : 'color'};
560
+ let output = ${transfer ? 'vec4(encodePropPresentation(color.rgb),color.a)' : 'color'};
561
+ if (mtl.medium.w > 0.0 && textureDimensions(transmittedScene).x > 1u) {
562
+ let size = vec2<f32>(textureDimensions(transmittedScene));
563
+ let V = normalize(u.cam.xyz-i.world);
564
+ let N = faceForward(normalize(i.n),-V,normalize(i.n));
565
+ let ray = refract(-V,N,1.0/mtl.medium.z);
566
+ let path = mtl.medium.w*i.glassScale;
567
+ let clear = u.mvp*vec4(i.world-V*path,1.0);
568
+ let bent = u.mvp*vec4(i.world+ray*path,1.0);
569
+ let shift = (bent.xy/max(0.001,bent.w)-clear.xy/max(0.001,clear.w))*vec2(0.5,-0.5);
570
+ let coord = clamp(i.pos.xy/size+shift,0.5/size,1.0-0.5/size);
571
+ let through = textureSampleLevel(transmittedScene,albedoSamp,coord,0.0).rgb;
572
+ let density = vec3(1.0)-clamp(srgbToLinear(i.c),vec3(0.0),vec3(1.0));
573
+ let absorb = exp(-density*mtl.medium.w/max(0.35,-dot(ray,N)));
574
+ return vec4(mix(through*absorb,output.rgb,output.a),1.0);
575
+ }
576
+ return output;
556
577
  }`;
557
578
  // Depth-only occluder pass: instanced prop depth from the sun's ortho view (so trees/rocks cast shadows).
558
579
  // Depth-only occluder. It MUST apply the identical sway, or the shadows stay put while the leaves
@@ -704,7 +725,13 @@ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
704
725
  `;
705
726
  export class GpuPropsRenderer {
706
727
  device;
728
+ format;
707
729
  inspection;
730
+ glassInstances = [];
731
+ glassVP = new Float32Array(16);
732
+ snapshots = [];
733
+ /** Number of source pixels copied by the most recent scene and late passes. */
734
+ glassCopyPixels = { scene: 0, presentation: 0 };
708
735
  srgbTarget;
709
736
  presentation;
710
737
  sceneCounts = new Uint32Array(0);
@@ -868,6 +895,7 @@ export class GpuPropsRenderer {
868
895
  }
869
896
  constructor(device, format, options = {}) {
870
897
  this.device = device;
898
+ this.format = format;
871
899
  const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', presentation, ...look } = options;
872
900
  // Runtime guard for untyped callers: WebGPU only guarantees 1 and 4.
873
901
  if (![1, 4].includes(sampleCount))
@@ -917,6 +945,11 @@ export class GpuPropsRenderer {
917
945
  visibility: GPUShaderStage.FRAGMENT,
918
946
  texture: { sampleType: 'float' },
919
947
  },
948
+ {
949
+ binding: 3,
950
+ visibility: GPUShaderStage.FRAGMENT,
951
+ texture: { sampleType: 'float' },
952
+ },
920
953
  ],
921
954
  });
922
955
  const bgl2 = device.createBindGroupLayout({
@@ -1221,6 +1254,9 @@ export class GpuPropsRenderer {
1221
1254
  this.device.queue.writeBuffer(packed.matBuf, 0, packed.materialValues);
1222
1255
  }
1223
1256
  setModels(meshes) {
1257
+ this.glassInstances.length = 0;
1258
+ if (!meshes.some((m) => m.glassThickness))
1259
+ this.releaseGlassSnapshots();
1224
1260
  this.inspectionGeometry?.destroy();
1225
1261
  if (this.inspection)
1226
1262
  this.inspectionGeometry = new PropInspectionGeometry(this.device, meshes);
@@ -1362,12 +1398,18 @@ export class GpuPropsRenderer {
1362
1398
  Math.max(0, Math.min(1, m.directClearcoat ?? 0)),
1363
1399
  Math.max(0, Math.min(8, m.interiorOpticalDepth ?? 0)),
1364
1400
  Math.max(0, m.wetRindHeight ?? 0),
1365
- 0,
1366
- 0,
1401
+ Math.min(2.8, Math.max(1, m.glassIOR ?? 1.5)),
1402
+ Math.max(0, m.glassThickness ?? 0),
1367
1403
  ]);
1368
1404
  dev.queue.writeBuffer(matBuf, 0, materialValues);
1369
1405
  return {
1370
1406
  alpha,
1407
+ ...(m.glassThickness &&
1408
+ m.glassThickness > 0 &&
1409
+ m.transmission &&
1410
+ alpha < 1
1411
+ ? { glassBounds: glassBounds(m.positions, m.glassThickness) }
1412
+ : {}),
1371
1413
  cullMode: m.cullMode ?? 'none',
1372
1414
  depthWrite: m.depthWrite ?? true,
1373
1415
  cutout,
@@ -1417,6 +1459,7 @@ export class GpuPropsRenderer {
1417
1459
  * re-allocating a megabyte of storage buffers per frame would cost more than the LOD saves.
1418
1460
  */
1419
1461
  setInstances(instances) {
1462
+ this.glassInstances.length = 0;
1420
1463
  const dev = this.device;
1421
1464
  const n = this.models.length;
1422
1465
  const counts = new Uint32Array(n);
@@ -1451,6 +1494,14 @@ export class GpuPropsRenderer {
1451
1494
  for (const it of instances) {
1452
1495
  if (it.model < 0 || it.model >= n)
1453
1496
  continue;
1497
+ const bounds = this.models[it.model].glassBounds;
1498
+ if (bounds)
1499
+ this.glassInstances.push({
1500
+ bounds,
1501
+ mat: it.mat,
1502
+ early: !split || it.presentation !== true,
1503
+ late: split && !!it.presentation,
1504
+ });
1454
1505
  const arr = arrays[it.model];
1455
1506
  const cursor = !split || !it.presentation
1456
1507
  ? cursors
@@ -1717,7 +1768,10 @@ export class GpuPropsRenderer {
1717
1768
  frame(enc, colorView, depthView, camVP, sunDir, sunCol, amb, camPos, fog, fogDensity, up,
1718
1769
  // Optional sun shadow-receive: pass the terrain's lightVP + shadow-map view + comparison sampler and props sit
1719
1770
  // in the same shadow. Omit all three (the demo path) → no shadowing, byte-identical to before.
1720
- lightVP, shadowView, shadowSamp, channel = 'lit') {
1771
+ lightVP, shadowView, shadowSamp, channel = 'lit', sceneTexture) {
1772
+ if (this.glassInstances.length)
1773
+ this.glassVP.set(camVP);
1774
+ this.glassCopyPixels.scene = this.glassCopyPixels.presentation = 0;
1721
1775
  if (channel !== 'lit' && !this.inspection)
1722
1776
  throw new Error('Prop inspection must be enabled at construction.');
1723
1777
  const receive = !!(lightVP && shadowView && shadowSamp);
@@ -1780,21 +1834,73 @@ export class GpuPropsRenderer {
1780
1834
  { binding: 0, resource: sv },
1781
1835
  { binding: 1, resource: ss },
1782
1836
  { binding: 2, resource: (env ?? this.dummyEnv).createView() },
1837
+ { binding: 3, resource: this.dummyEnv.createView() },
1783
1838
  ],
1784
1839
  });
1785
1840
  this.lastSV = sv;
1786
1841
  this.lastSS = ss;
1787
1842
  this.lastEnv = env;
1788
1843
  }
1789
- this.encodeColor(enc, colorView, depthView, channel, false);
1844
+ this.encodeColor(enc, colorView, depthView, channel, false, sceneTexture);
1790
1845
  }
1791
1846
  /** Draw over the presented compositor result, testing its final depth.
1792
1847
  * Reuses the same uploaded instances, material bindings and frame uniforms. */
1793
- framePresentation(enc, colorView, depthView) {
1848
+ framePresentation(enc, colorView, depthView, sceneTexture) {
1794
1849
  if (this.hasPresentation && this.presentation)
1795
- this.encodeColor(enc, colorView, depthView, 'lit', true);
1850
+ this.encodeColor(enc, colorView, depthView, 'lit', true, sceneTexture);
1851
+ }
1852
+ encodeColor(enc, colorView, depthView, channel, late, source) {
1853
+ const crop = source &&
1854
+ channel === 'lit' &&
1855
+ source.sampleCount === 1 &&
1856
+ this.glassInstances.length
1857
+ ? glassCopyRegion(this.glassInstances, this.glassVP, source.width, source.height, late)
1858
+ : undefined;
1859
+ this.colorPass(enc, colorView, depthView, channel, late, this.shadowBG, crop ? 'background' : 'all');
1860
+ if (!crop || !source)
1861
+ return;
1862
+ const format = late ? this.presentation.format : this.format;
1863
+ const slot = Number(late);
1864
+ let entry = this.snapshots[slot];
1865
+ if (entry?.texture.width !== source.width ||
1866
+ entry.texture.height !== source.height ||
1867
+ entry.texture.format !== format) {
1868
+ entry?.texture.destroy();
1869
+ const texture = this.device.createTexture({
1870
+ label: 'prop-glass-backdrop',
1871
+ format,
1872
+ size: [source.width, source.height],
1873
+ usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
1874
+ });
1875
+ this.snapshots[slot] = entry = { texture, view: texture.createView() };
1876
+ }
1877
+ enc.copyTextureToTexture({ texture: source, origin: crop.origin }, { texture: entry.texture, origin: crop.origin }, crop.size);
1878
+ this.glassCopyPixels[late ? 'presentation' : 'scene'] =
1879
+ crop.size.width * crop.size.height;
1880
+ if (!entry.group || entry.shadow !== this.shadowBG) {
1881
+ entry.shadow = this.shadowBG;
1882
+ entry.group = this.device.createBindGroup({
1883
+ layout: this.drawBGL[1],
1884
+ entries: [
1885
+ { binding: 0, resource: this.lastSV },
1886
+ { binding: 1, resource: this.lastSS },
1887
+ {
1888
+ binding: 2,
1889
+ resource: (this.lastEnv ?? this.dummyEnv).createView(),
1890
+ },
1891
+ { binding: 3, resource: entry.view },
1892
+ ],
1893
+ });
1894
+ }
1895
+ this.colorPass(enc, colorView, depthView, channel, late, entry.group, 'glass');
1796
1896
  }
1797
- encodeColor(enc, colorView, depthView, channel, late) {
1897
+ /** Release renderer-owned backdrop storage on teardown or after a resize. */
1898
+ releaseGlassSnapshots() {
1899
+ for (const snapshot of this.snapshots)
1900
+ snapshot?.texture.destroy();
1901
+ this.snapshots = [];
1902
+ }
1903
+ colorPass(enc, colorView, depthView, channel, late, lighting, selection) {
1798
1904
  const topology = channel === 'wireframe' || channel === 'density';
1799
1905
  const rp = enc.beginRenderPass({
1800
1906
  colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }],
@@ -1804,7 +1910,7 @@ export class GpuPropsRenderer {
1804
1910
  depthStoreOp: 'store',
1805
1911
  },
1806
1912
  });
1807
- rp.setBindGroup(1, this.shadowBG);
1913
+ rp.setBindGroup(1, lighting);
1808
1914
  // The arena, bound once for every model in both loops below.
1809
1915
  if (topology)
1810
1916
  this.inspectionGeometry?.bind(rp);
@@ -1836,6 +1942,9 @@ export class GpuPropsRenderer {
1836
1942
  for (const blended of [false, true]) {
1837
1943
  for (let m = 0; m < this.models.length; m++) {
1838
1944
  const model = this.models[m];
1945
+ if (selection !== 'all' &&
1946
+ !!model.glassBounds !== (selection === 'glass'))
1947
+ continue;
1839
1948
  const clay = channel === 'clay';
1840
1949
  const first = late ? this.presentationFirst[m] : 0;
1841
1950
  const count = this.presentation
@@ -0,0 +1,23 @@
1
+ /** Local bounds expanded to include the exit point of a refracted ray. */
2
+ export declare function glassBounds(positions: Float32Array, thickness: number): {
3
+ low: number[];
4
+ high: number[];
5
+ };
6
+ export interface GlassBoundsInstance {
7
+ bounds: ReturnType<typeof glassBounds>;
8
+ mat: Float32Array;
9
+ early: boolean;
10
+ late: boolean;
11
+ }
12
+ /** The copy keeps original pixel coordinates inside a retained scratch texture.
13
+ * Sampling is clamped to the viewport, including when a lens crosses its edge. */
14
+ export declare function glassCopyRegion(instances: readonly GlassBoundsInstance[], vp: Float32Array, width: number, height: number, late: boolean): {
15
+ origin: {
16
+ x: number;
17
+ y: number;
18
+ };
19
+ size: {
20
+ width: number;
21
+ height: number;
22
+ };
23
+ } | undefined;
@@ -0,0 +1,57 @@
1
+ /** Local bounds expanded to include the exit point of a refracted ray. */
2
+ export function glassBounds(positions, thickness) {
3
+ const low = [Infinity, Infinity, Infinity];
4
+ const high = [-Infinity, -Infinity, -Infinity];
5
+ for (let i = 0; i < positions.length; i += 3) {
6
+ for (let k = 0; k < 3; k++) {
7
+ low[k] = Math.min(low[k], positions[i + k] - thickness * 2);
8
+ high[k] = Math.max(high[k], positions[i + k] + thickness * 2);
9
+ }
10
+ }
11
+ return { low, high };
12
+ }
13
+ /** The copy keeps original pixel coordinates inside a retained scratch texture.
14
+ * Sampling is clamped to the viewport, including when a lens crosses its edge. */
15
+ export function glassCopyRegion(instances, vp, width, height, late) {
16
+ let left = width, right = 0, top = height, bottom = 0;
17
+ for (const instance of instances) {
18
+ if (!(late ? instance.late : instance.early))
19
+ continue;
20
+ const m = instance.mat, { low, high } = instance.bounds;
21
+ let l = width, r = 0, t = height, b = 0;
22
+ let inFront = false, behind = false;
23
+ for (let corner = 0; corner < 8; corner++) {
24
+ const x = corner & 1 ? high[0] : low[0], y = corner & 2 ? high[1] : low[1], z = corner & 4 ? high[2] : low[2];
25
+ const wx = m[0] * x + m[4] * y + m[8] * z + m[12];
26
+ const wy = m[1] * x + m[5] * y + m[9] * z + m[13];
27
+ const wz = m[2] * x + m[6] * y + m[10] * z + m[14];
28
+ const w = vp[3] * wx + vp[7] * wy + vp[11] * wz + vp[15];
29
+ if (w <= 0.001) {
30
+ behind = true;
31
+ continue;
32
+ }
33
+ inFront = true;
34
+ const sx = (0.5 + (0.5 * (vp[0] * wx + vp[4] * wy + vp[8] * wz + vp[12])) / w) *
35
+ width;
36
+ const sy = (0.5 - (0.5 * (vp[1] * wx + vp[5] * wy + vp[9] * wz + vp[13])) / w) *
37
+ height;
38
+ l = Math.min(l, sx);
39
+ r = Math.max(r, sx);
40
+ t = Math.min(t, sy);
41
+ b = Math.max(b, sy);
42
+ }
43
+ if (!inFront)
44
+ continue;
45
+ if (behind)
46
+ return { origin: { x: 0, y: 0 }, size: { width, height } };
47
+ left = Math.min(left, l);
48
+ right = Math.max(right, r);
49
+ top = Math.min(top, t);
50
+ bottom = Math.max(bottom, b);
51
+ }
52
+ const x = Math.max(0, Math.floor(left) - 2), y = Math.max(0, Math.floor(top) - 2);
53
+ const w = Math.min(width, Math.ceil(right) + 2) - x, h = Math.min(height, Math.ceil(bottom) + 2) - y;
54
+ return w > 0 && h > 0
55
+ ? { origin: { x, y }, size: { width: w, height: h } }
56
+ : undefined;
57
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.76",
3
+ "version": "0.15.77",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {