Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
VoxelGI.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 "./VoxelGI.hpp"
5#include "./RenderContext.hpp"
6#include "../RenderOrigin.hpp"
7#include <glm/gtc/type_ptr.hpp>
9#include "../../core/Log.hpp"
10
11#include <algorithm>
12#include <cmath>
13#include <vector>
14
15namespace esengine {
16
17namespace {
18
21constexpr u32 kVoxelWords = 8;
22
23#ifdef ES_ENABLE_WEBGPU
25const char* kCommon = R"WGSL(
26struct Frame { projection : mat4x4f, camera : vec4f, inverseViewProjection : mat4x4f, renderOrigin : vec4f };
27struct GI {
28 origin : vec4i, // xyz: the window's first cell; w: the frame
29 dims : vec4u, // xyz: voxels per axis; w: rays per point
30 a : vec4f, // x: voxel size, y: what the grid keeps, z: the brightest a surface gives, w: intensity
31 b : vec4f, // x: how far a ray looks (cells), y: where it starts (cells), z: how much of the last bounce feeds back, w: debug
32 view : vec4f, // x: the gather's divisor, y: 1 when the last gather is a history to blend with, z: how much of this one goes in
33 prevViewProjection : mat4x4f,
34};
35@group(0) @binding(0) var<uniform> frame : Frame;
36@group(0) @binding(1) var<uniform> gi : GI;
37@group(0) @binding(2) var<storage, read_write> grid : array<atomic<u32>>;
38@group(0) @binding(3) var<storage, read_write> tags : array<u32>;
39
40const WORDS : u32 = 8u;
41const FIXED : f32 = 1024.0;
42const FACING : f32 = 256.0;
43// A sample counts COUNT, not 1: the grid ages by a factor below one each frame and truncates, and a count of 1 aged to 0.93 truncates
44// to 0 — a voxel that one sample a frame lands in (a small voxel, or one far away) then never reached the 2 a ray asks for, and a
45// fine grid drew no bounce at all.
46const COUNT : u32 = 16u;
47// The covered area, in AREA parts of one voxel face. A ray that meets a voxel takes its light in proportion to how much of the voxel
48// a surface fills: averaged over a whole voxel, a bright patch that fills a corner of one would otherwise light like the whole voxel,
49// which spreads every light by up to a voxel and makes a coarse grid brighter than a fine one.
50const AREA : f32 = 4096.0;
51fn addArea(base : u32, area : f32) {
52 let vs = gi.a.x;
53 atomicAdd(&grid[base + 7u], u32(clamp(area / (vs * vs), 0.0, 1.0) * AREA));
54}
55
56// Set on a slot's tag by the inject when the picture showed its cell this frame, and cleared by the maintain each frame.
57const SEEN : u32 = 2u;
58// Set on a slot's tag while it holds anything. What a ray asks of every cell it crosses, most of them empty: the tags are an eighth of the
59// grid, so the answer is mostly in cache, where the grid's own count is a miss.
60const HELD : u32 = 4u;
61const MARKS : u32 = SEEN | HELD;
62fn hash3(c : vec3i) -> u32 {
63 var h = (u32(c.x) * 73856093u) ^ (u32(c.y) * 19349663u) ^ (u32(c.z) * 83492791u);
64 h = (h ^ (h >> 16u)) * 0x45d9f3bu;
65 h = h ^ (h >> 16u);
66 // Bit 0 always set (no live cell hashes to 0, which an empty slot holds); the marks are not part of the hash.
67 return (h | 1u) & ~MARKS;
68}
69fn wrapIndex(cell : vec3i) -> u32 {
70 // The dims are powers of two (VoxelGI.hpp), so a mask wraps a negative cell too, and costs nothing where a modulo is an integer
71 // division: a ray takes this every step.
72 let w = cell & (vec3i(gi.dims.xyz) - vec3i(1));
73 return u32(w.x) + u32(w.y) * gi.dims.x + u32(w.z) * gi.dims.x * gi.dims.y;
74}
75fn inWindow(cell : vec3i) -> bool {
76 let o = gi.origin.xyz;
77 let d = vec3i(gi.dims.xyz);
78 return all(cell >= o) && all(cell < o + d);
79}
80)WGSL";
81
83const char* kSurface = R"WGSL(
84fn worldFromDepth(uv : vec2f, depth : f32) -> vec3f {
85 let clip = vec4f(uv * 2.0 - 1.0, depth, 1.0);
86 let world = frame.inverseViewProjection * clip;
87 return world.xyz / world.w;
88}
89fn decodeNormal(g : vec4f) -> vec3f {
90 let f = g.rg * 2.0 - 1.0;
91 var n = vec3f(f.x, f.y, 1.0 - abs(f.x) - abs(f.y));
92 let k = clamp(-n.z, 0.0, 1.0);
93 n = vec3f(n.x + select(k, -k, n.x >= 0.0), n.y + select(k, -k, n.y >= 0.0), n.z);
94 return normalize(n);
95}
96fn viewDirection(p : vec3f) -> vec3f {
97 if (frame.camera.w > 0.5) { return normalize(frame.camera.xyz - p); }
98 return frame.camera.xyz;
99}
100)WGSL";
101
103const char* kMaintain = R"WGSL(
104@compute @workgroup_size(64)
105fn main(@builtin(global_invocation_id) id : vec3u) {
106 let total = gi.dims.x * gi.dims.y * gi.dims.z;
107 let i = id.x;
108 if (i >= total) { return; }
109 let g = vec3i(i32(i & (gi.dims.x - 1u)), i32((i >> countTrailingZeros(gi.dims.x)) & (gi.dims.y - 1u)),
110 i32(i >> countTrailingZeros(gi.dims.x * gi.dims.y)));
111 let d = vec3i(gi.dims.xyz);
112 // The cell this slot stands for in the window as it is now: toroidal, so the window slides over the same memory.
113 let rel = (g - gi.origin.xyz) & (d - vec3i(1));
114 let cell = gi.origin.xyz + rel;
115 let tag = hash3(cell);
116 let base = i * WORDS;
117 // Each invocation owns its slot, so the words are read and written plainly (readWriteCache): ageing a million slots through atomics
118 // every frame was most of what the cache cost a phone. An empty slot (no samples, no area) has nothing to age and is left alone.
119 if ((tags[i] & ~MARKS) != tag) {
120 tags[i] = tag;
121 for (var k = 0u; k < WORDS; k = k + 1u) { grid[base + k] = 0u; }
122 } else {
123 tags[i] = tag;
124 if ((grid[base] | grid[base + 1u] | grid[base + 2u] | grid[base + 3u] | grid[base + 7u]) == 0u) { return; }
125 for (var k = 0u; k < WORDS; k = k + 1u) { grid[base + k] = u32(f32(grid[base + k]) * gi.a.y); }
126 if (grid[base + 3u] != 0u) { tags[i] = tag | HELD; }
127 }
128}
129)WGSL";
130
134const char* kInject = R"WGSL(
135@group(0) @binding(4) var scene : texture_2d<f32>;
136@group(0) @binding(5) var depthTex : texture_depth_2d;
137@group(0) @binding(6) var gbuffer : texture_2d<f32>;
138@group(0) @binding(8) var albedoTex : texture_2d<f32>;
139@group(0) @binding(9) var histTex : texture_2d<f32>;
140
141@compute @workgroup_size(8, 8)
142fn main(@builtin(global_invocation_id) id : vec3u) {
143 let size = vec2i(textureDimensions(depthTex));
144 // One pixel in four, a different one each frame, as the gather takes its own: always the same four left a face two rows tall (a block's
145 // top seen nearly edge on) in the grid at one row or two by the size of the picture, and what it lit moved with it. The grid ages over
146 // more frames than this takes, so it holds them all.
147 let frameIndex = i32(gi.origin.w);
148 let t = vec2i(id.xy) * 2 + vec2i(frameIndex & 1, (frameIndex >> 1) & 1);
149 if (t.x >= size.x || t.y >= size.y) { return; }
150 let depth = textureLoad(depthTex, t, 0);
151 if (depth >= 1.0) { return; }
152 let g = textureLoad(gbuffer, t, 0);
153 if (g.a <= 0.7) { return; }
154 var n = decodeNormal(g);
155 let p = worldFromDepth((vec2f(t) + 0.5) / vec2f(size), depth);
156 if (dot(n, viewDirection(p)) < 0.0) { n = -n; }
157 let cell = vec3i(floor(p / gi.a.x));
158 if (!inWindow(cell)) { return; }
159 let base = wrapIndex(cell) * WORDS;
160 // The surface this sample stands for: the two-by-two pixels around it, measured on the surface from the neighbours' depth
161 // (which carries the slant). A neighbour off the surface (an edge) leaves the footprint the pixel's own square seen face on.
162 let tx = select(t + vec2i(2, 0), t - vec2i(2, 0), t.x + 2 >= size.x);
163 let ty = select(t + vec2i(0, 2), t - vec2i(0, 2), t.y + 2 >= size.y);
164 let px = worldFromDepth((vec2f(tx) + 0.5) / vec2f(size), textureLoad(depthTex, tx, 0));
165 let py = worldFromDepth((vec2f(ty) + 0.5) / vec2f(size), textureLoad(depthTex, ty, 0));
166 var footprint = length(cross(px - p, py - p));
167 let side = max(length(px - p), length(py - p));
168 if (side > gi.a.x) {
169 footprint = min(length(px - p), length(py - p));
170 footprint = footprint * footprint;
171 }
172 addArea(base, footprint);
173 // Every writer writes the same value, so the race is harmless.
174 tags[wrapIndex(cell)] = hash3(cell) | MARKS;
175 var lit = textureLoad(scene, t, 0).rgb;
176 let albedo = textureLoad(albedoTex, t, 0);
177 if (gi.view.y > 0.5 && albedo.a > 0.5) {
178 let div = i32(gi.view.x);
179 let q = clamp(t / div, vec2i(0), vec2i(textureDimensions(histTex)) - vec2i(1));
180 lit = lit + albedo.rgb * textureLoad(histTex, q, 0).rgb * (gi.a.w * gi.b.z);
181 }
182 let c = clamp(lit, vec3f(0.0), vec3f(gi.a.z));
183 atomicAdd(&grid[base], u32(c.r * FIXED));
184 atomicAdd(&grid[base + 1u], u32(c.g * FIXED));
185 atomicAdd(&grid[base + 2u], u32(c.b * FIXED));
186 atomicAdd(&grid[base + 3u], COUNT);
187 let f = n * 0.5 + 0.5;
188 atomicAdd(&grid[base + 4u], u32(f.x * FACING));
189 atomicAdd(&grid[base + 5u], u32(f.y * FACING));
190 atomicAdd(&grid[base + 6u], u32(f.z * FACING));
191}
192)WGSL";
193
197const char* kSun = R"WGSL(
198struct Sun {
199 light : vec4f, // rgb: the sun colour times its intensity; w: the albedo a surface is taken to have
200 toLight : vec4f, // xyz: unit vector toward the sun; w: how many tiles
201 samples : vec4u, // x: samples per tile side
202 rect : array<vec4f, 4>, // each tile square in the atlas, low corner and side, in GL terms
203 inverse : array<mat4x4f, 4>, // each tile clip space back to the world
204};
205// The atlas holds depth packed into colour (what the lit shaders unpack), not a depth texture.
206@group(0) @binding(4) var shadowTex : texture_2d<f32>;
207@group(0) @binding(10) var<uniform> sun : Sun;
208
209fn shadowPoint(k : u32, uv : vec2f, size : vec2f) -> vec4f {
210 let rect = sun.rect[k];
211 let at = rect.xy + uv * rect.z;
212 let texel = clamp(vec2i(at * size), vec2i(0), vec2i(size) - vec2i(1));
213 let c = textureLoad(shadowTex, texel, 0).rgb;
214 let d = dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));
215 // The map stores clip z remapped to [0, 1] (z * 0.5 + 0.5, as the lit shaders compare it): undone before the inverse.
216 let w = sun.inverse[k] * vec4f(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0);
217 return vec4f(w.xyz / w.w, d);
218}
219
220@compute @workgroup_size(8, 8)
221fn main(@builtin(global_invocation_id) id : vec3u) {
222 let n = sun.samples.x;
223 let k = id.x / n;
224 if (k >= u32(sun.toLight.w) || id.y >= n) { return; }
225 let size = vec2f(textureDimensions(shadowTex));
226 let step = 1.0 / f32(n);
227 let uv = (vec2f(f32(id.x % n), f32(id.y)) + 0.5) * step;
228 let p = shadowPoint(k, uv, size);
229 if (p.w >= 1.0 || p.w <= 0.0) { return; }
230 let px = shadowPoint(k, uv + vec2f(step, 0.0), size).xyz;
231 let py = shadowPoint(k, uv + vec2f(0.0, step), size).xyz;
232 let vs = gi.a.x;
233 // A neighbour across a depth edge (the top of a wall against the floor) gives no tangent: those samples carry no normal.
234 let ex = px - p.xyz;
235 let ey = py - p.xyz;
236 if (length(ex) > vs * 4.0 || length(ey) > vs * 4.0) { return; }
237 // Two neighbours on one texel (or on a line) give no plane: normalizing nothing is a NaN, and one NaN turned into the grid's
238 // fixed point poisons every ray that meets its voxel.
239 let cr = cross(ex, ey);
240 let area = dot(cr, cr);
241 if (!(area > 1e-12)) { return; }
242 var nrm = cr * inverseSqrt(area);
243 let L = sun.toLight.xyz;
244 if (dot(nrm, L) < 0.0) { nrm = -nrm; }
245 let cell = vec3i(floor((p.xyz + nrm * (vs * 0.25)) / vs));
246 if (!inWindow(cell)) { return; }
247 let base = wrapIndex(cell) * WORDS;
248 // Where the picture has shown this voxel (the inject ran first this frame), its own colour is the better answer than an assumed
249 // albedo: the sun's estimate is what stands in only where the camera has not looked.
250 if ((tags[wrapIndex(cell)] & SEEN) != 0u) { return; }
251 tags[wrapIndex(cell)] = hash3(cell) | HELD;
252 addArea(base, sqrt(area));
253 let c = clamp(sun.light.rgb * (sun.light.w * max(dot(nrm, L), 0.0)), vec3f(0.0), vec3f(gi.a.z));
254 atomicAdd(&grid[base], u32(c.r * FIXED));
255 atomicAdd(&grid[base + 1u], u32(c.g * FIXED));
256 atomicAdd(&grid[base + 2u], u32(c.b * FIXED));
257 atomicAdd(&grid[base + 3u], COUNT);
258 let f = nrm * 0.5 + 0.5;
259 atomicAdd(&grid[base + 4u], u32(f.x * FACING));
260 atomicAdd(&grid[base + 5u], u32(f.y * FACING));
261 atomicAdd(&grid[base + 6u], u32(f.z * FACING));
262}
263)WGSL";
264
266const char* kGather = R"WGSL(
267@group(0) @binding(5) var depthTex : texture_depth_2d;
268@group(0) @binding(6) var gbuffer : texture_2d<f32>;
269@group(0) @binding(7) var outTex : texture_storage_2d<rgba16float, write>;
270@group(0) @binding(9) var histTex : texture_2d<f32>;
271
272fn ign(p : vec2f) -> f32 {
273 return fract(52.9829189 * fract(dot(p, vec2f(0.06711056, 0.00583715))));
274}
275fn cosineDirection(n : vec3f, u : f32, v : f32) -> vec3f {
276 let r = sqrt(u);
277 let phi = 6.2831853 * v;
278 var up = vec3f(1.0, 0.0, 0.0);
279 if (abs(n.y) < 0.99) { up = vec3f(0.0, 1.0, 0.0); }
280 let t = normalize(cross(up, n));
281 let b = cross(n, t);
282 return normalize(t * (r * cos(phi)) + b * (r * sin(phi)) + n * sqrt(max(1.0 - u, 0.0)));
283}
284
286fn trace(origin : vec3f, dir : vec3f) -> vec3f {
287 let vs = gi.a.x;
288 let pos = origin / vs;
289 var cell = vec3i(floor(pos));
290 let stepv = vec3i(select(vec3f(-1.0), vec3f(1.0), dir >= vec3f(0.0)));
291 let safe = select(dir, vec3f(1e-6), abs(dir) < vec3f(1e-6));
292 let delta = abs(vec3f(1.0) / safe);
293 let next = select(vec3f(cell), vec3f(cell + vec3i(1)), dir >= vec3f(0.0));
294 var tMax = (next - pos) / safe;
295 let range = gi.b.x;
296 var t = 0.0;
297 var acc = vec3f(0.0);
298 var trans = 1.0;
299 for (var i = 0; i < 96; i = i + 1) {
300 if (t > range) { break; }
301 // Step into the neighbouring cell along the axis whose boundary comes first.
302 if (tMax.x < tMax.y && tMax.x < tMax.z) {
303 cell.x = cell.x + stepv.x; t = tMax.x; tMax.x = tMax.x + delta.x;
304 } else if (tMax.y < tMax.z) {
305 cell.y = cell.y + stepv.y; t = tMax.y; tMax.y = tMax.y + delta.y;
306 } else {
307 cell.z = cell.z + stepv.z; t = tMax.z; tMax.z = tMax.z + delta.z;
308 }
309 if (!inWindow(cell)) { break; }
310 // A slot in the window is that cell's: the maintain re-tagged every slot this frame, and the window was just asked.
311 let slot = wrapIndex(cell);
312 if ((tags[slot] & HELD) == 0u) { continue; }
313 let base = slot * WORDS;
314 let count = atomicLoad(&grid[base + 3u]);
315 if (count < 2u * COUNT) { continue; }
316 let inv = f32(COUNT) / f32(count);
317 let facing = (vec3f(f32(atomicLoad(&grid[base + 4u])), f32(atomicLoad(&grid[base + 5u])), f32(atomicLoad(&grid[base + 6u]))) * inv / FACING) * 2.0 - 1.0;
318 // A surface is met from the side it faces. One facing away is behind the ray, or the ray skims along it.
319 if (dot(normalize(facing), dir) > -0.15) { continue; }
320 let radiance = vec3f(f32(atomicLoad(&grid[base])), f32(atomicLoad(&grid[base + 1u])), f32(atomicLoad(&grid[base + 2u]))) * inv / FIXED;
321 // The area aged the way every word is (a frame adds `a`, the sum settles at a / (1 - keep)), so one frame's worth of it is the
322 // sum times (1 - keep). Two surfaces in one voxel (a corner) add past one face, which is a voxel fully covered.
323 let covered = min(f32(atomicLoad(&grid[base + 7u])) / AREA * (1.0 - gi.a.y), 1.0);
324 // What a ray meets is what it brings, however far it went: distance is already in how few rays reach a far surface. A fade over
325 // the last stretch of the range only, so the edge of what a ray can see does not draw a line. (A falloff over the whole range had
326 // darkened every bounce by its distance: 40% at 4 m with 12 cm voxels.)
327 // A voxel a surface only partly fills lets the rest of the ray through to what stands behind it.
328 acc = acc + trans * covered * radiance * clamp((range - t) / (range * 0.15), 0.0, 1.0);
329 trans = trans * (1.0 - covered);
330 if (trans < 0.05) { return acc; }
331 }
332 return acc;
333}
334
335@compute @workgroup_size(8, 8)
336fn main(@builtin(global_invocation_id) id : vec3u) {
337 let lowSize = vec2i(textureDimensions(outTex));
338 let p = vec2i(id.xy);
339 if (p.x >= lowSize.x || p.y >= lowSize.y) { return; }
340 let size = vec2i(textureDimensions(depthTex));
341 let div = i32(gi.view.x);
342 let t = min(p * div + vec2i(i32(gi.origin.w) % div, (i32(gi.origin.w) / div) % div), size - vec2i(1));
343 let depth = textureLoad(depthTex, t, 0);
344 let g = textureLoad(gbuffer, t, 0);
345 if (depth >= 1.0 || g.a <= 0.7) {
346 textureStore(outTex, p, vec4f(0.0));
347 return;
348 }
349 var n = decodeNormal(g);
350 let world = worldFromDepth((vec2f(t) + 0.5) / vec2f(size), depth);
351 if (dot(n, viewDirection(world)) < 0.0) { n = -n; }
352 let origin = world + n * (gi.a.x * gi.b.y);
353
354 let rays = i32(gi.dims.w);
355 let r1 = ign(vec2f(p) + vec2f(0.0, f32(gi.origin.w % 16)));
356 let r2 = ign(vec2f(p.yx) + vec2f(f32(gi.origin.w % 16) * 5.588238, 0.0));
357 var sum = vec3f(0.0);
358 for (var k = 0; k < rays; k = k + 1) {
359 let u = fract((f32(k) + 0.5) / f32(rays) + r1);
360 let v = fract(f32(k) * 0.61803399 + r2);
361 sum = sum + trace(origin, cosineDirection(n, u, v));
362 }
363 var light = sum / f32(rays);
364 // What the last frames agreed on, found where this surface was in the last frame's picture.
365 if (gi.view.y > 0.5) {
366 let prevClip = gi.prevViewProjection * vec4f(world, 1.0);
367 if (prevClip.w > 1e-4) {
368 let ndc = prevClip.xy / prevClip.w;
369 let uv = ndc * 0.5 + 0.5;
370 if (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0) {
371 let q = clamp(vec2i(uv * vec2f(lowSize)), vec2i(0), lowSize - vec2i(1));
372 light = mix(textureLoad(histTex, q, 0).rgb, light, gi.view.z);
373 }
374 }
375 }
376 textureStore(outTex, p, vec4f(light, 1.0));
377}
378)WGSL";
379
381const char* kApply = R"WGSL(
382@group(0) @binding(4) var scene : texture_2d<f32>;
383@group(0) @binding(5) var depthTex : texture_depth_2d;
384@group(0) @binding(6) var albedoTex : texture_2d<f32>;
385@group(0) @binding(7) var outTex : texture_storage_2d<rgba16float, write>;
386@group(0) @binding(8) var giTex : texture_2d<f32>;
387
388@compute @workgroup_size(8, 8)
389fn main(@builtin(global_invocation_id) id : vec3u) {
390 let size = vec2i(textureDimensions(depthTex));
391 let t = vec2i(id.xy);
392 if (t.x >= size.x || t.y >= size.y) { return; }
393 let src = textureLoad(scene, t, 0);
394 let lowSize = vec2i(textureDimensions(giTex));
395 let div = i32(gi.view.x);
396 let depth = textureLoad(depthTex, t, 0);
397 var light = vec3f(0.0);
398 if (depth < 1.0) {
399 // A depth-weighted blend of the low-resolution texels around the pixel: the ones on the same surface count, the ones
400 // across an edge do not. The window is wider than the bilinear four, which is what smooths the rays' noise.
401 let centre = vec2i(floor((vec2f(t) + 0.5) / f32(div) - 0.5));
402 var total = 0.0;
403 var acc = vec3f(0.0);
404 for (var dy = -1; dy <= 2; dy = dy + 1) {
405 for (var dx = -1; dx <= 2; dx = dx + 1) {
406 let q = clamp(centre + vec2i(dx, dy), vec2i(0), lowSize - vec2i(1));
407 let qd = textureLoad(depthTex, min(q * div, size - vec2i(1)), 0);
408 if (qd >= 1.0) { continue; }
409 let near = abs(vec2f(t) / f32(div) - 0.5 - vec2f(q));
410 let spatial = max(1.0 - 0.4 * (near.x + near.y), 0.05);
411 // Depth is nonlinear: it is the ratio of what is left to the far plane that says how far apart two surfaces are.
412 let w = spatial * exp(-abs(log((1.0 - qd + 1e-6) / (1.0 - depth + 1e-6))) * 24.0);
413 acc = acc + textureLoad(giTex, q, 0).rgb * w;
414 total = total + w;
415 }
416 }
417 if (total > 1e-4) { light = acc / total; }
418 }
419 // What the gathered light is lit onto reflects it by its own diffuse colour, which the surface wrote beside its
420 // normal. A surface that wrote none (a shader older than the attachment) has its colour guessed from the picture.
421 let written = textureLoad(albedoTex, t, 0);
422 let lum = max(dot(src.rgb, vec3f(0.2126, 0.7152, 0.0722)), 0.02);
423 let guessed = mix(vec3f(0.55), clamp(src.rgb / lum, vec3f(0.0), vec3f(1.6)) * 0.55, 0.7);
424 let albedo = select(guessed, written.rgb, written.a > 0.5);
425 var result = src.rgb + albedo * light * gi.a.w;
426 if (gi.b.w > 0.5) { result = light * gi.a.w; }
427 textureStore(outTex, t, vec4f(result, src.a));
428}
429)WGSL";
430#else
431// The kernels are WGSL and only the WebGPU device runs them: a build without it (WeChat, playables) carries none of the text.
432const char* const kCommon = "";
433const char* const kSurface = "";
434const char* const kMaintain = "";
435const char* const kInject = "";
436const char* const kSun = "";
437const char* const kGather = "";
438const char* const kApply = "";
439#endif
440
441std::string join(const char* a, const char* b, const char* c = "") {
442 return std::string(a) + b + c;
443}
444
448std::string plainCache(std::string s, const char* access) {
449 const auto replace = [&s](const std::string& from, const std::string& to) {
450 for (size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size())) s.replace(at, from.size(), to);
451 };
452 replace("var<storage, read_write> grid : array<atomic<u32>>;", std::string("var<storage, ") + access + "> grid : array<u32>;");
453 replace("var<storage, read_write> tags : array<u32>;", std::string("var<storage, ") + access + "> tags : array<u32>;");
454 // addArea adds atomically; neither kernel calls it, but a plain array cannot even name an atomicAdd.
455 const size_t from = s.find("fn addArea(");
456 if (from != std::string::npos) s.erase(from, s.find("\n}", from) + 2 - from);
457 replace("atomicLoad(&grid[", "(grid[");
458 return s;
459}
460std::string readOnlyCache(const std::string& s) { return plainCache(s, "read"); }
462std::string readWriteCache(const std::string& s) { return plainCache(s, "read_write"); }
463
464struct ParamsBlock {
465 i32 origin[4];
466 u32 dims[4];
467 f32 a[4];
468 f32 b[4];
469 f32 view[4];
470 f32 prevViewProjection[16];
471};
472static_assert(sizeof(ParamsBlock) == 144, "the GI block is five vec4s and a matrix");
473
475struct SunBlock {
476 f32 light[4];
477 f32 toLight[4];
478 u32 samples[4];
479 f32 rect[4][4];
480 f32 inverse[4][16];
481};
482static_assert(sizeof(SunBlock) == 368, "the sun block is three vec4s, four rects and four matrices");
483constexpr u32 kSunTiles = 4;
484
485} // namespace
486
487VoxelGI::VoxelGI(GfxDevice& device, RenderContext& context) : device_(device), context_(context) {}
488
492
494 for (BufferHandle* b : {&grid_, &tags_, &params_, &sun_}) {
495 if (*b != BufferHandle::Invalid) device_.deleteBuffer(*b);
497 }
498 for (TextureHandle& t : history_) {
499 if (t != TextureHandle::Invalid) device_.deleteTexture(t);
501 }
502 historyWidth_ = historyHeight_ = 0;
503 historyValid_ = false;
504 for (ComputeHandle* c : {&maintain_, &inject_, &gather_, &apply_, &sunInject_}) {
505 if (*c != ComputeHandle::Invalid) device_.deleteCompute(*c);
507 }
508 failed_ = false;
509}
510
512 u32 size = kMinGridSize;
513 while (size * 2u <= std::min(asked, kMaxGridSize)) size *= 2u;
514 return size;
515}
516
518 return std::clamp(asked, 8u, 256u);
519}
520
521bool VoxelGI::ensure(u32 gridSize) {
522 if (failed_) return false;
523 if (!device_.supportsCompute()) return false;
524 if (grid_ != BufferHandle::Invalid && gridSize_ != gridSize) {
525 device_.deleteBuffer(grid_);
526 device_.deleteBuffer(tags_);
527 grid_ = tags_ = BufferHandle::Invalid;
528 historyValid_ = false;
529 }
530 const u32 voxels = gridSize * (gridSize / 2u) * gridSize;
531 if (grid_ == BufferHandle::Invalid) {
532 grid_ = device_.createBuffer({GfxBufferUsage::Storage, voxels * kVoxelWords * 4u, false}, GfxContent::transient(), nullptr);
533 tags_ = device_.createBuffer({GfxBufferUsage::Storage, voxels * 4u, false}, GfxContent::transient(), nullptr);
534 gridSize_ = gridSize;
535 }
536 if (params_ == BufferHandle::Invalid) {
537 params_ = device_.createBuffer({GfxBufferUsage::Uniform, sizeof(ParamsBlock), true}, GfxContent::transient(), nullptr);
538 sun_ = device_.createBuffer({GfxBufferUsage::Uniform, sizeof(SunBlock), true}, GfxContent::transient(), nullptr);
539 }
540 if (grid_ == BufferHandle::Invalid || tags_ == BufferHandle::Invalid || params_ == BufferHandle::Invalid
541 || sun_ == BufferHandle::Invalid) {
542 ES_LOG_ERROR("VoxelGI: could not allocate the voxel cache");
543 failed_ = true;
544 return false;
545 }
546 const auto make = [&](ComputeHandle& handle, const std::string& source, const char* name) {
547 if (handle != ComputeHandle::Invalid) return true;
548 std::string log;
549 handle = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, source.c_str(), "main"}, &log);
550 if (handle == ComputeHandle::Invalid) {
551 ES_LOG_ERROR("VoxelGI: the {} kernel did not compile: {}", name, log);
552 failed_ = true;
553 return false;
554 }
555 return true;
556 };
557 return make(maintain_, readWriteCache(join(kCommon, kMaintain)), "maintain") && make(inject_, join(kCommon, kSurface, kInject), "inject")
558 && make(gather_, readOnlyCache(join(kCommon, kSurface, kGather)), "gather") && make(apply_, join(kCommon, kApply), "apply")
559 && make(sunInject_, join(kCommon, kSun), "sun");
560}
561
562bool VoxelGI::ensureHistory(u32 width, u32 height) {
563 if (history_[0] != TextureHandle::Invalid && historyWidth_ == width && historyHeight_ == height) return true;
564 for (TextureHandle& t : history_) {
565 if (t != TextureHandle::Invalid) device_.deleteTexture(t);
567 }
568 historyValid_ = false;
569 TextureDesc desc;
570 desc.width = width;
571 desc.height = height;
572 desc.format = GfxPixelFormat::RGBA16F;
573 desc.minFilter = desc.magFilter = TextureFilter::Nearest;
574 desc.storage = true;
575 for (TextureHandle& t : history_) t = device_.createTexture(desc, GfxContent::transient(), nullptr);
576 if (history_[0] == TextureHandle::Invalid || history_[1] == TextureHandle::Invalid) {
577 ES_LOG_ERROR("VoxelGI: could not allocate the gather history");
578 return false;
579 }
580 historyWidth_ = width;
581 historyHeight_ = height;
582 return true;
583}
584
585void VoxelGI::writeParams(const VoxelGIParams& p) {
586 // The window is centred on the eye, snapped to whole cells so the grid does not swim as the camera moves.
587 const glm::vec4 eye = cameraFromViewProjection(context_.viewProjection());
588 const u32 g = gridSize_;
589 const f32 coarser = static_cast<f32>(kMaxGridSize) / static_cast<f32>(g);
590 const f32 vs = std::max(p.voxelSize, 0.001f) * coarser;
591 ParamsBlock block{};
592 block.origin[0] = static_cast<i32>(std::floor(eye.x / vs)) - static_cast<i32>(g / 2);
593 block.origin[1] = static_cast<i32>(std::floor(eye.y / vs)) - static_cast<i32>(g / 4);
594 block.origin[2] = static_cast<i32>(std::floor(eye.z / vs)) - static_cast<i32>(g / 2);
595 block.origin[3] = static_cast<i32>(frame_);
596 block.dims[0] = g;
597 block.dims[1] = g / 2u;
598 block.dims[2] = g;
599 block.dims[3] = std::clamp(p.rays, 1u, 64u);
600 block.a[0] = vs;
601 block.a[1] = std::clamp(p.decay, 0.0f, 0.999f);
602 block.a[2] = std::max(p.maxBounce, 0.01f);
603 block.a[3] = p.intensity;
604 block.b[0] = std::clamp(p.range / coarser, 1.0f, 90.0f);
605 block.b[1] = std::max(p.bias, 0.0f);
606 block.b[2] = std::clamp(p.bounceFeedback, 0.0f, 1.0f);
607 block.b[3] = p.debug;
608 block.view[0] = static_cast<f32>(std::clamp(p.divisor, 1u, 4u));
609 // A change of voxel size makes every voxel a different place, so what was gathered under the old one is not history.
610 if (previousVoxelSize_ != vs) historyValid_ = false;
611 previousVoxelSize_ = vs;
612 block.view[1] = historyValid_ ? 1.0f : 0.0f;
613 block.view[2] = std::clamp(p.blend, 0.01f, 1.0f);
614 // A view of a frame drawn from another origin is taken to this one, and what was gathered under it is not history.
615 if (previousOrigin_ != renderOrigin()) historyValid_ = false;
616 {
617 const glm::mat4 previous = viewProjectionFromOrigin(glm::make_mat4(previousViewProjection_), previousOrigin_);
618 std::copy(glm::value_ptr(previous), glm::value_ptr(previous) + 16, block.prevViewProjection);
619 }
620 previousOrigin_ = renderOrigin();
621 const glm::mat4& vp = context_.viewProjection();
622 for (int c = 0; c < 4; ++c) for (int r = 0; r < 4; ++r) previousViewProjection_[c * 4 + r] = vp[c][r];
623 device_.updateBuffer(params_, 0, &block, sizeof(block));
624 origin_[0] = block.origin[0];
625 origin_[1] = block.origin[1];
626 origin_[2] = block.origin[2];
627 ++frame_;
628}
629
630u32 VoxelGI::writeSun(const VoxelGIParams& p) {
631 // The first directional light that owns shadow tiles: the sun whose map says what it reaches.
632 const LightConstants& lc = context_.lights().data();
633 if (lc.shadowParams.x < 0.5f || p.sunAlbedo <= 0.0f) return 0;
634 // Every slot, not a count: an empty slot reads as no light (zero colour, zero tiles).
635 for (u32 i = 0; i < MAX_LIGHTS; ++i) {
636 const GpuLight& l = lc.lights[i];
637 const bool directional = l.posDir.z > 0.5f && l.posDir.z < 1.5f;
638 const u32 tiles = static_cast<u32>(std::fmod(std::max(l.shadowMap.y, 0.0f), LIGHT_TILE_BITS));
639 if (!directional || tiles == 0) continue;
640 const u32 first = static_cast<u32>(std::max(l.shadowMap.x, 0.0f));
641 if (first >= MAX_SHADOW_TILES) continue;
642 SunBlock block{};
643 const glm::vec3 aim = glm::normalize(glm::vec3(l.posDir.x, l.posDir.y, l.posDir.w));
644 block.light[0] = l.color.r * l.color.a;
645 block.light[1] = l.color.g * l.color.a;
646 block.light[2] = l.color.b * l.color.a;
647 block.light[3] = p.sunAlbedo;
648 block.toLight[0] = -aim.x;
649 block.toLight[1] = -aim.y;
650 block.toLight[2] = -aim.z;
651 const u32 used = std::min({tiles, kSunTiles, MAX_SHADOW_TILES - first});
652 block.toLight[3] = static_cast<f32>(used);
653 block.samples[0] = sunSamplesOf(p.sunSamples);
654 for (u32 k = 0; k < used; ++k) {
655 const glm::vec4& r = lc.shadowTile[first + k];
656 block.rect[k][0] = r.x; block.rect[k][1] = r.y; block.rect[k][2] = r.z; block.rect[k][3] = r.w;
657 const glm::mat4 inv = glm::inverse(lc.shadowMatrix[first + k]);
658 std::copy(glm::value_ptr(inv), glm::value_ptr(inv) + 16, block.inverse[k]);
659 }
660 device_.updateBuffer(sun_, 0, &block, sizeof(block));
661 return used;
662 }
663 return 0;
664}
665
667 u32 width, u32 height, TextureHandle shadowAtlas, rg::ResourceId shadowResource) {
668 if (!ensure(gridSizeOf(params.gridSize)) || input == rg::kNoResource || scene == rg::kNoResource) return input;
669
670 // The passes are tied together by what each writes, since the graph only runs what the image reaches. The first two write a
671 // single texel nobody samples: their work is in the grid, and the texel is what says "this ran before that".
672 rg::TargetDesc token;
673 token.width = 1;
674 token.height = 1;
676 token.storage = true;
677 token.linearFilter = false;
678
679 const u32 divisor = std::clamp(params.divisor, 1u, 4u);
680 const VoxelGIParams p = params;
681 // The size the graph gives a target at 1 / divisor: the history has to be exactly that.
682 const f32 scale = 1.0f / static_cast<f32>(divisor);
683 const u32 lowWidth = std::max(1u, static_cast<u32>(static_cast<f32>(width) * scale));
684 const u32 lowHeight = std::max(1u, static_cast<u32>(static_cast<f32>(height) * scale));
685 if (!ensureHistory(lowWidth, lowHeight)) return input;
686 // This frame writes one of the two and reads the other.
687 const u32 cur = frame_ & 1u;
688
689 const rg::ResourceId maintainDone = graph.createTarget(token);
690 {
691 rg::PassDesc pass;
692 pass.name = "gi_maintain";
693 pass.compute = true;
694 pass.write = maintainDone;
695 pass.dependencies = {scene};
696 pass.execute = [this, p](const rg::PassContext&) {
697 writeParams(p);
698 const GfxComputeBinding bindings[4] = {
699 GfxComputeBinding::uniform(0, context_.frameUbo()),
700 GfxComputeBinding::uniform(1, params_),
703 };
704 device_.dispatchCompute(maintain_, bindings, 4, (gridSize_ * (gridSize_ / 2u) * gridSize_ + 63) / 64);
705 };
706 graph.addPass(std::move(pass));
707 }
708
709 const rg::ResourceId injectDone = graph.createTarget(token);
710 {
711 rg::PassDesc pass;
712 pass.name = "gi_inject";
713 pass.compute = true;
714 pass.reads = {input};
715 pass.dependencies = {scene, maintainDone};
716 pass.write = injectDone;
717 pass.execute = [this, &graph, scene, width, height, cur](const rg::PassContext& ctx) {
718 const TextureHandle depth = graph.depthTextureOf(scene);
719 const TextureHandle gbuffer = graph.gbufferTextureOf(scene);
720 const TextureHandle albedo = graph.albedoTextureOf(scene);
721 if (depth == TextureHandle::Invalid || gbuffer == TextureHandle::Invalid || albedo == TextureHandle::Invalid) return;
722 const GfxComputeBinding bindings[9] = {
723 GfxComputeBinding::uniform(0, context_.frameUbo()),
724 GfxComputeBinding::uniform(1, params_),
727 GfxComputeBinding::sampled(4, ctx.input(0)),
728 GfxComputeBinding::depth(5, depth),
729 GfxComputeBinding::sampled(6, gbuffer),
731 // The last frame gather: written by the gather of the frame before, so the other of the two.
732 GfxComputeBinding::sampled(9, history_[cur ^ 1u]),
733 };
734 device_.dispatchCompute(inject_, bindings, 9, (width / 2 + 7) / 8, (height / 2 + 7) / 8);
735 };
736 graph.addPass(std::move(pass));
737 }
738
739 // The sun own light into the grid, after the picture and before anything reads it.
740 rg::ResourceId sunDone = injectDone;
741 if (shadowAtlas != TextureHandle::Invalid && shadowResource != rg::kNoResource && p.sunAlbedo > 0.0f) {
742 sunDone = graph.createTarget(token);
743 rg::PassDesc pass;
744 pass.name = "gi_sun";
745 pass.compute = true;
746 pass.dependencies = {shadowResource, injectDone};
747 pass.write = sunDone;
748 pass.execute = [this, p, shadowAtlas](const rg::PassContext&) {
749 const u32 tiles = writeSun(p);
750 if (tiles == 0) return;
751 const GfxComputeBinding bindings[6] = {
752 GfxComputeBinding::uniform(0, context_.frameUbo()),
753 GfxComputeBinding::uniform(1, params_),
756 GfxComputeBinding::sampled(4, shadowAtlas),
758 };
759 const u32 n = sunSamplesOf(p.sunSamples);
760 device_.dispatchCompute(sunInject_, bindings, 6, (n * tiles + 7) / 8, (n + 7) / 8);
761 };
762 graph.addPass(std::move(pass));
763 }
764
765 const rg::ResourceId gathered = graph.createTarget(token);
766 {
767 rg::PassDesc pass;
768 pass.name = "gi_gather";
769 pass.compute = true;
770 pass.dependencies = {scene, sunDone};
771 pass.write = gathered;
772 pass.execute = [this, &graph, scene, cur](const rg::PassContext&) {
773 const TextureHandle depth = graph.depthTextureOf(scene);
774 const TextureHandle gbuffer = graph.gbufferTextureOf(scene);
775 if (depth == TextureHandle::Invalid || gbuffer == TextureHandle::Invalid) return;
776 const GfxComputeBinding bindings[8] = {
777 GfxComputeBinding::uniform(0, context_.frameUbo()),
778 GfxComputeBinding::uniform(1, params_),
781 GfxComputeBinding::depth(5, depth),
782 GfxComputeBinding::sampled(6, gbuffer),
783 GfxComputeBinding::storageTexture(7, history_[cur]),
784 GfxComputeBinding::sampled(9, history_[cur ^ 1u]),
785 };
786 device_.dispatchCompute(gather_, bindings, 8, (historyWidth_ + 7) / 8, (historyHeight_ + 7) / 8);
787 historyValid_ = true;
788 };
789 graph.addPass(std::move(pass));
790 }
791
792 rg::TargetDesc full;
794 full.storage = true;
795 full.linearFilter = true;
796 const rg::ResourceId result = graph.createTarget(full);
797 {
798 rg::PassDesc pass;
799 pass.name = "gi_apply";
800 pass.compute = true;
801 pass.reads = {input};
802 pass.dependencies = {scene, gathered};
803 pass.write = result;
804 pass.execute = [this, &graph, scene, cur](const rg::PassContext& ctx) {
805 const TextureHandle depth = graph.depthTextureOf(scene);
806 const TextureHandle albedo = graph.albedoTextureOf(scene);
807 if (depth == TextureHandle::Invalid || albedo == TextureHandle::Invalid
808 || ctx.output == TextureHandle::Invalid) return;
809 const GfxComputeBinding bindings[9] = {
810 GfxComputeBinding::uniform(0, context_.frameUbo()),
811 GfxComputeBinding::uniform(1, params_),
814 GfxComputeBinding::sampled(4, ctx.input(0)),
815 GfxComputeBinding::depth(5, depth),
818 GfxComputeBinding::sampled(8, history_[cur]),
819 };
820 device_.dispatchCompute(apply_, bindings, 9, (ctx.width + 7) / 8, (ctx.height + 7) / 8);
821 };
822 graph.addPass(std::move(pass));
823 }
824 return result;
825}
826
827} // namespace esengine
Per-frame shader constants shared via a single Uniform Buffer Object.
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.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
Diffuse global illumination from a world-space voxel cache, run as compute passes (WebGPU).
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.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
static constexpr u32 kMinGridSize
Definition VoxelGI.hpp:91
rg::ResourceId declare(rg::RenderGraph &graph, rg::ResourceId input, rg::ResourceId scene, const VoxelGIParams &params, u32 width, u32 height, TextureHandle shadowAtlas=TextureHandle::Invalid, rg::ResourceId shadowResource=rg::kNoResource)
Declares the four passes onto graph, reading input and the scene's depth and G-buffer.
Definition VoxelGI.cpp:666
static constexpr u32 kMaxGridSize
Definition VoxelGI.hpp:90
static u32 gridSizeOf(u32 asked)
Definition VoxelGI.cpp:511
static u32 sunSamplesOf(u32 asked)
Definition VoxelGI.cpp:517
VoxelGI(GfxDevice &device, RenderContext &context)
Definition VoxelGI.cpp:487
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
constexpr u32 MAX_LIGHTS
Max simultaneous 2D lights packed into the UBO. The injected fragment loop is a fixed bound; inactive...
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
constexpr u32 MAX_SHADOW_TILES
Max shadow tiles one frame's atlas hands out — the shader's array bound.
glm::mat4 viewProjectionFromOrigin(const glm::mat4 &viewProjection, const glm::dvec3 &origin)
A view-projection made for origin, for a point given from the origin now: the point from the old orig...
@ 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
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
constexpr f32 LIGHT_TILE_BITS
The sprite layers a light reaches ride in GpuLight::shadowMap.y above the atlas tile count: tiles + 8...
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
static EstellaContext & ctx()
glm::vec4 cameraFromViewProjection(const glm::mat4 &viewProjection)
Where the frame is seen from, read out of the matrix that projects it.
float f32
32-bit floating point
Definition Types.hpp:59
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
u32 divisor
The gather runs at 1 / this of the picture's size per axis.
Definition VoxelGI.hpp:56
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.