ugly-game 0.8.0 → 0.9.0
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.
- package/dist/assets/gpuProps.d.ts +30 -0
- package/dist/assets/gpuProps.js +122 -12
- package/dist/gpuTaaResolve.d.ts +33 -0
- package/dist/gpuTaaResolve.js +231 -0
- package/dist/gpuTimer.d.ts +31 -0
- package/dist/gpuTimer.js +165 -0
- package/dist/lodRing.d.ts +35 -0
- package/dist/lodRing.js +95 -0
- package/dist/mat4.d.ts +9 -0
- package/dist/mat4.js +34 -0
- package/package.json +1 -1
|
@@ -25,6 +25,19 @@ export interface PropMesh {
|
|
|
25
25
|
normals: Float32Array;
|
|
26
26
|
colors: Float32Array;
|
|
27
27
|
indices: Uint32Array;
|
|
28
|
+
/**
|
|
29
|
+
* Optional UVs. Omitted ⇒ the model renders exactly as it did before textures existed, because a
|
|
30
|
+
* zero-filled buffer is bound in their place and the 1x1 white fallback texture samples to 1.
|
|
31
|
+
*/
|
|
32
|
+
uvs?: Float32Array;
|
|
33
|
+
/**
|
|
34
|
+
* Optional base-colour map, already decoded.
|
|
35
|
+
*
|
|
36
|
+
* Decoding is the caller's job: a Worker has no ImageBitmap for a URL and the renderer has no
|
|
37
|
+
* business fetching. Providers ship a full PBR set (albedo, metallic-roughness, normal); only
|
|
38
|
+
* albedo is consumed today, and the rest follow once tangents or a derivative TBN land.
|
|
39
|
+
*/
|
|
40
|
+
albedo?: ImageBitmap;
|
|
28
41
|
}
|
|
29
42
|
/**
|
|
30
43
|
* Per-instance deformation. Every field is neutral at its default, so an instance that supplies none
|
|
@@ -71,6 +84,10 @@ export declare class GpuPropsRenderer {
|
|
|
71
84
|
private bgs;
|
|
72
85
|
private occBGs;
|
|
73
86
|
private counts;
|
|
87
|
+
/** Shared across every model — one sampler is all a prop atlas needs. */
|
|
88
|
+
private sampler;
|
|
89
|
+
/** 1x1 white, so an untextured model binds the same resources and multiplies by 1. */
|
|
90
|
+
private white;
|
|
74
91
|
private dummyShadowView;
|
|
75
92
|
private dummyShadowSamp;
|
|
76
93
|
private shadowBG;
|
|
@@ -88,6 +105,19 @@ export declare class GpuPropsRenderer {
|
|
|
88
105
|
/** Advance the wind phase. Pass the frame delta; sway is skipped entirely when windAmp is 0. */
|
|
89
106
|
tick(dt: number): void;
|
|
90
107
|
constructor(device: GPUDevice, format: GPUTextureFormat);
|
|
108
|
+
/**
|
|
109
|
+
* Upload a decoded base-colour map with a full mip chain.
|
|
110
|
+
*
|
|
111
|
+
* WebGPU has no generateMipmap, so the chain is built by successive half-scale blits through the
|
|
112
|
+
* device's own copyExternalImageToTexture — cheap, because it happens once at load rather than per
|
|
113
|
+
* frame. Skipping mips is not an option here: props are drawn at tens of thousands of instances
|
|
114
|
+
* stretching to the horizon, and an unmipped texture aliases into shimmering noise at distance,
|
|
115
|
+
* which looks markedly worse than the flat vertex colours it replaced.
|
|
116
|
+
*
|
|
117
|
+
* sRGB format, because a base-colour map is authored in sRGB and the shader works in linear —
|
|
118
|
+
* getting this wrong is the classic washed-out-albedo bug.
|
|
119
|
+
*/
|
|
120
|
+
private uploadAlbedo;
|
|
91
121
|
setModels(meshes: PropMesh[]): void;
|
|
92
122
|
/**
|
|
93
123
|
* Group instances by model and upload the per-model instance buffers.
|
package/dist/assets/gpuProps.js
CHANGED
|
@@ -18,9 +18,11 @@ struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<
|
|
|
18
18
|
// d2 = (yaw, valueJitter, 1/halfWidth, unused)
|
|
19
19
|
struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32> };
|
|
20
20
|
@group(0) @binding(1) var<storage,read> models: array<Inst>;
|
|
21
|
+
@group(2) @binding(0) var albedoTex: texture_2d<f32>;
|
|
22
|
+
@group(2) @binding(1) var albedoSamp: sampler;
|
|
21
23
|
@group(1) @binding(0) var shadowMap: texture_depth_2d; // the SAME sun shadow map the terrain cubes sample
|
|
22
24
|
@group(1) @binding(1) var shadowSamp: sampler_comparison;
|
|
23
|
-
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> };
|
|
25
|
+
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> };
|
|
24
26
|
// WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
|
|
25
27
|
// planted while the canopy moves, and the phase is offset by world position so a grove never sways
|
|
26
28
|
// in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
|
|
@@ -82,7 +84,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
|
|
|
82
84
|
let ca = cos(a); let sa = sin(a);
|
|
83
85
|
return normalize(vec3(v.x * ca - v.z * sa, v.y, v.x * sa + v.z * ca));
|
|
84
86
|
}
|
|
85
|
-
@vertex fn vs(@location(0) p: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) col: vec3<f32>, @builtin(instance_index) ii: u32) -> VO {
|
|
87
|
+
@vertex fn vs(@location(0) p: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) col: vec3<f32>, @location(3) uv: vec2<f32>, @builtin(instance_index) ii: u32) -> VO {
|
|
86
88
|
let inst = models[ii];
|
|
87
89
|
let m = inst.m;
|
|
88
90
|
let lp = deformLocal(p, inst.d0, inst.d1, inst.d2);
|
|
@@ -92,7 +94,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
|
|
|
92
94
|
let sc = length(m[0].xyz);
|
|
93
95
|
world = sway(lp, world, upv, sc);
|
|
94
96
|
var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
|
|
95
|
-
o.c = col * inst.d2.y; o.l = lp; return o;
|
|
97
|
+
o.c = col * inst.d2.y; o.l = lp; o.uv = uv; return o;
|
|
96
98
|
}
|
|
97
99
|
// same fixed directional FILL as the terrain cubes (gpuShadow.fixedFill) so plants/rocks read the same 3D shape,
|
|
98
100
|
// day or night, under one shared light. up.w > 0.5 signals a valid local-up was supplied (else fall back to flat).
|
|
@@ -163,7 +165,10 @@ fn hsvShift(c: vec3<f32>, hue: f32, sat: f32, val: f32) -> vec3<f32> {
|
|
|
163
165
|
let d = clamp(dot(N, -normalize(u.sun.xyz)), 0.0, 1.0);
|
|
164
166
|
let sh = mix(1.0, shadowFactor(i.world, d), u.sun.w); // u.sun.w = shadow-receive enable (0 ⇒ off, byte-identical for demo)
|
|
165
167
|
// procedural grain modulates the role colour; the per-world grade then re-tints the whole planet
|
|
166
|
-
|
|
168
|
+
// Albedo modulates the vertex colour rather than replacing it, so the StyleGuide role tint and the
|
|
169
|
+
// per-instance hue jitter still act on a textured prop — and an untextured one samples the 1x1
|
|
170
|
+
// white fallback and is unchanged.
|
|
171
|
+
var base = i.c * textureSample(albedoTex, albedoSamp, i.uv).rgb;
|
|
167
172
|
if (u.surf.x > 0.0) {
|
|
168
173
|
let grain = triplanar(i.l, N, u.surf.x);
|
|
169
174
|
base = base * (1.0 - u.surf.y * 0.5 + u.surf.y * grain);
|
|
@@ -240,6 +245,10 @@ export class GpuPropsRenderer {
|
|
|
240
245
|
bgs = [];
|
|
241
246
|
occBGs = [];
|
|
242
247
|
counts = [];
|
|
248
|
+
/** Shared across every model — one sampler is all a prop atlas needs. */
|
|
249
|
+
sampler = null;
|
|
250
|
+
/** 1x1 white, so an untextured model binds the same resources and multiplies by 1. */
|
|
251
|
+
white = null;
|
|
243
252
|
// shadow-receive (group 1): a dummy 1×1 depth map when no sun shadow is supplied (demo path), else the terrain's
|
|
244
253
|
// shared shadow map. The bind group is cached and only rebuilt when the supplied view/sampler identity changes.
|
|
245
254
|
dummyShadowView;
|
|
@@ -294,6 +303,12 @@ export class GpuPropsRenderer {
|
|
|
294
303
|
arrayStride: 12,
|
|
295
304
|
attributes: [{ shaderLocation: 2, offset: 0, format: 'float32x3' }],
|
|
296
305
|
},
|
|
306
|
+
{
|
|
307
|
+
// UVs. Always bound — a model without them gets a zero-filled buffer, which samples the
|
|
308
|
+
// 1x1 white fallback and leaves its appearance byte-identical to before textures existed.
|
|
309
|
+
arrayStride: 8,
|
|
310
|
+
attributes: [{ shaderLocation: 3, offset: 0, format: 'float32x2' }],
|
|
311
|
+
},
|
|
297
312
|
],
|
|
298
313
|
},
|
|
299
314
|
fragment: { module: sm, entryPoint: 'fs', targets: [{ format }] },
|
|
@@ -340,27 +355,120 @@ export class GpuPropsRenderer {
|
|
|
340
355
|
this.dummyShadowView = dummy.createView();
|
|
341
356
|
this.dummyShadowSamp = device.createSampler({ compare: 'less' });
|
|
342
357
|
}
|
|
358
|
+
/**
|
|
359
|
+
* Upload a decoded base-colour map with a full mip chain.
|
|
360
|
+
*
|
|
361
|
+
* WebGPU has no generateMipmap, so the chain is built by successive half-scale blits through the
|
|
362
|
+
* device's own copyExternalImageToTexture — cheap, because it happens once at load rather than per
|
|
363
|
+
* frame. Skipping mips is not an option here: props are drawn at tens of thousands of instances
|
|
364
|
+
* stretching to the horizon, and an unmipped texture aliases into shimmering noise at distance,
|
|
365
|
+
* which looks markedly worse than the flat vertex colours it replaced.
|
|
366
|
+
*
|
|
367
|
+
* sRGB format, because a base-colour map is authored in sRGB and the shader works in linear —
|
|
368
|
+
* getting this wrong is the classic washed-out-albedo bug.
|
|
369
|
+
*/
|
|
370
|
+
uploadAlbedo(src) {
|
|
371
|
+
const dev = this.device;
|
|
372
|
+
const w = src.width, h = src.height;
|
|
373
|
+
let levels = 1;
|
|
374
|
+
for (let d = Math.max(w, h); d > 1; d = d >> 1)
|
|
375
|
+
levels++;
|
|
376
|
+
const tex = dev.createTexture({
|
|
377
|
+
size: [w, h],
|
|
378
|
+
format: 'rgba8unorm-srgb',
|
|
379
|
+
mipLevelCount: levels,
|
|
380
|
+
usage: GPUTextureUsage.TEXTURE_BINDING |
|
|
381
|
+
GPUTextureUsage.COPY_DST |
|
|
382
|
+
GPUTextureUsage.RENDER_ATTACHMENT,
|
|
383
|
+
});
|
|
384
|
+
dev.queue.copyExternalImageToTexture({ source: src }, { texture: tex }, [
|
|
385
|
+
w,
|
|
386
|
+
h,
|
|
387
|
+
]);
|
|
388
|
+
// Downsample by re-encoding the bitmap at each level. Uses the platform's own resampler via
|
|
389
|
+
// createImageBitmap rather than a render pass, which keeps this out of the render graph
|
|
390
|
+
// entirely — it is a load-time cost, not a frame cost.
|
|
391
|
+
let lw = w, lh = h;
|
|
392
|
+
for (let lvl = 1; lvl < levels; lvl++) {
|
|
393
|
+
lw = Math.max(1, lw >> 1);
|
|
394
|
+
lh = Math.max(1, lh >> 1);
|
|
395
|
+
void createImageBitmap(src, {
|
|
396
|
+
resizeWidth: lw,
|
|
397
|
+
resizeHeight: lh,
|
|
398
|
+
resizeQuality: 'high',
|
|
399
|
+
})
|
|
400
|
+
.then((bm) => {
|
|
401
|
+
dev.queue.copyExternalImageToTexture({ source: bm }, { texture: tex, mipLevel: lvl }, [bm.width, bm.height]);
|
|
402
|
+
bm.close();
|
|
403
|
+
})
|
|
404
|
+
// A failed mip leaves that level undefined rather than killing the frame: the base level is
|
|
405
|
+
// already uploaded, so the prop renders — just with more aliasing at distance.
|
|
406
|
+
.catch(() => {
|
|
407
|
+
// deliberately swallowed — see above
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
return tex;
|
|
411
|
+
}
|
|
343
412
|
setModels(meshes) {
|
|
344
413
|
const dev = this.device, U = GPUBufferUsage;
|
|
345
414
|
for (const p of this.models) {
|
|
346
415
|
p.posB.destroy();
|
|
347
416
|
p.nrmB.destroy();
|
|
348
417
|
p.colB.destroy();
|
|
418
|
+
p.uvB.destroy();
|
|
349
419
|
p.idxB.destroy();
|
|
420
|
+
p.tex?.destroy();
|
|
350
421
|
}
|
|
351
422
|
const mk = (d, u) => {
|
|
352
423
|
const b = dev.createBuffer({ size: d.byteLength, usage: u });
|
|
353
424
|
dev.queue.writeBuffer(b, 0, d);
|
|
354
425
|
return b;
|
|
355
426
|
};
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
427
|
+
// One sampler for every prop. Repeat + trilinear: props are UV-mapped charts, not tiled
|
|
428
|
+
// surfaces, but mipmapping is not optional — at tens of thousands of instances an unmipped
|
|
429
|
+
// texture aliases into noise at distance, which looks worse than the vertex colours it replaced.
|
|
430
|
+
this.sampler ??= dev.createSampler({
|
|
431
|
+
magFilter: 'linear',
|
|
432
|
+
minFilter: 'linear',
|
|
433
|
+
mipmapFilter: 'linear',
|
|
434
|
+
addressModeU: 'repeat',
|
|
435
|
+
addressModeV: 'repeat',
|
|
436
|
+
});
|
|
437
|
+
// A 1x1 white texture stands in for every model without a map, so the pipeline binds the same
|
|
438
|
+
// resources either way and an untextured prop multiplies by 1 — byte-identical to before.
|
|
439
|
+
this.white ??= (() => {
|
|
440
|
+
const t = dev.createTexture({
|
|
441
|
+
size: [1, 1],
|
|
442
|
+
format: 'rgba8unorm-srgb',
|
|
443
|
+
usage: GPUTextureUsage.TEXTURE_BINDING |
|
|
444
|
+
GPUTextureUsage.COPY_DST |
|
|
445
|
+
GPUTextureUsage.RENDER_ATTACHMENT,
|
|
446
|
+
});
|
|
447
|
+
dev.queue.writeTexture({ texture: t }, new Uint8Array([255, 255, 255, 255]), {}, [1, 1]);
|
|
448
|
+
return t;
|
|
449
|
+
})();
|
|
450
|
+
this.models = meshes.map((m) => {
|
|
451
|
+
const verts = m.positions.length / 3;
|
|
452
|
+
const tex = m.albedo ? this.uploadAlbedo(m.albedo) : null;
|
|
453
|
+
return {
|
|
454
|
+
posB: mk(m.positions, U.VERTEX | U.COPY_DST),
|
|
455
|
+
nrmB: mk(m.normals, U.VERTEX | U.COPY_DST),
|
|
456
|
+
colB: mk(m.colors, U.VERTEX | U.COPY_DST),
|
|
457
|
+
// zero-filled when absent: the shader still reads location 3, and white x anything is anything
|
|
458
|
+
uvB: mk(m.uvs ?? new Float32Array(verts * 2), U.VERTEX | U.COPY_DST),
|
|
459
|
+
idxB: mk(m.indices, U.INDEX | U.COPY_DST),
|
|
460
|
+
idxCount: m.indices.length,
|
|
461
|
+
extent: measureExtent(m.positions),
|
|
462
|
+
tex,
|
|
463
|
+
matBG: dev.createBindGroup({
|
|
464
|
+
layout: this.pipe.getBindGroupLayout(2),
|
|
465
|
+
entries: [
|
|
466
|
+
{ binding: 0, resource: (tex ?? this.white).createView() },
|
|
467
|
+
{ binding: 1, resource: this.sampler },
|
|
468
|
+
],
|
|
469
|
+
}),
|
|
470
|
+
};
|
|
471
|
+
});
|
|
364
472
|
this.caps = meshes.map(() => 0);
|
|
365
473
|
this.instBufs = meshes.map(() => null);
|
|
366
474
|
this.bgs = meshes.map(() => null);
|
|
@@ -506,6 +614,8 @@ export class GpuPropsRenderer {
|
|
|
506
614
|
rp.setVertexBuffer(0, mdl.posB);
|
|
507
615
|
rp.setVertexBuffer(1, mdl.nrmB);
|
|
508
616
|
rp.setVertexBuffer(2, mdl.colB);
|
|
617
|
+
rp.setVertexBuffer(3, mdl.uvB);
|
|
618
|
+
rp.setBindGroup(2, mdl.matBG);
|
|
509
619
|
rp.setIndexBuffer(mdl.idxB, 'uint32');
|
|
510
620
|
rp.drawIndexed(mdl.idxCount, this.counts[m]);
|
|
511
621
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Halton(2,3) sub-pixel jitter for frame `i`, in CLIP space. Multiply into the projection. */
|
|
2
|
+
export declare function haltonJitter(i: number, w: number, h: number, samples?: number): [number, number];
|
|
3
|
+
export declare class GpuTaaResolve {
|
|
4
|
+
private device;
|
|
5
|
+
private format;
|
|
6
|
+
private pipe;
|
|
7
|
+
private uBuf;
|
|
8
|
+
private u;
|
|
9
|
+
private samp;
|
|
10
|
+
private hist;
|
|
11
|
+
private histView;
|
|
12
|
+
private bg;
|
|
13
|
+
private ping;
|
|
14
|
+
private w;
|
|
15
|
+
private h;
|
|
16
|
+
private primed;
|
|
17
|
+
constructor(device: GPUDevice, format: GPUTextureFormat);
|
|
18
|
+
/** (Re)allocate history at the render size. Also invalidates history — a resize is a cut. */
|
|
19
|
+
resize(w: number, h: number, colorView: GPUTextureView, depthView: GPUTextureView): void;
|
|
20
|
+
/** Bind group i READS history[i]; the same frame WRITES history[1-i]. */
|
|
21
|
+
private rebind;
|
|
22
|
+
/** Call when the colour/depth VIEWS change identity without a size change. */
|
|
23
|
+
setInputs(colorView: GPUTextureView, depthView: GPUTextureView): void;
|
|
24
|
+
/** Throw the history away — camera cuts, teleports, origin rebases, pause→resume. */
|
|
25
|
+
invalidate(): void;
|
|
26
|
+
/**
|
|
27
|
+
* Resolve one frame. `invCurrVP` inverts the UNJITTERED current view-projection; `prevVP` is the
|
|
28
|
+
* previous frame's UNJITTERED view-projection. Jitter belongs in the geometry pass's projection
|
|
29
|
+
* only — reprojection done with a jittered matrix would chase its own offset.
|
|
30
|
+
*/
|
|
31
|
+
frame(enc: GPUCommandEncoder, out: GPUTextureView, invCurrVP: Float32Array, prevVP: Float32Array, blend?: number, enabled?: boolean): void;
|
|
32
|
+
destroy(): void;
|
|
33
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// PLATFORM PASS. Temporal anti-aliasing as a POST PASS over an existing colour+depth pair, so any
|
|
2
|
+
// renderer in this package can get TAA without becoming a TAA renderer.
|
|
3
|
+
//
|
|
4
|
+
// `GpuTaaRenderer` (gpuTaa.ts) already does TAA, but it is a closed demo renderer: it owns its own
|
|
5
|
+
// cube pipeline, its own scene, and its own MRT colour+motion targets. There is no seam to feed it
|
|
6
|
+
// someone else's frame. This module lifts the part that was general -- the reprojection, the 3x3
|
|
7
|
+
// neighbourhood clamp and the history ping-pong -- and gives it the shape GpuSSAO already has:
|
|
8
|
+
//
|
|
9
|
+
// frame(enc, out, colorView, depthView, invCurrVP, prevVP, blend, reset)
|
|
10
|
+
//
|
|
11
|
+
// MOTION COMES FROM DEPTH, not a motion buffer. GpuSSAO reconstructs normals from depth rather than
|
|
12
|
+
// demanding a normal target; the same trick applies here: unproject each pixel with the current
|
|
13
|
+
// inverse view-projection, reproject it with the previous frame's view-projection, and the
|
|
14
|
+
// difference is the screen-space velocity. That covers the case that dominates a voxel world -- a
|
|
15
|
+
// static world under a moving camera -- and costs the caller nothing but a matrix it already has.
|
|
16
|
+
//
|
|
17
|
+
// The limit, stated plainly: a pixel whose GEOMETRY moved between frames (a walking creature, a
|
|
18
|
+
// flying ship) reprojects as though it were static, so its history is wrong and it ghosts. The 3x3
|
|
19
|
+
// colour-box clamp suppresses most of that -- history is clamped to the range of the current
|
|
20
|
+
// frame's neighbourhood, so it can only ever be a plausible colour for that pixel -- but fast,
|
|
21
|
+
// high-contrast movers will still smear. When that shows up, the fix is per-object motion vectors
|
|
22
|
+
// (an MRT motion target on the geometry pass), and this pass gains a `motionView` input rather than
|
|
23
|
+
// being replaced.
|
|
24
|
+
//
|
|
25
|
+
// Sky pixels sit at depth 1.0. Unprojecting them yields a point on the far plane, which reprojects
|
|
26
|
+
// correctly under camera ROTATION and slightly wrongly under camera TRANSLATION -- the parallax of
|
|
27
|
+
// something infinitely far away is zero, and the far plane is not infinite. At normal draw
|
|
28
|
+
// distances the error is far below a pixel.
|
|
29
|
+
/** Halton(2,3) sub-pixel jitter for frame `i`, in CLIP space. Multiply into the projection. */
|
|
30
|
+
export function haltonJitter(i, w, h, samples = 8) {
|
|
31
|
+
const radical = (n, base) => {
|
|
32
|
+
let f = 1, r = 0;
|
|
33
|
+
while (n > 0) {
|
|
34
|
+
f /= base;
|
|
35
|
+
r += f * (n % base);
|
|
36
|
+
n = Math.floor(n / base);
|
|
37
|
+
}
|
|
38
|
+
return r;
|
|
39
|
+
};
|
|
40
|
+
const k = (i % samples) + 1;
|
|
41
|
+
// Halton is in [0,1); centre it on the pixel, then convert pixels -> clip (clip spans 2 units).
|
|
42
|
+
return [((radical(k, 2) - 0.5) * 2) / w, ((radical(k, 3) - 0.5) * 2) / h];
|
|
43
|
+
}
|
|
44
|
+
const RESOLVE_WGSL = /* wgsl */ `
|
|
45
|
+
struct RU {
|
|
46
|
+
invCurrVP: mat4x4<f32>,
|
|
47
|
+
prevVP: mat4x4<f32>,
|
|
48
|
+
texel: vec4<f32>, // xy = 1/size, zw = size
|
|
49
|
+
ctrl: vec4<f32>, // x = history blend, y = enabled, z = reset
|
|
50
|
+
};
|
|
51
|
+
@group(0) @binding(0) var<uniform> ru: RU;
|
|
52
|
+
@group(0) @binding(1) var histSamp: sampler;
|
|
53
|
+
@group(0) @binding(2) var colorTex: texture_2d<f32>;
|
|
54
|
+
@group(0) @binding(3) var depthTex: texture_depth_2d;
|
|
55
|
+
@group(0) @binding(4) var histTex: texture_2d<f32>;
|
|
56
|
+
|
|
57
|
+
@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
|
|
58
|
+
var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
|
|
59
|
+
return vec4(p[vi], 0.0, 1.0);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
struct ROut { @location(0) screen: vec4<f32>, @location(1) hist: vec4<f32> };
|
|
63
|
+
|
|
64
|
+
@fragment fn fs(@builtin(position) fc: vec4<f32>) -> ROut {
|
|
65
|
+
let dim = vec2<i32>(i32(ru.texel.z), i32(ru.texel.w));
|
|
66
|
+
let px = clamp(vec2<i32>(floor(fc.xy)), vec2<i32>(0, 0), dim - vec2<i32>(1, 1));
|
|
67
|
+
let cur = textureLoad(colorTex, px, 0).rgb;
|
|
68
|
+
var o: ROut;
|
|
69
|
+
// Disabled, or the first frame after a cut: the current frame IS the answer and the history.
|
|
70
|
+
if (ru.ctrl.y < 0.5 || ru.ctrl.z > 0.5) { o.screen = vec4(cur, 1.0); o.hist = vec4(cur, 1.0); return o; }
|
|
71
|
+
|
|
72
|
+
// 3x3 neighbourhood colour box of the current frame -- the anti-ghosting clamp. Coordinates are
|
|
73
|
+
// clamped to the texture: an out-of-range textureLoad returns zero in WGSL, which would drag the
|
|
74
|
+
// box's minimum to black along every screen edge and put a dark rim on the frame.
|
|
75
|
+
var mn = cur; var mx = cur;
|
|
76
|
+
for (var dy = -1; dy <= 1; dy = dy + 1) {
|
|
77
|
+
for (var dx = -1; dx <= 1; dx = dx + 1) {
|
|
78
|
+
let q = clamp(px + vec2<i32>(dx, dy), vec2<i32>(0, 0), dim - vec2<i32>(1, 1));
|
|
79
|
+
let c = textureLoad(colorTex, q, 0).rgb;
|
|
80
|
+
mn = min(mn, c); mx = max(mx, c);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Depth -> world -> previous clip. WebGPU depth is [0,1] and clip-space Y is up while the
|
|
85
|
+
// framebuffer's Y is down, hence the flip in both directions.
|
|
86
|
+
let d = textureLoad(depthTex, px, 0);
|
|
87
|
+
let uv = fc.xy * ru.texel.xy;
|
|
88
|
+
let ndc = vec3<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d);
|
|
89
|
+
let wp4 = ru.invCurrVP * vec4(ndc, 1.0);
|
|
90
|
+
let world = wp4.xyz / wp4.w;
|
|
91
|
+
let pc = ru.prevVP * vec4(world, 1.0);
|
|
92
|
+
|
|
93
|
+
var outc = cur;
|
|
94
|
+
if (pc.w > 0.0) { // behind the previous camera -> no usable history
|
|
95
|
+
let pndc = pc.xyz / pc.w;
|
|
96
|
+
let prevUV = vec2<f32>(pndc.x * 0.5 + 0.5, 0.5 - pndc.y * 0.5);
|
|
97
|
+
if (prevUV.x >= 0.0 && prevUV.x <= 1.0 && prevUV.y >= 0.0 && prevUV.y <= 1.0) {
|
|
98
|
+
let hist = clamp(textureSampleLevel(histTex, histSamp, prevUV, 0.0).rgb, mn, mx);
|
|
99
|
+
outc = mix(cur, hist, ru.ctrl.x); // ctrl.x ~ 0.9 => 10% current, 90% reprojected history
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
o.screen = vec4(outc, 1.0); o.hist = vec4(outc, 1.0);
|
|
103
|
+
return o;
|
|
104
|
+
}
|
|
105
|
+
`;
|
|
106
|
+
export class GpuTaaResolve {
|
|
107
|
+
device;
|
|
108
|
+
format;
|
|
109
|
+
pipe;
|
|
110
|
+
uBuf;
|
|
111
|
+
u = new Float32Array(40); // 2 x mat4 + 2 x vec4
|
|
112
|
+
samp;
|
|
113
|
+
hist = [];
|
|
114
|
+
histView = [];
|
|
115
|
+
bg = [];
|
|
116
|
+
ping = 0;
|
|
117
|
+
w = 0;
|
|
118
|
+
h = 0;
|
|
119
|
+
primed = false;
|
|
120
|
+
constructor(device, format) {
|
|
121
|
+
this.device = device;
|
|
122
|
+
this.format = format;
|
|
123
|
+
const mod = device.createShaderModule({ code: RESOLVE_WGSL });
|
|
124
|
+
this.pipe = device.createRenderPipeline({
|
|
125
|
+
layout: 'auto',
|
|
126
|
+
vertex: { module: mod, entryPoint: 'vs' },
|
|
127
|
+
fragment: {
|
|
128
|
+
module: mod,
|
|
129
|
+
entryPoint: 'fs',
|
|
130
|
+
targets: [{ format }, { format }],
|
|
131
|
+
},
|
|
132
|
+
primitive: { topology: 'triangle-list' },
|
|
133
|
+
});
|
|
134
|
+
this.uBuf = device.createBuffer({
|
|
135
|
+
size: this.u.byteLength,
|
|
136
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
|
|
137
|
+
});
|
|
138
|
+
this.samp = device.createSampler({
|
|
139
|
+
magFilter: 'linear',
|
|
140
|
+
minFilter: 'linear',
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** (Re)allocate history at the render size. Also invalidates history — a resize is a cut. */
|
|
144
|
+
resize(w, h, colorView, depthView) {
|
|
145
|
+
if (w === this.w && h === this.h && this.bg.length === 2)
|
|
146
|
+
return;
|
|
147
|
+
for (const t of this.hist)
|
|
148
|
+
t.destroy();
|
|
149
|
+
this.w = w;
|
|
150
|
+
this.h = h;
|
|
151
|
+
const mk = () => this.device.createTexture({
|
|
152
|
+
size: [w, h],
|
|
153
|
+
format: this.format,
|
|
154
|
+
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
|
|
155
|
+
});
|
|
156
|
+
this.hist = [mk(), mk()];
|
|
157
|
+
this.histView = this.hist.map((t) => t.createView());
|
|
158
|
+
this.rebind(colorView, depthView);
|
|
159
|
+
this.primed = false;
|
|
160
|
+
}
|
|
161
|
+
/** Bind group i READS history[i]; the same frame WRITES history[1-i]. */
|
|
162
|
+
rebind(colorView, depthView) {
|
|
163
|
+
this.bg = [0, 1].map((i) => this.device.createBindGroup({
|
|
164
|
+
layout: this.pipe.getBindGroupLayout(0),
|
|
165
|
+
entries: [
|
|
166
|
+
{ binding: 0, resource: { buffer: this.uBuf } },
|
|
167
|
+
{ binding: 1, resource: this.samp },
|
|
168
|
+
{ binding: 2, resource: colorView },
|
|
169
|
+
{ binding: 3, resource: depthView },
|
|
170
|
+
{ binding: 4, resource: this.histView[i] },
|
|
171
|
+
],
|
|
172
|
+
}));
|
|
173
|
+
}
|
|
174
|
+
/** Call when the colour/depth VIEWS change identity without a size change. */
|
|
175
|
+
setInputs(colorView, depthView) {
|
|
176
|
+
if (this.histView.length === 2)
|
|
177
|
+
this.rebind(colorView, depthView);
|
|
178
|
+
}
|
|
179
|
+
/** Throw the history away — camera cuts, teleports, origin rebases, pause→resume. */
|
|
180
|
+
invalidate() {
|
|
181
|
+
this.primed = false;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Resolve one frame. `invCurrVP` inverts the UNJITTERED current view-projection; `prevVP` is the
|
|
185
|
+
* previous frame's UNJITTERED view-projection. Jitter belongs in the geometry pass's projection
|
|
186
|
+
* only — reprojection done with a jittered matrix would chase its own offset.
|
|
187
|
+
*/
|
|
188
|
+
frame(enc, out, invCurrVP, prevVP, blend = 0.9, enabled = true) {
|
|
189
|
+
if (this.histView.length !== 2)
|
|
190
|
+
return;
|
|
191
|
+
this.u.set(invCurrVP, 0);
|
|
192
|
+
this.u.set(prevVP, 16);
|
|
193
|
+
this.u[32] = 1 / this.w;
|
|
194
|
+
this.u[33] = 1 / this.h;
|
|
195
|
+
this.u[34] = this.w;
|
|
196
|
+
this.u[35] = this.h;
|
|
197
|
+
this.u[36] = blend;
|
|
198
|
+
this.u[37] = enabled ? 1 : 0;
|
|
199
|
+
this.u[38] = this.primed ? 0 : 1; // first frame after a cut has no history to blend
|
|
200
|
+
this.device.queue.writeBuffer(this.uBuf, 0, this.u);
|
|
201
|
+
const pass = enc.beginRenderPass({
|
|
202
|
+
colorAttachments: [
|
|
203
|
+
{
|
|
204
|
+
view: out,
|
|
205
|
+
loadOp: 'clear',
|
|
206
|
+
storeOp: 'store',
|
|
207
|
+
clearValue: { r: 0, g: 0, b: 0, a: 1 },
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
view: this.histView[1 - this.ping],
|
|
211
|
+
loadOp: 'clear',
|
|
212
|
+
storeOp: 'store',
|
|
213
|
+
clearValue: { r: 0, g: 0, b: 0, a: 1 },
|
|
214
|
+
},
|
|
215
|
+
],
|
|
216
|
+
});
|
|
217
|
+
pass.setPipeline(this.pipe);
|
|
218
|
+
pass.setBindGroup(0, this.bg[this.ping]);
|
|
219
|
+
pass.draw(3);
|
|
220
|
+
pass.end();
|
|
221
|
+
this.ping = 1 - this.ping;
|
|
222
|
+
this.primed = true;
|
|
223
|
+
}
|
|
224
|
+
destroy() {
|
|
225
|
+
for (const t of this.hist)
|
|
226
|
+
t.destroy();
|
|
227
|
+
this.hist = [];
|
|
228
|
+
this.histView = [];
|
|
229
|
+
this.bg = [];
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Milliseconds per labelled span, plus the whole bracketed region as `total`. */
|
|
2
|
+
export type GpuSpans = Record<string, number>;
|
|
3
|
+
export declare class GpuTimer {
|
|
4
|
+
private smoothing;
|
|
5
|
+
readonly supported: boolean;
|
|
6
|
+
private device;
|
|
7
|
+
private qs;
|
|
8
|
+
private resolve;
|
|
9
|
+
private ring;
|
|
10
|
+
private labels;
|
|
11
|
+
private active;
|
|
12
|
+
private last;
|
|
13
|
+
private ewma;
|
|
14
|
+
constructor(device: GPUDevice, smoothing?: number);
|
|
15
|
+
/** A device advertising the feature is not proof the encoder exposes the call — check both. */
|
|
16
|
+
static isSupported(device: GPUDevice): boolean;
|
|
17
|
+
private write;
|
|
18
|
+
/** Open a timed frame. No-op (and no slot consumed) when every readback buffer is still in flight. */
|
|
19
|
+
begin(enc: GPUCommandEncoder): void;
|
|
20
|
+
/** Close the span that started at the previous mark (or at `begin`) and name it. */
|
|
21
|
+
mark(enc: GPUCommandEncoder, label: string): void;
|
|
22
|
+
/** Resolve the frame's queries into the claimed readback slot. Call before `submit`. */
|
|
23
|
+
end(enc: GPUCommandEncoder): void;
|
|
24
|
+
/** Map any finished slot and fold it into the running averages. Never blocks; call once a frame. */
|
|
25
|
+
poll(): void;
|
|
26
|
+
/** Most recent complete frame, ms per label. Empty until the first readback lands. */
|
|
27
|
+
spans(): GpuSpans;
|
|
28
|
+
/** Smoothed ms per label — what a HUD or an IR scalar should report. */
|
|
29
|
+
average(): GpuSpans;
|
|
30
|
+
destroy(): void;
|
|
31
|
+
}
|
package/dist/gpuTimer.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// PLATFORM PASS-TIMER. Real GPU time per render pass, via `timestamp-query`.
|
|
2
|
+
//
|
|
3
|
+
// Why marks between passes rather than `timestampWrites` on the pass descriptor: every renderer in
|
|
4
|
+
// this package (GpuShadowRenderer, GpuSSAO, GpuPropsRenderer, …) opens its own `beginRenderPass`
|
|
5
|
+
// inside `frame()`. Timing via the pass descriptor would mean threading a query set through every
|
|
6
|
+
// one of those private call sites. `encoder.writeTimestamp` brackets spans on the ENCODER instead,
|
|
7
|
+
// so a caller can time existing renderers without any of them changing:
|
|
8
|
+
//
|
|
9
|
+
// timer.begin(enc);
|
|
10
|
+
// skyR.frame(enc, …); timer.mark(enc, 'sky');
|
|
11
|
+
// renderer.frame(enc, …); timer.mark(enc, 'cubes');
|
|
12
|
+
// ssaoR.frame(enc, …); timer.mark(enc, 'ssao');
|
|
13
|
+
// timer.end(enc);
|
|
14
|
+
// device.queue.submit([enc.finish()]);
|
|
15
|
+
// timer.poll(); // non-blocking; results land a few frames later
|
|
16
|
+
//
|
|
17
|
+
// MEASURED on the Electron WebGPU host, timing two 512² passes whose fragment loops differ 5000×:
|
|
18
|
+
// `timestampWrites` reported 0.072 / 79.19 ms and `encoder.writeTimestamp` 0.137 / 70.32 ms. Both
|
|
19
|
+
// attribute correctly, so the encoder path was chosen purely because it needs no renderer changes.
|
|
20
|
+
//
|
|
21
|
+
// THE TRAP, worth knowing before trusting any number this produces: a render pass whose result is
|
|
22
|
+
// never consumed can be dropped by the driver, and then its time lands in a NEIGHBOURING span. An
|
|
23
|
+
// early version of the oracle drew two passes into one texture with `loadOp: 'clear'` and never
|
|
24
|
+
// read it; the first pass was dead work, got elided, and the timer duly reported the heavy pass at
|
|
25
|
+
// 0.01 ms. The timer was right and the scene was a lie. If a span looks impossibly cheap, check
|
|
26
|
+
// that something downstream actually reads what the pass wrote.
|
|
27
|
+
//
|
|
28
|
+
// Unsupported devices degrade quietly: `supported` is false, marks are no-ops, and `spans()` stays
|
|
29
|
+
// empty so callers fall back to wall-clock frame time.
|
|
30
|
+
const MAX_MARKS = 32; // query-set slots: 1 begin + up to 31 marks
|
|
31
|
+
const RING = 3; // readback buffers in flight — enough to never stall a 60fps loop
|
|
32
|
+
export class GpuTimer {
|
|
33
|
+
smoothing;
|
|
34
|
+
supported;
|
|
35
|
+
device;
|
|
36
|
+
qs = null;
|
|
37
|
+
resolve = null;
|
|
38
|
+
ring = [];
|
|
39
|
+
labels = []; // labels for the frame currently being encoded
|
|
40
|
+
active = null; // slot claimed by the frame being encoded
|
|
41
|
+
last = {};
|
|
42
|
+
// A Map, not a Record: `Record<string, number>` claims every key is present, so the "have I seen
|
|
43
|
+
// this label before" check reads as dead code to the type checker even though it decides whether
|
|
44
|
+
// a sample seeds the average or blends into it. A Map says what is actually true.
|
|
45
|
+
ewma = new Map();
|
|
46
|
+
constructor(device, smoothing = 0.1) {
|
|
47
|
+
this.smoothing = smoothing;
|
|
48
|
+
this.device = device;
|
|
49
|
+
this.supported = GpuTimer.isSupported(device);
|
|
50
|
+
if (!this.supported)
|
|
51
|
+
return;
|
|
52
|
+
this.qs = device.createQuerySet({ type: 'timestamp', count: MAX_MARKS });
|
|
53
|
+
this.resolve = device.createBuffer({
|
|
54
|
+
size: MAX_MARKS * 8,
|
|
55
|
+
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
|
|
56
|
+
});
|
|
57
|
+
for (let i = 0; i < RING; i++)
|
|
58
|
+
this.ring.push({
|
|
59
|
+
read: device.createBuffer({
|
|
60
|
+
size: MAX_MARKS * 8,
|
|
61
|
+
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
|
|
62
|
+
}),
|
|
63
|
+
busy: false,
|
|
64
|
+
labels: [],
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** A device advertising the feature is not proof the encoder exposes the call — check both. */
|
|
68
|
+
static isSupported(device) {
|
|
69
|
+
if (!device.features.has('timestamp-query'))
|
|
70
|
+
return false;
|
|
71
|
+
const enc = device.createCommandEncoder();
|
|
72
|
+
return (typeof enc.writeTimestamp ===
|
|
73
|
+
'function');
|
|
74
|
+
}
|
|
75
|
+
write(enc, index) {
|
|
76
|
+
enc.writeTimestamp(this.qs, index);
|
|
77
|
+
}
|
|
78
|
+
/** Open a timed frame. No-op (and no slot consumed) when every readback buffer is still in flight. */
|
|
79
|
+
begin(enc) {
|
|
80
|
+
if (!this.supported)
|
|
81
|
+
return;
|
|
82
|
+
const slot = this.ring.find((s) => !s.busy);
|
|
83
|
+
if (!slot) {
|
|
84
|
+
this.active = null; // all buffers mapped — skip timing this frame rather than stall
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
this.active = slot;
|
|
88
|
+
this.labels = [];
|
|
89
|
+
this.write(enc, 0);
|
|
90
|
+
}
|
|
91
|
+
/** Close the span that started at the previous mark (or at `begin`) and name it. */
|
|
92
|
+
mark(enc, label) {
|
|
93
|
+
if (!this.supported || !this.active)
|
|
94
|
+
return;
|
|
95
|
+
if (this.labels.length + 1 >= MAX_MARKS)
|
|
96
|
+
return;
|
|
97
|
+
this.labels.push(label);
|
|
98
|
+
this.write(enc, this.labels.length);
|
|
99
|
+
}
|
|
100
|
+
/** Resolve the frame's queries into the claimed readback slot. Call before `submit`. */
|
|
101
|
+
end(enc) {
|
|
102
|
+
if (!this.supported || !this.active || this.labels.length === 0) {
|
|
103
|
+
this.active = null;
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const n = this.labels.length + 1;
|
|
107
|
+
enc.resolveQuerySet(this.qs, 0, n, this.resolve, 0);
|
|
108
|
+
enc.copyBufferToBuffer(this.resolve, 0, this.active.read, 0, n * 8);
|
|
109
|
+
this.active.busy = true;
|
|
110
|
+
this.active.labels = this.labels.slice();
|
|
111
|
+
this.active = null;
|
|
112
|
+
}
|
|
113
|
+
/** Map any finished slot and fold it into the running averages. Never blocks; call once a frame. */
|
|
114
|
+
poll() {
|
|
115
|
+
if (!this.supported)
|
|
116
|
+
return;
|
|
117
|
+
for (const slot of this.ring) {
|
|
118
|
+
if (!slot.busy || slot.read.mapState !== 'unmapped')
|
|
119
|
+
continue;
|
|
120
|
+
const labels = slot.labels;
|
|
121
|
+
void slot.read
|
|
122
|
+
.mapAsync(GPUMapMode.READ)
|
|
123
|
+
.then(() => {
|
|
124
|
+
const t = new BigUint64Array(slot.read.getMappedRange().slice(0));
|
|
125
|
+
slot.read.unmap();
|
|
126
|
+
slot.busy = false;
|
|
127
|
+
// A GPU that reorders or drops a write leaves a zero — a zero timestamp is missing data,
|
|
128
|
+
// not a 0ms pass, so discard the whole frame rather than report a fabricated span. The
|
|
129
|
+
// range is guaranteed: `end` resolved exactly labels.length + 1 queries into this slot.
|
|
130
|
+
for (let i = 0; i <= labels.length; i++)
|
|
131
|
+
if (t[i] === 0n)
|
|
132
|
+
return;
|
|
133
|
+
const out = {};
|
|
134
|
+
for (let i = 0; i < labels.length; i++)
|
|
135
|
+
out[labels[i]] =
|
|
136
|
+
(out[labels[i]] ?? 0) + Number(t[i + 1] - t[i]) / 1e6;
|
|
137
|
+
out.total = Number(t[labels.length] - t[0]) / 1e6;
|
|
138
|
+
this.last = out;
|
|
139
|
+
const a = this.smoothing;
|
|
140
|
+
for (const k of Object.keys(out)) {
|
|
141
|
+
const prev = this.ewma.get(k);
|
|
142
|
+
this.ewma.set(k, prev === undefined ? out[k] : prev * (1 - a) + out[k] * a);
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
.catch(() => {
|
|
146
|
+
slot.busy = false;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** Most recent complete frame, ms per label. Empty until the first readback lands. */
|
|
151
|
+
spans() {
|
|
152
|
+
return this.last;
|
|
153
|
+
}
|
|
154
|
+
/** Smoothed ms per label — what a HUD or an IR scalar should report. */
|
|
155
|
+
average() {
|
|
156
|
+
return Object.fromEntries(this.ewma);
|
|
157
|
+
}
|
|
158
|
+
destroy() {
|
|
159
|
+
this.qs?.destroy();
|
|
160
|
+
this.resolve?.destroy();
|
|
161
|
+
for (const s of this.ring)
|
|
162
|
+
s.read.destroy();
|
|
163
|
+
this.ring = [];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which LOD ring a distance falls in, biased to keep whatever was already chosen.
|
|
3
|
+
*
|
|
4
|
+
* `radii` are the OUTER edges of each ring, ascending — `[64, 128, 256]` means LOD0 out to 64,
|
|
5
|
+
* LOD1 to 128, LOD2 to 256, LOD3 beyond. `current` is last frame's answer for this item (pass -1
|
|
6
|
+
* the first time, when there is nothing to be sticky about). `hysteresis` is in the same units as
|
|
7
|
+
* `dist`, and is the distance you must overshoot a boundary before it lets go.
|
|
8
|
+
*/
|
|
9
|
+
export declare function selectLod(dist: number, radii: readonly number[], current?: number, hysteresis?: number): number;
|
|
10
|
+
/**
|
|
11
|
+
* How much of `lod` to show while it hands over to its neighbour, in [0,1].
|
|
12
|
+
*
|
|
13
|
+
* 1 means fully this LOD, 0 means fully the next one. Within `band` of the boundary the two are
|
|
14
|
+
* meant to be drawn TOGETHER with alphas that sum to 1 — `crossfadeAlpha(d, radii, lod)` and
|
|
15
|
+
* `1 - crossfadeAlpha(...)` — so nothing ever blinks between representations.
|
|
16
|
+
*/
|
|
17
|
+
export declare function crossfadeAlpha(dist: number, radii: readonly number[], lod: number, band?: number): number;
|
|
18
|
+
/** Per-item LOD state, so a caller can keep hysteresis without inventing its own bookkeeping. */
|
|
19
|
+
export declare class LodTracker {
|
|
20
|
+
private radii;
|
|
21
|
+
private hysteresis;
|
|
22
|
+
private band;
|
|
23
|
+
private state;
|
|
24
|
+
constructor(radii: readonly number[], hysteresis?: number, band?: number);
|
|
25
|
+
/** Resolve one item by stable id. Returns the ring and how much of it to draw. */
|
|
26
|
+
select(id: number, dist: number): {
|
|
27
|
+
lod: number;
|
|
28
|
+
alpha: number;
|
|
29
|
+
next: number;
|
|
30
|
+
};
|
|
31
|
+
/** Drop items that are no longer streamed in, so the map can't grow without bound. */
|
|
32
|
+
forget(id: number): void;
|
|
33
|
+
clear(): void;
|
|
34
|
+
get size(): number;
|
|
35
|
+
}
|
package/dist/lodRing.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// PLATFORM. LOD ring selection with HYSTERESIS and a CROSSFADE band — the two things that turn a
|
|
2
|
+
// set of detail rings into something that doesn't flicker.
|
|
3
|
+
//
|
|
4
|
+
// The naive rule is `lod = count of radii below dist`, and it has one specific failure: a camera
|
|
5
|
+
// sitting near a boundary. Walk back and forth across r=64 and the ring flips every frame, so a
|
|
6
|
+
// whole band of the world rebuilds its mesh, re-uploads, and pops — at exactly the moment the
|
|
7
|
+
// player is standing still enough to notice. `selectLod` fixes it by making the boundary depend on
|
|
8
|
+
// which side you are already on: you must travel `hysteresis` PAST the radius to promote, and
|
|
9
|
+
// `hysteresis` back INSIDE it to demote. The two thresholds never coincide, so no amount of jitter
|
|
10
|
+
// at a single distance can oscillate.
|
|
11
|
+
//
|
|
12
|
+
// `crossfadeAlpha` covers the other half: even a correct, stable switch is a visible pop if the two
|
|
13
|
+
// LODs differ. Fading one out as the other comes in across a band around the boundary turns the pop
|
|
14
|
+
// into a dissolve. It is deliberately a plain number rather than a shader: GpuShadowRenderer already
|
|
15
|
+
// carries per-instance alpha for its translucent overlay, so a caller feeds this straight into the
|
|
16
|
+
// instance it was already going to submit.
|
|
17
|
+
//
|
|
18
|
+
// Pure functions, no GPU, no game knowledge — so the oracle is headless and the same logic serves
|
|
19
|
+
// voxel rings, mesh LOD ladders and impostor handoff alike.
|
|
20
|
+
/**
|
|
21
|
+
* Which LOD ring a distance falls in, biased to keep whatever was already chosen.
|
|
22
|
+
*
|
|
23
|
+
* `radii` are the OUTER edges of each ring, ascending — `[64, 128, 256]` means LOD0 out to 64,
|
|
24
|
+
* LOD1 to 128, LOD2 to 256, LOD3 beyond. `current` is last frame's answer for this item (pass -1
|
|
25
|
+
* the first time, when there is nothing to be sticky about). `hysteresis` is in the same units as
|
|
26
|
+
* `dist`, and is the distance you must overshoot a boundary before it lets go.
|
|
27
|
+
*/
|
|
28
|
+
export function selectLod(dist, radii, current = -1, hysteresis = 0) {
|
|
29
|
+
// No prior state: the plain rule is the honest answer, since there is nothing to stick to.
|
|
30
|
+
if (current < 0 || hysteresis <= 0) {
|
|
31
|
+
let l = 0;
|
|
32
|
+
while (l < radii.length && dist > radii[l])
|
|
33
|
+
l++;
|
|
34
|
+
return l;
|
|
35
|
+
}
|
|
36
|
+
const clamped = Math.max(0, Math.min(radii.length, current));
|
|
37
|
+
// Promote (coarser) only once past the outer edge PLUS the margin; demote (finer) only once back
|
|
38
|
+
// inside the inner edge MINUS it. Between the two the previous choice simply stands.
|
|
39
|
+
let l = clamped;
|
|
40
|
+
while (l < radii.length && dist > radii[l] + hysteresis)
|
|
41
|
+
l++;
|
|
42
|
+
while (l > 0 && dist < radii[l - 1] - hysteresis)
|
|
43
|
+
l--;
|
|
44
|
+
return l;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* How much of `lod` to show while it hands over to its neighbour, in [0,1].
|
|
48
|
+
*
|
|
49
|
+
* 1 means fully this LOD, 0 means fully the next one. Within `band` of the boundary the two are
|
|
50
|
+
* meant to be drawn TOGETHER with alphas that sum to 1 — `crossfadeAlpha(d, radii, lod)` and
|
|
51
|
+
* `1 - crossfadeAlpha(...)` — so nothing ever blinks between representations.
|
|
52
|
+
*/
|
|
53
|
+
export function crossfadeAlpha(dist, radii, lod, band = 0) {
|
|
54
|
+
if (band <= 0 || lod < 0 || lod >= radii.length)
|
|
55
|
+
return 1;
|
|
56
|
+
const edge = radii[lod];
|
|
57
|
+
if (dist <= edge - band)
|
|
58
|
+
return 1;
|
|
59
|
+
if (dist >= edge + band)
|
|
60
|
+
return 0;
|
|
61
|
+
const t = (dist - (edge - band)) / (2 * band);
|
|
62
|
+
return 1 - t * t * (3 - 2 * t); // smoothstep — a linear ramp shows its corners as a brightness kink
|
|
63
|
+
}
|
|
64
|
+
/** Per-item LOD state, so a caller can keep hysteresis without inventing its own bookkeeping. */
|
|
65
|
+
export class LodTracker {
|
|
66
|
+
radii;
|
|
67
|
+
hysteresis;
|
|
68
|
+
band;
|
|
69
|
+
state = new Map();
|
|
70
|
+
constructor(radii, hysteresis = 0, band = 0) {
|
|
71
|
+
this.radii = radii;
|
|
72
|
+
this.hysteresis = hysteresis;
|
|
73
|
+
this.band = band;
|
|
74
|
+
}
|
|
75
|
+
/** Resolve one item by stable id. Returns the ring and how much of it to draw. */
|
|
76
|
+
select(id, dist) {
|
|
77
|
+
const lod = selectLod(dist, this.radii, this.state.get(id) ?? -1, this.hysteresis);
|
|
78
|
+
this.state.set(id, lod);
|
|
79
|
+
return {
|
|
80
|
+
lod,
|
|
81
|
+
alpha: crossfadeAlpha(dist, this.radii, lod, this.band),
|
|
82
|
+
next: Math.min(lod + 1, this.radii.length),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** Drop items that are no longer streamed in, so the map can't grow without bound. */
|
|
86
|
+
forget(id) {
|
|
87
|
+
this.state.delete(id);
|
|
88
|
+
}
|
|
89
|
+
clear() {
|
|
90
|
+
this.state.clear();
|
|
91
|
+
}
|
|
92
|
+
get size() {
|
|
93
|
+
return this.state.size;
|
|
94
|
+
}
|
|
95
|
+
}
|
package/dist/mat4.d.ts
CHANGED
|
@@ -3,6 +3,15 @@ export type Vec3 = readonly [number, number, number];
|
|
|
3
3
|
export declare function perspective(fovY: number, aspect: number, near: number, far: number): Mat4;
|
|
4
4
|
export declare function lookAt(eye: Vec3, target: Vec3, up: Vec3): Mat4;
|
|
5
5
|
export declare function mul(a: Mat4, b: Mat4): Mat4;
|
|
6
|
+
/**
|
|
7
|
+
* General 4×4 inverse (cofactor / Laplace expansion), or `null` when `m` is singular.
|
|
8
|
+
*
|
|
9
|
+
* Needed to go the other way through a projection: TAA's depth reprojection unprojects a pixel with
|
|
10
|
+
* `invert(camVP)` to recover its world position. A view-projection is not affine — the perspective
|
|
11
|
+
* divide puts values in the bottom row — so the cheap "transpose the rotation, negate the
|
|
12
|
+
* translation" shortcut does not apply here and the full inverse is the honest one.
|
|
13
|
+
*/
|
|
14
|
+
export declare function invert(m: Mat4): Mat4 | null;
|
|
6
15
|
/** camera view-projection = perspective · lookAt (world → clip). */
|
|
7
16
|
export declare function viewProjection(eye: Vec3, target: Vec3, fovY: number, aspect: number, near?: number, far?: number): Mat4;
|
|
8
17
|
/** Orthographic projection, WebGPU clip z ∈ [0,1] (for shadow-map light views). */
|
package/dist/mat4.js
CHANGED
|
@@ -51,6 +51,40 @@ export function mul(a, b) {
|
|
|
51
51
|
}
|
|
52
52
|
return o;
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* General 4×4 inverse (cofactor / Laplace expansion), or `null` when `m` is singular.
|
|
56
|
+
*
|
|
57
|
+
* Needed to go the other way through a projection: TAA's depth reprojection unprojects a pixel with
|
|
58
|
+
* `invert(camVP)` to recover its world position. A view-projection is not affine — the perspective
|
|
59
|
+
* divide puts values in the bottom row — so the cheap "transpose the rotation, negate the
|
|
60
|
+
* translation" shortcut does not apply here and the full inverse is the honest one.
|
|
61
|
+
*/
|
|
62
|
+
export function invert(m) {
|
|
63
|
+
const a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3], a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7], a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11], a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15];
|
|
64
|
+
const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
|
|
65
|
+
const det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
|
|
66
|
+
if (det === 0 || !Number.isFinite(det))
|
|
67
|
+
return null;
|
|
68
|
+
const d = 1 / det;
|
|
69
|
+
const o = new Float64Array(16);
|
|
70
|
+
o[0] = (a11 * b11 - a12 * b10 + a13 * b09) * d;
|
|
71
|
+
o[1] = (a02 * b10 - a01 * b11 - a03 * b09) * d;
|
|
72
|
+
o[2] = (a31 * b05 - a32 * b04 + a33 * b03) * d;
|
|
73
|
+
o[3] = (a22 * b04 - a21 * b05 - a23 * b03) * d;
|
|
74
|
+
o[4] = (a12 * b08 - a10 * b11 - a13 * b07) * d;
|
|
75
|
+
o[5] = (a00 * b11 - a02 * b08 + a03 * b07) * d;
|
|
76
|
+
o[6] = (a32 * b02 - a30 * b05 - a33 * b01) * d;
|
|
77
|
+
o[7] = (a20 * b05 - a22 * b02 + a23 * b01) * d;
|
|
78
|
+
o[8] = (a10 * b10 - a11 * b08 + a13 * b06) * d;
|
|
79
|
+
o[9] = (a01 * b08 - a00 * b10 - a03 * b06) * d;
|
|
80
|
+
o[10] = (a30 * b04 - a31 * b02 + a33 * b00) * d;
|
|
81
|
+
o[11] = (a21 * b02 - a20 * b04 - a23 * b00) * d;
|
|
82
|
+
o[12] = (a11 * b07 - a10 * b09 - a12 * b06) * d;
|
|
83
|
+
o[13] = (a00 * b09 - a01 * b07 + a02 * b06) * d;
|
|
84
|
+
o[14] = (a31 * b01 - a30 * b03 - a32 * b00) * d;
|
|
85
|
+
o[15] = (a20 * b03 - a21 * b01 + a22 * b00) * d;
|
|
86
|
+
return o;
|
|
87
|
+
}
|
|
54
88
|
/** camera view-projection = perspective · lookAt (world → clip). */
|
|
55
89
|
export function viewProjection(eye, target, fovY, aspect, near = 0.1, far = 1000) {
|
|
56
90
|
return mul(perspective(fovY, aspect, near, far), lookAt(eye, target, [0, 1, 0]));
|