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(sky): a project's own sky lights the scene; probes chosen by a mesh's box

yhh8261a27640f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 929f91dae..0cecf8446 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ published separately; it ships inside the editor.
- **The sky lights the scene.** Sky Atmosphere's **Light the Scene** makes the sky the scene's environment: every Ambient light that names no environment of its own lights with it, its diffuse light from the dome and the clouds and its reflection on metal and wet ground, scaled by the light's colour and intensity as an imported one is. The sky is worked out again as it changes (the sun moving, a weather coming in, clouds drifting), at most once a second; with clouds that takes about 20 ms on a desktop. The sun's disc is left out, since the directional light the sky follows is its direct light. Below the horizon it is the ground, lit by the sky's sun and dome and giving back **Ground Albedo** of it (0.2 by default, between asphalt and grass; Unreal's atmosphere uses 0.4), so a wall in shadow takes the sunlit ground's bounce as well as the sky's: under a high clear sun that doubles its fill, under a low hazy one it adds little. Off by default, so a scene already lit by hand looks as it did.
- **Rooms stay dark under a sky that changes (sky occlusion).** With **Sky occlusion** on in the Lighting settings (`BakedLighting.skyOcclusion`), a probe bake keeps how much of the sky each probe sees instead of the sky itself: the probes hold the lights and their bounces, and the sky the frame has now (a live Sky Atmosphere, a weather, an environment) is added through what each probe sees of it, to the diffuse light and to the sky's reflection. A ball inside a roofed room measured 119 where the baked sky gave it 150, and a ball outside kept its light. A `.esprobes` baked this way carries `skyVisibility`; one without it lights as before. Probes are read per object, as Unity's light probes are: one large mesh spanning indoors and out takes one value.
+- **A sky of your own lights the scene.** `defineSkyEffect({ type, label, glsl, wgsl, ... })` turns one function, the sky's radiance along a direction, into an effect a PostProcessVolume carries: drawn behind the scene and, with **Light the Scene** on, read back from the GPU as a small panorama about once a second and made the scene's environment, diffuse light and reflections, as Sky Atmosphere's is. A stylised sky lights the world with the light it shows, as an Unreal sky material does under a real-time Sky Light; the custom-sky gate checks that a ball under a blue-above, red-below sky is blue on top and red underneath on both backends. Effect textures can tile (`wrap: 'repeat'`).
- **Direct Lighting Only and Indirect Lighting Only view modes.** Beside Clay in the viewport's Show menu (and `Renderer.setViewShading(view, 'directLighting' | 'indirectLighting')`), as Unreal's lighting components: clay lit by the lights alone, or by everything that is not a light (ambient, sky, reflections, probes, bakes). The two add up to Clay, so a dark shadow says at once whether its fill is missing or merely weak.
- **A post-process pass can read an earlier pass of its own effect.** A texture param named `u_pass_<name>` is bound to the output of the sub-pass called `<name>`, which the chain keeps alive until it has been read, so an effect can be a pyramid (down, then up, adding each level back) and not only a line of passes.
- **A probe volume lights each pixel, not each object.** A lit mesh inside a `LightProbeVolume` reads the baked grid where each of its pixels stands, so one large mesh that spans a dark room and the open yard outside it (a merged building, an imported level) is dark inside and lit outside, as in Unity's Adaptive Probe Volumes; before, it took the one value at its origin and was lit the same end to end. The grids ride one half-float atlas the frame builds when a bake changes. A mesh with lightmap UVs that has no bake still reads its volume per object, as before.
@@ -43,6 +44,7 @@ published separately; it ships inside the editor.
### Fixed
+- **A mesh is lit by the probe volume it draws in, not the one its origin is in.** An imported level's meshes keep the origin the file gave them, often the world's centre, so a shed's walls were in no volume and took the open sky's light indoors. The volume is now chosen by the mesh's world box (its centre, else the smallest volume it overlaps), and per pixel each pixel reads the grid where it stands.
- **Rain does not fall through a glass roof.** The rain's map of what stands overhead took only what casts a shadow, so a see-through roof set to cast none — glass, as it usually is — left the floor under it wet. A see-through surface keeps rain off whether or not light passes it; what is opaque and casts no shadow (a held gun) still stays out. Gate: ssr-shelter-glass.
- **A character controller or a 3D collider added with its defaults is a real size.** Their defaults were metres (a 0.3 radius, a 0.5 box) under a world that reads centimetres unless told otherwise: a 3 mm character, a 5 mm crate. They are a 1.6 m person and a 1 m box now, in whatever units the project uses. Every example and template stated its sizes, so none changes.
- **A model's import no longer calls it tiny in a metre project.** The note read every model as if a world unit were a design pixel; it now measures the model in metres by the project's units per metre and suggests that as the Scale.
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 6303ece93..b0f7501c2 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -509,6 +509,34 @@ and the chain binds the output of the pass called `<name>`, keeping it alive unt
has run. That is how bloom's upsample adds back the downsample of its own size; a sub-pass
with `scale` below 1 draws at that fraction of the chain.
+### A sky of your own
+
+`defineSkyEffect` turns one function you write — the sky's radiance along a direction — into an effect a
+PostProcessVolume carries like any other. It is drawn behind the scene, and with **Light the Scene** on, the engine
+reads back a small panorama of it about once a second and makes it the scene's environment, its diffuse light and
+its reflections, as Sky Atmosphere's is: a stylised sky lights the world with the light it shows.
+
+```typescript
+import { defineSkyEffect } from 'esengine';
+
+defineSkyEffect({
+ type: 'duskSky',
+ label: 'Dusk Sky',
+ colors: [{ name: 'u_horizon', label: 'Horizon', defaultValue: { r: 0.95, g: 0.55, b: 0.28, a: 1 } }],
+ glsl: `vec3 skyRadiance(vec3 dir, vec3 sun, vec3 sunColor, float env) {
+ return mix(u_horizon.rgb, vec3(0.05, 0.09, 0.14), smoothstep(0.0, 0.4, dir.y));
+ }`,
+ wgsl: `fn skyRadiance(dir : vec3f, sun : vec3f, sunColor : vec3f, env : f32) -> vec3f {
+ return mix(mc.u_horizon.rgb, vec3f(0.05, 0.09, 0.14), smoothstep(0.0, 0.4, dir.y));
+ }`,
+});
+```
+
+`sun` is the first directional light's direction, `sunColor` its colour times intensity, and `env` is 1 while the
+panorama is drawn (leave a sun disc out then: the directional light is the sun's direct light). Return linear
+radiance. Params are uniforms (`mc.` in WGSL), the time is `u_time.x`, and `textures` brings tables the sky needs
+(`wrap: 'repeat'` for noise).
+
| Method | Description |
|---|---|
| `PostProcess.createStack()` | Create an empty effect stack. |
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 d54045873..92b0d9397 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
@@ -390,6 +390,32 @@ sub-pass 不只能读上一个 pass,还能读同一效果里更早的 pass:声
并让它一直保留到这个 pass 跑完。bloom 的上采样就是这样把同尺寸的下采样加回来的;`scale` 小于 1 的 sub-pass
以链尺寸的这个比例绘制。
+### 自己写的天空
+
+`defineSkyEffect` 把你写的一个函数——天空在某个方向上的辐亮度——变成一个效果,PostProcessVolume 像放别的效果一样放它。
+它画在场景后面;打开 **Light the Scene** 后,引擎大约每秒读回一张它的小全景图,作为场景的环境(漫反射光和反射),
+和 Sky Atmosphere 的做法一样:风格化的天空用它看起来的光照亮世界。
+
+```typescript
+import { defineSkyEffect } from 'esengine';
+
+defineSkyEffect({
+ type: 'duskSky',
+ label: 'Dusk Sky',
+ colors: [{ name: 'u_horizon', label: 'Horizon', defaultValue: { r: 0.95, g: 0.55, b: 0.28, a: 1 } }],
+ glsl: `vec3 skyRadiance(vec3 dir, vec3 sun, vec3 sunColor, float env) {
+ return mix(u_horizon.rgb, vec3(0.05, 0.09, 0.14), smoothstep(0.0, 0.4, dir.y));
+ }`,
+ wgsl: `fn skyRadiance(dir : vec3f, sun : vec3f, sunColor : vec3f, env : f32) -> vec3f {
+ return mix(mc.u_horizon.rgb, vec3f(0.05, 0.09, 0.14), smoothstep(0.0, 0.4, dir.y));
+ }`,
+});
+```
+
+`sun` 是第一盏方向光的方向,`sunColor` 是它的颜色乘强度;画全景图时 `env` 为 1(这时别画太阳圆盘:
+方向光就是太阳的直射光)。返回线性辐亮度。参数是 uniform(WGSL 里写 `mc.`),时间是 `u_time.x`,
+`textures` 用来带上天空需要的贴图(噪声用 `wrap: 'repeat'`)。
+
| 方法 | 说明 |
|---|---|
| `PostProcess.createStack()` | 创建一个空效果栈。 |
diff --git a/fixtures/scenes/custom-sky.esscene b/fixtures/scenes/custom-sky.esscene
new file mode 100644
index 000000000..7e17197d9
--- /dev/null
+++ b/fixtures/scenes/custom-sky.esscene
@@ -0,0 +1,144 @@
+{
+ "version": 4,
+ "name": "CustomSky",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 60,
+ "nearPlane": 1,
+ "farPlane": 5000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Ball",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 1.5,
+ "y": 1.5,
+ "z": 1.5
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:sphere",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Ambient",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 2,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "intensity": 1
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Post",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "PostProcessVolume",
+ "data": {
+ "isGlobal": true,
+ "priority": 0,
+ "weight": 1,
+ "effects": [
+ {
+ "type": "verifySky",
+ "enabled": true,
+ "uniforms": {
+ "u_lightScene": 1
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/probe-off-origin.esscene b/fixtures/scenes/probe-off-origin.esscene
new file mode 100644
index 000000000..e46b17f1d
--- /dev/null
+++ b/fixtures/scenes/probe-off-origin.esscene
@@ -0,0 +1,104 @@
+{
+ "version": 4,
+ "name": "ProbeOffOrigin",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 300,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Probes",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "LightProbeVolume",
+ "data": {
+ "probes": "/scenes/probe-ends.esprobes",
+ "halfExtents": {
+ "x": 120,
+ "y": 400,
+ "z": 400
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Wide",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -200,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 1,
+ "y": 0.2,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "lit": true,
+ "mesh": "/scenes/lit-triangles.esmesh"
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/probe-off-origin.textures.json b/fixtures/scenes/probe-off-origin.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/fixtures/scenes/probe-off-origin.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 2d1c62ca9..10777ed09 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -200,6 +200,8 @@ export {
currentTimeOfDay,
TimeDrive,
type TimeOfDayState,
+ defineSkyEffect,
+ type SkyEffectSource,
} from './postprocess';
// =============================================================================
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 4e09e26be..2287ca53e 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -119,6 +119,8 @@ export interface NativeEngineApi {
postprocess_init?(width: number, height: number): boolean;
postprocess_isInitialized?(): boolean;
postprocess_maxMsaaSamples?(): number;
+ postprocess_pollSkyCapture?(): number;
+ postprocess_requestSkyCapture?(passName: string, width: number, height: number): void;
postprocess_resize?(width: number, height: number): void;
postprocess_setBypass?(bypass: boolean): void;
postprocess_setDisplayLut?(textureHandle: number, amount: number): void;
@@ -136,6 +138,7 @@ export interface NativeEngineApi {
postprocess_setViewExposure?(ev: number): void;
postprocess_shutdown?(): void;
postprocess_supportsCompute?(): boolean;
+ postprocess_takeSkyCapture?(dst: number, bytes: number): boolean;
probe_volume_create?(resX: number, resY: number, resZ: number, shPtr: number): number;
probe_volume_release?(volumeHandle: number): void;
probe_volume_setSkyVisibility?(volumeHandle: number, visibilityPtr: number): void;
@@ -464,6 +467,8 @@ export function createNativeEngineApi(
bind('postprocess_init', 'es_postprocess_init', false);
bind('postprocess_isInitialized', 'es_postprocess_isInitialized', false);
bind('postprocess_maxMsaaSamples', 'es_postprocess_maxMsaaSamples', false);
+ bind('postprocess_pollSkyCapture', 'es_postprocess_pollSkyCapture', false);
+ bind('postprocess_requestSkyCapture', 'es_postprocess_requestSkyCapture', false);
bind('postprocess_resize', 'es_postprocess_resize', false);
bind('postprocess_setBypass', 'es_postprocess_setBypass', false);
bind('postprocess_setDisplayLut', 'es_postprocess_setDisplayLut', false);
@@ -481,6 +486,7 @@ export function createNativeEngineApi(
bind('postprocess_setViewExposure', 'es_postprocess_setViewExposure', false);
bind('postprocess_shutdown', 'es_postprocess_shutdown', false);
bind('postprocess_supportsCompute', 'es_postprocess_supportsCompute', false);
+ bind('postprocess_takeSkyCapture', 'es_postprocess_takeSkyCapture', false);
bind('probe_volume_create', 'es_probe_volume_create', false);
bind('probe_volume_release', 'es_probe_volume_release', false);
bind('probe_volume_setSkyVisibility', 'es_probe_volume_setSkyVisibility', false);
diff --git a/sdk/src/postprocess.ts b/sdk/src/postprocess.ts
index db260904c..4b61ff56f 100644
--- a/sdk/src/postprocess.ts
+++ b/sdk/src/postprocess.ts
@@ -23,6 +23,8 @@ export {
getAllEffectDefs,
PostProcessPlugin,
postProcessPlugin,
+ defineSkyEffect,
+ type SkyEffectSource,
registerWeatherPreset,
weatherPresetId,
weatherPresetNames,
diff --git a/sdk/src/postprocess/PostProcessPlugin.ts b/sdk/src/postprocess/PostProcessPlugin.ts
index 149d84405..0612e77cb 100644
--- a/sdk/src/postprocess/PostProcessPlugin.ts
+++ b/sdk/src/postprocess/PostProcessPlugin.ts
@@ -40,8 +40,11 @@ function skyEnvironmentSystem(app: App, sky: SkyEnvironment) {
(lights: Iterable<[Entity, LightData, TransformData]>) => {
if (!app.hasResource(PostProcess)) return;
const view = app.hasResource(EditorView) ? app.getResource(EditorView) : null;
- const effect = resolvedLightingSky(app.getResource(PostProcess), !!view?.active);
- if (!effect) { sky.update(app.wasmModule, null, 0); return; }
+ const lighting = resolvedLightingSky(app.getResource(PostProcess), !!view?.active);
+ if (!lighting) { sky.update(app.wasmModule, null, 0); return; }
+ // A sky a project wrote is read back from the GPU, where it is drawn; Sky Atmosphere is worked out here.
+ if (lighting.type !== 'skyAtmosphere') { sky.updateCaptured(app.wasmModule, lighting.type, performance.now() / 1000); return; }
+ const effect = lighting.effect;
const params = skyParamsOf(effect);
sky.update(app.wasmModule, { sun: skySunOf(params, sunFromLights(lights)), params, linear: linearColorSpace() },
performance.now() / 1000);
@@ -71,7 +74,7 @@ export class PostProcessPlugin implements Plugin {
app.hasResource(Assets) ? (app.getResource(Assets).getTexture(ref)?.handle ?? 0) : 0);
// Textures an effect brings itself (AgX's table): uploaded as data, linear, clamped, with this App's module.
setBuiltinTextureMaker((pixels) => createTextureFromPixels(app.wasmModule, pixels, TextureContent.Retained, false,
- { srgb: false, filterMode: 'linear', wrapMode: 'clamp' }));
+ { srgb: false, filterMode: 'linear', wrapMode: pixels.wrap === 'repeat' ? 'repeat' : 'clamp' }));
// The weather first: the volumes read what it has decided.
app.addSystemToSchedule(Schedule.PostUpdate, weatherSystem);
app.addSystemToSchedule(Schedule.PostUpdate, postProcessVolumeSystem);
diff --git a/sdk/src/postprocess/customSky.ts b/sdk/src/postprocess/customSky.ts
new file mode 100644
index 000000000..06b4b8724
--- /dev/null
+++ b/sdk/src/postprocess/customSky.ts
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file customSky.ts
+ * @brief A sky a project writes itself, drawn behind the scene and, when it asks, lighting it.
+ *
+ * @details The author writes one function, the sky's radiance along a direction, in GLSL and WGSL. Around it this builds a
+ * post-process effect that draws it where nothing else was drawn, as Sky Atmosphere does, and that can draw the
+ * same function as a small panorama for the engine to read back: that panorama is made into the scene's
+ * environment (its diffuse light and its reflections) exactly as Sky Atmosphere's is, at most once a second. So a
+ * stylised sky lights the scene with the light it shows, as Unreal's sky material does under a real-time Sky Light.
+ *
+ * The function is `skyRadiance(dir, sun, sunColor, env)`: `dir` and `sun` unit world directions (the sun is the
+ * first directional light, or straight up without one), `sunColor` that light's colour times intensity, and `env`
+ * 1 while the panorama is drawn — when a sun disc should be left out, since the directional light is the sun's
+ * direct light there. It returns linear radiance, before exposure. The effect's own params are uniforms like any
+ * effect's: in GLSL by name, in WGSL as `mc.<name>`; the time is `u_time.x` / `tc.u_time.x`.
+ */
+
+import type { ShaderHandle } from '../render/material';
+import { Material } from '../render/material';
+import { registerEffect, type EffectColorDef, type EffectUniformDef } from './effects';
+import type { BuiltinTexture } from './effects';
+
+export interface SkyEffectSource {
+ /** The effect's type, as a volume names it. */
+ type: string;
+ label: string;
+ /** The sky's own float params. Brightness (`u_intensity`) and Light the Scene (`u_lightScene`) are added. */
+ uniforms?: EffectUniformDef[];
+ /** Colour params (vec4). */
+ colors?: EffectColorDef[];
+ /** Textures the sky brings itself (a noise table), by sampler name: GLSL `name`, WGSL `name` with `name_s`. */
+ textures?: Record<string, () => BuiltinTexture>;
+ /** GLSL declarations and `vec3 skyRadiance(vec3 dir, vec3 sun, vec3 sunColor, float env)`. */
+ glsl: string;
+ /** The same in WGSL: `fn skyRadiance(dir : vec3f, sun : vec3f, sunColor : vec3f, env : f32) -> vec3f`. */
+ wgsl: string;
+}
+
+/** The sky types defined here: what the volumes look for, beside Sky Atmosphere, to light the scene. */
+const skyTypes = new Set<string>();
+
+export function isCustomSky(type: string): boolean {
+ return skyTypes.has(type);
+}
+
+/** The panorama's size: the light a sky sends is smooth. Equal to Sky Atmosphere's. */
+export const CUSTOM_SKY_WIDTH = 64;
+export const CUSTOM_SKY_HEIGHT = 32;
+/** The panorama is stored as RGBM over this range (the environment's own reflection range). */
+export const CUSTOM_SKY_RANGE = 8;
+
+function pragmaLine(u: EffectUniformDef): string {
+ return `#pragma param ${u.name} float default(${u.defaultValue}) range(${u.min},${u.max})`;
+}
+
+function colorPragma(c: EffectColorDef): string {
+ const v = c.defaultValue;
+ return `#pragma param ${c.name} color default(${v.r},${v.g},${v.b},${v.a})`;
+}
+
+/** The effect's shader: the author's function, drawn under the scene or, with u_skyCapture, as the panorama. */
+export function skyEffectSource(src: SkyEffectSource): string {
+ const params = [
+ '#pragma param u_intensity float default(1) range(0,8)',
+ '#pragma param u_lightScene float default(0) range(0,1)',
+ '#pragma param u_skyCapture float default(0) range(0,1)',
+ // A marker the engine reads (see Sky Atmosphere): the scene is cleared to nothing, so its alpha is its coverage.
+ '#pragma param u_sceneCoverage float default(1) range(0,1)',
+ ...(src.uniforms ?? []).map(pragmaLine),
+ ...(src.colors ?? []).map(colorPragma),
+ ...Object.keys(src.textures ?? {}).map((name) => `#pragma param ${name} texture default(black)`),
+ ].join('\n');
+ // The panorama's direction for a texel, in Panorama's own mapping (lightmap/panorama.ts). Its v runs down from the
+ // zenith; the readback lands rows bottom-up on both backends while the pass's uv runs up the target on GL and down it
+ // on WebGPU, so v is 1 - uv.y there and uv.y here, and the reader turns the rows over.
+ return `#pragma shader "Sky ${src.label}"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma lights
+${params}
+
+#pragma fragment
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform sampler2D u_sceneTexture;
+uniform highp sampler2D u_sceneDepth;
+out vec4 fragColor;
+
+${src.glsl}
+
+vec3 esSkyPanoramaDir(vec2 uv) {
+ float phi = (uv.x - 0.5) * 6.28318531;
+ float theta = (1.0 - uv.y) * 3.14159265;
+ float s = sin(theta);
+ return vec3(-s * sin(phi), cos(theta), s * cos(phi));
+}
+
+void main() {
+ vec4 lightDir, lightColor;
+ ivec2 tiles;
+ findSun(lightDir, lightColor, tiles);
+ vec3 sun = lightDir.w > 0.5 ? lightDir.xyz : vec3(0.0, 1.0, 0.0);
+ vec3 sunColor = lightColor.rgb * lightColor.a;
+ if (u_skyCapture > 0.5) {
+ vec3 c = clamp(skyRadiance(esSkyPanoramaDir(v_texCoord), sun, sunColor, 1.0) * u_intensity, vec3(0.0), vec3(${CUSTOM_SKY_RANGE.toFixed(1)}));
+ float m = clamp(max(max(c.r, c.g), max(c.b, 1e-6)) / ${CUSTOM_SKY_RANGE.toFixed(1)}, 1.0 / 255.0, 1.0);
+ m = ceil(m * 255.0) / 255.0;
+ fragColor = vec4(c / (m * ${CUSTOM_SKY_RANGE.toFixed(1)}), m);
+ return;
+ }
+ vec4 src = texture(u_sceneTexture, v_texCoord);
+ ivec2 size = textureSize(u_sceneDepth, 0);
+ float depth = texelFetch(u_sceneDepth, clamp(ivec2(v_texCoord * vec2(size)), ivec2(0), size - ivec2(1)), 0).r;
+ if (depth < 1.0 && src.a > 0.999) { fragColor = src; return; }
+ vec3 entry = worldFromDepth(v_texCoord, 0.0);
+ vec3 dir = normalize(worldFromDepth(v_texCoord, 1.0) - entry);
+ vec3 col = skyRadiance(dir, sun, sunColor, 0.0) * u_intensity;
+ fragColor = vec4(src.rgb + (1.0 - src.a) * col, src.a > 0.99 ? src.a : 1.0);
+}
+#pragma end
+
+#pragma fragment wgsl
+${src.wgsl}
+
+fn esSkyPanoramaDir(uv : vec2f) -> vec3f {
+ let phi = (uv.x - 0.5) * 6.28318531;
+ let theta = uv.y * 3.14159265;
+ let s = sin(theta);
+ return vec3f(-s * sin(phi), cos(theta), s * cos(phi));
+}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let found = findSun();
+ var sun = vec3f(0.0, 1.0, 0.0);
+ if (found.dir.w > 0.5) { sun = found.dir.xyz; }
+ let sunColor = found.color.rgb * found.color.a;
+ if (mc.u_skyCapture > 0.5) {
+ let c = clamp(skyRadiance(esSkyPanoramaDir(v.v_texCoord), sun, sunColor, 1.0) * mc.u_intensity, vec3f(0.0), vec3f(${CUSTOM_SKY_RANGE.toFixed(1)}));
+ var m = clamp(max(max(c.r, c.g), max(c.b, 1e-6)) / ${CUSTOM_SKY_RANGE.toFixed(1)}, 1.0 / 255.0, 1.0);
+ m = ceil(m * 255.0) / 255.0;
+ return vec4f(c / (m * ${CUSTOM_SKY_RANGE.toFixed(1)}), m);
+ }
+ let src = textureSampleLevel(t1, s1, v.v_texCoord, 0.0);
+ let size = vec2i(textureDimensions(t7, 0));
+ let depth = textureLoad(t7, clamp(vec2i(v.v_texCoord * vec2f(size)), vec2i(0), size - vec2i(1)), 0);
+ if (depth < 1.0 && src.a > 0.999) { return src; }
+ let entry = worldFromDepth(v.v_texCoord, 0.0);
+ let dir = normalize(worldFromDepth(v.v_texCoord, 1.0) - entry);
+ let col = skyRadiance(dir, sun, sunColor, 0.0) * mc.u_intensity;
+ var a = 1.0;
+ if (src.a > 0.99) { a = src.a; }
+ return vec4f(src.rgb + (1.0 - src.a) * col, a);
+}
+#pragma end
+`;
+}
+
+/**
+ * Registers a sky a project wrote: an effect of `type` a PostProcessVolume can carry, with Brightness and Light the
+ * Scene beside the sky's own params. One per type; defining a type again replaces it.
+ */
+export function defineSkyEffect(src: SkyEffectSource): void {
+ let shader: ShaderHandle | null = null;
+ skyTypes.add(src.type);
+ registerEffect({
+ type: src.type,
+ label: src.label,
+ factory: () => (shader ??= Material.compileShader(skyEffectSource(src))),
+ uniforms: [
+ { name: 'u_intensity', label: 'Brightness', min: 0, max: 8, step: 0.01, defaultValue: 1 },
+ { name: 'u_lightScene', label: 'Light the Scene', min: 0, max: 1, step: 1, defaultValue: 0, neutralValue: 0 },
+ ...(src.uniforms ?? []),
+ ],
+ colors: src.colors,
+ builtinTextures: src.textures,
+ });
+}
+
+/**
+ * The capture as a panorama of linear radiance, top row the zenith (Panorama's layout): the RGBM pixels decoded and the
+ * readback's bottom-up rows turned over.
+ */
+export function decodeSkyCapture(rgba: Uint8Array, width: number, height: number): { width: number; height: number; rgb: Float32Array } {
+ const rgb = new Float32Array(width * height * 3);
+ for (let y = 0; y < height; y++) {
+ const from = (height - 1 - y) * width;
+ for (let x = 0; x < width; x++) {
+ const i = (from + x) * 4;
+ const m = (rgba[i + 3]! / 255) * CUSTOM_SKY_RANGE;
+ const o = (y * width + x) * 3;
+ rgb[o] = (rgba[i]! / 255) * m;
+ rgb[o + 1] = (rgba[i + 1]! / 255) * m;
+ rgb[o + 2] = (rgba[i + 2]! / 255) * m;
+ }
+ }
+ return { width, height, rgb };
+}
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 08e79fd02..ec7121479 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -67,6 +67,14 @@ export interface EffectTextureDef {
internal?: boolean;
}
+/** Pixels an effect brings itself, RGBA8. Clamped at the edges unless `wrap` says it tiles (a noise table read far past 0..1). */
+export interface BuiltinTexture {
+ width: number;
+ height: number;
+ pixels: Uint8Array;
+ wrap?: 'clamp' | 'repeat';
+}
+
/** A colour parameter (fog colour): the vec4 uniform it feeds and its default. */
export interface EffectColorDef {
name: string;
@@ -131,7 +139,7 @@ export interface EffectDef {
* Textures the effect brings itself, by sampler uniform: made once per App from the pixels a source group installed and bound unless
* the volume names one. For data an effect is meaningless without (AgX's table), not for a choice an author makes.
*/
- builtinTextures?: Record<string, () => { width: number; height: number; pixels: Uint8Array }>;
+ builtinTextures?: Record<string, () => BuiltinTexture>;
/** Colour params, carried on the volume as `colors`. */
colors?: EffectColorDef[];
multiPass?: EffectSubPass[];
diff --git a/sdk/src/postprocess/index.ts b/sdk/src/postprocess/index.ts
index f0606450c..0adddfeb5 100644
--- a/sdk/src/postprocess/index.ts
+++ b/sdk/src/postprocess/index.ts
@@ -33,6 +33,7 @@ export {
type PostProcessVolumeConfig,
} from './volumeSystem';
export { PostProcessPlugin, postProcessPlugin } from './PostProcessPlugin';
+export { defineSkyEffect, type SkyEffectSource } from './customSky';
export {
registerWeatherPreset,
weatherPresetId,
diff --git a/sdk/src/postprocess/skyEnvironment.ts b/sdk/src/postprocess/skyEnvironment.ts
index 3dc5ee45e..9f6b48bf4 100644
--- a/sdk/src/postprocess/skyEnvironment.ts
+++ b/sdk/src/postprocess/skyEnvironment.ts
@@ -28,6 +28,7 @@ import { TextureContent } from '../wasm';
import type { ESEngineModule } from '../wasm';
import { withScratch } from '../wasm/wasmScratch';
import { log } from '../util/logger';
+import { CUSTOM_SKY_HEIGHT, CUSTOM_SKY_WIDTH, decodeSkyCapture } from './customSky';
/** What the sky is made from: the effect's resolved parameters and the direction toward the sun. */
export interface SkyEnvironmentInput {
@@ -405,6 +406,10 @@ interface BakedSky {
interface SkyEnvironmentCore {
HEAPF32: Float32Array;
+ HEAPU8: Uint8Array;
+ postprocess_requestSkyCapture?(passName: string, width: number, height: number): void;
+ postprocess_pollSkyCapture?(): number;
+ postprocess_takeSkyCapture?(dst: number, bytes: number): boolean;
environment_create?(shPtr: number, specularHandle: number, faceSize: number, mipCount: number, maxRange: number, columns: number): number;
environment_release?(environmentHandle: number): void;
renderer_setSkyEnvironment?(environmentHandle: number): void;
@@ -419,6 +424,7 @@ export class SkyEnvironment {
private key_ = '';
private lastBake_ = -Infinity;
private warned_ = false;
+ private capturing_ = false;
constructor(private readonly minInterval = 1) {}
@@ -446,9 +452,47 @@ export class SkyEnvironment {
if (key === this.key_) return;
// A first sky is made at once; a sky that keeps changing waits its turn.
if (this.baked_ && now - this.lastBake_ < this.minInterval) return;
- const made = bakeSky(module, core, input);
+ const made = bakePanorama(module, core, skyPanorama(input));
if (!made) return;
- core.renderer_setSkyEnvironment(made.environment);
+ this.adopt(core, made, key, now);
+ }
+
+ /**
+ * A sky a project wrote (customSky.ts), lighting the scene from what the GPU drew of it: a panorama of the effect `type`
+ * is asked for, read back over the frames that follow, and made into the environment, once a `minInterval`.
+ */
+ updateCaptured(module: ESEngineModule | null, type: string, now: number): void {
+ const core = module as unknown as SkyEnvironmentCore | null;
+ if (!core?.postprocess_requestSkyCapture || !core.postprocess_pollSkyCapture || !core.postprocess_takeSkyCapture
+ || !core.environment_create || !core.renderer_setSkyEnvironment) {
+ if (!this.warned_) {
+ this.warned_ = true;
+ log.warn('postprocess', 'A custom sky cannot light the scene: this engine build cannot capture it');
+ }
+ return;
+ }
+ if (this.capturing_) {
+ const status = core.postprocess_pollSkyCapture();
+ if (status === 0) return;
+ this.capturing_ = false;
+ if (status !== 1) return;
+ const bytes = CUSTOM_SKY_WIDTH * CUSTOM_SKY_HEIGHT * 4;
+ const pixels = withScratch(core as never, (alloc: (n: number) => number) => {
+ const ptr = alloc(bytes);
+ return core.postprocess_takeSkyCapture!(ptr, bytes) ? core.HEAPU8.slice(ptr, ptr + bytes) : null;
+ });
+ if (!pixels) return;
+ const made = bakePanorama(module, core, decodeSkyCapture(pixels, CUSTOM_SKY_WIDTH, CUSTOM_SKY_HEIGHT));
+ if (made) this.adopt(core, made, `custom:${type}`, now);
+ return;
+ }
+ if (this.baked_ && this.key_ === `custom:${type}` && now - this.lastBake_ < this.minInterval) return;
+ core.postprocess_requestSkyCapture(type, CUSTOM_SKY_WIDTH, CUSTOM_SKY_HEIGHT);
+ this.capturing_ = true;
+ }
+
+ private adopt(core: SkyEnvironmentCore, made: BakedSky, key: string, now: number): void {
+ core.renderer_setSkyEnvironment!(made.environment);
this.drop(core);
this.baked_ = made;
this.key_ = key;
@@ -472,8 +516,8 @@ export class SkyEnvironment {
}
}
-function bakeSky(module: ESEngineModule | null, core: SkyEnvironmentCore, input: SkyEnvironmentInput): BakedSky | null {
- const panorama = skyPanorama(input);
+/** A panorama of radiance made into an environment: its nine irradiance coefficients and its prefiltered reflection. */
+function bakePanorama(module: ESEngineModule | null, core: SkyEnvironmentCore, panorama: Panorama): BakedSky | null {
const irradiance = projectIrradianceSH(panorama);
const atlas = prefilterOctahedral(panorama, SKY_FACE_SIZE, SKY_MIP_COUNT, SKY_MAX_RANGE);
// flipY false: the atlas' rows are a layout (row 0 is mip 0), as the environment loader takes it.
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
index 9bf296998..cac8803e5 100644
--- a/sdk/src/postprocess/volumeSystem.ts
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { isCustomSky } from './customSky';
+import type { BuiltinTexture } from './effects';
import { defineSystem } from '../ecs/system';
import type { App } from '../app/app';
import { EditorView, editorViewEye } from '../camera/EditorView';
@@ -61,7 +63,7 @@ function applyTextures(
}
/** Uploads the pixels of a texture an effect brings itself: set by the plugin, which is the one that knows the App's module. */
-type BuiltinTextureMaker = (pixels: { width: number; height: number; pixels: Uint8Array }) => number;
+type BuiltinTextureMaker = (pixels: BuiltinTexture) => number;
let builtinTextureMaker: BuiltinTextureMaker | null = null;
export function setBuiltinTextureMaker(maker: BuiltinTextureMaker | null): void {
@@ -327,8 +329,11 @@ export function effectsAt(volumes: { data: PostProcessVolumeData; tx: VolumeTran
return blended;
}
-/** The Sky Atmosphere a view resolved this frame, where it asks to light the scene: the game's camera and the editor's eye each. */
-interface ResolvedSkies { game: BlendedEffect | null; editor: BlendedEffect | null }
+/** A sky that lights the scene: Sky Atmosphere, or one a project defined (customSky.ts), and what the volumes resolved for it. */
+export interface LightingSky { type: string; effect: BlendedEffect }
+
+/** The sky a view resolved this frame, where it asks to light the scene: the game's camera and the editor's eye each. */
+interface ResolvedSkies { game: LightingSky | null; editor: LightingSky | null }
const resolvedSkies = new WeakMap<PostProcessAPI, ResolvedSkies>();
function skiesOf(api: PostProcessAPI): ResolvedSkies {
@@ -337,16 +342,19 @@ function skiesOf(api: PostProcessAPI): ResolvedSkies {
return s;
}
-const lightingSky = (effects: ResolvedEffects): BlendedEffect | null => {
- const sky = effects.get('skyAtmosphere');
- return sky?.enabled && (sky.uniforms.get('u_lightScene') ?? 0) > 0.5 ? sky : null;
+const lightingSky = (effects: ResolvedEffects): LightingSky | null => {
+ for (const [type, effect] of effects) {
+ if (type !== 'skyAtmosphere' && !isCustomSky(type)) continue;
+ if (effect.enabled && (effect.uniforms.get('u_lightScene') ?? 0) > 0.5) return { type, effect };
+ }
+ return null;
};
/**
* The Sky Atmosphere that lights the scene this frame, as resolved for the view being drawn: the editor's eye while it looks,
* else the first active game camera's. Null when that view's sky does not ask to light the scene (or there is none).
*/
-export function resolvedLightingSky(api: PostProcessAPI, editorLooking: boolean): BlendedEffect | null {
+export function resolvedLightingSky(api: PostProcessAPI, editorLooking: boolean): LightingSky | null {
const s = skiesOf(api);
return editorLooking ? s.editor : s.game;
}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 868dc0149..fe3b9a439 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -558,6 +558,9 @@ export interface ESEngineModule {
postprocess_addNativePass?(name: string, kind: string): number;
postprocess_setPassScale(name: string, scale: number): void;
postprocess_setPassContinuesEffect(name: string): void;
+ postprocess_requestSkyCapture?(passName: string, width: number, height: number): void;
+ postprocess_pollSkyCapture?(): number;
+ postprocess_takeSkyCapture?(dst: number, bytes: number): boolean;
postprocess_setMsaaSamples(samples: number): void;
postprocess_effectiveMsaaSamples?(): number;
postprocess_maxMsaaSamples?(): number;
diff --git a/sdk/tests/custom-sky.test.ts b/sdk/tests/custom-sky.test.ts
new file mode 100644
index 000000000..bdf822c06
--- /dev/null
+++ b/sdk/tests/custom-sky.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect } from 'vitest';
+import { decodeSkyCapture, skyEffectSource, defineSkyEffect, isCustomSky, CUSTOM_SKY_RANGE } from '../src/postprocess/customSky';
+import { getEffectDef } from '../src/postprocess/effects';
+
+describe('custom sky', () => {
+ it('decodes the RGBM capture and turns the readback\'s bottom-up rows over', () => {
+ // Two rows of one texel: the readback's first row is the panorama's LAST (the ground), its second the zenith.
+ const rgba = new Uint8Array([255, 0, 0, 128, /* bottom */ 0, 0, 255, 255 /* top */]);
+ const p = decodeSkyCapture(rgba, 1, 2);
+ expect(p.rgb[2]).toBeCloseTo(CUSTOM_SKY_RANGE, 3); // zenith first: blue at the full range
+ expect(p.rgb[0]).toBeCloseTo(0);
+ expect(p.rgb[3]).toBeCloseTo(CUSTOM_SKY_RANGE * 128 / 255, 3); // then the ground: red at half
+ });
+
+ it('wraps the author\'s function in both languages, with the capture switch and the coverage marker', () => {
+ const src = skyEffectSource({
+ type: 't', label: 'T',
+ uniforms: [{ name: 'u_glow', label: 'Glow', min: 0, max: 2, step: 0.1, defaultValue: 1 }],
+ textures: { tNoise: () => ({ width: 1, height: 1, pixels: new Uint8Array(4), wrap: 'repeat' }) },
+ glsl: 'vec3 skyRadiance(vec3 d, vec3 s, vec3 c, float e) { return vec3(u_glow); }',
+ wgsl: 'fn skyRadiance(d : vec3f, s : vec3f, c : vec3f, e : f32) -> vec3f { return vec3f(mc.u_glow); }',
+ });
+ for (const line of ['#pragma domain PostProcess', '#pragma lights', '#pragma param u_skyCapture', '#pragma param u_sceneCoverage',
+ '#pragma param u_glow float default(1) range(0,2)', '#pragma param tNoise texture', '#pragma fragment wgsl']) {
+ expect(src).toContain(line);
+ }
+ expect(src.match(/skyRadiance\(/g)!.length).toBeGreaterThanOrEqual(6);
+ });
+
+ it('registers an effect that can light the scene', () => {
+ defineSkyEffect({ type: 'unitSky', label: 'Unit Sky', glsl: '', wgsl: '' });
+ expect(isCustomSky('unitSky')).toBe(true);
+ expect(isCustomSky('skyAtmosphere')).toBe(false);
+ const names = getEffectDef('unitSky')!.uniforms.map((u) => u.name);
+ expect(names).toEqual(expect.arrayContaining(['u_intensity', 'u_lightScene']));
+ });
+});
diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cpp
index 2561e0edd..f08c1231f 100644
--- a/src/esengine/bindings/PostProcessBindings.cpp
+++ b/src/esengine/bindings/PostProcessBindings.cpp
@@ -15,6 +15,7 @@
#include "../ecs/TransformSystem.hpp"
#include <glm/glm.hpp>
+#include <cstring>
namespace esengine {
@@ -128,6 +129,22 @@ void postprocess_setPassScale(const std::string& passName, f32 scale) {
}
}
+void postprocess_requestSkyCapture(const std::string& passName, u32 width, u32 height) {
+ if (g_postProcessPipeline) g_postProcessPipeline->requestSkyCapture(passName, width, height);
+}
+
+i32 postprocess_pollSkyCapture() {
+ return g_postProcessPipeline ? g_postProcessPipeline->pollSkyCapture() : 2;
+}
+
+bool postprocess_takeSkyCapture(uintptr_t dst, u32 bytes) {
+ if (!g_postProcessPipeline || dst == 0) return false;
+ const std::vector<u8>& px = g_postProcessPipeline->skyCapturePixels();
+ if (px.empty() || px.size() > bytes) return false;
+ std::memcpy(reinterpret_cast<void*>(dst), px.data(), px.size());
+ return true;
+}
+
void postprocess_setPassContinuesEffect(const std::string& passName) {
if (g_postProcessPipeline) {
g_postProcessPipeline->setPassContinuesEffect(passName);
diff --git a/src/esengine/bindings/PostProcessBindings.hpp b/src/esengine/bindings/PostProcessBindings.hpp
index 5304a5d16..7fb2d5e5f 100644
--- a/src/esengine/bindings/PostProcessBindings.hpp
+++ b/src/esengine/bindings/PostProcessBindings.hpp
@@ -53,6 +53,12 @@ std::string postprocess_hdrFormatNames();
void postprocess_setPassScale(const std::string& passName, f32 scale);
/** A later pass of a multi-pass effect: it composites over that effect's input. */
void postprocess_setPassContinuesEffect(const std::string& passName);
+/** Draw @p passName once more next frame into a width x height RGBA8 panorama, its `u_skyCapture` param at 1. */
+void postprocess_requestSkyCapture(const std::string& passName, u32 width, u32 height);
+/** 0 = not yet, 1 = ready to take, 2 = nothing asked for or it failed. Call between frames. */
+i32 postprocess_pollSkyCapture();
+/** Copies the ready capture (RGBA8, rows bottom-up) to @p dst; false when it does not fit @p bytes or is not ready. */
+bool postprocess_takeSkyCapture(uintptr_t dst, u32 bytes);
void postprocess_setUniformFloat(const std::string& passName,
const std::string& uniform, f32 value);
void postprocess_setPassTexture(const std::string& passName,
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index a028409f4..0377e27b1 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -609,6 +609,9 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("postprocess_addNativePass", &esengine::postprocess_addNativePass);
emscripten::function("postprocess_setPassScale", &esengine::postprocess_setPassScale);
emscripten::function("postprocess_setPassContinuesEffect", &esengine::postprocess_setPassContinuesEffect);
+ emscripten::function("postprocess_requestSkyCapture", &esengine::postprocess_requestSkyCapture);
+ emscripten::function("postprocess_pollSkyCapture", &esengine::postprocess_pollSkyCapture);
+ emscripten::function("postprocess_takeSkyCapture", &esengine::postprocess_takeSkyCapture);
emscripten::function("postprocess_setMsaaSamples", &esengine::postprocess_setMsaaSamples);
emscripten::function("postprocess_effectiveMsaaSamples", &esengine::postprocess_effectiveMsaaSamples);
emscripten::function("postprocess_maxMsaaSamples", &esengine::postprocess_maxMsaaSamples);
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index 73f815191..2a525a9a5 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -207,6 +207,9 @@ void PostProcessPipeline::shutdown() {
for (auto& pass : passes_) releasePassResources(pass);
for (auto& pass : screenPasses_) releasePassResources(pass);
+ releasePassResources(sky_capture_.copy);
+ sky_capture_.target.reset();
+ sky_capture_.state = SkyCapture::State::Idle;
for (auto& [source, program] : compute_cache_) device_.deleteCompute(program);
compute_cache_.clear();
voxel_gis_.clear();
@@ -629,6 +632,75 @@ PostProcessPipeline::TemporalState* PostProcessPipeline::prepareHistory(Temporal
return &state;
}
+void PostProcessPipeline::requestSkyCapture(const std::string& passName, u32 width, u32 height) {
+ sky_capture_.pass = passName;
+ sky_capture_.width = std::clamp(width, 4u, 512u);
+ sky_capture_.height = std::clamp(height, 2u, 256u);
+ sky_capture_.state = SkyCapture::State::Requested;
+ sky_capture_.readback = ReadbackHandle::Invalid;
+}
+
+i32 PostProcessPipeline::pollSkyCapture() {
+ SkyCapture& c = sky_capture_;
+ switch (c.state) {
+ case SkyCapture::State::Idle: return 2;
+ case SkyCapture::State::Requested: return 0;
+ case SkyCapture::State::Drawn:
+ c.readback = c.target ? device_.requestReadback(c.target->handle(), c.width, c.height) : ReadbackHandle::Invalid;
+ if (c.readback == ReadbackHandle::Invalid) { c.state = SkyCapture::State::Idle; return 2; }
+ c.state = SkyCapture::State::Reading;
+ [[fallthrough]];
+ case SkyCapture::State::Reading: {
+ const GfxReadbackStatus status = device_.pollReadback(c.readback);
+ if (status == GfxReadbackStatus::Pending) return 0;
+ c.state = SkyCapture::State::Idle;
+ if (status != GfxReadbackStatus::Ready) return 2;
+ c.pixels.resize(static_cast<usize>(c.width) * c.height * 4);
+ return device_.takeReadback(c.readback, c.pixels.data(), c.pixels.size()) ? 1 : 2;
+ }
+ }
+ return 2;
+}
+
+void PostProcessPipeline::declareSkyCapture(const PostProcessPass& pass, rg::ResourceId input, rg::ResourceId effectInput) {
+ SkyCapture& c = sky_capture_;
+ if (!c.target || c.target->getSpecification().width != c.width || c.target->getSpecification().height != c.height) {
+ FramebufferSpec spec;
+ spec.colorFormat = GfxPixelFormat::RGBA8;
+ spec.width = c.width;
+ spec.height = c.height;
+ spec.depthStencil = false;
+ spec.linearFilter = true;
+ c.target = Framebuffer::create(device_, spec);
+ if (!c.target) {
+ ES_LOG_ERROR("PostProcessPipeline: could not make the sky capture target");
+ c.state = SkyCapture::State::Idle;
+ return;
+ }
+ }
+ // The pass's shader and settings, its own parameter buffer kept.
+ const BufferHandle ubo = c.copy.paramUbo;
+ c.copy = pass;
+ c.copy.paramUbo = ubo;
+ c.copy.name = pass.name + "_skyCapture";
+ c.copy.temporal = false;
+ c.copy.feedback = false;
+ c.copy.earlierInputs.clear();
+ c.copy.floatUniforms["u_skyCapture"] = 1.0f;
+ c.copy.paramDirty = true;
+
+ rg::PassDesc node;
+ node.name = c.copy.name;
+ node.reads = {input, effectInput};
+ node.keep = true;
+ node.write = graph_->importTarget(c.target->handle(), c.width, c.height, /*output=*/false, c.target->getColorAttachment());
+ node.execute = [this](const rg::PassContext& ctx) {
+ renderPass(sky_capture_.copy, ctx);
+ sky_capture_.state = SkyCapture::State::Drawn;
+ };
+ graph_->addPass(std::move(node));
+}
+
void PostProcessPipeline::releasePassResources(PostProcessPass& pass) {
if (pass.paramUbo != BufferHandle::Invalid) {
device_.deleteBuffer(pass.paramUbo);
@@ -1285,6 +1357,9 @@ void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, rg::Res
graph_->addPass(std::move(node));
continue;
}
+ if (sky_capture_.state == SkyCapture::State::Requested && pass.name == sky_capture_.pass && &passes == &passes_) {
+ declareSkyCapture(pass, input, effectInput);
+ }
// A temporal pass writes the history target itself, so that what it wrote is
// still there next frame, and the passes after it read it from there.
TemporalState* temporal = nullptr;
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hpp
index 949e24be8..230e4a018 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp
@@ -598,8 +598,24 @@ public:
* land HERE — rebinding the default target mid-capture breaks the stack. */
FramebufferHandle currentSceneFBO() const;
+ /**
+ * @brief Draws pass @p passName once more, next frame, into a @p width x @p height RGBA8 target with its float param
+ * `u_skyCapture` at 1, and reads it back: a sky effect's panorama (see the SDK's defineSkyEffect).
+ * @details The pass is drawn from a copy with a parameter buffer of its own — the same buffer written twice in one
+ * frame is one write on WebGPU. A request while one is in flight replaces it.
+ */
+ void requestSkyCapture(const std::string& passName, u32 width, u32 height);
+ /** @brief 0 = not yet, 1 = the pixels are ready (skyCapturePixels), 2 = none was asked for or it failed. Issues the
+ * readback itself once the capture has been drawn, so call it between frames, never inside one. */
+ i32 pollSkyCapture();
+ /** @brief The captured pixels, RGBA8, rows bottom-up as every readback lands. Valid after poll answered 1. */
+ const std::vector<u8>& skyCapturePixels() const { return sky_capture_.pixels; }
+
private:
PostProcessPass* findPass(const std::string& name);
+ /// The capture's node: the copy of @p pass drawn into the capture target. Declared in the chain so it runs with the
+ /// frame's light and time bound, as the pass itself does.
+ void declareSkyCapture(const PostProcessPass& pass, rg::ResourceId input, rg::ResourceId effectInput);
/** Intermediate/capture attachment format for the active pipeline mode. */
GfxPixelFormat interFormat() const;
void commitFormat();
@@ -730,6 +746,19 @@ private:
/// The motion pass's target, kept across frames for its size, and whether this frame drew into it.
Unique<Framebuffer> cover_fbo_;
rg::ResourceId cover_resource_ = rg::kNoResource;
+ /// A sky's panorama, drawn on request from a copy of its pass and read back (requestSkyCapture).
+ struct SkyCapture {
+ enum class State : u8 { Idle, Requested, Drawn, Reading };
+ State state = State::Idle;
+ std::string pass;
+ u32 width = 64;
+ u32 height = 32;
+ Unique<Framebuffer> target;
+ PostProcessPass copy;
+ ReadbackHandle readback = ReadbackHandle::Invalid;
+ std::vector<u8> pixels;
+ };
+ SkyCapture sky_capture_;
bool cover_active_ = false;
glm::mat4 cover_matrix_{1.0f};
Unique<Framebuffer> velocity_fbo_;
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index a3c57b5d9..228c81e5e 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -1111,8 +1111,9 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
// Per pixel where the program can read the atlas: a mesh with lightmap UVs is compiled with
// the bake's sampler on that unit, so it keeps the one value its position reads.
const ProbeStore& store = ctx.render_context.probes();
+ // By the mesh's world box, not its origin: an imported level's origins are wherever the file put them.
const bool volume = key.lightmapTextureId == 0
- && store.sample(position, probe, !resident->hasLightmapUV);
+ && store.sampleBox(aabbCenter, halfExtents, probe, !resident->hasLightmapUV);
if (volume && probe.irradiance[0].w > 1.5f) key.probeGridTextureId = store.atlasTexture();
const u32 slot = ctx.render_context.reflections().slotAt(position);
probe.reflection.x = static_cast<f32>(slot);
diff --git a/src/esengine/renderer/store/ProbeStore.hpp b/src/esengine/renderer/store/ProbeStore.hpp
index a4f5c812d..c0ac8511d 100644
--- a/src/esengine/renderer/store/ProbeStore.hpp
+++ b/src/esengine/renderer/store/ProbeStore.hpp
@@ -126,6 +126,29 @@ public:
return true;
}
+ /**
+ * @brief The volume a whole object stands in, by its world box rather than its origin.
+ * @details An imported level's meshes keep their origin where the file put it — often the world's origin, far from
+ * the walls they draw — so asking at the origin leaves a shed's walls in no volume at all. The box's centre
+ * is asked first; a box whose centre is in none reads the smallest volume it overlaps, at the point of that
+ * volume nearest its centre. Per pixel, every pixel then reads the grid where it stands anyway.
+ */
+ bool sampleBox(const glm::vec3& centre, const glm::vec3& half, ProbeConstants& out, bool perPixel = false) const {
+ if (sample(centre, out, perPixel)) return true;
+ const Volume* best = nullptr;
+ f32 bestSize = 0.0f;
+ for (const Volume& v : volumes_) {
+ const glm::vec3 vc = (v.min + v.max) * 0.5f;
+ const glm::vec3 vh = (v.max - v.min) * 0.5f;
+ const glm::vec3 gap = glm::abs(centre - vc) - (half + vh);
+ if (gap.x > 0.0f || gap.y > 0.0f || gap.z > 0.0f) continue;
+ const f32 size = vh.x * vh.y * vh.z;
+ if (!best || size < bestSize) { best = &v; bestSize = size; }
+ }
+ if (!best) return false;
+ return sample(glm::clamp(centre, best->min, best->max), out, perPixel);
+ }
+
/**
* @brief Places every volume's grid in the atlas. True when the atlas's texels changed and want uploading.
*
diff --git a/tests/renderer/test_probe_store.cpp b/tests/renderer/test_probe_store.cpp
index 2e51ad1c3..ce9784b92 100644
--- a/tests/renderer/test_probe_store.cpp
+++ b/tests/renderer/test_probe_store.cpp
@@ -179,6 +179,24 @@ static void testGridRun() {
"a draw that cannot read the atlas still gets its nine");
}
+/** An object is held by the volume its box is in, not the one its origin is in: a level's mesh whose origin is the
+ * world's centre still reads the room it draws. The centre wins when it is inside; otherwise the smallest overlap. */
+static void testSampleByBox() {
+ ProbeVolume room = ramp({1, 1, 1}, {3.0f, 0.0f, 0.0f}, {3.0f, 0.0f, 0.0f});
+ ProbeVolume hall = ramp({1, 1, 1}, {7.0f, 0.0f, 0.0f}, {7.0f, 0.0f, 0.0f});
+ ProbeStore store;
+ store.add({10.0f, 0.0f, 10.0f}, {20.0f, 5.0f, 20.0f}, &room);
+ store.add({0.0f, 0.0f, 0.0f}, {40.0f, 10.0f, 40.0f}, &hall);
+
+ ProbeConstants out{};
+ CHECK(!store.sample({-5.0f, 0.0f, -5.0f}, out), "the origin is in no volume");
+ CHECK(store.sampleBox({15.0f, 2.0f, 15.0f}, {20.0f, 3.0f, 20.0f}, out) && near(out.irradiance[0].x, 3.0f),
+ "a box whose centre is in the room reads the room");
+ CHECK(store.sampleBox({-2.0f, 2.0f, -2.0f}, {4.0f, 3.0f, 4.0f}, out) && near(out.irradiance[0].x, 7.0f),
+ "a box whose centre is outside reads the volume it overlaps");
+ CHECK(!store.sampleBox({-50.0f, 0.0f, -50.0f}, {1.0f, 1.0f, 1.0f}, out), "and one touching nothing reads nothing");
+}
+
int main() {
testInsideAndOutside();
testTrilinearOnEachAxis();
@@ -186,6 +204,7 @@ int main() {
testMalformedGridsRefused();
testAtlasLayout();
testGridRun();
+ testSampleByBox();
std::printf(g_failures ? "\n%d failure(s)\n" : "\nall probe store claims hold\n",
g_failures);
return g_failures ? 1 : 0;
diff --git a/tools/render-host/host.ts b/tools/render-host/host.ts
index 15f13baee..83a8d1195 100644
--- a/tools/render-host/host.ts
+++ b/tools/render-host/host.ts
@@ -28,7 +28,7 @@ import {
planarReflectionStatus,
EditorViewLighting, EditorViewShading, EditorView, EditorGrid, installEditorGrid, editorViewHalfHeight, setEditorViewHalfHeight,
ProfileRecorder, AnimatorController, Timeline, onDeviceRestored, Schedule, defineSystem,
- textureImportSettingsFrom, shadersCompiled,
+ textureImportSettingsFrom, shadersCompiled, defineSkyEffect,
} from 'esengine';
import type { App, SceneData, SceneEntityData, PrefabData, RenderSurfaceSource } from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
@@ -81,6 +81,19 @@ function editorOnly(door: string): never {
);
}
+// The host's own sky, for the custom-sky gate: blue above the horizon and red below, so which half lit a surface reads
+// off its colour and a panorama read upside down swaps them.
+defineSkyEffect({
+ type: 'verifySky',
+ label: 'Verify Sky',
+ glsl: `vec3 skyRadiance(vec3 dir, vec3 sun, vec3 sunColor, float env) {
+ return dir.y >= 0.0 ? vec3(0.1, 0.2, 0.9) : vec3(0.8, 0.15, 0.05);
+}`,
+ wgsl: `fn skyRadiance(dir : vec3f, sun : vec3f, sunColor : vec3f, env : f32) -> vec3f {
+ return select(vec3f(0.8, 0.15, 0.05), vec3f(0.1, 0.2, 0.9), dir.y >= 0.0);
+}`,
+});
+
async function boot(): Promise<void> {
canvas = document.createElement('canvas');
canvas.id = 'canvas';
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 4a513ca90..f4c267ed7 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -285,6 +285,10 @@ export const SCENES = [
// pixel (the grid through the frame's probe atlas) its left end is red and its right blue, as a merged building
// spanning a shed and the yard is dark under the roof and lit outside.
{ id: "probe-per-pixel", tier: "pr", webgpu: true, env: { "ESTELLA_VERIFY_SCENE": "/scenes/probe-per-pixel.esscene", "ESTELLA_VERIFY_MANIFEST": "/scenes/probe-per-pixel.textures.json", "ESTELLA_VERIFY_W": "256", "ESTELLA_VERIFY_H": "256", "ESTELLA_VERIFY_STEPS": "2", "ESTELLA_VERIFY_EXPECT": "[{\"x\":0.36,\"y\":0.5,\"rgb\":[213,0,38],\"tol\":20},{\"x\":0.625,\"y\":0.5,\"rgb\":[43,0,193],\"tol\":20}]" } },
+ // The same box, and a mesh whose ORIGIN is outside it (x -200) while its right end draws inside: an imported level's
+ // walls keep the origin the file gave them. Chosen by its origin it is in no volume and black; by its box it reads the
+ // grid where each pixel stands.
+ { id: "probe-off-origin", tier: "pr", webgpu: true, env: { "ESTELLA_VERIFY_SCENE": "/scenes/probe-off-origin.esscene", "ESTELLA_VERIFY_MANIFEST": "/scenes/probe-off-origin.textures.json", "ESTELLA_VERIFY_W": "256", "ESTELLA_VERIFY_H": "256", "ESTELLA_VERIFY_STEPS": "2", "ESTELLA_VERIFY_EXPECT": "[{\"x\":0.353,\"y\":0.508,\"rgb\":[205,0,31],\"tol\":20},{\"x\":0.432,\"y\":0.508,\"rgb\":[158,0,77],\"tol\":20}]" } },
{ id: "probe-lightmap", tier: "pr", webgpu: true, env: { "ESTELLA_VERIFY_SCENE": "/scenes/probe-lightmap.esscene", "ESTELLA_VERIFY_MANIFEST": "/scenes/probe-lightmap.textures.json", "ESTELLA_VERIFY_W": "256", "ESTELLA_VERIFY_H": "256", "ESTELLA_VERIFY_STEPS": "2", "ESTELLA_VERIFY_EXPECT": "[{\"x\":0.25,\"y\":0.5667,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.85,\"y\":0.5,\"rgb\":[0,0,255],\"tol\":30}]" } },
// A clip driving the weight, which is what an imported `weights` channel
// becomes. The shape has to cross the boundary as a LIST — a weight written
@@ -910,6 +914,10 @@ export const SCENES = [
// sky with the sun up behind it. The sky lights it as an environment: the blue of the dome above it and, below, the sunlit ground's
// bounce (Ground Albedo 0.2), which lifts it and warms it a little; off, it is the flat white 255.
{ id: "sky-lights-scene", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_SCENE: "/scenes/sky-lights-scene.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "6", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[142,150,150],\"tol\":12}]" } },
+ // A sky the project wrote (defineSkyEffect): blue above the horizon, red below. It is drawn behind the ball, and with Light
+ // the Scene the engine reads back a panorama of it and lights the ball with it: blue on top, red underneath. Upside
+ // down, the two swap; never captured, the ball is the Ambient light's flat white.
+ { id: "custom-sky", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SETTLE_MS: "1500", ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_SCENE: "/scenes/custom-sky.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.08,\"y\":0.08,\"rgb\":[89,124,243],\"tol\":10},{\"x\":0.08,\"y\":0.92,\"rgb\":[231,108,63],\"tol\":10},{\"x\":0.5,\"y\":0.32,\"rgb\":[127,121,226],\"tol\":20},{\"x\":0.5,\"y\":0.68,\"rgb\":[217,111,118],\"tol\":20}]" } },
{ id: "sky-fog", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/sky-fog.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/depth-outline.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.2, \"y\": 0.1, \"rgb\": [144, 175, 187], \"tol\": 12}, {\"x\": 0.5, \"y\": 0.1, \"rgb\": [141, 174, 183], \"tol\": 12}, {\"x\": 0.8, \"y\": 0.2, \"rgb\": [143, 174, 186], \"tol\": 12}, {\"x\": 0.5, \"y\": 0.4, \"rgb\": [139, 171, 180], \"tol\": 12}, {\"x\": 0.2, \"y\": 0.8, \"rgb\": [62, 70, 70], \"tol\": 12}, {\"x\": 0.8, \"y\": 0.8, \"rgb\": [57, 64, 67], \"tol\": 12}]" } },
// SSAO: one unlit grey floor read at seven places. Contact, corner and
// step come back darker than the open floor they are made of, the floating