Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): Voxel GI runs on WebGL2 with fragment passes

yhh72f0bb5c79af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4209b6903..889ae341e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ published separately; it ships inside the editor.
### Added
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
+- **Voxel GI on WebGL2.** Voxel GI now runs on WebGL2: the world-space bounce light is built with fragment passes where there is no compute stage. The result matches the WebGPU one in the editor check; the gather is fixed at half size, grazing surfaces are thinner in the cache, a 32 MB half-float atlas is used, and the `low` quality tier leaves the effect out. Its cost on real GPUs has not been measured.
- **Cyber Rooftop example.** Cyber Rooftop adds a rooftop survival-base example with a 2D HUD and a first-person build tool. The world is editable 3D models (a rooftop shelter, planters, containers, pipework, a water plant, city buildings, a train) with rain, steam and puddle reflections; the HUD is built from Canvas, UINode, UIVisual and Text. It is a runnable reconstruction of a reference image, not a pixel match, and its survival systems (inventory, saving) are not implemented.
- **Thin lines against the sky.** A wire or railing thinner than a pixel stays one line against the sky instead of breaking into dashes. The Sky Atmosphere effect paints every pixel whose depth is the far plane, and depth is resolved from a single sample of a multisampled target, so a wire covered at some samples and not at that one was painted over wherever the sample missed. With the sky in the chain the scene is now cleared to nothing, its alpha is how much of each pixel geometry covers, and the sky is laid under it by that coverage: on a half-pixel wire across the sky the columns that show it went from 49% to 100%, on WebGL2 and WebGPU. An effect asks for this by declaring `u_sceneCoverage`; with Keep Background above zero the scene is cleared to the camera's colour as before.
- **Cleaner contact shadows.** Contact shadows are soft and keep off surfaces facing away from the sun, so a wall no longer carries a speckle a temporal pass could not average, and the effect stack flags a Temporal Anti-Aliasing that sits before a noisy effect. The march now fades along its length (a hit at the far end is half a shadow), starts at a different offset every frame as well as every pixel so a temporal pass averages the whole march, and skips a surface facing away from the sun. On the Bistro hero the grain on a flat wall fell from 3.95 to 2.82 (the same wall with the effect off: 2.72); the example now runs `taa` after the fog, where it can average the noise before it.
diff --git a/desktop b/desktop
index a2e05a02f..8b7706862 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit a2e05a02fa3fb679a24a4316d07173876db3b98e
+Subproject commit 8b77068628a8bfa58a5fbb60f96016a73cbb4ff4
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 9cfe909f3..1f87497ec 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -25,7 +25,7 @@ several can stack in one frame at no extra target cost beyond the passes.
| `distanceFog` | Linear fog by distance from the camera | `near`, `far`, `intensity`, colour |
| `heightFog` | Exponential height fog with the sun's glow and a hazy horizon | `density`, `heightFalloff`, `baseHeight`, `sunAzimuth`, `sunElevation`, `skyFog`, colours |
| `skyAtmosphere` | An atmosphere that scatters the sun's light, with sun, moon, stars and volumetric clouds, drawn where there is no surface | `intensity`, `haze`, `altitude`, `clouds`, `cloudBase`, `cloudThickness`, `windSpeed`, `overcast`, `sunAzimuth`, `sunElevation` |
-| `voxelGI` | Diffuse global illumination from a world-space voxel cache the camera remembers (WebGPU only) | `intensity`, `rays`, `voxelSize`, `range`, `maxBounce`, `decay`, `blend`, `divisor` |
+| `voxelGI` | Diffuse global illumination from a world-space voxel cache the camera remembers (WebGPU compute; fragment passes on WebGL2) | `intensity`, `rays`, `voxelSize`, `range`, `maxBounce`, `decay`, `blend`, `divisor` |
| `sharpen` | Sharpening that cannot make a halo (a compute effect: WebGPU only) | `intensity`, `limit` |
| `lightShafts` | Sun rays through whatever stands in front of it | `intensity`, `sunAzimuth`, `sunElevation`, `decay`, `reach` |
| `ssao` | Ambient occlusion from a ring of depth samples around each point | `radius`, `intensity`, `bias`, `power` |
@@ -198,7 +198,7 @@ a second output (`layout(location = 1) out vec4`, or a struct return in WGSL) an
On WebGL2 and WebGPU alike the attachment is multisampled with the scene and resolved with it. A blended draw never writes
it — a normal averaged with the one behind it is neither's — and the scene's own background clears it to 0.
-### Voxel GI (WebGPU)
+### Voxel GI
`voxelGI` is diffuse global illumination from a **world-space voxel cache**. A grid of voxels (128 × 64 × 128 around the camera, `voxelSize`
world units each) remembers what the camera has seen: every frame the lit picture is written into the voxels its visible surfaces
@@ -214,8 +214,8 @@ It is **not a trace of the scene's geometry**, and it says so:
- the cache holds the surfaces the camera has *seen*, at the voxel's size — a surface it has not seen yet sends no light, and a thin one is as thick as a cell;
- one bounce, diffuse only (no glossy transport), and the picture it is injected from carries last frame's light, so a bright surface feeds itself a little;
-- it needs a **compute stage**: WebGPU. On WebGL2 the effect is left out and the picture goes through as it was — use `ssgi` there;
-- it costs a grid of memory (about 32 MB), four compute passes a frame and one cache per camera.
+- on WebGPU it runs as compute passes. On **WebGL2**, which has no compute stage, the same cache is built by three fragment passes into one half-float atlas (2048 × 1024, 32 MB): each atlas texel asks the picture what stands in its voxel, so the result matches the WebGPU one but the gather is always at half size (`divisor` is ignored), surfaces seen at a grazing angle are thinner in the cache, and the cost is higher. The `low` quality tier leaves it out on WebGL2;
+- it costs a grid of memory (about 32 MB), a few passes a frame and one cache per camera.
It is not Unreal's Lumen: there is no distance-field or hardware ray tracing and no surface cache of the scene's meshes, which is what lets Lumen light what
has never been on screen. Voxel GI is the version of the idea that needs only the picture.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
index 3f7352fef..8da2c09f9 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
@@ -27,7 +27,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
| `distanceFog` | 按到相机的距离做线性雾 | `near`、`far`、`intensity`、颜色 |
| `heightFog` | 指数高度雾,带太阳辉光和朦胧的地平线 | `density`、`heightFalloff`、`baseHeight`、`sunAzimuth`、`sunElevation`、`skyFog`、颜色 |
| `skyAtmosphere` | 散射太阳光的大气,带太阳、月亮、星星和体积云,画在没有表面的地方 | `intensity`、`haze`、`altitude`、`clouds`、`cloudBase`、`cloudThickness`、`windSpeed`、`overcast`、`sunAzimuth`、`sunElevation` |
-| `voxelGI` | 基于相机记住的世界空间体素缓存的漫反射全局光照(仅 WebGPU) | `intensity`、`rays`、`voxelSize`、`range`、`maxBounce`、`decay`、`blend`、`divisor` |
+| `voxelGI` | 基于相机记住的世界空间体素缓存的漫反射全局光照(WebGPU 用计算 pass,WebGL2 用片元 pass) | `intensity`、`rays`、`voxelSize`、`range`、`maxBounce`、`decay`、`blend`、`divisor` |
| `sharpen` | 不会出光晕的锐化(计算特效:仅 WebGPU) | `intensity`、`limit` |
| `lightShafts` | 太阳光穿过前方遮挡物形成的光束 | `intensity`、`sunAzimuth`、`sunElevation`、`decay`、`reach` |
| `ssao` | 由每个点周围一圈深度采样得出的环境光遮蔽 | `radius`、`intensity`、`bias`、`power` |
@@ -142,7 +142,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
在 WebGL2 和 WebGPU 上,附件都与场景一起多重采样、一起解析。混合绘制从不写它——与背后那个平均过的法线谁也不是——场景自己的背景把它清成 0。
-### 体素 GI(WebGPU)
+### 体素 GI
`voxelGI` 是基于**世界空间体素缓存**的漫反射全局光照。一个围绕相机的体素网格(128 × 64 × 128,每个 `voxelSize` 世界单位)记住相机见过的东西:
每一帧,被照亮的画面被写进它可见表面所在的体素——它们的平均辐射度和朝向——原有的内容按 `decay` 衰减。然后像路径追踪那样收集光,只是穿过网格:
@@ -155,8 +155,8 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
- 缓存里只有相机*见过*的表面,精度是体素大小——没见过的表面不发光,薄的东西和一格一样厚;
- 一次弹射,只有漫反射(没有光泽传输),注入用的画面带着上一帧的光,所以很亮的表面会稍微自己给自己供光;
-- 它需要**计算阶段**:WebGPU。在 WebGL2 上该特效会被拿掉,画面原样通过——那里请用 `ssgi`;
-- 它要一块网格内存(约 32 MB)、每帧四个计算 pass、每个相机一份缓存。
+- 在 WebGPU 上它是计算 pass。**WebGL2** 没有计算阶段,同样的缓存由三个片元 pass 写进一张半精度浮点图集(2048 × 1024,32 MB):图集的每个纹素向画面询问自己的体素里有什么,所以结果与 WebGPU 版一致,但收集固定在半尺寸(`divisor` 被忽略),掠射角看到的表面在缓存里更薄,开销也更高。WebGL2 上 `low` 画质档会跳过它;
+- 它要一块网格内存(约 32 MB)、每帧若干 pass、每个相机一份缓存。
它不是虚幻的 Lumen:没有距离场或硬件光追,也没有场景网格的表面缓存——这正是 Lumen 能照亮从未出现在屏幕上的东西的原因。体素 GI 是这个思路中只需要画面的那一版。
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 5cb1ce910..8acd15ac2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -3580,6 +3580,7 @@ category: EffectCategory | undefined
colors: EffectColorDef[] | undefined
compute: ComputeEffectSource | undefined
factory: (() => ShaderHandle) | undefined
+fallback: EffectSubPass[] | undefined
label: string
multiPass: EffectSubPass[] | undefined
native: string | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c35c8efc4..db40e4c8b 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -3588,6 +3588,7 @@ category: EffectCategory | undefined
colors: EffectColorDef[] | undefined
compute: ComputeEffectSource | undefined
factory: (() => ShaderHandle) | undefined
+fallback: EffectSubPass[] | undefined
label: string
multiPass: EffectSubPass[] | undefined
native: string | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 1c2d13aff..bd9ff82ca 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -3575,6 +3575,7 @@ category: EffectCategory | undefined
colors: EffectColorDef[] | undefined
compute: ComputeEffectSource | undefined
factory: (() => ShaderHandle) | undefined
+fallback: EffectSubPass[] | undefined
label: string
multiPass: EffectSubPass[] | undefined
native: string | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d36f265d9..87ff733d8 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -3575,6 +3575,7 @@ category: EffectCategory | undefined
colors: EffectColorDef[] | undefined
compute: ComputeEffectSource | undefined
factory: (() => ShaderHandle) | undefined
+fallback: EffectSubPass[] | undefined
label: string
multiPass: EffectSubPass[] | undefined
native: string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index facafb958..500e000ee 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -3575,6 +3575,7 @@ category: EffectCategory | undefined
colors: EffectColorDef[] | undefined
compute: ComputeEffectSource | undefined
factory: (() => ShaderHandle) | undefined
+fallback: EffectSubPass[] | undefined
label: string
multiPass: EffectSubPass[] | undefined
native: string | undefined
diff --git a/sdk/src/postprocess/PostProcessAPI.ts b/sdk/src/postprocess/PostProcessAPI.ts
index e924ea463..5edcce6e7 100644
--- a/sdk/src/postprocess/PostProcessAPI.ts
+++ b/sdk/src/postprocess/PostProcessAPI.ts
@@ -91,6 +91,18 @@ export function shutdownPostProcessAPI(): void {
module = null;
}
+/**
+ * Whether the device the chain runs on has a compute stage (WebGPU). False before the chain is up, and on WebGL2.
+ * An effect that has a compute version and a fragment one asks which to build.
+ */
+export function deviceHasCompute(): boolean {
+ try {
+ return getModule().postprocess_supportsCompute?.() === true;
+ } catch {
+ return false;
+ }
+}
+
function getModule(): PostProcessCore {
if (!module) {
throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index bd73edca9..55cd4d98b 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -5,6 +5,7 @@ import { postProcessEffects } from './postProcessEffects';
import { lensEffects } from './lensEffects';
import { gtaoPasses } from './gtao';
import { subsurfacePasses } from './subsurface';
+import { voxelGIFallback, VOXEL_ATLAS } from './voxelGIFallback';
import { SHARPEN_WGSL } from './computeEffects';
export interface EffectUniformDef {
@@ -45,6 +46,8 @@ export interface EffectSubPass {
* effect ends on a pass that reads the small result and writes the big one.
*/
scale?: number;
+ /** Uniforms this pass always carries, whatever the volume says: constants of its design (the voxel atlas's size). */
+ uniforms?: Record<string, number>;
}
/**
@@ -74,6 +77,11 @@ export interface EffectDef {
compute?: ComputeEffectSource;
/** Set instead of `factory` for an effect the engine implements itself, in compute passes of its own ("voxelGI"). */
native?: string;
+ /**
+ * Passes that stand in for a `native` or `compute` effect on a device that cannot run it (a fragment version of a compute
+ * one). They take every one of the effect's uniforms, as a multi-pass effect's passes do.
+ */
+ fallback?: EffectSubPass[];
uniforms: EffectUniformDef[];
/** Texture params, carried on the volume as serialized refs (`textures`). */
textures?: EffectTextureDef[];
@@ -102,7 +110,7 @@ export function effectPassNames(type: string): string[] {
const wanted = type.toLowerCase();
for (const def of effectRegistry.values()) {
if (def.type.toLowerCase() !== wanted) continue;
- return def.multiPass ? def.multiPass.map((pass) => pass.name) : [def.type];
+ return def.multiPass ? def.multiPass.map((pass) => pass.name) : [def.type, ...(def.fallback?.map((pass) => pass.name) ?? [])];
}
return [];
}
@@ -304,6 +312,12 @@ registerEffect({
type: 'voxelGI',
label: 'Voxel GI',
native: 'voxelGI',
+ // WebGL2 has no compute: the same cache built by fragment passes, at a fixed half-size gather.
+ fallback: [
+ { name: 'gi_voxels', factory: () => voxelGIFallback.createVoxels(), uniforms: { u_feedbackWidth: VOXEL_ATLAS.width, u_feedbackHeight: VOXEL_ATLAS.height } },
+ { name: 'gi_gather', factory: () => voxelGIFallback.createGather(), scale: 0.5 },
+ { name: 'gi_apply', factory: () => voxelGIFallback.createApply() },
+ ],
uniforms: [
// How much of the gathered light is added over the picture.
{ name: 'u_intensity', label: 'Intensity', min: 0, max: 4, step: 0.01, defaultValue: 1, neutralValue: 0 },
diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.ts
index 2135e8ba7..40361d221 100644
--- a/sdk/src/postprocess/postProcessEffects.ts
+++ b/sdk/src/postprocess/postProcessEffects.ts
@@ -172,7 +172,7 @@ fn basinCoverage(c : vec2i, size : vec2i, P : vec3f, coverage : f32, scale : f32
* unwritten pixel — at most 0.5 — is told from a surface). An effect that wants it says `#pragma gbuffer`,
* which is what makes the frame draw one, and finds it at `u_gbuffer`.
*/
-const GBUFFER_GLSL = `
+export const GBUFFER_GLSL = `
struct Surface { vec3 normal; float roughness; float metallic; bool known; };
Surface readSurface(ivec2 t) {
vec4 g = texelFetch(u_gbuffer, t, 0);
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
index fbf132dfd..099182ed5 100644
--- a/sdk/src/postprocess/volumeSystem.ts
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -5,7 +5,7 @@ import { defineResource, Res } from '../ecs/resource';
import { Query } from '../ecs/query';
import type { Entity } from '../types';
import { PostProcessVolume, Transform, Camera, type PostProcessVolumeData, type TransformData, type CameraData } from '../ecs/component';
-import { PostProcess, type PostProcessAPI } from './PostProcessAPI';
+import { PostProcess, deviceHasCompute, type PostProcessAPI } from './PostProcessAPI';
import { getEffectDef } from './effects';
import { blendVolumeEffects, computeVolumeFactor, type ActiveVolume, type BlendedEffect, type VolumeTransform } from './volumeBlending';
import type { ShaderHandle } from '../render/material';
@@ -175,6 +175,14 @@ function applyBlendedEffects(
applyTextures(stack, subPass.name, effectData.textures);
applyColors(stack, subPass.name, effectData.colors);
}
+ } else if (def.native && def.fallback && !deviceHasCompute()) {
+ // No compute stage: the fragment version of the same effect stands in for it.
+ for (const [index, subPass] of def.fallback.entries()) {
+ const shader = getOrCreateShader(api, subPass.name, subPass.factory);
+ stack.addPass(subPass.name, shader, subPass.scale ?? 1, index > 0);
+ for (const u of def.uniforms) stack.setUniform(subPass.name, u.name, effectData.uniforms.get(u.name) ?? u.defaultValue);
+ for (const [name, value] of Object.entries(subPass.uniforms ?? {})) stack.setUniform(subPass.name, name, value);
+ }
} else if (def.native) {
stack.addNativePass(effectType, def.native);
for (const u of def.uniforms) stack.setUniform(effectType, u.name, effectData.uniforms.get(u.name) ?? u.defaultValue);
diff --git a/sdk/src/postprocess/voxelGIFallback.ts b/sdk/src/postprocess/voxelGIFallback.ts
new file mode 100644
index 000000000..98d45a290
--- /dev/null
+++ b/sdk/src/postprocess/voxelGIFallback.ts
@@ -0,0 +1,323 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file voxelGIFallback.ts
+ * @brief The Voxel GI effect for a device with no compute stage (WebGL2): the same cache, built by fragment passes.
+ * @details The WebGPU effect keeps a world-space grid of voxels in a storage buffer and scatters the lit picture into it with atomics.
+ * A fragment shader can only write the texel it is running for, so the cache here is a texture and it is built the other way
+ * round: every texel of an atlas is a voxel, and it asks the picture what stands in it (it projects itself to the screen, looks
+ * at the depth buffer around where it lands, and takes the radiance and the facing of the pixels whose surface is inside it).
+ * What it held last frame is carried over, shifted when the window moved with the camera, and faded.
+ *
+ * Three passes: `gi_voxels` (the atlas, which the engine keeps from frame to frame), `gi_gather` (rays marched through the
+ * atlas from each visible surface, at half size, blended with the last frames) and `gi_apply` (the gathered light over the
+ * picture, upsampled with the depth). The gather and the apply are the compute kernels' own, in GLSL.
+ *
+ * The atlas is 2048 x 1024 half floats: 128 slices of 128 x 64 voxels laid out 16 across and 8 down, radiance and a sample
+ * count in the top half and facing and a count in the bottom. The last texel of the bottom half is not a voxel: it holds the
+ * window's origin (mod 1024, which half floats hold exactly) and the voxel size, which is how the next frame knows how far the
+ * window moved.
+ *
+ * It is the same idea at a lower price, and says so: the gather samples the depth buffer around each voxel instead of
+ * being scattered into, so a surface seen at a grazing angle is thinner in the cache than in the compute version.
+ */
+import type { ShaderHandle } from '../render/material';
+import { Material } from '../render/material';
+import { SSAO_GLSL, GBUFFER_GLSL } from './postProcessEffects';
+
+/** The atlas, and where the engine is told to make the memory it keeps for the pass that writes it. */
+export const VOXEL_ATLAS = { width: 2048, height: 1024 } as const;
+
+const COMMON = `
+const ivec3 DIMS = ivec3(128, 64, 128);
+const ivec2 META = ivec2(2047, 1023);
+ivec2 slotTexel(ivec3 s, int region) { return ivec2((s.z & 15) * 128 + s.x, region * 512 + (s.z >> 4) * 64 + s.y); }
+ivec3 windowOrigin(float vs) {
+ vec3 eye = u_camera.w > 0.5 ? u_camera.xyz : worldFromDepth(vec2(0.5), 0.5);
+ return ivec3(floor(eye / vs)) - DIMS / 2;
+}
+float hash1(vec3 p) {
+ p = fract(p * vec3(0.1031, 0.1030, 0.0973));
+ p += dot(p, p.yxz + 33.33);
+ return fract((p.x + p.y) * p.z);
+}`;
+
+export const voxelGIFallback = {
+ /** The atlas: carries the last frame's, shifted and faded, and adds what the picture shows stands in each voxel. */
+ createVoxels(): ShaderHandle {
+ const source = `#pragma shader "PP VoxelGI Voxels"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma highprecision
+#pragma gbuffer
+#pragma param u_voxelSize float default(40) range(4,400)
+#pragma param u_decay float default(0.93) range(0,0.99)
+#pragma param u_maxBounce float default(3) range(0.5,16)
+#pragma param u_feedback texture default(black)
+
+#pragma fragment
+precision highp float;
+precision highp int;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform highp sampler2D u_sceneDepth;
+uniform highp sampler2D u_gbuffer;
+out vec4 fragColor;
+
+${SSAO_GLSL}
+${GBUFFER_GLSL}
+${COMMON}
+
+void main() {
+ ivec2 t = ivec2(gl_FragCoord.xy);
+ float vs = max(u_voxelSize, 1.0);
+ ivec3 origin = windowOrigin(vs);
+ if (t == META) { fragColor = vec4(mod(vec3(origin), 1024.0), vs); return; }
+ vec4 meta = texelFetch(u_feedback, META, 0);
+
+ int region = t.y >= 512 ? 1 : 0;
+ int y = t.y - region * 512;
+ ivec3 slot = ivec3(t.x % 128, y % 64, (y / 64) * 16 + t.x / 128);
+ ivec3 cell = origin + slot;
+
+ // What the last frame held for this cell, where the window has moved: the cell was at its old slot, this many over.
+ vec3 moved = mod(vec3(origin) - meta.xyz + 512.0, 1024.0) - 512.0;
+ ivec3 was = slot + ivec3(floor(moved + 0.5));
+ vec4 held = vec4(0.0);
+ if (abs(meta.w - vs) < 0.5 && all(greaterThanEqual(was, ivec3(0))) && all(lessThan(was, DIMS))) {
+ held = texelFetch(u_feedback, slotTexel(was, region), 0) * u_decay;
+ }
+
+ // Where this voxel is on the screen, and how big.
+ vec3 centre = (vec3(cell) + 0.5) * vs;
+ vec4 clip = u_projection * vec4(centre, 1.0);
+ ivec2 size = textureSize(u_sceneDepth, 0);
+ if (clip.w <= 1e-3) { fragColor = held; return; }
+ vec2 ndc = clip.xy / clip.w;
+ if (abs(ndc.x) > 1.25 || abs(ndc.y) > 1.25) { fragColor = held; return; }
+ vec2 px = (ndc * 0.5 + 0.5) * vec2(size);
+ float radius = clamp(vs * 0.5 * abs(u_projection[1][1]) * 0.5 * float(size.y) / clip.w, 0.5, 48.0) * 1.15;
+
+ // Five looks first: if the surfaces the screen shows around this voxel are all well in front of it or well behind it, it is
+ // empty air or hidden, and the rest of the work is skipped. Most voxels are.
+ bool near = false;
+ for (int k = 0; k < 5; ++k) {
+ vec2 o = k == 0 ? vec2(0.0) : (k == 1 ? vec2(radius, 0.0) : (k == 2 ? vec2(-radius, 0.0) : (k == 3 ? vec2(0.0, radius) : vec2(0.0, -radius))));
+ ivec2 tp = clamp(ivec2(px + o), ivec2(0), size - ivec2(1));
+ float d = depthAt(tp, size);
+ if (d >= 1.0) continue;
+ float w = (u_projection * vec4(worldAt(tp, size), 1.0)).w;
+ if (abs(w - clip.w) < vs * 3.0) { near = true; break; }
+ }
+ if (!near) { fragColor = held; return; }
+
+ // Then the pixels in its footprint whose surface is inside it. The grid is jittered per voxel and per frame, so what the memory
+ // averages is the whole footprint and not one fixed pattern of it.
+ float frameSeed = floor(u_time.x * 30.0);
+ vec2 jit = vec2(hash1(vec3(cell) + frameSeed), hash1(vec3(cell.zxy) * 1.7 + frameSeed * 3.1)) - 0.5;
+ vec3 sum = vec3(0.0);
+ float count = 0.0;
+ for (int j = -2; j <= 2; ++j) {
+ for (int i = -2; i <= 2; ++i) {
+ ivec2 tp = ivec2(px + (vec2(float(i), float(j)) + jit * 0.9) * radius * 0.5);
+ if (tp.x < 0 || tp.y < 0 || tp.x >= size.x || tp.y >= size.y) continue;
+ float d = depthAt(tp, size);
+ if (d >= 1.0) continue;
+ vec3 world = worldAt(tp, size);
+ if (any(notEqual(ivec3(floor(world / vs)), cell))) continue;
+ if (region == 0) {
+ sum += clamp(texelFetch(u_texture, tp, 0).rgb, vec3(0.0), vec3(u_maxBounce));
+ } else {
+ Surface s = readSurface(tp);
+ if (!s.known) continue;
+ vec3 n = s.normal;
+ if (dot(n, viewDirection(world)) < 0.0) n = -n;
+ sum += n * 0.5 + 0.5;
+ }
+ count += 1.0;
+ }
+ }
+ fragColor = held + vec4(sum, count);
+}
+#pragma end
+`;
+ return Material.compileShader(source);
+ },
+
+ /** Rays from each visible surface through the atlas, at half the picture's size, blended with the last frames' gathers. */
+ createGather(): ShaderHandle {
+ const source = `#pragma shader "PP VoxelGI Gather"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma highprecision
+#pragma gbuffer
+#pragma param u_voxelSize float default(40) range(4,400)
+#pragma param u_rays float default(8) range(1,32)
+#pragma param u_range float default(48) range(4,90)
+#pragma param u_bias float default(1.2) range(0,4)
+#pragma param u_blend float default(0.2) range(0.02,1)
+#pragma param u_prevViewProjection0 color default(1,0,0,0)
+#pragma param u_prevViewProjection1 color default(0,1,0,0)
+#pragma param u_prevViewProjection2 color default(0,0,1,0)
+#pragma param u_prevViewProjection3 color default(0,0,0,1)
+#pragma param u_feedback texture default(black)
+
+#pragma fragment
+precision highp float;
+precision highp int;
+
+in vec2 v_texCoord;
+uniform highp sampler2D u_texture;
+uniform highp sampler2D u_sceneDepth;
+uniform highp sampler2D u_gbuffer;
+out vec4 fragColor;
+
+${SSAO_GLSL}
+${GBUFFER_GLSL}
+${COMMON}
+
+float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
+vec3 cosineDirection(vec3 n, float u, float v) {
+ float r = sqrt(u);
+ float phi = 6.2831853 * v;
+ vec3 up = abs(n.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
+ vec3 t = normalize(cross(up, n));
+ vec3 b = cross(n, t);
+ return normalize(t * (r * cos(phi)) + b * (r * sin(phi)) + n * sqrt(max(1.0 - u, 0.0)));
+}
+
+/// The light a ray from origin along dir brings: that of the first voxel it meets that faces it.
+vec3 trace(vec3 origin, vec3 dir, ivec3 window, float vs) {
+ vec3 pos = origin / vs;
+ ivec3 cell = ivec3(floor(pos));
+ ivec3 stepv = ivec3(dir.x >= 0.0 ? 1 : -1, dir.y >= 0.0 ? 1 : -1, dir.z >= 0.0 ? 1 : -1);
+ vec3 safe = vec3(abs(dir.x) < 1e-6 ? 1e-6 : dir.x, abs(dir.y) < 1e-6 ? 1e-6 : dir.y, abs(dir.z) < 1e-6 ? 1e-6 : dir.z);
+ vec3 delta = abs(vec3(1.0) / safe);
+ vec3 next = vec3(dir.x >= 0.0 ? float(cell.x + 1) : float(cell.x), dir.y >= 0.0 ? float(cell.y + 1) : float(cell.y), dir.z >= 0.0 ? float(cell.z + 1) : float(cell.z));
+ vec3 tMax = (next - pos) / safe;
+ float t = 0.0;
+ for (int i = 0; i < 96; ++i) {
+ if (t > u_range) break;
+ if (tMax.x < tMax.y && tMax.x < tMax.z) { cell.x += stepv.x; t = tMax.x; tMax.x += delta.x; }
+ else if (tMax.y < tMax.z) { cell.y += stepv.y; t = tMax.y; tMax.y += delta.y; }
+ else { cell.z += stepv.z; t = tMax.z; tMax.z += delta.z; }
+ ivec3 slot = cell - window;
+ if (any(lessThan(slot, ivec3(0))) || any(greaterThanEqual(slot, DIMS))) break;
+ vec4 a = texelFetch(u_texture, slotTexel(slot, 0), 0);
+ if (a.a < 2.0) continue;
+ vec4 b = texelFetch(u_texture, slotTexel(slot, 1), 0);
+ vec3 facing = (b.xyz / max(b.w, 1.0)) * 2.0 - 1.0;
+ // A surface is met from the side it faces. One facing away is behind the ray, or the ray skims along it.
+ if (dot(normalize(facing), dir) > -0.15) continue;
+ return (a.rgb / a.a) * clamp(1.0 - t / u_range, 0.0, 1.0);
+ }
+ return vec3(0.0);
+}
+
+void main() {
+ ivec2 p = ivec2(gl_FragCoord.xy);
+ ivec2 size = textureSize(u_sceneDepth, 0);
+ ivec2 low = textureSize(u_feedback, 0);
+ int frame = int(u_time.x * 60.0);
+ ivec2 t = min(p * 2 + ivec2(frame % 2, (frame / 2) % 2), size - ivec2(1));
+ float d = depthAt(t, size);
+ Surface s = readSurface(t);
+ if (d >= 1.0 || !s.known) { fragColor = vec4(0.0); return; }
+
+ float vs = max(u_voxelSize, 1.0);
+ ivec3 window = windowOrigin(vs);
+ vec3 world = worldAt(t, size);
+ vec3 n = s.normal;
+ if (dot(n, viewDirection(world)) < 0.0) n = -n;
+ vec3 origin = world + n * (vs * u_bias);
+
+ int rays = int(u_rays);
+ float r1 = ign(vec2(p) + vec2(0.0, float(frame % 16)));
+ float r2 = ign(vec2(p.yx) + vec2(float(frame % 16) * 5.588238, 0.0));
+ vec3 sum = vec3(0.0);
+ for (int k = 0; k < rays; ++k) {
+ float u = fract((float(k) + 0.5) / float(rays) + r1);
+ float v = fract(float(k) * 0.61803399 + r2);
+ sum += trace(origin, cosineDirection(n, u, v), window, vs);
+ }
+ vec3 light = sum / float(rays);
+
+ // What the last frames agreed on, found where this surface was in the last frame's picture.
+ mat4 prevVP = mat4(u_prevViewProjection0, u_prevViewProjection1, u_prevViewProjection2, u_prevViewProjection3);
+ vec4 prev = prevVP * vec4(world, 1.0);
+ if (prev.w > 1e-4) {
+ vec2 uv = prev.xy / prev.w * 0.5 + 0.5;
+ if (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0) {
+ ivec2 q = clamp(ivec2(uv * vec2(low)), ivec2(0), low - ivec2(1));
+ light = mix(texelFetch(u_feedback, q, 0).rgb, light, u_blend);
+ }
+ }
+ fragColor = vec4(light, 1.0);
+}
+#pragma end
+`;
+ return Material.compileShader(source);
+ },
+
+ /** The gathered light over the picture, upsampled with the depth so it does not bleed across an edge. */
+ createApply(): ShaderHandle {
+ const source = `#pragma shader "PP VoxelGI Apply"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1) range(0,4)
+#pragma param u_debug float default(0) range(0,1)
+
+#pragma fragment
+precision highp float;
+precision highp int;
+
+in vec2 v_texCoord;
+uniform highp sampler2D u_texture;
+uniform sampler2D u_sceneTexture;
+uniform highp sampler2D u_sceneDepth;
+out vec4 fragColor;
+
+${SSAO_GLSL}
+
+void main() {
+ ivec2 size = textureSize(u_sceneDepth, 0);
+ ivec2 t = screenTexel(v_texCoord, size);
+ vec4 src = texelFetch(u_sceneTexture, ivec2(gl_FragCoord.xy), 0);
+ ivec2 low = textureSize(u_texture, 0);
+ const int DIV = 2;
+ float depth = depthAt(t, size);
+ vec3 light = vec3(0.0);
+ if (depth < 1.0) {
+ // A depth-weighted blend of the low-resolution texels around the pixel: the ones on the same surface count, the ones across an
+ // edge do not. The window is wider than the bilinear four, which is what smooths the rays' noise.
+ ivec2 centre = ivec2(floor((vec2(t) + 0.5) / float(DIV) - 0.5));
+ float total = 0.0;
+ vec3 acc = vec3(0.0);
+ for (int dy = -1; dy <= 2; ++dy) {
+ for (int dx = -1; dx <= 2; ++dx) {
+ ivec2 q = clamp(centre + ivec2(dx, dy), ivec2(0), low - ivec2(1));
+ float qd = depthAt(min(q * DIV, size - ivec2(1)), size);
+ if (qd >= 1.0) continue;
+ vec2 nearv = abs(vec2(t) / float(DIV) - 0.5 - vec2(q));
+ float spatial = max(1.0 - 0.4 * (nearv.x + nearv.y), 0.05);
+ // Depth is nonlinear: it is the ratio of what is left to the far plane that says how far apart two surfaces are.
+ float w = spatial * exp(-abs(log((1.0 - qd + 1e-6) / (1.0 - depth + 1e-6))) * 24.0);
+ acc += texelFetch(u_texture, q, 0).rgb * w;
+ total += w;
+ }
+ }
+ if (total > 1e-4) light = acc / total;
+ }
+ // What the gathered light is lit onto wears the surface's own colour (its chroma, kept below white).
+ float lum = max(dot(src.rgb, vec3(0.2126, 0.7152, 0.0722)), 0.02);
+ vec3 albedo = mix(vec3(0.55), clamp(src.rgb / lum, vec3(0.0), vec3(1.6)) * 0.55, 0.7);
+ vec3 result = src.rgb + albedo * light * u_intensity;
+ if (u_debug > 0.5) result = light * u_intensity;
+ fragColor = vec4(result, src.a);
+}
+#pragma end
+`;
+ return Material.compileShader(source);
+ },
+};
diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.ts
index 1f9382a78..f1af28ad3 100644
--- a/sdk/src/render/quality.ts
+++ b/sdk/src/render/quality.ts
@@ -60,7 +60,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {
shadowAtlasSize: 1024, shadowCellSize: 256, shadowCascades: 2,
planarReflectionScale: 0.25, planarReflectionMaxSize: 512, planarReflectionUpdatesPerSecond: 0,
shadowDistance: 0, particleLimit: 1000, postProcess: true, ssao: false,
- skipEffects: ['ssr', 'taa', 'depthOfField', 'lightShafts', 'motionBlur', 'lensFlare', 'gtao', 'subsurface'],
+ skipEffects: ['ssr', 'taa', 'depthOfField', 'lightShafts', 'motionBlur', 'lensFlare', 'gtao', 'subsurface', 'voxelGI'],
},
medium: {
renderScale: 1, minRenderScale: 0.65, msaaSamples: 2,
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index 1545157d1..c503b31b5 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -1156,8 +1156,15 @@ void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, rg::Res
} else if (passHasTexture(pass, "u_feedback")) {
// At the pass's own size: a measurement is a few texels, not a picture.
pass.historyKey = feedbackKey(pass.name);
- const u32 fw = static_cast<u32>(static_cast<f32>(width_) * pass.scale);
- const u32 fh = static_cast<u32>(static_cast<f32>(height_) * pass.scale);
+ u32 fw = static_cast<u32>(static_cast<f32>(width_) * pass.scale);
+ u32 fh = static_cast<u32>(static_cast<f32>(height_) * pass.scale);
+ // A memory that is not a picture (the voxel cache laid out as an atlas) names its own size, in texels.
+ const auto sized = [&pass](const char* name, u32 fallback) {
+ const auto it = pass.floatUniforms.find(name);
+ return it != pass.floatUniforms.end() && it->second >= 1.0f ? std::min(static_cast<u32>(it->second), 4096u) : fallback;
+ };
+ fw = sized("u_feedbackWidth", fw);
+ fh = sized("u_feedbackHeight", fh);
// What it remembers is a measurement: kept in a float even where the picture is 8 bits a channel.
temporal = prepareHistory(feedback_[pass.historyKey], fw, fh,
passIsHighPrecision(pass) ? GfxPixelFormat::RGBA16F : interFormat());
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index dac3fcd56..a0d4743f9 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2497,6 +2497,10 @@ export const NOTED = {
{"internal":"the desktop half of the Details panels entry just below, which carries the note"},
"feat(examples): add cyberpunk rooftop scene and building HUD":
{"note":"Cyber Rooftop adds a rooftop survival-base example with a 2D HUD and a first-person build tool."},
+ "feat(render): Voxel GI runs on WebGL2 with fragment passes":
+ {"note":"Voxel GI now runs on WebGL2: the world-space bounce light is built with fragment passes where there is no compute stage."},
+ "chore(editor-checks): Voxel GI is checked on WebGL2 as well":
+ {"internal":"the editor check for the WebGL2 Voxel GI entry above"},
"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":
{"note":"A wire or railing thinner than a pixel stays one line against the sky instead of breaking into dashes."},
"fix(render): contact shadows no longer speckle a surface the sun does not reach, and a temporal pass placed before a noisy effect is flagged":