Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
DynamicGI.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "./DynamicGI.hpp"
4#include "./RenderContext.hpp"
6#include "../../core/Log.hpp"
7
8#include <algorithm>
9#include <cmath>
10#include <cstring>
11#include <string>
12
13namespace esengine {
14
16 static DynamicGIScene scene;
17 return scene;
18}
19
20namespace {
21DynamicGIStats g_stats;
22}
23
25 return g_stats;
26}
27
28namespace {
29
30constexpr u32 kInstanceVec4 = 20;
31constexpr u32 kProbeSize = 8;
32constexpr u32 kProbeTexels = 3; // the vector that integrates a probe against a normal, one texel a colour channel
33
35enum Header : u32 {
36 kDim = 0, kCell, kOriginX, kOriginY, kOriginZ, kReach, kInstances, kPixels,
37 kSunX, kSunY, kSunZ, kSunOn, kSunR, kSunG, kSunB, kBias, kRange, kTolerance, kSkyR, kSkyG, kSkyB, kHit, kLevels, kLights,
39 kLevelBlock = 24, kLightBlock = 40, kHeaderSize = 40,
41 kGrowth = 40 + 8 * 16
42};
43constexpr u32 kMaxLevels = 3, kMaxLights = 8, kLightFloats = 16;
44
45struct ParamsBlock {
46 f32 sdf[4];
47 i32 origin[4];
48 u32 counts[4];
49 f32 sunDir[4];
50 f32 sunRad[4];
51 f32 trace[4];
52 f32 sky[4];
53 f32 misc[4];
54 i32 levelA[kMaxLevels][4]; // origin xyz, cells per axis
55 f32 levelB[kMaxLevels][4]; // cell size, reach
56 u32 levelC[kMaxLevels][4]; // where the field starts in the buffer, and its owner words
57 f32 lights[kMaxLights * 4][4];
58};
59static_assert(sizeof(ParamsBlock) == 128 + 3 * 48 + 512, "the GI block: eight vec4s, three levels, eight lights of four");
60
61#ifdef ES_ENABLE_WEBGPU
62// The CPU twin of what is here is in sdk/src/gi (globalSdf.ts sphereTrace, surfaceCache.ts lookup, screenProbes.ts tracePoint);
63// pipeline/tests/gi-lab.test.ts holds the twin to Cycles, and tools/gi/check-sdf-wgsl.mjs ran the trace of this on a GPU.
64//
65// An instance is 20 vec4: 0-3 the matrix local to world; 4-6 the rows of world to local (w the translation, the scale already divided
66// out); 7 the world box min and w the scale; 8 the world box max and w the card pixel size; 9 the local box min and w the emission
67// scale; 10 the local box max; 11-16 the six faces (width, height, first pixel in the card pixel array).
68const char* kCommon = R"WGSL(
69struct Frame { projection : mat4x4f, camera : vec4f, inverseViewProjection : mat4x4f, renderOrigin : vec4f };
70struct GI {
71 sdf : vec4f, // x: levels of the field, y: lights, w: intensity
72 origin : vec4i, // w: the frame
73 counts : vec4u, // x: instances, y: card pixels, z: probe tiles x, w: probe tiles y
74 sunDir : vec4f, // xyz: toward the sun; w: 1 when there is one
75 sunRad : vec4f, // rgb: radiance; w: how far off a surface a ray starts
76 trace : vec4f, // x: how far a ray looks, y: card tolerance, z: blend, w: hit fraction of a cell
77 sky : vec4f, // rgb: what a ray that meets nothing brings
78 misc : vec4f, // x: how many frames the cards are spread over; y: 1 of every this many rays of a probe is traced a frame; z: pixels between probes; w: how much fatter than its mesh a body's field is
79 levelA : array<vec4i, 3>, // per level: the first cell of its window, cells per axis
80 levelB : array<vec4f, 3>, // per level: cell size, reach
81 levelC : array<vec4u, 3>, // per level: where its field starts in sdfData, and its owner words
82 lights : array<vec4f, 32>, // eight lights of four: position and reach | colour and kind | aim and falloff | inner radius and cone cosines
83};
84@group(0) @binding(0) var<uniform> frame : Frame;
85@group(0) @binding(1) var<uniform> gi : GI;
86@group(0) @binding(2) var<storage, read> sdfData : array<f32>;
87@group(0) @binding(3) var<storage, read> insts : array<vec4f>;
88@group(0) @binding(4) var<storage, read> cardPix : array<vec4u>;
89@group(0) @binding(5) var<storage, read> radIn : array<vec4f>;
90
91const PI : f32 = 3.14159265;
92
93fn cellValue(l : u32, c : vec3i) -> f32 {
94 let d = gi.levelA[l].w;
95 let w = c & vec3i(d - 1);
96 return sdfData[gi.levelC[l].x + u32(w.x + w.y * d + w.z * d * d)];
97}
98fn sdfSample(l : u32, p : vec3f) -> f32 {
99 let g = p / gi.levelB[l].x - vec3f(0.5);
100 let i0 = vec3i(floor(g));
101 let f = g - vec3f(i0);
102 let c000 = cellValue(l, i0);
103 let c100 = cellValue(l, i0 + vec3i(1, 0, 0));
104 let c010 = cellValue(l, i0 + vec3i(0, 1, 0));
105 let c110 = cellValue(l, i0 + vec3i(1, 1, 0));
106 let c001 = cellValue(l, i0 + vec3i(0, 0, 1));
107 let c101 = cellValue(l, i0 + vec3i(1, 0, 1));
108 let c011 = cellValue(l, i0 + vec3i(0, 1, 1));
109 let c111 = cellValue(l, i0 + vec3i(1, 1, 1));
110 return mix(mix(mix(c000, c100, f.x), mix(c010, c110, f.x), f.y), mix(mix(c001, c101, f.x), mix(c011, c111, f.x), f.y), f.z);
111}
112// The finest level whose window holds p at least a cell from its edge, or -1.
113fn levelAt(p : vec3f) -> i32 {
114 for (var l = 0u; l < u32(gi.sdf.x); l = l + 1u) {
115 let c = p / gi.levelB[l].x - vec3f(gi.levelA[l].xyz);
116 if (all(c >= vec3f(1.0)) && all(c <= vec3f(f32(gi.levelA[l].w) - 1.0))) { return i32(l); }
117 }
118 return -1;
119}
120// Distance along dir to the first surface within maxT, or -1. A ray that starts inside a body hits at 0. It walks the finest level
121// that holds it and hands over to a coarser one where the finer ends.
122fn sdfTrace(origin : vec3f, dir : vec3f, maxT : f32) -> f32 {
123 var t = 0.0;
124 for (var i = 0; i < 160; i = i + 1) {
125 if (t >= maxT) { return -1.0; }
126 let p = origin + dir * t;
127 let li = levelAt(p);
128 if (li < 0) { return -1.0; }
129 let l = u32(li);
130 let cell = gi.levelB[l].x;
131 // Far from anything (the cell the point is in says so by more than three cells) one read is enough: the field there, less the
132 // farthest a point can be from its cell centre, is a distance nothing is nearer than. Close to a surface the 8 reads of a trilinear.
133 let near = cellValue(l, vec3i(floor(p / cell)));
134 if (near > cell * 3.0) { t = t + near - cell * 0.87; continue; }
135 let d = sdfSample(l, p);
136 if (d < cell * gi.trace.w) { return t; }
137 t = t + max(d, cell * 0.25);
138 }
139 return -1.0;
140}
141// Which way the field rises at p (away from the nearest surface), or zero where no level holds p.
142fn sdfSlope(p : vec3f) -> vec3f {
143 let li = levelAt(p);
144 if (li < 0) { return vec3f(0.0); }
145 let l = u32(li);
146 let h = gi.levelB[l].x * 0.5;
147 let g = vec3f(sdfSample(l, p + vec3f(h, 0.0, 0.0)) - sdfSample(l, p - vec3f(h, 0.0, 0.0)),
148 sdfSample(l, p + vec3f(0.0, h, 0.0)) - sdfSample(l, p - vec3f(0.0, h, 0.0)),
149 sdfSample(l, p + vec3f(0.0, 0.0, h)) - sdfSample(l, p - vec3f(0.0, 0.0, h)));
150 let len = length(g);
151 if (len < 1e-6) { return vec3f(0.0); }
152 return g / len;
153}
154// Where a ray from a surface point may start. Lifted off its own surface the point can still be inside what a trace calls a hit of ANOTHER
155// surface (a wall the next wall over meets: the corner of a room), and every ray from there would hit at 0 and bring nothing, which is a
156// black band along every edge of the room, as wide as the cell is coarse. It is moved out along the field's slope until it is clear.
157fn clearOrigin(o : vec3f, seen : bool) -> vec3f {
158 var p = o;
159 for (var i = 0; i < 3; i = i + 1) {
160 let li = levelAt(p);
161 if (li < 0) { return p; }
162 let l = u32(li);
163 let cell = gi.levelB[l].x;
164 let want = cell * (gi.trace.w + 0.25);
165 let d = sdfSample(l, p);
166 if (d >= want) { return p; }
167 // Under the surface of another body (a card pixel of a wall's end, buried in the wall it meets): left where it is, to bring nothing.
168 // Moved out it would come up on whichever side is nearer, the lit outside of a sealed room among them, and the room would leak.
169 // A point the eye sees (`seen`: a screen probe) is under nothing, whatever the field says of it a tenth of a cell from a wall.
170 if (!seen && i == 0 && d < cell * 0.1 - gi.misc.w) { return p; }
171 let h = cell * 0.5;
172 let g = vec3f(sdfSample(l, p + vec3f(h, 0.0, 0.0)) - sdfSample(l, p - vec3f(h, 0.0, 0.0)),
173 sdfSample(l, p + vec3f(0.0, h, 0.0)) - sdfSample(l, p - vec3f(0.0, h, 0.0)),
174 sdfSample(l, p + vec3f(0.0, 0.0, h)) - sdfSample(l, p - vec3f(0.0, 0.0, h)));
175 let len = length(g);
176 if (len < 1e-6) { return p; }
177 p = p + g / len * (want - d);
178 }
179 return p;
180}
181
182fn instBase(i : u32) -> u32 { return i * 20u; }
183fn faceAxes(face : u32) -> vec2u {
184 let axis = face / 2u;
185 if (axis == 0u) { return vec2u(1u, 2u); }
186 if (axis == 1u) { return vec2u(0u, 2u); }
187 return vec2u(0u, 1u);
188}
189fn comp(v : vec3f, k : u32) -> f32 { return select(select(v.z, v.y, k == 1u), v.x, k == 0u); }
190fn setComp(v : vec3f, k : u32, x : f32) -> vec3f {
191 var r = v;
192 if (k == 0u) { r.x = x; } else if (k == 1u) { r.y = x; } else { r.z = x; }
193 return r;
194}
195fn unpackNormal(w0 : u32, w1 : u32) -> vec3f {
196 let nx = f32(bitcast<i32>((w0 >> 16u) << 24u) >> 24u) / 127.0;
197 let ny = f32(bitcast<i32>((w0 >> 24u) << 24u) >> 24u) / 127.0;
198 let nz = f32(bitcast<i32>(w1 << 24u) >> 24u) / 127.0;
199 return vec3f(nx, ny, nz);
200}
201fn unpackColour(w : u32) -> vec3f {
202 return vec3f(f32(w & 255u), f32((w >> 8u) & 255u), f32((w >> 16u) & 255u)) / 255.0;
203}
204
205// What the cards of one instance say a ray brings back from the surface it hit at point, travelling along dir: the cards that face it,
206// blended by how squarely each does, from the pixel whose surface is within the tolerance of the point. w is how far that pixel is, or
207// -1 when no card of the instance holds the point.
208fn lookupIn(i : u32, point : vec3f, dir : vec3f, tol : f32) -> vec4f {
209 let b = instBase(i);
210 let wmin = insts[b + 7u];
211 let wmax = insts[b + 8u];
212 if (any(point < wmin.xyz - vec3f(tol)) || any(point > wmax.xyz + vec3f(tol))) { return vec4f(0.0, 0.0, 0.0, -1.0); }
213 let r0 = insts[b + 4u]; let r1 = insts[b + 5u]; let r2 = insts[b + 6u];
214 let local = vec3f(dot(r0.xyz, point) + r0.w, dot(r1.xyz, point) + r1.w, dot(r2.xyz, point) + r2.w);
215 var d = vec3f(dot(r0.xyz, dir), dot(r1.xyz, dir), dot(r2.xyz, dir));
216 d = d / max(length(d), 1e-9);
217 let lmin = insts[b + 9u].xyz;
218 let lmax = insts[b + 10u].xyz;
219 let scale = wmin.w;
220 let cell = wmax.w;
221 var sum = vec3f(0.0);
222 var total = 0.0;
223 var error = 0.0;
224 for (var axis = 0u; axis < 3u; axis = axis + 1u) {
225 let da = comp(d, axis);
226 let weight = abs(da);
227 if (weight < 0.05) { continue; }
228 let face = axis * 2u + select(0u, 1u, da > 0.0);
229 let uv = faceAxes(face);
230 let lu = comp(local, uv.x); let lv = comp(local, uv.y);
231 if (lu < comp(lmin, uv.x) - cell || lu > comp(lmax, uv.x) + cell || lv < comp(lmin, uv.y) - cell || lv > comp(lmax, uv.y) + cell) { continue; }
232 let f = insts[b + 11u + face];
233 let fu = clamp((lu - comp(lmin, uv.x)) / max(comp(lmax, uv.x) - comp(lmin, uv.x), 1e-9), 0.0, 0.99999);
234 let fv = clamp((lv - comp(lmin, uv.y)) / max(comp(lmax, uv.y) - comp(lmin, uv.y), 1e-9), 0.0, 0.99999);
235 let px = u32(floor(fu * f.x));
236 let py = u32(floor(fv * f.y));
237 let idx = u32(f.z) + px + py * u32(f.x);
238 let pix = cardPix[idx];
239 let depth16 = pix.x & 0xffffu;
240 if (depth16 == 65535u) { continue; }
241 let ext = comp(lmax, axis) - comp(lmin, axis);
242 let sgn = face % 2u == 0u;
243 let la = comp(local, axis);
244 let pointDepth = select(la - comp(lmin, axis), comp(lmax, axis) - la, sgn);
245 let cardDepth = f32(depth16) / 65534.0 * ext;
246 let off = abs(cardDepth - pointDepth) * scale;
247 if (off > tol) { continue; }
248 error = max(error, off);
249 sum = sum + weight * radIn[idx].xyz;
250 total = total + weight;
251 }
252 if (total <= 0.0) { return vec4f(0.0, 0.0, 0.0, -1.0); }
253 return vec4f(sum / total, error);
254}
255
256// Which instance a cell of a level is nearest to (id + 1; 0 for none, 127 for an id the table cannot hold). The words after the field hold four each.
257fn ownerAt(l : u32, c : vec3i) -> u32 {
258 let d = gi.levelA[l].w;
259 let w = c & vec3i(d - 1);
260 let idx = u32(w.x + w.y * d + w.z * d * d);
261 return (bitcast<u32>(sdfData[gi.levelC[l].y + (idx >> 2u)]) >> ((idx & 3u) * 8u)) & 127u;
262}
263
264// What a ray brings back from the surface it hit at point. The field names the instance the point is by, so the cards of that one are
265// asked; only where it says none (or its cards do not hold the point) are all of them, and of those the nearest wins. A hit found in a
266// coarse level is a cell of that level off the surface, and the cards are asked to forgive as much.
267fn lookup(point : vec3f, dir : vec3f) -> vec3f {
268 let l = u32(max(levelAt(point), 0));
269 let cell = gi.levelB[l].x;
270 let tol = max(gi.trace.y, cell * 1.5);
271 let owner = ownerAt(l, vec3i(floor(point / cell)));
272 if (owner > 0u && owner < 127u && owner <= gi.counts.x) {
273 let r = lookupIn(owner - 1u, point, dir, tol);
274 if (r.w >= 0.0) { return r.xyz; }
275 }
276 var best = vec3f(0.0);
277 var bestError = 1e30;
278 for (var i = 0u; i < gi.counts.x; i = i + 1u) {
279 let r = lookupIn(i, point, dir, tol);
280 if (r.w >= 0.0 && r.w < bestError) { bestError = r.w; best = r.xyz; }
281 }
282 return best;
283}
284
285// The frame falloff of a light over a distance (distanceFalloff in ShaderParser.cpp): held at full to the inner radius, ramped to the reach
286// raised to the power fy; or, for fy < 0, 1 / d^2 in metres (-fy world units to one) let go over the reach.
287fn lightFalloff(dist : f32, reach : f32, inner : f32, fy : f32) -> f32 {
288 let ramp = clamp((reach - dist) / max(reach - inner, 1e-4), 0.0, 1.0);
289 let shaped = pow(ramp, max(fy, 1e-3));
290 let metres = dist / max(-fy, 1e-4);
291 let q = dist / max(reach, 1e-4);
292 let w = clamp(1.0 - q * q * q * q, 0.0, 1.0);
293 return select(shaped, w * w / max(metres * metres, 0.01), fy < 0.0);
294}
295
296// What the point and spot lights give a surface at pos facing n, shadowed by the field: each is a ray from just off the surface to the light.
297fn lightsDirect(pos : vec3f, n : vec3f, origin : vec3f) -> vec3f {
298 var sum = vec3f(0.0);
299 for (var i = 0u; i < u32(gi.sdf.y); i = i + 1u) {
300 let a = gi.lights[i * 4u]; let b = gi.lights[i * 4u + 1u]; let c = gi.lights[i * 4u + 2u]; let d = gi.lights[i * 4u + 3u];
301 let to = a.xyz - pos;
302 let dist = length(to);
303 if (dist < 1e-4 || dist >= a.w) { continue; }
304 let dir = to / dist;
305 let ndl = dot(n, dir);
306 if (ndl <= 0.0) { continue; }
307 var atten = lightFalloff(dist, a.w, d.x, c.w);
308 if (b.w > 1.5) { atten = atten * smoothstep(d.z, d.y, dot(c.xyz, -dir)); }
309 if (atten <= 0.0) { continue; }
310 let t = sdfTrace(origin, dir, max(dist - gi.sunRad.w, 0.0));
311 if (t < 0.0) { sum = sum + b.xyz * atten * ndl; }
312 }
313 return sum;
314}
315
316fn hash3(a : u32, b : u32, c : u32) -> f32 {
317 var h = (a * 73856093u) ^ (b * 19349663u) ^ (c * 83492791u);
318 h = (h ^ (h >> 16u)) * 0x45d9f3bu;
319 h = h ^ (h >> 16u);
320 return f32(h) / 4294967296.0;
321}
322fn octahedral(u : f32, v : f32) -> vec3f {
323 let x = u * 2.0 - 1.0; let y = v * 2.0 - 1.0;
324 var p = vec2f(x, y);
325 let z = 1.0 - abs(x) - abs(y);
326 if (z < 0.0) { p = vec2f((1.0 - abs(y)) * select(-1.0, 1.0, x >= 0.0), (1.0 - abs(x)) * select(-1.0, 1.0, y >= 0.0)); }
327 return normalize(vec3f(p.x, p.y, z));
328}
329// One ray of a probe about normal n: the octahedral cell (i, j), jittered inside it, folded into n's hemisphere.
330fn probeRay(i : u32, j : u32, n : vec3f, seed : u32, frame : u32) -> vec3f {
331 let jx = hash3(i, j, seed * 31u + frame * 7u + 1u);
332 let jy = hash3(i, j, seed * 17u + frame * 13u + 2u);
333 var d = octahedral((f32(i) + jx) / 8.0, (f32(j) + jy) / 8.0);
334 let dn = dot(d, n);
335 if (dn < 0.0) { d = d - 2.0 * dn * n; }
336 return d;
337}
338// The light a ray from origin along d brings.
339fn rayRadiance(origin : vec3f, d : vec3f) -> vec3f {
340 let t = sdfTrace(origin, d, gi.trace.x);
341 if (t < 0.0) { return gi.sky.xyz; }
342 if (t < 0.001) { return vec3f(0.0); }
343 return lookup(origin + d * t, d);
344}
345)WGSL";
346
347// One workgroup relights one card pixel: its 64 threads are the 64 rays (one a thread, so the GPU is kept busy where one thread tracing
348// 64 in turn left it waiting on its own chain of reads), reduced in shared memory. Only a slice of the cards is relit each frame, round
349// robin. The cards are updated in place (a ray that reads a card another workgroup is rewriting sees the old or the new light, either
350// of which is a frame of the right answer), so radIn is declared read-write here.
351const char* kCardLight = R"WGSL(
352var<workgroup> cardSum : array<vec3f, 64>;
353
354@compute @workgroup_size(64)
355fn main(@builtin(workgroup_id) wg : vec3u, @builtin(local_invocation_index) lid : u32) {
356 let slices = max(u32(gi.misc.x), 1u);
357 let chunk = (gi.counts.y + slices - 1u) / slices;
358 let settled = gi.origin.w >= 2;
359 let start = select(0u, (u32(gi.origin.w) % slices) * chunk, settled);
360 let end = select(gi.counts.y, min(start + chunk, gi.counts.y), settled);
361 let p = start + wg.x + wg.y * 65535u;
362 if (p >= end) { return; }
363 let pix = cardPix[p];
364 let depth16 = pix.x & 0xffffu;
365 if (depth16 == 65535u) { if (lid == 0u) { radIn[p] = vec4f(0.0); } return; }
366 let instance = pix.w >> 3u;
367 let face = pix.w & 7u;
368 let b = instBase(instance);
369 let f = insts[b + 11u + face];
370 let idx = p - u32(f.z);
371 let w = u32(f.x);
372 let px = idx % w;
373 let py = idx / w;
374 let lmin = insts[b + 9u].xyz;
375 let lmax = insts[b + 10u].xyz;
376 let axis = face / 2u;
377 let uv = faceAxes(face);
378 var local = vec3f(0.0);
379 local = setComp(local, uv.x, comp(lmin, uv.x) + (f32(px) + 0.5) / f.x * (comp(lmax, uv.x) - comp(lmin, uv.x)));
380 local = setComp(local, uv.y, comp(lmin, uv.y) + (f32(py) + 0.5) / f.y * (comp(lmax, uv.y) - comp(lmin, uv.y)));
381 let depth = f32(depth16) / 65534.0 * (comp(lmax, axis) - comp(lmin, axis));
382 local = setComp(local, axis, select(comp(lmin, axis) + depth, comp(lmax, axis) - depth, face % 2u == 0u));
383 let m0 = insts[b]; let m1 = insts[b + 1u]; let m2 = insts[b + 2u]; let m3 = insts[b + 3u];
384 let pos = m0.xyz * local.x + m1.xyz * local.y + m2.xyz * local.z + m3.xyz;
385 let scale = insts[b + 7u].w;
386 let nl = unpackNormal(pix.x, pix.y);
387 let n = normalize((m0.xyz * nl.x + m1.xyz * nl.y + m2.xyz * nl.z) / scale);
388 let origin = clearOrigin(pos + n * gi.sunRad.w, false);
389 let d = probeRay(lid & 7u, lid >> 3u, n, p, u32(gi.origin.w));
390 cardSum[lid] = rayRadiance(origin, d) * dot(d, n);
391 workgroupBarrier();
392 for (var s = 32u; s > 0u; s = s >> 1u) {
393 if (lid < s) { cardSum[lid] = cardSum[lid] + cardSum[lid + s]; }
394 workgroupBarrier();
395 }
396 if (lid != 0u) { return; }
397 let albedo = unpackColour(pix.y >> 8u);
398 let emissive = unpackColour(pix.z) * insts[b + 9u].w;
399 var direct = vec3f(0.0);
400 if (gi.sunDir.w > 0.5) {
401 let ndl = dot(n, gi.sunDir.xyz);
402 if (ndl > 0.0 && sdfTrace(origin, gi.sunDir.xyz, gi.trace.x) < 0.0) { direct = gi.sunRad.xyz * ndl; }
403 }
404 direct = direct + lightsDirect(pos, n, origin);
405 let now = albedo * (direct + cardSum[0] * (2.0 / 64.0)) + emissive;
406 // A card is relit once in `slices` frames, so each relight carries that much more of the change.
407 let blend = select(min(gi.trace.z * f32(slices), 1.0), 1.0, !settled);
408 radIn[p] = vec4f(mix(radIn[p].xyz, now, blend), 1.0);
409}
410)WGSL";
411
412const char* kSurface = R"WGSL(
413fn worldFromDepth(uv : vec2f, depth : f32) -> vec3f {
414 let clip = vec4f(uv * 2.0 - 1.0, depth, 1.0);
415 let world = frame.inverseViewProjection * clip;
416 return world.xyz / world.w;
417}
418fn decodeNormal(g : vec4f) -> vec3f {
419 let f = g.rg * 2.0 - 1.0;
420 var n = vec3f(f.x, f.y, 1.0 - abs(f.x) - abs(f.y));
421 let k = clamp(-n.z, 0.0, 1.0);
422 n = vec3f(n.x + select(k, -k, n.x >= 0.0), n.y + select(k, -k, n.y >= 0.0), n.z);
423 return normalize(n);
424}
425fn viewDirection(p : vec3f) -> vec3f {
426 if (frame.camera.w > 0.5) { return normalize(frame.camera.xyz - p); }
427 return frame.camera.xyz;
428}
429)WGSL";
430
431// One workgroup is one probe: its 64 threads are the 64 rays, reduced to the vector V = 2/64 * sum(L d) per colour channel, with which
432// the diffuse light for any normal n is max(V.n, 0) (exact for the probe's own normal, and linear in n around it).
433const char* kProbe = R"WGSL(
434@group(0) @binding(6) var depthTex : texture_depth_2d;
435@group(0) @binding(7) var gbuffer : texture_2d<f32>;
436@group(0) @binding(8) var probeOut : texture_storage_2d<rgba16float, write>;
437@group(0) @binding(9) var probeHist : texture_2d<f32>;
438@group(0) @binding(10) var probeGeo : texture_storage_2d<rgba32float, write>;
439
440// A probe's normal in two numbers (octahedral), for the history: see where it is read.
441fn packHistNormal(n : vec3f) -> vec2f {
442 let p = n.xy / (abs(n.x) + abs(n.y) + abs(n.z));
443 if (n.z >= 0.0) { return p; }
444 return (vec2f(1.0) - abs(p.yx)) * vec2f(select(-1.0, 1.0, p.x >= 0.0), select(-1.0, 1.0, p.y >= 0.0));
445}
446fn histNormal(x : f32, y : f32) -> vec3f {
447 var n = vec3f(x, y, 1.0 - abs(x) - abs(y));
448 let t = max(-n.z, 0.0);
449 n.x = n.x + select(t, -t, n.x >= 0.0); n.y = n.y + select(t, -t, n.y >= 0.0);
450 return normalize(n);
451}
452var<workgroup> shR : array<vec3f, 64>;
453var<workgroup> shG : array<vec3f, 64>;
454var<workgroup> shB : array<vec3f, 64>;
455
456@compute @workgroup_size(8, 8)
457fn main(@builtin(workgroup_id) wg : vec3u, @builtin(local_invocation_id) lid3 : vec3u, @builtin(local_invocation_index) lid : u32) {
458 let size = vec2i(textureDimensions(depthTex));
459 let spacing = i32(gi.misc.z);
460 let t = min(vec2i(wg.xy) * spacing + vec2i(spacing / 2), size - vec2i(1));
461 let depth = textureLoad(depthTex, t, 0);
462 let g = textureLoad(gbuffer, t, 0);
463 let valid = depth < 1.0 && g.a > 0.7;
464 var contribution = array<vec3f, 3>(vec3f(0.0), vec3f(0.0), vec3f(0.0));
465 var eyeDistance = 0.0;
466 var probePos = vec3f(0.0);
467 var probeNormal = vec3f(0.0, 1.0, 0.0);
468 if (valid) {
469 var n = decodeNormal(g);
470 let pos = worldFromDepth((vec2f(t) + 0.5) / vec2f(size), depth);
471 if (dot(n, viewDirection(pos)) < 0.0) { n = -n; }
472 eyeDistance = length(pos - frame.camera.xyz);
473 // A pixel on the edge two walls share holds, in a resolved G-buffer, a normal that is neither wall's (two octahedral codes averaged)
474 // and may face into one of them: a probe there would gather what comes out of that wall alone, and the edge pixels beside it, which
475 // hold the same wrong normal, would take it as theirs - a dashed dark line down the edge. The field knows which way is out.
476 let away = sdfSlope(pos);
477 if (dot(away, away) > 0.5 && dot(n, away) < 0.2) { n = away; }
478 probePos = pos;
479 probeNormal = n;
480 // One ray in `stride` of the 64 is traced this frame, the cells alternating like a checkerboard from frame to frame.
481 let stride = max(u32(gi.misc.y), 1u);
482 if (((lid3.x + lid3.y * 3u + u32(gi.origin.w)) % stride) == 0u) {
483 let d = probeRay(lid3.x, lid3.y, n, wg.x + wg.y * gi.counts.z, u32(gi.origin.w));
484 let L = rayRadiance(clearOrigin(pos + n * gi.sunRad.w, true), d);
485 contribution = array<vec3f, 3>(d * L.x * f32(stride), d * L.y * f32(stride), d * L.z * f32(stride));
486 }
487 }
488 shR[lid] = contribution[0]; shG[lid] = contribution[1]; shB[lid] = contribution[2];
489 workgroupBarrier();
490 for (var s = 32u; s > 0u; s = s >> 1u) {
491 if (lid < s) { shR[lid] = shR[lid] + shR[lid + s]; shG[lid] = shG[lid] + shG[lid + s]; shB[lid] = shB[lid] + shB[lid + s]; }
492 workgroupBarrier();
493 }
494 if (lid == 0u) {
495 let k = 2.0 / 64.0;
496 var vr = shR[0] * k; var vg = shG[0] * k; var vb = shB[0] * k;
497 let base = vec2i(i32(wg.x) * 3, i32(wg.y));
498 // The last frames agree where the probe still looks at the same surface (its distance from the eye is the key, kept in w).
499 // And the probes round it agree with it where they stand on the same surface (as far from the eye, facing the same way: the normal
500 // is kept in the w of the other two texels). What is mixed in is the last frame of the nine, the middle one counting for most: 32
501 // rays a frame toward a sun patch a few of them find is grain a probe wide, and the neighbours are the rays it did not trace.
502 let hr = textureLoad(probeHist, base, 0);
503 // A probe whose own last frame is of another surface (the camera moved and the tile now lies across an edge) still has the
504 // neighbours that are on this one: without them it shows the 32 rays of one frame, a bright or a dark blob beside every moving edge.
505 if (valid && gi.origin.w > 1) {
506 var hR = vec3f(0.0); var hG = vec3f(0.0); var hB = vec3f(0.0); var hW = 0.0;
507 for (var oy = -1; oy <= 1; oy = oy + 1) {
508 for (var ox = -1; ox <= 1; ox = ox + 1) {
509 let tx = i32(wg.x) + ox; let ty = i32(wg.y) + oy;
510 if (tx < 0 || ty < 0 || tx >= i32(gi.counts.z) || ty >= i32(gi.counts.w)) { continue; }
511 let nb = vec2i(tx * 3, ty);
512 let r = textureLoad(probeHist, nb, 0);
513 let g2 = textureLoad(probeHist, nb + vec2i(1, 0), 0);
514 let b2 = textureLoad(probeHist, nb + vec2i(2, 0), 0);
515 if (r.w <= 0.0 || abs(r.w - eyeDistance) > 0.03 * eyeDistance) { continue; }
516 let facing = dot(histNormal(g2.w, b2.w), probeNormal);
517 if (facing < 0.95) { continue; }
518 let w = select(0.3, 1.0, ox == 0 && oy == 0);
519 hR = hR + r.xyz * w; hG = hG + g2.xyz * w; hB = hB + b2.xyz * w; hW = hW + w;
520 }
521 }
522 // A probe that has not moved (the eye is where it was, to a five-hundredth of the distance) keeps five times the history: what is left of the
523 // grain after the neighbours is blotches a few probes wide, which on a still wall read as dirt.
524 let a = select(gi.trace.z, gi.trace.z * 0.2, abs(hr.w - eyeDistance) < 2e-3 * eyeDistance);
525 // None agrees, the probe's own last frame among them (its normal changed: it stands on an edge), and there is nothing to mix.
526 if (hW > 0.0) { vr = mix(hR / hW, vr, a); vg = mix(hG / hW, vg, a); vb = mix(hB / hW, vb, a); }
527 }
528 // Where the probe stands and which way it faces, for the pixels that take its light: stored once here, so that the apply does not read the
529 // depth and the G-buffer and rebuild a world position for each probe it looks at, for every pixel.
530 textureStore(probeGeo, vec2i(i32(wg.x) * 2, i32(wg.y)), vec4f(probePos, eyeDistance));
531 textureStore(probeGeo, vec2i(i32(wg.x) * 2 + 1, i32(wg.y)), vec4f(probeNormal, select(0.0, 1.0, valid)));
532 textureStore(probeOut, base, vec4f(vr, eyeDistance));
533 let packedN = packHistNormal(probeNormal);
534 textureStore(probeOut, base + vec2i(1, 0), vec4f(vg, packedN.x));
535 textureStore(probeOut, base + vec2i(2, 0), vec4f(vb, packedN.y));
536 }
537}
538)WGSL";
539
540const char* kApply = R"WGSL(
541@group(0) @binding(6) var depthTex : texture_depth_2d;
542@group(0) @binding(7) var gbuffer : texture_2d<f32>;
543@group(0) @binding(8) var albedoTex : texture_2d<f32>;
544@group(0) @binding(9) var probes : texture_2d<f32>;
545@group(0) @binding(10) var sceneTex : texture_2d<f32>;
546@group(0) @binding(11) var outTex : texture_storage_2d<rgba16float, write>;
547@group(0) @binding(12) var probeGeo : texture_2d<f32>;
548
549// What one probe says about the pixel at pos facing n: its light by the normal, and how much it should count (plane, then normal).
550fn probeTerm(tile : vec2i, q : vec2f, radius : f32, pos : vec3f, n : vec3f, eye : f32, e : ptr<function, vec3f>, own : ptr<function, vec3f>, w : ptr<function, vec2f>) -> bool {
551 let geo1 = textureLoad(probeGeo, vec2i(tile.x * 2 + 1, tile.y), 0);
552 if (geo1.w < 0.5) { return false; }
553 let d = abs(vec2f(tile) - q);
554 let tent = max(1.0 - d.x / radius, 0.0) * max(1.0 - d.y / radius, 0.0);
555 if (tent <= 0.0) { return false; }
556 let geo0 = textureLoad(probeGeo, vec2i(tile.x * 2, tile.y), 0);
557 let plane = abs(dot(n, geo0.xyz - pos)) / (0.02 * eye);
558 let wPlane = tent / (1.0 + plane * plane);
559 let wNormal = pow(max(dot(geo1.xyz, n), 0.0), 4.0);
560 let base = vec2i(tile.x * 3, tile.y);
561 let vr = textureLoad(probes, base, 0).xyz;
562 let vg = textureLoad(probes, base + vec2i(1, 0), 0).xyz;
563 let vb = textureLoad(probes, base + vec2i(2, 0), 0).xyz;
564 *e = max(vec3f(dot(vr, n), dot(vg, n), dot(vb, n)), vec3f(0.0));
565 // What the probe gets itself, for a pixel whose own normal no probe agrees with: a pixel on the edge two walls share, where the
566 // resolved G-buffer holds a normal that is neither wall's and may face along both.
567 *own = max(vec3f(dot(vr, geo1.xyz), dot(vg, geo1.xyz), dot(vb, geo1.xyz)), vec3f(0.0));
568 // The less the probe faces the pixel's way, the more of what it gets itself: a pixel whose normal is wrong (see the probes) is not let
569 // weigh the light by it.
570 *e = mix(*own, *e, wNormal);
571 *w = vec2f(wPlane * wNormal, wPlane);
572 return true;
573}
574
575// The light the probes round pixel p give it (rgb), and how far the pixel is from the eye (a).
576fn irradiance(p : vec2i, size : vec2i, depth : f32, g : vec4f) -> vec4f {
577 var n = decodeNormal(g);
578 let pos = worldFromDepth((vec2f(p) + 0.5) / vec2f(size), depth);
579 if (dot(n, viewDirection(pos)) < 0.0) { n = -n; }
580 let tiles = vec2i(gi.counts.zw);
581 // The probes round the pixel: probe (tx, ty) stands at pixel (tx * spacing + spacing / 2, ...). The four nearest are asked first (a pixel
582 // in the open has all it needs there); only where they are on another plane or face another way, as at the corner of two walls, are the
583 // twelve beyond them.
584 let spacing = i32(gi.misc.z);
585 let q = (vec2f(p) - vec2f(f32(spacing / 2))) / f32(spacing);
586 let q0 = vec2i(floor(q));
587 let eye = max(length(pos - frame.camera.xyz), 1.0);
588 var E = vec3f(0.0);
589 var total = 0.0;
590 var Erelaxed = vec3f(0.0);
591 var totalRelaxed = 0.0;
592 // The four nearest with a bilinear weight, which is nothing at a tile's far edge: that the weights go to zero exactly where the set of
593 // probes changes is what keeps the picture from showing the probe grid as squares. Only where those four are on another plane or face
594 // another way (the corner of two walls) are the sixteen round them asked, with a wider tent.
595 for (var k = 0; k < 4; k = k + 1) {
596 let tile = q0 + vec2i(k & 1, k >> 1);
597 if (any(tile < vec2i(0)) || any(tile >= tiles)) { continue; }
598 var e = vec3f(0.0);
599 var w = vec2f(0.0);
600 var own = vec3f(0.0);
601 if (!probeTerm(tile, q, 1.0, pos, n, eye, &e, &own, &w)) { continue; }
602 E = E + e * w.x;
603 total = total + w.x;
604 Erelaxed = Erelaxed + own * w.y;
605 totalRelaxed = totalRelaxed + w.y;
606 }
607 if (total <= 0.15) {
608 E = vec3f(0.0);
609 total = 0.0;
610 Erelaxed = vec3f(0.0);
611 totalRelaxed = 0.0;
612 for (var k = 0; k < 16; k = k + 1) {
613 let tile = q0 + vec2i(k & 3, k >> 2) - vec2i(1);
614 if (any(tile < vec2i(0)) || any(tile >= tiles)) { continue; }
615 var e = vec3f(0.0);
616 var w = vec2f(0.0);
617 var own = vec3f(0.0);
618 if (!probeTerm(tile, q, 1.6, pos, n, eye, &e, &own, &w)) { continue; }
619 E = E + e * w.x;
620 total = total + w.x;
621 Erelaxed = Erelaxed + own * w.y;
622 totalRelaxed = totalRelaxed + w.y;
623 }
624 }
625 if (total > 0.05) { E = E / total; } else if (totalRelaxed > 1e-5) { E = Erelaxed / totalRelaxed; } else { E = vec3f(0.0); }
626 return vec4f(E, eye);
627}
628)WGSL";
629
630// The light added to every pixel, each asking the probes itself.
631const char* kApplyFull = R"WGSL(
632@compute @workgroup_size(8, 8)
633fn main(@builtin(global_invocation_id) id : vec3u) {
634 let size = vec2i(textureDimensions(depthTex));
635 let p = vec2i(id.xy);
636 if (p.x >= size.x || p.y >= size.y) { return; }
637 let scene = textureLoad(sceneTex, p, 0);
638 let depth = textureLoad(depthTex, p, 0);
639 let g = textureLoad(gbuffer, p, 0);
640 let albedo = textureLoad(albedoTex, p, 0);
641 if (depth >= 1.0 || g.a <= 0.7 || albedo.a <= 0.5) { textureStore(outTex, p, scene); return; }
642 let E = irradiance(p, size, depth, g).rgb;
643 textureStore(outTex, p, vec4f(scene.rgb + albedo.rgb * E * gi.sdf.w, scene.a));
644}
645)WGSL";
646
647// The cheaper way, in two: one pixel in four asks the probes (this), and every pixel takes its light from the four of those round it (kComposite).
648// outTex is half the picture a side; a is the distance from the eye, or -1 where there is no surface.
649const char* kGather = R"WGSL(
650@compute @workgroup_size(8, 8)
651fn main(@builtin(global_invocation_id) id : vec3u) {
652 let size = vec2i(textureDimensions(depthTex));
653 let h = vec2i(id.xy);
654 if (h.x * 2 >= size.x + 1 || h.y * 2 >= size.y + 1) { return; }
655 let p = min(h * 2, size - vec2i(1));
656 let depth = textureLoad(depthTex, p, 0);
657 let g = textureLoad(gbuffer, p, 0);
658 if (depth >= 1.0 || g.a <= 0.7) { textureStore(outTex, h, vec4f(0.0, 0.0, 0.0, -1.0)); return; }
659 textureStore(outTex, h, irradiance(p, size, depth, g));
660}
661)WGSL";
662
663// Every pixel: the light of the four gathered pixels round it, each counting by how near it is on the screen and how nearly as far from the eye
664// (so the light of a wall does not run onto what stands in front of it). Normals are not asked: across the edge two walls share, where both are
665// as far from the eye, the light of one runs a pixel or two onto the other.
666const char* kComposite = R"WGSL(
667@group(0) @binding(6) var depthTex : texture_depth_2d;
668@group(0) @binding(8) var albedoTex : texture_2d<f32>;
669@group(0) @binding(10) var sceneTex : texture_2d<f32>;
670@group(0) @binding(11) var outTex : texture_storage_2d<rgba16float, write>;
671@group(0) @binding(13) var gathered : texture_2d<f32>;
672
673@compute @workgroup_size(8, 8)
674fn main(@builtin(global_invocation_id) id : vec3u) {
675 let size = vec2i(textureDimensions(depthTex));
676 let p = vec2i(id.xy);
677 if (p.x >= size.x || p.y >= size.y) { return; }
678 let scene = textureLoad(sceneTex, p, 0);
679 let depth = textureLoad(depthTex, p, 0);
680 let albedo = textureLoad(albedoTex, p, 0);
681 if (depth >= 1.0 || albedo.a <= 0.5) { textureStore(outTex, p, scene); return; }
682 let pos = worldFromDepth((vec2f(p) + 0.5) / vec2f(size), depth);
683 let eye = max(length(pos - frame.camera.xyz), 1.0);
684 let hs = vec2i(textureDimensions(gathered));
685 let q = vec2f(p) * 0.5;
686 let q0 = vec2i(floor(q));
687 let f = q - vec2f(q0);
688 var E = vec3f(0.0); var total = 0.0;
689 var plain = vec3f(0.0); var count = 0.0;
690 for (var k = 0; k < 4; k = k + 1) {
691 let o = vec2i(k & 1, k >> 1);
692 let v = textureLoad(gathered, clamp(q0 + o, vec2i(0), hs - vec2i(1)), 0);
693 if (v.a < 0.0) { continue; }
694 let wb = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1) + 0.01;
695 let off = (v.a - eye) / (0.03 * eye);
696 let w = wb / (1.0 + off * off * off * off);
697 E = E + v.rgb * w; total = total + w;
698 plain = plain + v.rgb; count = count + 1.0;
699 }
700 if (total > 0.02) { E = E / total; } else if (count > 0.0) { E = plain / count; } else { E = vec3f(0.0); }
701 textureStore(outTex, p, vec4f(scene.rgb + albedo.rgb * E * gi.sdf.w, scene.a));
702}
703)WGSL";
704#else
705const char* kCommon = "";
706const char* kCardLight = "";
707const char* kSurface = "";
708const char* kProbe = "";
709const char* kApply = "";
710const char* kApplyFull = "";
711const char* kGather = "";
712const char* kComposite = "";
713#endif
714
716std::string readWriteCards(std::string s) {
717 const std::string from = "var<storage, read> radIn";
718 const size_t at = s.find(from);
719 if (at != std::string::npos) s.replace(at, from.size(), "var<storage, read_write> radIn");
720 return s;
721}
722
723std::string join(const char* a, const char* b, const char* c = "") {
724 return std::string(a) + b + c;
725}
726
727} // namespace
728
729DynamicGI::DynamicGI(GfxDevice& device, RenderContext& context) : device_(device), context_(context) {}
730
734
736 for (BufferHandle* b : {&params_, &sdf_, &instances_, &pixels_, &radiance_[0], &radiance_[1]}) {
737 if (*b != BufferHandle::Invalid) device_.deleteBuffer(*b);
739 }
740 for (TextureHandle& t : probes_) {
741 if (t != TextureHandle::Invalid) device_.deleteTexture(t);
743 }
744 for (ComputeHandle* c : {&cardLight_, &probe_, &apply_, &gather_, &composite_}) {
745 if (*c != ComputeHandle::Invalid) device_.deleteCompute(*c);
747 }
748 if (probeGeo_ != TextureHandle::Invalid) device_.deleteTexture(probeGeo_);
749 probeGeo_ = TextureHandle::Invalid;
750 probeTilesX_ = probeTilesY_ = 0;
751 sdfBytes_ = instanceBytes_ = pixelBytes_ = radianceBytes_ = 0;
752 uploadedVersion_ = 0;
753 failed_ = false;
754}
755
756bool DynamicGI::ensure() {
757 if (failed_) return false;
758 if (!device_.supportsCompute()) return false;
759 if (params_ == BufferHandle::Invalid) {
760 params_ = device_.createBuffer({GfxBufferUsage::Uniform, sizeof(ParamsBlock), true}, GfxContent::transient(), nullptr);
761 if (params_ == BufferHandle::Invalid) { failed_ = true; return false; }
762 }
763 const auto make = [&](ComputeHandle& handle, const std::string& source, const char* name) {
764 if (handle != ComputeHandle::Invalid) return true;
765 std::string log;
766 handle = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, source.c_str(), "main"}, &log);
767 if (handle == ComputeHandle::Invalid) {
768 ES_LOG_ERROR("DynamicGI: the {} kernel did not compile: {}", name, log);
769 failed_ = true;
770 return false;
771 }
772 return true;
773 };
774 return make(cardLight_, readWriteCards(join(kCommon, kCardLight)), "card light") && make(probe_, join(kCommon, kSurface, kProbe), "probe")
775 && make(apply_, join(kCommon, kSurface, (std::string(kApply) + kApplyFull).c_str()), "apply")
776 && make(gather_, join(kCommon, kSurface, (std::string(kApply) + kGather).c_str()), "gather") && make(composite_, join(kCommon, kSurface, kComposite), "composite");
777}
778
779bool DynamicGI::upload() {
780 DynamicGIScene& s = dynamicGIScene();
781 if (s.header.size() < kHeaderSize || s.sdf.empty() || s.instances.empty() || s.pixels.empty()) return false;
782 if (s.version == uploadedVersion_) return true;
783 // A camera moved: only the range of the field that was rewritten goes over. The cards, the instances and the light the cards hold stay as they
784 // are (a whole upload zeroes the light and starts the bounces again from the first, which a moving camera would see as a pop every step).
785 if (!s.full && sdf_ != BufferHandle::Invalid && sdfBytes_ == std::max(static_cast<u32>(s.sdf.size() * 4), 16u) && s.dirtyEnd <= s.sdf.size()) {
786 if (s.dirtyEnd > s.dirtyBegin) device_.updateBuffer(sdf_, s.dirtyBegin * 4u, s.sdf.data() + s.dirtyBegin, (s.dirtyEnd - s.dirtyBegin) * 4u);
787 s.dirtyBegin = s.dirtyEnd = 0;
788 uploadedVersion_ = s.version;
789 return true;
790 }
791 const auto put = [&](BufferHandle& buffer, u32& have, const void* data, u32 bytes) {
792 bytes = std::max(bytes, 16u);
793 if (buffer == BufferHandle::Invalid || have != bytes) {
794 if (buffer != BufferHandle::Invalid) device_.deleteBuffer(buffer);
795 buffer = device_.createBuffer({GfxBufferUsage::Storage, bytes, false}, GfxContent::transient(), nullptr);
796 have = bytes;
797 }
798 if (buffer == BufferHandle::Invalid) return false;
799 device_.updateBuffer(buffer, 0, data, bytes);
800 return true;
801 };
802 if (!put(sdf_, sdfBytes_, s.sdf.data(), static_cast<u32>(s.sdf.size() * 4)) ||
803 !put(instances_, instanceBytes_, s.instances.data(), static_cast<u32>(s.instances.size() * 4)) ||
804 !put(pixels_, pixelBytes_, s.pixels.data(), static_cast<u32>(s.pixels.size() * 4))) {
805 ES_LOG_ERROR("DynamicGI: could not upload the scene");
806 failed_ = true;
807 return false;
808 }
809 pixelCount_ = static_cast<u32>(s.header[kPixels]);
810 // The radiance the cards hold: 16 bytes a pixel, zeroed again on a new scene.
811 const u32 radianceBytes = std::max(pixelCount_ * 16u, 16u);
812 if (radianceBytes != radianceBytes_ || radiance_[0] == BufferHandle::Invalid) {
813 if (radiance_[0] != BufferHandle::Invalid) device_.deleteBuffer(radiance_[0]);
814 radiance_[0] = device_.createBuffer({GfxBufferUsage::Storage, radianceBytes, false}, GfxContent::transient(), nullptr);
815 radianceBytes_ = radianceBytes;
816 if (radiance_[0] == BufferHandle::Invalid) { failed_ = true; return false; }
817 }
818 std::vector<f32> zero(radianceBytes / 4, 0.0f);
819 device_.updateBuffer(radiance_[0], 0, zero.data(), radianceBytes);
820 frame_ = 0;
821 uploadedVersion_ = s.version;
822 s.full = false;
823 s.dirtyBegin = s.dirtyEnd = 0;
824 return true;
825}
826
827bool DynamicGI::ensureProbes(u32 tilesX, u32 tilesY) {
828 if (probes_[0] != TextureHandle::Invalid && probeTilesX_ == tilesX && probeTilesY_ == tilesY) return true;
829 for (TextureHandle& t : probes_) {
830 if (t != TextureHandle::Invalid) device_.deleteTexture(t);
832 }
833 if (probeGeo_ != TextureHandle::Invalid) device_.deleteTexture(probeGeo_);
834 probeGeo_ = TextureHandle::Invalid;
835 TextureDesc desc;
836 desc.width = tilesX * kProbeTexels;
837 desc.height = tilesY;
838 desc.format = GfxPixelFormat::RGBA16F;
839 desc.minFilter = desc.magFilter = TextureFilter::Nearest;
840 desc.storage = true;
841 for (TextureHandle& t : probes_) t = device_.createTexture(desc, GfxContent::transient(), nullptr);
842 // Where each probe stands and which way it faces: full floats, a position is more than a half can hold.
843 TextureDesc geo;
844 geo.width = tilesX * 2;
845 geo.height = tilesY;
846 geo.format = GfxPixelFormat::RGBA32F;
847 geo.minFilter = geo.magFilter = TextureFilter::Nearest;
848 geo.storage = true;
849 probeGeo_ = device_.createTexture(geo, GfxContent::transient(), nullptr);
850 if (probes_[0] == TextureHandle::Invalid || probes_[1] == TextureHandle::Invalid || probeGeo_ == TextureHandle::Invalid) {
851 ES_LOG_ERROR("DynamicGI: could not allocate the probes");
852 return false;
853 }
854 probeTilesX_ = tilesX;
855 probeTilesY_ = tilesY;
856 return true;
857}
858
860 u32 width, u32 height) {
861 if (!ensure() || input == rg::kNoResource || scene == rg::kNoResource) return input;
862 if (!upload()) return input;
863 if (params.skip & 8u) return input; // measuring: nothing declared at all
864 const u32 probeRows = std::clamp(params.probeRows, 8u, 90u);
865 const u32 rows = std::max(static_cast<u32>(static_cast<f32>(probeRows) * std::clamp(params.probeDensity, 0.25f, 1.0f) + 0.5f), 8u);
866 probeSpacing_ = params.probeSpacing > 0 ? std::clamp(params.probeSpacing, 4u, 64u)
867 : std::clamp(((height + rows - 1) / rows + 1) / 2 * 2, 8u, 48u);
868 const u32 tilesX = (width + probeSpacing_ - 1) / probeSpacing_, tilesY = (height + probeSpacing_ - 1) / probeSpacing_;
869 if (!ensureProbes(tilesX, tilesY)) return input;
870
871 rg::TargetDesc token;
872 token.width = 1;
873 token.height = 1;
875 token.storage = true;
876 token.linearFilter = false;
877 const DynamicGIParams p = params;
878
879 // The frame's constants for every pass: the scene's header and the effect's parameters.
880 const auto writeParams = [this, p]() {
881 const DynamicGIScene& s = dynamicGIScene();
882 const std::vector<f32>& h = s.header;
883 ParamsBlock b{};
884 const u32 levels = std::clamp(static_cast<u32>(h[kLevels]), 1u, kMaxLevels);
885 const u32 lights = std::min(static_cast<u32>(h[kLights]), kMaxLights);
886 b.sdf[0] = static_cast<f32>(levels); b.sdf[1] = static_cast<f32>(lights); b.sdf[3] = p.intensity;
887 b.origin[3] = static_cast<i32>(frame_);
888 // Level 0 is the header's own fields; its field starts the buffer and its owner words follow it.
889 const u32 dim0 = static_cast<u32>(h[kDim]);
890 b.levelA[0][0] = static_cast<i32>(h[kOriginX]); b.levelA[0][1] = static_cast<i32>(h[kOriginY]); b.levelA[0][2] = static_cast<i32>(h[kOriginZ]);
891 b.levelA[0][3] = static_cast<i32>(dim0);
892 b.levelB[0][0] = h[kCell]; b.levelB[0][1] = h[kReach];
893 b.levelC[0][0] = 0; b.levelC[0][1] = dim0 * dim0 * dim0;
894 for (u32 k = 1; k < levels; ++k) {
895 const u32 at = kLevelBlock + (k - 1) * 8;
896 b.levelA[k][0] = static_cast<i32>(h[at + 2]); b.levelA[k][1] = static_cast<i32>(h[at + 3]); b.levelA[k][2] = static_cast<i32>(h[at + 4]);
897 b.levelA[k][3] = static_cast<i32>(h[at]);
898 b.levelB[k][0] = h[at + 1]; b.levelB[k][1] = h[at + 5];
899 b.levelC[k][0] = static_cast<u32>(h[at + 6]); b.levelC[k][1] = static_cast<u32>(h[at + 7]);
900 }
901 for (u32 i = 0; i < lights; ++i) {
902 for (u32 v = 0; v < 4; ++v) for (u32 c = 0; c < 4; ++c) b.lights[i * 4 + v][c] = h[kLightBlock + i * kLightFloats + v * 4 + c];
903 }
904 b.counts[0] = static_cast<u32>(h[kInstances]); b.counts[1] = static_cast<u32>(h[kPixels]);
905 b.counts[2] = probeTilesX_; b.counts[3] = probeTilesY_;
906 b.sunDir[0] = h[kSunX]; b.sunDir[1] = h[kSunY]; b.sunDir[2] = h[kSunZ]; b.sunDir[3] = h[kSunOn];
907 b.sunRad[0] = h[kSunR]; b.sunRad[1] = h[kSunG]; b.sunRad[2] = h[kSunB]; b.sunRad[3] = h[kBias];
908 b.trace[0] = h[kRange]; b.trace[1] = h[kTolerance]; b.trace[2] = std::clamp(p.blend, 0.01f, 1.0f); b.trace[3] = h[kHit];
909 b.sky[0] = h[kSkyR]; b.sky[1] = h[kSkyG]; b.sky[2] = h[kSkyB];
910 b.misc[0] = static_cast<f32>(std::clamp(p.cardSlices, 1u, 4096u)); b.misc[1] = static_cast<f32>(std::clamp(p.probeStride, 1u, 8u));
911 b.misc[2] = static_cast<f32>(probeSpacing_);
912 b.misc[3] = h.size() > kGrowth ? h[kGrowth] : 0.0f;
913 device_.updateBuffer(params_, 0, &b, sizeof(b));
914 };
915
916 const rg::ResourceId lit = graph.createTarget(token);
917 {
918 rg::PassDesc pass;
919 pass.name = "dgi_cards";
920 pass.compute = true;
921 pass.dependencies = {scene};
922 pass.write = lit;
923 pass.execute = [this, writeParams, p](const rg::PassContext&) {
924 writeParams();
925 const GfxComputeBinding bindings[6] = {
926 GfxComputeBinding::uniform(0, context_.frameUbo()),
927 GfxComputeBinding::uniform(1, params_),
929 GfxComputeBinding::storageRead(3, instances_),
931 GfxComputeBinding::storage(5, radiance_[0]),
932 };
933 // One workgroup a card pixel to relight: all of them for the first frames, then one slice of them.
934 const u32 slices = std::clamp(p.cardSlices, 1u, 4096u);
935 const u32 chunk = (pixelCount_ + slices - 1) / slices;
936 const u32 active = frame_ < 2 ? pixelCount_ : chunk;
937 g_stats.cardPixels = static_cast<f32>(pixelCount_);
938 g_stats.cardPixelsRelit = (p.skip & 1u) ? 0.0f : static_cast<f32>(active);
939 g_stats.cardRays = g_stats.cardPixelsRelit * 64.0f;
940 if (active == 0 || (p.skip & 1u)) return;
941 device_.dispatchCompute(cardLight_, bindings, 6, std::min(active, 65535u), (active + 65534u) / 65535u);
942 };
943 graph.addPass(std::move(pass));
944 }
945
946 const rg::ResourceId probed = graph.createTarget(token);
947 {
948 rg::PassDesc pass;
949 pass.name = "dgi_probes";
950 pass.compute = true;
951 pass.dependencies = {scene, lit};
952 pass.write = probed;
953 pass.execute = [this, &graph, scene, p](const rg::PassContext&) {
954 g_stats.probes = static_cast<f32>(probeTilesX_ * probeTilesY_);
955 g_stats.probeSpacing = static_cast<f32>(probeSpacing_);
956 g_stats.probeRays = (p.skip & 2u) ? 0.0f : g_stats.probes * 64.0f / static_cast<f32>(std::max(p.probeStride, 1u));
957 if (p.skip & 2u) return;
958 const TextureHandle depth = graph.depthTextureOf(scene);
959 const TextureHandle gbuffer = graph.gbufferTextureOf(scene);
960 if (depth == TextureHandle::Invalid || gbuffer == TextureHandle::Invalid) return;
961 // The cards were just written into the buffer the next frame reads: the probes see this frame's lighting.
962 const BufferHandle cards = radiance_[0];
963 const u32 cur = frame_ & 1u;
964 const GfxComputeBinding bindings[11] = {
965 GfxComputeBinding::uniform(0, context_.frameUbo()),
966 GfxComputeBinding::uniform(1, params_),
968 GfxComputeBinding::storageRead(3, instances_),
971 GfxComputeBinding::depth(6, depth),
972 GfxComputeBinding::sampled(7, gbuffer),
973 GfxComputeBinding::storageTexture(8, probes_[cur]),
974 GfxComputeBinding::sampled(9, probes_[cur ^ 1u]),
976 };
977 device_.dispatchCompute(probe_, bindings, 11, probeTilesX_, probeTilesY_);
978 };
979 graph.addPass(std::move(pass));
980 }
981
982 if (params.skip & 16u) return input; // measuring: the cards and the probes, and no apply pass nor the target it writes
983 // Half resolution: the probes are asked by one pixel in four, into a target half the picture a side, and the pass below spreads it.
985 if (params.halfRes) {
986 rg::TargetDesc half;
987 half.scale = 0.5f;
989 half.storage = true;
990 half.linearFilter = false;
991 gathered = graph.createTarget(half);
992 rg::PassDesc pass;
993 pass.name = "dgi_gather";
994 pass.compute = true;
995 pass.dependencies = {scene, probed};
996 pass.write = gathered;
997 pass.execute = [this, &graph, scene, p](const rg::PassContext& ctx) {
998 if (p.skip & 4u) return;
999 const TextureHandle depth = graph.depthTextureOf(scene);
1000 const TextureHandle gbuffer = graph.gbufferTextureOf(scene);
1001 if (depth == TextureHandle::Invalid || gbuffer == TextureHandle::Invalid || ctx.output == TextureHandle::Invalid) return;
1002 const GfxComputeBinding bindings[11] = {
1003 GfxComputeBinding::uniform(0, context_.frameUbo()),
1004 GfxComputeBinding::uniform(1, params_),
1006 GfxComputeBinding::storageRead(3, instances_),
1008 GfxComputeBinding::storageRead(5, radiance_[0]),
1009 GfxComputeBinding::depth(6, depth),
1010 GfxComputeBinding::sampled(7, gbuffer),
1011 GfxComputeBinding::sampled(9, probes_[frame_ & 1u]),
1013 GfxComputeBinding::sampled(12, probeGeo_),
1014 };
1015 device_.dispatchCompute(gather_, bindings, 11, (ctx.width + 7) / 8, (ctx.height + 7) / 8);
1016 };
1017 graph.addPass(std::move(pass));
1018 }
1019 rg::TargetDesc full;
1021 full.storage = true;
1022 full.linearFilter = true;
1023 const rg::ResourceId result = graph.createTarget(full);
1024 {
1025 rg::PassDesc pass;
1026 pass.name = "dgi_apply";
1027 pass.compute = true;
1028 pass.reads = gathered != rg::kNoResource ? std::vector<rg::ResourceId>{input, gathered} : std::vector<rg::ResourceId>{input};
1029 pass.dependencies = {scene, probed};
1030 pass.write = result;
1031 pass.execute = [this, &graph, scene, p](const rg::PassContext& ctx) {
1032 // A pixel reads the scene, the depth, the G-buffer and the albedo, and from each of the four nearest probes two geometry texels and three of light.
1033 g_stats.applyPixels = (p.skip & 4u) ? 0.0f : static_cast<f32>(ctx.width) * static_cast<f32>(ctx.height);
1034 // Half resolution: a pixel reads the scene, the depth, the albedo and four gathered pixels, and a quarter of what a gathering pixel reads
1035 // (the depth, the G-buffer, and the probes as above).
1036 g_stats.applyLoadsPerPixel = p.halfRes ? 3.0f + 4.0f + (2.0f + 4.0f * 5.0f) / 4.0f : 4.0f + 4.0f * 5.0f;
1037 g_stats.width = static_cast<f32>(ctx.width);
1038 g_stats.height = static_cast<f32>(ctx.height);
1039 g_stats.forcedAttachmentBytes = static_cast<f32>(ctx.width) * static_cast<f32>(ctx.height) * 12.0f;
1040 g_stats.residentBytes = static_cast<f32>(sdfBytes_ + instanceBytes_ + pixelBytes_ + radianceBytes_)
1041 + static_cast<f32>(probeTilesX_) * static_cast<f32>(probeTilesY_) * (3.0f * 8.0f * 2.0f + 2.0f * 16.0f);
1042 const DynamicGIScene& sc = dynamicGIScene();
1043 g_stats.levels = sc.header.size() > kLevels ? sc.header[kLevels] : 0.0f;
1044 g_stats.lights = sc.header.size() > kLights ? sc.header[kLights] : 0.0f;
1045 g_stats.instances = sc.header.size() > kInstances ? sc.header[kInstances] : 0.0f;
1046 g_stats.frame = static_cast<f32>(frame_);
1047 if (p.skip & 4u) { ++frame_; return; }
1048 const TextureHandle depth = graph.depthTextureOf(scene);
1049 const TextureHandle gbuffer = graph.gbufferTextureOf(scene);
1050 const TextureHandle albedo = graph.albedoTextureOf(scene);
1051 if (depth == TextureHandle::Invalid || gbuffer == TextureHandle::Invalid || albedo == TextureHandle::Invalid
1052 || ctx.output == TextureHandle::Invalid) return;
1053 if (p.halfRes) {
1054 const TextureHandle half = ctx.input(1);
1055 if (depth == TextureHandle::Invalid || albedo == TextureHandle::Invalid || half == TextureHandle::Invalid || ctx.output == TextureHandle::Invalid) return;
1056 const GfxComputeBinding composite[11] = {
1057 GfxComputeBinding::uniform(0, context_.frameUbo()),
1058 GfxComputeBinding::uniform(1, params_),
1060 GfxComputeBinding::storageRead(3, instances_),
1062 GfxComputeBinding::storageRead(5, radiance_[0]),
1063 GfxComputeBinding::depth(6, depth),
1064 GfxComputeBinding::sampled(8, albedo),
1065 GfxComputeBinding::sampled(10, ctx.input(0)),
1068 };
1069 device_.dispatchCompute(composite_, composite, 11, (ctx.width + 7) / 8, (ctx.height + 7) / 8);
1070 ++frame_;
1071 return;
1072 }
1073 const u32 cur = frame_ & 1u;
1074 const GfxComputeBinding bindings[13] = {
1075 GfxComputeBinding::uniform(0, context_.frameUbo()),
1076 GfxComputeBinding::uniform(1, params_),
1078 GfxComputeBinding::storageRead(3, instances_),
1080 GfxComputeBinding::storageRead(5, radiance_[0]),
1081 GfxComputeBinding::depth(6, depth),
1082 GfxComputeBinding::sampled(7, gbuffer),
1083 GfxComputeBinding::sampled(8, albedo),
1084 GfxComputeBinding::sampled(9, probes_[cur]),
1085 GfxComputeBinding::sampled(10, ctx.input(0)),
1087 GfxComputeBinding::sampled(12, probeGeo_),
1088 };
1089 device_.dispatchCompute(apply_, bindings, 13, (ctx.width + 7) / 8, (ctx.height + 7) / 8);
1090 ++frame_;
1091 };
1092 graph.addPass(std::move(pass));
1093 }
1094 return result;
1095}
1096
1097} // namespace esengine
Diffuse global illumination from the scene's distance field and surface cache, run as compute passes ...
Abstract graphics device interface.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Rendering context containing all renderer state.
rg::ResourceId declare(rg::RenderGraph &graph, rg::ResourceId input, rg::ResourceId scene, const DynamicGIParams &params, u32 width, u32 height)
DynamicGI(GfxDevice &device, RenderContext &context)
static constexpr GfxContent transient()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
TextureHandle albedoTextureOf(ResourceId id) const
The third attachment of a gbuffer target: the surface's diffuse colour (alpha 1 where one was written...
void addPass(PassDesc pass)
ResourceId createTarget(const TargetDesc &desc)
TextureHandle gbufferTextureOf(ResourceId id) const
TextureHandle depthTextureOf(ResourceId id) const
constexpr ResourceId kNoResource
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
DynamicGIScene & dynamicGIScene()
Definition DynamicGI.cpp:15
@ Storage
Read and written by compute shaders (var<storage, read_write>), and readable back....
Definition GfxEnums.hpp:77
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
Definition GfxEnums.hpp:39
const DynamicGIStats & dynamicGIStats()
Definition DynamicGI.cpp:24
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59
f32 intensity
How much of the gathered light is added over the picture.
Definition DynamicGI.hpp:37
f32 blend
How much of each frame's card lighting replaces what the card held (the rest is history,...
Definition DynamicGI.hpp:39
u32 skip
For measuring: skip the cards (1), the probes (2) or the apply (4), to read what the rest of the fram...
Definition DynamicGI.hpp:45
u32 cardSlices
The cards are relit a slice at a time over this many frames (their light changes slowly; the cost is ...
Definition DynamicGI.hpp:41
u32 probeSpacing
Pixels between probes: 0 picks about 160 x 90 probes whatever the picture size.
Definition DynamicGI.hpp:47
u32 probeStride
One in this many of a probe rays is traced each frame, alternating, so the history fills the rest in.
Definition DynamicGI.hpp:43
f32 probeDensity
How many of the rows of probes the picture would have are kept, 0.25 to 1 (it acts where probeSpacing...
Definition DynamicGI.hpp:52
std::vector< f32 > header
Header: sdf dim, cell size, origin x y z (cells), reach, instance count, card pixel count,...
Definition DynamicGI.hpp:61
One resource a compute dispatch binds, at @group(0) @binding(binding).
Definition GfxEnums.hpp:689
static GfxComputeBinding storageTexture(u32 binding, TextureHandle texture)
Definition GfxEnums.hpp:713
static GfxComputeBinding depth(u32 binding, TextureHandle texture)
Definition GfxEnums.hpp:718
static GfxComputeBinding uniform(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:701
static GfxComputeBinding sampled(u32 binding, TextureHandle texture)
Definition GfxEnums.hpp:710
static GfxComputeBinding storageRead(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:704
static GfxComputeBinding storage(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:707
One full-screen pass.
std::function< void(const PassContext &)> execute
std::vector< ResourceId > reads
bool compute
A compute pass: no render pass is opened and no unit is bound — execute dispatches,...
std::vector< ResourceId > dependencies
Resources the pass uses but the graph must not bind.
Shape of a target the graph allocates.
bool storage
Written by a compute shader (a pass with compute set), then sampled like any target.