ugly-game 0.15.75 → 0.15.76

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.
@@ -96,6 +96,13 @@ export interface PropLook {
96
96
  }
97
97
  /** Constructor options. All optional; omitting them is the historical renderer. */
98
98
  export interface PropRendererOptions extends Partial<PropLook> {
99
+ /** Optional second colour attachment for translucent props layered after a
100
+ * compositor. The caller supplies WGSL defining encodePropPresentation(rgb:
101
+ * vec3<f32>) -> vec3<f32>. Use linear tone mapping for a scene-linear input. */
102
+ presentation?: {
103
+ format: GPUTextureFormat;
104
+ transferWGSL: string;
105
+ };
99
106
  /** Compile material/topology inspection channels. Off by default. On the
100
107
  * first topology view, an expanded corner stream is built for wire/density. */
101
108
  inspection?: boolean;
@@ -291,6 +298,10 @@ export interface PropDeform {
291
298
  tint?: readonly [number, number, number];
292
299
  }
293
300
  export interface PropInstance {
301
+ /** Draw after the compositor, or split at a plane in the same rebased world
302
+ * coordinates as mat. Positive distances go to presentation, negative to
303
+ * the original scene. The default remains wholly in the original scene. */
304
+ presentation?: true | readonly [number, number, number, number];
294
305
  model: number;
295
306
  mat: Float32Array;
296
307
  /** Optional per-instance deform. Omitted ⇒ the mesh is drawn exactly as authored. */
@@ -300,6 +311,10 @@ export declare class GpuPropsRenderer {
300
311
  private device;
301
312
  private inspection;
302
313
  private srgbTarget;
314
+ private presentation?;
315
+ private sceneCounts;
316
+ private presentationFirst;
317
+ private hasPresentation;
303
318
  private inspectionGeometry?;
304
319
  private pipe;
305
320
  /**
@@ -473,4 +488,8 @@ export declare class GpuPropsRenderer {
473
488
  */
474
489
  shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array, cascade?: number): void;
475
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;
491
+ /** Draw over the presented compositor result, testing its final depth.
492
+ * Reuses the same uploaded instances, material bindings and frame uniforms. */
493
+ framePresentation(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView): void;
494
+ private encodeColor;
476
495
  }
@@ -19,7 +19,7 @@ export const MAX_CASCADES = 4; // must match gpuShadow's
19
19
  export const MAX_PROP_POINT_LIGHTS = 8;
20
20
  const POINT_LIGHT_WORDS = 4 + MAX_PROP_POINT_LIGHTS * 16;
21
21
  const PROP_UNIFORM_WORDS = 72 + 16 * MAX_CASCADES + 8 + POINT_LIGHT_WORDS;
22
- const drawShader = (inspect) => /* wgsl */ `
22
+ const drawShader = (inspect, split, transfer = '') => /* wgsl */ `
23
23
  // wind = (dirX, dirZ, amplitude, phase) — sway, amplitude scaled by the world's air density
24
24
  // surf = (grainScale, grainDepth, roughness, emissive)
25
25
  // grade = (hueShift, saturation, valueLift, unused)
@@ -62,7 +62,7 @@ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32
62
62
  // Renderer-wide linear HDR equirect (PropLook.environment). A 1×1 dummy when unset, and then never
63
63
  // sampled: look.z and look.w are forced to 0 on the CPU without it.
64
64
  @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> ${inspect ? ', @location(5) @interpolate(linear) bary:vec3<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
66
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
67
67
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
68
68
  // in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
@@ -134,6 +134,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
134
134
  let sc = length(m[0].xyz);
135
135
  world = sway(lp, world, upv, sc * inst.d2.w);
136
136
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
137
+ ${split ? 'o.clipDistance = dot(world,vec3(m[0].w,m[1].w,m[2].w))+inst.d3.w;' : ''}
137
138
  o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
138
139
  ${inspect ? 'o.bary = vec3<f32>(f32(vi%3u==0u),f32(vi%3u==1u),f32(vi%3u==2u));' : ''}
139
140
  return o;
@@ -377,7 +378,9 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
377
378
  return clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
378
379
  }
379
380
  ${THIN_TISSUE_WGSL}
380
- @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
381
+ ${transfer}
382
+ fn shade(i: VO) -> vec4<f32> {
383
+ ${split ? (transfer ? 'if (i.clipDistance < 0.0) { discard; }' : 'if (i.clipDistance >= 0.0) { discard; }') : ''}
381
384
  var N = normalize(i.n);
382
385
  let materialUV=i.uv*mtl.maps.w;
383
386
  let px=dpdx(i.world); let py=dpdy(i.world);
@@ -546,6 +549,10 @@ ${THIN_TISSUE_WGSL}
546
549
  // A display-referred render texture (rear-view camera) is already lit.
547
550
  if (mtl.optics.y > 0.5) { return vec4(tex.rgb, mtl.mat.x); }
548
551
  return vec4(mix(lit, u.fog.xyz, f), opacity);
552
+ }
553
+ @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
554
+ let color = shade(i);
555
+ return ${transfer ? 'vec4(encodePropPresentation(color.rgb),color.a)' : 'color'};
549
556
  }`;
550
557
  // Depth-only occluder pass: instanced prop depth from the sun's ortho view (so trees/rocks cast shadows).
551
558
  // Depth-only occluder. It MUST apply the identical sway, or the shadows stay put while the leaves
@@ -699,6 +706,10 @@ export class GpuPropsRenderer {
699
706
  device;
700
707
  inspection;
701
708
  srgbTarget;
709
+ presentation;
710
+ sceneCounts = new Uint32Array(0);
711
+ presentationFirst = new Uint32Array(0);
712
+ hasPresentation = false;
702
713
  inspectionGeometry;
703
714
  pipe;
704
715
  /**
@@ -857,7 +868,7 @@ export class GpuPropsRenderer {
857
868
  }
858
869
  constructor(device, format, options = {}) {
859
870
  this.device = device;
860
- const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', ...look } = options;
871
+ const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', presentation, ...look } = options;
861
872
  // Runtime guard for untyped callers: WebGPU only guarantees 1 and 4.
862
873
  if (![1, 4].includes(sampleCount))
863
874
  throw new RangeError(`Unsupported prop sampleCount ${String(sampleCount)}`);
@@ -865,10 +876,13 @@ export class GpuPropsRenderer {
865
876
  throw new RangeError(`Unsupported prop shadowDepthFormat ${shadowDepthFormat}`);
866
877
  this.sampleCount = sampleCount;
867
878
  this.depth = depth;
879
+ this.presentation = presentation;
868
880
  this.setLook(look);
869
881
  this.inspection = inspection;
870
882
  this.srgbTarget = format.endsWith('-srgb');
871
- const sm = device.createShaderModule({ code: drawShader(inspection) });
883
+ const sm = device.createShaderModule({
884
+ code: drawShader(inspection, !!presentation),
885
+ });
872
886
  // The three groups the SHADER declares, written out so BOTH render pipelines share them. Under
873
887
  // `layout: 'auto'` each pipeline would mint its own and the bind groups built elsewhere in this
874
888
  // class could only ever be used by one of them.
@@ -1009,13 +1023,39 @@ export class GpuPropsRenderer {
1009
1023
  ['false:none:true', this.pipe],
1010
1024
  ['true:none:true', this.blendPipe],
1011
1025
  ]);
1012
- this.drawPipeline = (blend, cull, depthWrite) => {
1013
- const key = `${blend}:${cull}:${depthWrite}`;
1026
+ let presentationModule;
1027
+ this.drawPipeline = (blend, cull, depthWrite, late = false) => {
1028
+ const key = `${blend}:${cull}:${depthWrite}${late ? ':presentation' : ''}`;
1014
1029
  let pipeline = variants.get(key);
1015
1030
  if (!pipeline) {
1016
1031
  const base = blend ? blendDescriptor : opaqueDescriptor;
1017
1032
  pipeline = device.createRenderPipeline({
1018
1033
  ...base,
1034
+ ...(late && presentation
1035
+ ? {
1036
+ fragment: {
1037
+ ...base.fragment,
1038
+ module: (presentationModule ??= device.createShaderModule({
1039
+ code: drawShader(inspection, true, presentation.transferWGSL),
1040
+ })),
1041
+ targets: [
1042
+ {
1043
+ format: presentation.format,
1044
+ blend: {
1045
+ color: {
1046
+ srcFactor: 'src-alpha',
1047
+ dstFactor: 'one-minus-src-alpha',
1048
+ },
1049
+ alpha: {
1050
+ srcFactor: 'one',
1051
+ dstFactor: 'one-minus-src-alpha',
1052
+ },
1053
+ },
1054
+ },
1055
+ ],
1056
+ },
1057
+ }
1058
+ : {}),
1019
1059
  primitive: { ...base.primitive, cullMode: cull },
1020
1060
  depthStencil: {
1021
1061
  ...base.depthStencil,
@@ -1360,6 +1400,7 @@ export class GpuPropsRenderer {
1360
1400
  this.bgs = meshes.map(() => null);
1361
1401
  this.occBGs = meshes.map(() => []);
1362
1402
  this.counts = meshes.map(() => 0);
1403
+ this.hasPresentation = false;
1363
1404
  this.cullU = meshes.map(() => []);
1364
1405
  this.cullArgs = meshes.map(() => []);
1365
1406
  this.cullBGs = meshes.map(() => []);
@@ -1379,10 +1420,31 @@ export class GpuPropsRenderer {
1379
1420
  const dev = this.device;
1380
1421
  const n = this.models.length;
1381
1422
  const counts = new Uint32Array(n);
1382
- for (const it of instances)
1383
- if (it.model >= 0 && it.model < n)
1384
- counts[it.model]++;
1423
+ this.hasPresentation = false;
1424
+ const split = !!this.presentation;
1425
+ if (this.presentation) {
1426
+ this.sceneCounts = new Uint32Array(n);
1427
+ this.presentationFirst = new Uint32Array(n);
1428
+ }
1429
+ for (const it of instances) {
1430
+ if (it.model < 0 || it.model >= n)
1431
+ continue;
1432
+ counts[it.model]++;
1433
+ if (!split)
1434
+ continue;
1435
+ if (!it.presentation)
1436
+ this.presentationFirst[it.model]++;
1437
+ else {
1438
+ this.hasPresentation = true;
1439
+ }
1440
+ if (it.presentation !== true)
1441
+ this.sceneCounts[it.model]++;
1442
+ }
1443
+ // Scene-only, split, presentation-only: each stage has one contiguous draw
1444
+ // per model. A crossing instance appears in both ranges at its single GPU address.
1385
1445
  const cursors = new Uint32Array(n);
1446
+ const splitCursors = split ? this.presentationFirst.slice() : cursors;
1447
+ const lateCursors = split ? this.sceneCounts.slice() : cursors;
1386
1448
  const arrays = new Array(n);
1387
1449
  for (let m = 0; m < n; m++)
1388
1450
  arrays[m] = counts[m] ? new Float32Array(counts[m] * INST_FLOATS) : null;
@@ -1390,9 +1452,24 @@ export class GpuPropsRenderer {
1390
1452
  if (it.model < 0 || it.model >= n)
1391
1453
  continue;
1392
1454
  const arr = arrays[it.model];
1393
- const o = cursors[it.model]++ * INST_FLOATS;
1455
+ const cursor = !split || !it.presentation
1456
+ ? cursors
1457
+ : it.presentation === true
1458
+ ? lateCursors
1459
+ : splitCursors;
1460
+ const o = cursor[it.model]++ * INST_FLOATS;
1394
1461
  arr.set(it.mat.subarray(0, 16), o);
1395
1462
  writeDeform(arr, o + 16, it.deform, this.models[it.model].extent);
1463
+ if (this.presentation) {
1464
+ const plane = it.presentation && it.presentation !== true ? it.presentation : null;
1465
+ // Placement is affine. Its unused fourth row and deformation padding
1466
+ // hold the clip plane with no added per-instance bytes; all passes
1467
+ // read world position from the first three rows.
1468
+ arr[o + 3] = plane?.[0] ?? 0;
1469
+ arr[o + 7] = plane?.[1] ?? 0;
1470
+ arr[o + 11] = plane?.[2] ?? 0;
1471
+ arr[o + 31] = plane?.[3] ?? (it.presentation ? 1 : -1);
1472
+ }
1396
1473
  }
1397
1474
  for (let m = 0; m < n; m++) {
1398
1475
  const arr = arrays[m];
@@ -1643,7 +1720,6 @@ export class GpuPropsRenderer {
1643
1720
  lightVP, shadowView, shadowSamp, channel = 'lit') {
1644
1721
  if (channel !== 'lit' && !this.inspection)
1645
1722
  throw new Error('Prop inspection must be enabled at construction.');
1646
- const topology = channel === 'wireframe' || channel === 'density';
1647
1723
  const receive = !!(lightVP && shadowView && shadowSamp);
1648
1724
  const mats = lightVP ? (Array.isArray(lightVP) ? lightVP : [lightVP]) : [];
1649
1725
  const u = new Float32Array(PROP_UNIFORM_WORDS);
@@ -1710,6 +1786,16 @@ export class GpuPropsRenderer {
1710
1786
  this.lastSS = ss;
1711
1787
  this.lastEnv = env;
1712
1788
  }
1789
+ this.encodeColor(enc, colorView, depthView, channel, false);
1790
+ }
1791
+ /** Draw over the presented compositor result, testing its final depth.
1792
+ * Reuses the same uploaded instances, material bindings and frame uniforms. */
1793
+ framePresentation(enc, colorView, depthView) {
1794
+ if (this.hasPresentation && this.presentation)
1795
+ this.encodeColor(enc, colorView, depthView, 'lit', true);
1796
+ }
1797
+ encodeColor(enc, colorView, depthView, channel, late) {
1798
+ const topology = channel === 'wireframe' || channel === 'density';
1713
1799
  const rp = enc.beginRenderPass({
1714
1800
  colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }],
1715
1801
  depthStencilAttachment: {
@@ -1729,7 +1815,7 @@ export class GpuPropsRenderer {
1729
1815
  rp.setVertexBuffer(3, this.geo.uv);
1730
1816
  rp.setIndexBuffer(this.geo.idx, 'uint32');
1731
1817
  }
1732
- const drawModel = (m) => {
1818
+ const drawModel = (m, count, first) => {
1733
1819
  const bg = this.bgs[m], mdl = this.models[m];
1734
1820
  if (!bg || this.counts[m] === 0)
1735
1821
  return;
@@ -1737,9 +1823,9 @@ export class GpuPropsRenderer {
1737
1823
  rp.setBindGroup(2, mdl.matBG);
1738
1824
  // Geometry is bound ONCE for the whole pass; a model is a range inside it.
1739
1825
  if (topology)
1740
- rp.draw(mdl.idxCount, this.counts[m], mdl.firstIndex);
1826
+ rp.draw(mdl.idxCount, count, mdl.firstIndex, first);
1741
1827
  else
1742
- rp.drawIndexed(mdl.idxCount, this.counts[m], mdl.firstIndex, mdl.baseVertex);
1828
+ rp.drawIndexed(mdl.idxCount, count, mdl.firstIndex, mdl.baseVertex, first);
1743
1829
  };
1744
1830
  // OPAQUE FIRST, then the blended models — the whole point of the second pass. A translucent
1745
1831
  // crystal drawn before an opaque rock composites against whatever the sky left in the target and
@@ -1751,14 +1837,20 @@ export class GpuPropsRenderer {
1751
1837
  for (let m = 0; m < this.models.length; m++) {
1752
1838
  const model = this.models[m];
1753
1839
  const clay = channel === 'clay';
1754
- if ((model.alpha < 1 && !clay) !== blended || this.counts[m] === 0)
1840
+ const first = late ? this.presentationFirst[m] : 0;
1841
+ const count = this.presentation
1842
+ ? late
1843
+ ? this.counts[m] - first
1844
+ : this.sceneCounts[m]
1845
+ : this.counts[m];
1846
+ if ((model.alpha < 1 && !clay) !== blended || !count)
1755
1847
  continue;
1756
- const pipeline = this.drawPipeline(blended, model.cullMode, clay || model.depthWrite);
1848
+ const pipeline = this.drawPipeline(blended, model.cullMode, clay || model.depthWrite, late);
1757
1849
  if (pipeline !== activePipeline) {
1758
1850
  rp.setPipeline(pipeline);
1759
1851
  activePipeline = pipeline;
1760
1852
  }
1761
- drawModel(m);
1853
+ drawModel(m, count, first);
1762
1854
  }
1763
1855
  }
1764
1856
  rp.end();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.75",
3
+ "version": "0.15.76",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {