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): the sky is drawn from the panorama it was imported from

esenginee788dbe1246c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c95f13f5c..83ece05b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,7 @@ published separately; it ships inside the editor.
### Fixed
+- **A drawn sky is the panorama you imported, not a blur of it.** The sky was drawn from the environment's reflection atlas — the whole sphere in 128 texels a side, laid out so a straight horizon became a staircase and a round sun an oval, and filtered in its encoded form, which blotted every sharp edge. Importing a `.hdr` now also writes the panorama at its own resolution (up to 2048 wide; `skyWidth` in the import settings, 0 for none), the sky is drawn from it, and a package carries it. Environments imported before draw their sky from the atlas as they did. The `lighting-3d` example draws its sky, from a panorama generated at 1024×512.
- **A drawn sky no longer vanishes, or half-vanishes, as the view turns.** The sky was a quad on the far plane, and where rounding put it a hair past that plane it was clipped: in the editor, with its distant far plane, more than half the angles showed black behind the grid, or a sky cut along a diagonal. It now sits inside the view volume and fills the frame from every angle, in the editor and in the game.
- **With more than one camera, the profiler and the draw-call count cover the whole frame.** Each camera reset the frame's tally and closed the profiler's frame, so a split screen, or a scene with a UI camera, reported only the last camera's draw calls, triangles, merge counts and C++ timings, and the batch-break reasons of the others were lost. The frame now counts every camera and the screen overlay, once, and an asset preview rendered in between counts toward none of them.
- **A game started right after the project opened no longer restarts itself about ten seconds in.** Pressing Play while the editor was still warming the game's engine up handed the scene over twice: once when the engine greeted the editor, and again when the warm-up's ten-second wait ran out — so the game restarted, and everything that had happened in it was gone. It now starts once, as soon as the engine is up.
diff --git a/desktop b/desktop
index 70e68fe54..6d8df1923 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 70e68fe5448547170e05435d2e81607408db5ff3
+Subproject commit 6d8df19235fecd3643b316f284ff938b9e0200b8
diff --git a/examples/lighting-3d/assets/env/sky.esenv b/examples/lighting-3d/assets/env/sky.esenv
index 25c1a36c6..4b7dcc8f7 100644
--- a/examples/lighting-3d/assets/env/sky.esenv
+++ b/examples/lighting-3d/assets/env/sky.esenv
@@ -1,36 +1,37 @@
{
"version": 1,
"irradiance": [
- 2.0511929988861084,
- 2.072725534439087,
- 2.286590814590454,
- 0.665151059627533,
- 0.7634183764457703,
- 1.0356460809707642,
- 0.31100958585739136,
- 0.28894010186195374,
- 0.24245516955852509,
- 0.3600952625274658,
- 0.3345319926738739,
- 0.280729204416275,
- 0.22621849179267883,
- 0.21016038954257965,
- 0.17636042833328247,
- 0.19538240134716034,
- 0.1815185546875,
- 0.15231551229953766,
- -0.03863278776407242,
- -0.04841402918100357,
- -0.06949380785226822,
- 0.12712392210960388,
- 0.11810252815485,
- 0.0991038829088211,
- -0.029520845040678978,
- -0.049125563353300095,
- -0.09120915085077286
+ 1.9948318004608154,
+ 2.021829605102539,
+ 2.2553813457489014,
+ 0.6504198908805847,
+ 0.7454109787940979,
+ 1.0267984867095947,
+ 0.3032611310482025,
+ 0.2814396321773529,
+ 0.2426409274339676,
+ 0.348867803812027,
+ 0.3237597644329071,
+ 0.27912864089012146,
+ 0.2204694151878357,
+ 0.20459811389446259,
+ 0.1763657182455063,
+ 0.19164758920669556,
+ 0.17785480618476868,
+ 0.153310626745224,
+ -0.0379367433488369,
+ -0.04696005582809448,
+ -0.068850576877594,
+ 0.12576553225517273,
+ 0.11670052260160446,
+ 0.10056661069393158,
+ -0.03035384602844715,
+ -0.048511214554309845,
+ -0.09097834676504135
],
"specular": "sky_env.png",
"faceSize": 128,
"mipCount": 5,
- "maxRange": 8
+ "maxRange": 8,
+ "sky": "sky_sky.png"
}
diff --git a/examples/lighting-3d/assets/env/sky.hdr b/examples/lighting-3d/assets/env/sky.hdr
index f22c2e37a..3754feb86 100644
Binary files a/examples/lighting-3d/assets/env/sky.hdr and b/examples/lighting-3d/assets/env/sky.hdr differ
diff --git a/examples/lighting-3d/assets/env/sky_env.png b/examples/lighting-3d/assets/env/sky_env.png
index 302525dc4..65c756c5f 100644
Binary files a/examples/lighting-3d/assets/env/sky_env.png and b/examples/lighting-3d/assets/env/sky_env.png differ
diff --git a/examples/lighting-3d/assets/env/sky_sky.png b/examples/lighting-3d/assets/env/sky_sky.png
new file mode 100644
index 000000000..533d19445
Binary files /dev/null and b/examples/lighting-3d/assets/env/sky_sky.png differ
diff --git a/examples/lighting-3d/assets/env/sky_sky.png.meta b/examples/lighting-3d/assets/env/sky_sky.png.meta
new file mode 100644
index 000000000..420d3e2f2
--- /dev/null
+++ b/examples/lighting-3d/assets/env/sky_sky.png.meta
@@ -0,0 +1,25 @@
+{
+ "uuid": "bee9fe11-9eb9-4c9b-afc6-80f3dc481118",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {
+ "maxSize": 2048,
+ "compress": false,
+ "compressFormat": "uastc",
+ "filterMode": "linear",
+ "wrapMode": "clamp",
+ "sRGB": false,
+ "sliceBorder": {
+ "left": 0,
+ "right": 0,
+ "top": 0,
+ "bottom": 0
+ },
+ "sheet": {
+ "cellWidth": 0,
+ "cellHeight": 0,
+ "margin": 0,
+ "spacing": 0
+ }
+ }
+}
diff --git a/examples/lighting-3d/assets/scenes/main.esscene b/examples/lighting-3d/assets/scenes/main.esscene
index b849a4f2c..f74710e1a 100644
--- a/examples/lighting-3d/assets/scenes/main.esscene
+++ b/examples/lighting-3d/assets/scenes/main.esscene
@@ -99,7 +99,8 @@
},
"intensity": 0.55,
"enabled": true,
- "environment": "assets/env/sky.esenv"
+ "environment": "assets/env/sky.esenv",
+ "drawEnvironment": true
}
}
]
diff --git a/examples/lighting-3d/tools/generate-sky.mjs b/examples/lighting-3d/tools/generate-sky.mjs
new file mode 100644
index 000000000..d08f215da
--- /dev/null
+++ b/examples/lighting-3d/tools/generate-sky.mjs
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The example's sky, written rather than photographed: a Radiance `.hdr`
+ * panorama of a clear day — a blue zenith, a warm horizon, the ground
+ * below, and a sun. It is looked at directly as well as lit by, so it is
+ * written at a resolution a viewport can magnify.
+ *
+ * node examples/lighting-3d/tools/generate-sky.mjs [width]
+ */
+import { writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const WIDTH = Number(process.argv[2]) || 1024;
+const HEIGHT = WIDTH / 2;
+const OUT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'env', 'sky.hdr');
+
+const ZENITH = [0.30, 0.45, 0.85];
+const HORIZON = [0.83, 0.74, 0.61];
+const GROUND = [0.39, 0.355, 0.30];
+const NADIR = [0.23, 0.21, 0.18];
+// As bright as it has to be for the irradiance the scene is lit by: a small disc
+// carries its light in radiance, and the screen clips it to white either way.
+const SUN = { elevation: 49, azimuth: 49, radius: 2.5, radiance: [357, 331, 283] };
+
+const mix = (a, b, t) => a.map((v, i) => v + (b[i] - v) * t);
+
+/** Radiance toward a direction, as the importer reads one: +Z at the centre, row 0 up. */
+function radiance(dx, dy, dz) {
+ const elevation = Math.asin(Math.max(-1, Math.min(1, dy))) * 180 / Math.PI;
+ let c = elevation >= 0
+ ? mix(ZENITH, HORIZON, (1 - elevation / 90) ** 3.2)
+ : mix(GROUND, NADIR, (-elevation / 90) ** 0.5);
+ const se = SUN.elevation * Math.PI / 180, sa = SUN.azimuth * Math.PI / 180;
+ const sun = [Math.sin(sa) * Math.cos(se), Math.sin(se), Math.cos(sa) * Math.cos(se)];
+ const angle = Math.acos(Math.max(-1, Math.min(1, dx * sun[0] + dy * sun[1] + dz * sun[2]))) * 180 / Math.PI;
+ // A disc with a soft limb, then a glow that fades over a few degrees.
+ const disc = Math.max(0, Math.min(1, (SUN.radius + 0.5 - angle) / 1.0));
+ const glow = Math.exp(-angle / 6) * 0.35;
+ c = c.map((v, i) => v + SUN.radiance[i] * disc + v * glow);
+ return c;
+}
+
+function rgbe([r, g, b]) {
+ const m = Math.max(r, g, b);
+ if (m < 1e-32) return [0, 0, 0, 0];
+ const e = Math.ceil(Math.log2(m) + 1e-9);
+ const scale = 256 / 2 ** e;
+ return [Math.min(255, Math.floor(r * scale)), Math.min(255, Math.floor(g * scale)),
+ Math.min(255, Math.floor(b * scale)), e + 128];
+}
+
+/** One scanline in the adaptive-RLE encoding: each channel apart, runs where they repeat. */
+function encodeScanline(pixels) {
+ const out = [2, 2, (WIDTH >> 8) & 0xff, WIDTH & 0xff];
+ for (let c = 0; c < 4; c++) {
+ const ch = pixels.map((p) => p[c]);
+ let i = 0;
+ while (i < WIDTH) {
+ let run = 1;
+ while (i + run < WIDTH && run < 127 && ch[i + run] === ch[i]) run++;
+ if (run >= 4) {
+ out.push(128 + run, ch[i]);
+ i += run;
+ continue;
+ }
+ let lit = 0;
+ while (i + lit < WIDTH && lit < 128) {
+ const j = i + lit;
+ if (j + 3 < WIDTH && ch[j] === ch[j + 1] && ch[j] === ch[j + 2] && ch[j] === ch[j + 3]) break;
+ lit++;
+ }
+ out.push(lit, ...ch.slice(i, i + lit));
+ i += lit;
+ }
+ }
+ return out;
+}
+
+const header = `#?RADIANCE\n# generated for estella examples/lighting-3d (tools/generate-sky.mjs)\nFORMAT=32-bit_rle_rgbe\n\n-Y ${HEIGHT} +X ${WIDTH}\n`;
+const body = [];
+for (let y = 0; y < HEIGHT; y++) {
+ const theta = (y + 0.5) / HEIGHT * Math.PI;
+ const row = [];
+ for (let x = 0; x < WIDTH; x++) {
+ const phi = ((x + 0.5) / WIDTH - 0.5) * 2 * Math.PI;
+ row.push(rgbe(radiance(Math.sin(phi) * Math.sin(theta), Math.cos(theta), Math.cos(phi) * Math.sin(theta))));
+ }
+ body.push(...encodeScanline(row));
+}
+writeFileSync(OUT, Buffer.concat([Buffer.from(header, 'ascii'), Buffer.from(body)]));
+console.log(`${path.relative(process.cwd(), OUT)}: ${WIDTH}x${HEIGHT}`);
diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjs
index e1af55c0c..18fe7c032 100644
--- a/pipeline/bin/estella.mjs
+++ b/pipeline/bin/estella.mjs
@@ -717,11 +717,15 @@ if (opts.command === 'import-hdr') {
const atlasFile = path.join(dir, result.atlasName);
writeFileSync(atlasFile, result.atlasBytes);
- // An RGBM encoding of radiance, not a picture: sRGB would linearize what is
- // already linear, and a block compressor would quantize the shared multiplier
- // along with the colour it scales.
- await meta.adoptOrphan(atlasFile, { sRGB: false, compress: false, wrapMode: 'clamp' });
+ await meta.adoptOrphan(atlasFile, { ...importer.ENV_IMAGE_SETTINGS });
report(atlasFile, `${result.document.mipCount} prefiltered mips`);
+ if (result.sky) {
+ const skyFile = path.join(dir, result.sky.name);
+ writeFileSync(skyFile, result.sky.bytes);
+ await meta.adoptOrphan(skyFile, { ...importer.ENV_IMAGE_SETTINGS });
+ result.document.sky = result.sky.name;
+ report(skyFile, 'the sky, at the panorama\'s resolution');
+ }
// Beside the document, the way an imported material names its images.
result.document.specular = result.atlasName;
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.ts
index 2c63fd489..9738c93dd 100644
--- a/pipeline/src/assets/cookAssets.ts
+++ b/pipeline/src/assets/cookAssets.ts
@@ -17,6 +17,7 @@
* native), texture atlasing, and the full web-build (html + runtime + scripts).
* This is the reachability + manifest + staging core they all build on.
*/
+import { ENV_IMAGE_FIELDS } from './environmentFormat';
import { writeFile, mkdir, readFile } from 'node:fs/promises';
import { statSync } from 'node:fs';
import { isInsideRoot } from '../fs/pathSandbox';
@@ -329,9 +330,9 @@ function rewriteAnimatorRefs(
}
/**
- * A baked environment names its reflection atlas as a SIBLING file, which staging
- * moves out from under it — the runtime then asks for `assets/sky_env.png` and gets
- * a 404, and the frame silently loses every reflection the game was lit for.
+ * A baked environment names its images as SIBLING files, which staging moves out
+ * from under it — the runtime then asks for `assets/sky_env.png` and gets a 404,
+ * and the frame silently loses every reflection, or the sky, the game was made with.
*/
function rewriteEnvironmentRefs(
bytes: Uint8Array,
@@ -339,7 +340,9 @@ function rewriteEnvironmentRefs(
byPath: Map<string, AssetEntry>,
): Uint8Array {
const json = JSON.parse(Buffer.from(bytes).toString('utf8')) as Record<string, unknown>;
- if (typeof json.specular === 'string') json.specular = logicalRef(json.specular, envPath, byPath);
+ for (const field of ENV_IMAGE_FIELDS) {
+ if (typeof json[field] === 'string') json[field] = logicalRef(json[field], envPath, byPath);
+ }
return new TextEncoder().encode(JSON.stringify(json, null, 2) + '\n');
}
diff --git a/pipeline/src/assets/environmentFormat.ts b/pipeline/src/assets/environmentFormat.ts
new file mode 100644
index 000000000..a5f070885
--- /dev/null
+++ b/pipeline/src/assets/environmentFormat.ts
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What an `.esenv` document names beside it, apart from the importer that
+ * writes one: a package reads this and nothing else of the import.
+ */
+
+/** The document's fields that name an image beside it — everything a package
+ * has to move with it and re-point. */
+export const ENV_IMAGE_FIELDS = ['specular', 'sky'] as const;
diff --git a/pipeline/src/assets/environmentImport.ts b/pipeline/src/assets/environmentImport.ts
index 7fd4fc9d9..3f117391e 100644
--- a/pipeline/src/assets/environmentImport.ts
+++ b/pipeline/src/assets/environmentImport.ts
@@ -41,9 +41,13 @@ export interface EnvironmentAssetData {
* a sky. A scene BAKE writes several, column 0 the sky and the rest a
* reflection probe each. */
columns?: number;
+ /** The panorama itself, for drawing the sky: equirectangular, row 0 up, RGBM
+ * under the same `maxRange`. Absent draws the sky from the atlas' mip 0. */
+ sky?: string;
}
export const ENVIRONMENT_FORMAT_VERSION = 1;
+export { ENV_IMAGE_FIELDS } from './environmentFormat';
/** Mip 0's face size, and how many mips follow it. Five mips put roughness on a
* 0.25 grid, which is finer than the prefilter's own error at the rough end. */
@@ -58,6 +62,15 @@ export const ENV_MIN_FACE = 8;
export function mipCountFor(faceSize: number, want = ENV_MIP_COUNT): number {
return Math.max(1, Math.min(want, Math.floor(Math.log2(faceSize / ENV_MIN_FACE)) + 1));
}
+/** The widest sky texture an import writes by default. The sky is looked at
+ * directly, so it keeps the source's resolution up to here. */
+export const ENV_SKY_MAX_WIDTH = 2048;
+
+/** The `.meta` settings every image an environment import writes carries: RGBM
+ * radiance, not a picture — sRGB would linearize what is already linear, and a
+ * block compressor would quantize the shared multiplier with the colour. */
+export const ENV_IMAGE_SETTINGS = { sRGB: false, compress: false, wrapMode: 'clamp' } as const;
+
/** Radiance above this clips. Sky detail lives well below it; a sun disc does not,
* and is meant to survive as a bright blob rather than as its true thousands. */
export const ENV_MAX_RANGE = 8;
@@ -398,11 +411,43 @@ export function prefilterOctahedral(env: Panorama, faceSize = ENV_FACE_SIZE,
return { width, height, rgba };
}
+/**
+ * The panorama as the sky texture, at most `maxWidth` wide: box-filtered down by
+ * a whole factor where it is wider, so each texel is an average of whole source
+ * texels rather than a point sample that skips some.
+ */
+export function encodeSkyPanorama(env: Panorama, maxWidth = ENV_SKY_MAX_WIDTH,
+ maxRange = ENV_MAX_RANGE): {
+ width: number; height: number; rgba: Uint8Array;
+} {
+ const factor = Math.max(1, Math.ceil(env.width / Math.max(1, maxWidth)));
+ const width = Math.max(1, Math.floor(env.width / factor));
+ const height = Math.max(1, Math.floor(env.height / factor));
+ const rgba = new Uint8Array(width * height * 4);
+ const area = factor * factor;
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ let r = 0, g = 0, b = 0;
+ for (let sy = 0; sy < factor; sy++) {
+ for (let sx = 0; sx < factor; sx++) {
+ const o = ((y * factor + sy) * env.width + (x * factor + sx)) * 3;
+ r += env.rgb[o]!; g += env.rgb[o + 1]!; b += env.rgb[o + 2]!;
+ }
+ }
+ encodeRgbm(r / area, g / area, b / area, maxRange, rgba, (y * width + x) * 4);
+ }
+ }
+ return { width, height, rgba };
+}
+
/** Everything a `.hdr` becomes, less the reference the caller has to resolve. */
export interface ImportedEnvironment {
/** `<stem>_env.png` — the octahedral atlas. */
atlasName: string;
atlasBytes: Uint8Array;
+ /** `<stem>_sky.png` — the panorama the sky is drawn from; null when the import
+ * was asked for none (`skyWidth: 0`). */
+ sky: { name: string; bytes: Uint8Array } | null;
/** The `.esenv` document, with `specular` still empty. */
document: EnvironmentAssetData;
/** What the source says that this import had to reinterpret. */
@@ -413,9 +458,10 @@ export interface ImportedEnvironment {
* Turn a Radiance panorama into the assets a scene can reference.
*
* @param faceSize Mip 0's face size; smaller is faster and is what tests use.
+ * @param skyWidth The sky texture's widest edge; 0 writes none.
*/
export function importEnvironment(bytes: Uint8Array, stem: string,
- options: { faceSize?: number; mipCount?: number } = {}):
+ options: { faceSize?: number; mipCount?: number; skyWidth?: number } = {}):
ImportedEnvironment {
const faceSize = options.faceSize ?? ENV_FACE_SIZE;
const mipCount = mipCountFor(faceSize, options.mipCount ?? ENV_MIP_COUNT);
@@ -429,9 +475,12 @@ export function importEnvironment(bytes: Uint8Array, stem: string,
}
const irradiance = projectIrradianceSH(panorama);
const atlas = prefilterOctahedral(panorama, faceSize, mipCount, ENV_MAX_RANGE);
+ const skyWidth = options.skyWidth ?? ENV_SKY_MAX_WIDTH;
+ const sky = skyWidth > 0 ? encodeSkyPanorama(panorama, skyWidth, ENV_MAX_RANGE) : null;
return {
atlasName: `${stem}_env.png`,
atlasBytes: encodeRgbaPng(atlas.width, atlas.height, atlas.rgba),
+ sky: sky ? { name: `${stem}_sky.png`, bytes: encodeRgbaPng(sky.width, sky.height, sky.rgba) } : null,
warnings,
document: {
version: ENVIRONMENT_FORMAT_VERSION,
diff --git a/pipeline/tests/document-ref-cook-deps.test.ts b/pipeline/tests/document-ref-cook-deps.test.ts
index a6b2a7f37..478015d72 100644
--- a/pipeline/tests/document-ref-cook-deps.test.ts
+++ b/pipeline/tests/document-ref-cook-deps.test.ts
@@ -23,6 +23,7 @@ let root: string;
const SPECULAR = '11111111-1111-4111-8111-111111111111';
const ESENV = '22222222-2222-4222-8222-222222222222';
+const SKY = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
const CLIP = '33333333-3333-4333-8333-333333333333';
const CONTROLLER = '44444444-4444-4444-8444-444444444444';
const LAYER_CLIP = '88888888-8888-4888-8888-888888888888';
@@ -41,7 +42,7 @@ function writeAsset(rel: string, type: string, uuid: string, body: string | Uint
// The importer writes the atlas as a SIBLING file name, resolved against the
// document — not as a project path.
const esenv = JSON.stringify({
- version: 1, irradiance: new Array(27).fill(0), specular: 'sky_env.png',
+ version: 1, irradiance: new Array(27).fill(0), specular: 'sky_env.png', sky: 'sky_sky.png',
faceSize: 8, mipCount: 1, maxRange: 8,
});
@@ -104,6 +105,7 @@ const scene = JSON.stringify({
beforeAll(() => {
root = mkdtempSync(path.join(tmpdir(), 'estella-docrefs-'));
writeAsset('assets/env/sky_env.png', 'texture', SPECULAR, 'PNG');
+ writeAsset('assets/env/sky_sky.png', 'texture', SKY, 'PNG');
writeAsset('assets/env/sky.esenv', 'environment', ESENV, esenv);
writeAsset('assets/anim/frame0.png', 'texture', FRAME, 'PNG');
writeAsset('assets/anim/idle.esanim', 'animclip', CLIP, clip);
@@ -161,9 +163,12 @@ describe('assets named only inside another document are cooked', () => {
entries: Array<{ uuid: string; path: string; sourcePath: string }>;
};
const env = manifest.entries.find((e) => e.uuid === ESENV)!;
- const staged = JSON.parse(readFileSync(path.join(res.outDir, env.path), 'utf8')) as { specular: string };
+ const staged = JSON.parse(readFileSync(path.join(res.outDir, env.path), 'utf8')) as { specular: string; sky: string };
expect(staged.specular).toBe('assets/env/sky_env.png');
expect(manifest.entries.some((e) => e.sourcePath === staged.specular)).toBe(true);
+ // The sky it draws is the same kind of sibling, and lost the same way.
+ expect(staged.sky).toBe('assets/env/sky_sky.png');
+ expect(manifest.entries.some((e) => e.sourcePath === staged.sky)).toBe(true);
// The bitmap font says the same thing in text rather than JSON.
const font = manifest.entries.find((e) => e.uuid === FNT)!;
diff --git a/pipeline/tests/environment-import.test.ts b/pipeline/tests/environment-import.test.ts
index 0293c5a25..cb6146297 100644
--- a/pipeline/tests/environment-import.test.ts
+++ b/pipeline/tests/environment-import.test.ts
@@ -14,7 +14,7 @@ import { describe, it, expect } from 'vitest';
import {
decodeRadianceHdr, projectIrradianceSH, evalIrradianceSH, samplePanorama,
octEncode, octDecode, encodeRgbm, decodeRgbm, atlasLayout, prefilterOctahedral,
- importEnvironment, mipCountFor, ENV_MAX_RANGE,
+ importEnvironment, mipCountFor, ENV_MAX_RANGE, encodeSkyPanorama,
type Panorama,
} from '../src/assets/environmentImport';
@@ -258,6 +258,31 @@ describe('importEnvironment', () => {
});
});
+describe('the sky texture', () => {
+ it('is the panorama itself, row 0 up, beside the atlas', () => {
+ const hdr = flatHdr(32, 16, (_x, y) => (y < 8 ? [2, 2, 2] : [0, 0, 0]));
+ const result = importEnvironment(hdr, 'studio', { faceSize: 32, mipCount: 3 });
+ expect(result.sky?.name).toBe('studio_sky.png');
+ const sky = encodeSkyPanorama(decodeRadianceHdr(hdr));
+ expect([sky.width, sky.height]).toEqual([32, 16]);
+ const at = (x: number, y: number) => decodeRgbm(...(Array.from(sky.rgba.subarray((y * 32 + x) * 4, (y * 32 + x) * 4 + 4)) as [number, number, number, number]), ENV_MAX_RANGE)[0];
+ expect(at(5, 2)).toBeCloseTo(2, 1);
+ expect(at(5, 13)).toBeCloseTo(0, 2);
+ });
+
+ it('comes down by a whole factor, averaging, where the panorama is wider than asked', () => {
+ const env = panorama(8, 4, (x) => [x % 2 === 0 ? 4 : 0, 0, 0]);
+ const sky = encodeSkyPanorama(env, 4);
+ expect([sky.width, sky.height]).toEqual([4, 2]);
+ expect(decodeRgbm(sky.rgba[0]!, sky.rgba[1]!, sky.rgba[2]!, sky.rgba[3]!, ENV_MAX_RANGE)[0]).toBeCloseTo(2, 1);
+ });
+
+ it('is not written when the import asks for none', () => {
+ const hdr = flatHdr(32, 16, () => [1, 1, 1]);
+ expect(importEnvironment(hdr, 'studio', { faceSize: 32, mipCount: 3, skyWidth: 0 }).sky).toBeNull();
+ });
+});
+
describe('panorama sampling', () => {
it('reads the image centre as +Z and row 0 as +Y', () => {
const env = panorama(8, 4, (x, y) => [x, y, 0]);
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 2a62300e5..9d5e9b80f 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -305,6 +305,7 @@ engine_setCpuProfiling: ((on: boolean) => void) | undefined
engine_setRandomSeed: ((seed: number) => void) | undefined
environment_create: ((shPtr: number, specularHandle: number, faceSize: number, mipCount: number, maxRange: number, columns: number) => number) | undefined
environment_release: ((environmentHandle: number) => void) | undefined
+environment_setSky: ((environmentHandle: number, skyHandle: number) => void) | undefined
es_getMallocBytes: (() => number) | undefined
esshader_cookInfo: (source: string, featuresCsv: string) => { valid: boolean; error?: string; name: string; domain: string; hasWgslVertex: boolean; hasWgslFragment: boolean; hasSwitches: boolean; vertGlsl: string; fragGlsl: string; textures: Array<{ name: string; unit: number; }>; }
geometry_create: () => number
diff --git a/sdk/src/asset/loaders/EnvironmentAssetLoader.ts b/sdk/src/asset/loaders/EnvironmentAssetLoader.ts
index c54099473..615e47152 100644
--- a/sdk/src/asset/loaders/EnvironmentAssetLoader.ts
+++ b/sdk/src/asset/loaders/EnvironmentAssetLoader.ts
@@ -19,6 +19,8 @@ interface EnvironmentAssetData {
/** Octahedral pyramids standing side by side in that atlas. A scene BAKE
* writes several — column 0 the sky, the rest a reflection probe each. */
columns?: number;
+ /** The panorama the sky is drawn from, a sibling of the document. */
+ sky?: string;
}
/** A baked environment, named by the handle a Light references. */
@@ -79,6 +81,18 @@ export class EnvironmentAssetLoader implements AssetLoader<EnvironmentResult> {
if (!handle) {
throw new Error(`the engine rejected the environment in ${path}`);
}
+
+ // Missing, the sky falls back to the atlas: coarser, never absent.
+ if (data.sky && m.environment_setSky) {
+ const resolved = resolveDocumentRef(path, data.sky);
+ try {
+ // flipY false for the atlas' reason: row 0 is up, and the shader
+ // reads rows by index.
+ m.environment_setSky(handle, (await ctx.acquireTexture(resolved, false)).value.handle);
+ } catch (e) {
+ log.warn('asset', `${path}: no sky panorama at '${resolved}'`, e);
+ }
+ }
return { handle };
}
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 547393f8e..6a864d982 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -53,6 +53,7 @@ export interface NativeEngineApi {
engine_setRandomSeed?(seed: number): void;
environment_create?(shPtr: number, specularHandle: number, faceSize: number, mipCount: number, maxRange: number, columns: number): number;
environment_release?(environmentHandle: number): void;
+ environment_setSky?(environmentHandle: number, skyHandle: number): void;
geometry_create?(): number;
geometry_init?(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
geometry_isValid?(handle: number): boolean;
@@ -324,6 +325,7 @@ export function createNativeEngineApi(
bind('engine_setRandomSeed', 'es_engine_setRandomSeed', false);
bind('environment_create', 'es_environment_create', false);
bind('environment_release', 'es_environment_release', false);
+ bind('environment_setSky', 'es_environment_setSky', false);
bind('geometry_create', 'es_geometry_create', false);
bind('geometry_init', 'es_geometry_init', false);
bind('geometry_isValid', 'es_geometry_isValid', false);
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 34431494b..e19683867 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -339,6 +339,7 @@ export interface ESEngineModule {
mipCount: number, maxRange: number, columns: number): number;
/** Release an environment; its atlas is an ordinary texture and outlives it. */
environment_release?(environmentHandle: number): void;
+ environment_setSky?(environmentHandle: number, skyHandle: number): void;
/**
* Register a grid of baked irradiance: `resX*resY*resZ*27` floats, nine RGB
* coefficients per probe with x varying fastest. The same nine an environment
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index bc12c3809..351f0c34c 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -424,6 +424,15 @@ u32 environment_create(uintptr_t shPtr, u32 specularHandle, f32 faceSize, u32 mi
faceSize, mipCount, maxRange, columns).id();
}
+/** @brief Gives an environment the panorama its sky is drawn from. */
+void environment_setSky(u32 environmentHandle, u32 skyHandle) {
+ auto* rm = ctx().tryGet<resource::ResourceManager>();
+ if (!rm) return;
+ if (Environment* environment = rm->getEnvironment(resource::EnvironmentHandle(environmentHandle))) {
+ environment->sky = resource::TextureHandle(skyHandle);
+ }
+}
+
/** @brief Releases an environment. Its atlas is an ordinary texture and outlives it. */
void environment_release(u32 environmentHandle) {
if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index b0af49982..64a6508dd 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -99,6 +99,7 @@ void mesh_release(u32 meshHandle);
* which holds `columns` pyramids side by side). */
u32 environment_create(uintptr_t shPtr, u32 specularHandle, f32 faceSize, u32 mipCount,
f32 maxRange, u32 columns);
+void environment_setSky(u32 environmentHandle, u32 skyHandle);
/** @brief Releases an environment; its atlas is an ordinary texture and outlives it. */
void environment_release(u32 environmentHandle);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 637998fb8..edd93d397 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -526,6 +526,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("mesh_rematerializeFromChannels", &esengine::mesh_rematerializeFromChannels);
emscripten::function("mesh_release", &esengine::mesh_release);
emscripten::function("environment_create", &esengine::environment_create);
+ emscripten::function("environment_setSky", &esengine::environment_setSky);
emscripten::function("environment_release", &esengine::environment_release);
emscripten::function("probe_volume_create", &esengine::probe_volume_create);
emscripten::function("probe_volume_release", &esengine::probe_volume_release);
diff --git a/src/esengine/data/shaders/sky.esshader b/src/esengine/data/shaders/sky.esshader
index 42298b148..bc72cdd2b 100644
--- a/src/esengine/data/shaders/sky.esshader
+++ b/src/esengine/data/shaders/sky.esshader
@@ -27,10 +27,38 @@ precision highp float;
in highp vec3 v_worldPos;
out vec4 fragColor;
+#ifdef ES_SKY_PANORAMA
+uniform sampler2D u_texture;
+
+// Decoded before it is blended: RGBM filtered by the hardware mixes multipliers
+// and colours apart, which blots every high-contrast edge of the sky.
+highp vec3 skyTexel(in ivec2 p, in ivec2 size) {
+ ivec2 q = ivec2(((p.x % size.x) + size.x) % size.x, clamp(p.y, 0, size.y - 1));
+ highp vec4 t = texelFetch(u_texture, q, 0);
+ return t.rgb * t.rgb * (t.a * t.a * u_envParams.y);
+}
+
+// The importer's own mapping (samplePanorama): +Z at the centre, row 0 up.
+highp vec3 skyPanorama(in highp vec3 d) {
+ ivec2 size = textureSize(u_texture, 0);
+ highp float u = 0.5 + atan(d.x, d.z) / 6.28318530718;
+ highp float v = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265359;
+ highp vec2 f = vec2(u * float(size.x), v * float(size.y)) - 0.5;
+ ivec2 i = ivec2(floor(f));
+ highp vec2 t = f - floor(f);
+ return mix(mix(skyTexel(i, size), skyTexel(i + ivec2(1, 0), size), t.x),
+ mix(skyTexel(i + ivec2(0, 1), size), skyTexel(i + ivec2(1, 1), size), t.x), t.y);
+}
+#endif
+
void main() {
- // Mip 0: the sharpest level of the prefiltered atlas is the sky as it was
- // photographed. The rougher ones exist to be reflected, not to be looked at.
+#ifdef ES_SKY_PANORAMA
+ fragColor = vec4(skyPanorama(envDirection(-viewDirection(v_worldPos))), 1.0);
+#else
+ // Mip 0: the sharpest level of the prefiltered atlas, the fallback for an
+ // environment imported before it carried its panorama.
fragColor = vec4(envSampleMip(-viewDirection(v_worldPos), 0.0), 1.0);
+#endif
}
#pragma end
@@ -72,7 +100,30 @@ struct VSOut {
@location(0) v_worldPos : vec3f,
};
+#ifdef ES_SKY_PANORAMA
+fn skyTexel(p : vec2i, size : vec2i) -> vec3f {
+ let q = vec2i(((p.x % size.x) + size.x) % size.x, clamp(p.y, 0, size.y - 1));
+ let t = textureLoad(t0, q, 0);
+ return t.rgb * t.rgb * (t.a * t.a * lc.u_envParams.y);
+}
+
+fn skyPanorama(d : vec3f) -> vec3f {
+ let size = vec2i(textureDimensions(t0, 0));
+ let u = 0.5 + atan2(d.x, d.z) / 6.28318530718;
+ let v = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265359;
+ let f = vec2f(u * f32(size.x), v * f32(size.y)) - 0.5;
+ let i = vec2i(floor(f));
+ let t = f - floor(f);
+ return mix(mix(skyTexel(i, size), skyTexel(i + vec2i(1, 0), size), t.x),
+ mix(skyTexel(i + vec2i(0, 1), size), skyTexel(i + vec2i(1, 1), size), t.x), t.y);
+}
+#endif
+
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+#ifdef ES_SKY_PANORAMA
+ return vec4f(skyPanorama(envDirection(-viewDirection(v.v_worldPos))), 1.0);
+#else
return vec4f(envSampleMip(-viewDirection(v.v_worldPos), 0.0), 1.0);
+#endif
}
#pragma end
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index c88693732..fb614c971 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -1223,6 +1223,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {
lights.clear();
shadow_casters_.clear();
environment_texture_id_ = 0;
+ sky_texture_id_ = 0;
draw_sky_ = false;
// Gather non-ambient lights, then (if over the UBO's cap) keep the most intense — the
@@ -1385,9 +1386,13 @@ bool RenderFrame::collectEnvironment(const ecs::Light& light, const glm::vec3& s
return false;
}
environment_texture_id_ = textureId;
- // Only a reflection can be looked at directly: the nine coefficients are the
- // sky averaged over every direction, which as a background is one flat colour.
- draw_sky_ = light.drawEnvironment && textureId != 0;
+ sky_texture_id_ = 0;
+ if (environment->sky.isValid()) {
+ if (Texture* sky = resource_manager_.getTexture(environment->sky)) sky_texture_id_ = sky->getId();
+ }
+ // Only an image can be looked at directly: the nine coefficients are the sky
+ // averaged over every direction, which as a background is one flat colour.
+ draw_sky_ = light.drawEnvironment && (textureId != 0 || sky_texture_id_ != 0);
return true;
}
@@ -1846,21 +1851,35 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {
* from the eye through it — which viewDirection() already answers.
*/
void RenderFrame::collectSky(RenderCollectContext& ctx) {
- if (!draw_sky_ || environment_texture_id_ == 0) return;
- if (!sky_compiled_) {
- sky_compiled_ = true;
+ if (!draw_sky_) return;
+ // The panorama where the environment carries one; the atlas' mip 0 is a
+ // reflection's resolution, too coarse to look at, and only the fallback.
+ const bool panorama = sky_texture_id_ != 0;
+ if (!panorama && environment_texture_id_ == 0) return;
+ u32& program = sky_programs_[panorama ? 1 : 0];
+ bool& compiled = sky_compiled_[panorama ? 1 : 0];
+ if (!compiled) {
+ compiled = true;
auto parsed = resource::ShaderParser::parse(ShaderEmbeds::SKY);
const auto target = resource_manager_.preferredShaderTarget();
- const std::vector<std::string> features{"ES_ENV_MAP"};
+ std::vector<std::string> features{"ES_ENV_MAP"};
+ if (panorama) features.push_back("ES_SKY_PANORAMA");
resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "",
features, target),
resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "",
features, target),
{}, resource_manager_.preferredShaderLanguage());
- if (auto* shader = resource_manager_.getShader(handle)) sky_program_ = shader->getProgramId();
+ if (auto* shader = resource_manager_.getShader(handle)) {
+ program = shader->getProgramId();
+ if (panorama && shader->language() == GfxShaderLanguage::GLSL_ES300) {
+ shader->bind();
+ shader->setUniform("u_texture", 0);
+ shader->unbind();
+ }
+ }
}
- if (sky_program_ == 0) return;
+ if (program == 0) return;
// The rays through the screen's corners, at a depth inside both backends'
// ranges: a quad at clip z = 1 rounds past the far plane at some view angles and
@@ -1876,12 +1895,12 @@ void RenderFrame::collectSky(RenderCollectContext& ctx) {
BatchDrawKey key{};
key.stage = RenderStage::Background;
key.layer = std::numeric_limits<i32>::min();
- key.shaderId = sky_program_;
+ key.shaderId = program;
key.blend = BlendMode::None;
key.layoutId = LayoutId::Sky;
- // Slot 0 is filled with white and never sampled: the atlas rides the unit the
- // shaders pin it to, and the fill is what the slot walk below it expects.
- key.textureId = ctx.frame_context.white_texture_id;
+ // Slot 0 is the panorama, or a white fill the atlas variant never samples: the
+ // atlas rides the unit the shaders pin it to either way.
+ key.textureId = panorama ? sky_texture_id_ : ctx.frame_context.white_texture_id;
key.envTextureId = environment_texture_id_;
key.type = RenderType::Mesh;
// Neither tested nor written: the sky is behind everything by being first, and
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index de14e27e9..8e2baf118 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -879,8 +879,10 @@ private:
/// Whether that environment is also the background this frame.
bool draw_sky_ = false;
/// The far-plane quad's program, compiled on first use.
- u32 sky_program_ = 0;
- bool sky_compiled_ = false;
+ u32 sky_texture_id_ = 0;
+ /// The atlas variant, then the panorama one; each compiled when first drawn.
+ u32 sky_programs_[2] = {};
+ bool sky_compiled_[2] = {};
/// Emits the background quad when an environment asked to be seen behind the scene.
void collectSky(RenderCollectContext& ctx);
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index 2e253631e..086591aca 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -1067,10 +1067,38 @@ precision highp float;
in highp vec3 v_worldPos;
out vec4 fragColor;
+#ifdef ES_SKY_PANORAMA
+uniform sampler2D u_texture;
+
+
+
+highp vec3 skyTexel(in ivec2 p, in ivec2 size) {
+ ivec2 q = ivec2(((p.x % size.x) + size.x) % size.x, clamp(p.y, 0, size.y - 1));
+ highp vec4 t = texelFetch(u_texture, q, 0);
+ return t.rgb * t.rgb * (t.a * t.a * u_envParams.y);
+}
+
+
+highp vec3 skyPanorama(in highp vec3 d) {
+ ivec2 size = textureSize(u_texture, 0);
+ highp float u = 0.5 + atan(d.x, d.z) / 6.28318530718;
+ highp float v = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265359;
+ highp vec2 f = vec2(u * float(size.x), v * float(size.y)) - 0.5;
+ ivec2 i = ivec2(floor(f));
+ highp vec2 t = f - floor(f);
+ return mix(mix(skyTexel(i, size), skyTexel(i + ivec2(1, 0), size), t.x),
+ mix(skyTexel(i + ivec2(0, 1), size), skyTexel(i + ivec2(1, 1), size), t.x), t.y);
+}
+#endif
+
void main() {
+#ifdef ES_SKY_PANORAMA
+ fragColor = vec4(skyPanorama(envDirection(-viewDirection(v_worldPos))), 1.0);
+#else
fragColor = vec4(envSampleMip(-viewDirection(v_worldPos), 0.0), 1.0);
+#endif
}
#pragma end
@@ -1112,8 +1140,31 @@ struct VSOut {
@location(0) v_worldPos : vec3f,
};
+#ifdef ES_SKY_PANORAMA
+fn skyTexel(p : vec2i, size : vec2i) -> vec3f {
+ let q = vec2i(((p.x % size.x) + size.x) % size.x, clamp(p.y, 0, size.y - 1));
+ let t = textureLoad(t0, q, 0);
+ return t.rgb * t.rgb * (t.a * t.a * lc.u_envParams.y);
+}
+
+fn skyPanorama(d : vec3f) -> vec3f {
+ let size = vec2i(textureDimensions(t0, 0));
+ let u = 0.5 + atan2(d.x, d.z) / 6.28318530718;
+ let v = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265359;
+ let f = vec2f(u * f32(size.x), v * f32(size.y)) - 0.5;
+ let i = vec2i(floor(f));
+ let t = f - floor(f);
+ return mix(mix(skyTexel(i, size), skyTexel(i + vec2i(1, 0), size), t.x),
+ mix(skyTexel(i + vec2i(0, 1), size), skyTexel(i + vec2i(1, 1), size), t.x), t.y);
+}
+#endif
+
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+#ifdef ES_SKY_PANORAMA
+ return vec4f(skyPanorama(envDirection(-viewDirection(v.v_worldPos))), 1.0);
+#else
return vec4f(envSampleMip(-viewDirection(v.v_worldPos), 0.0), 1.0);
+#endif
}
#pragma end
)esshader";
diff --git a/src/esengine/resource/Environment.hpp b/src/esengine/resource/Environment.hpp
index 57481918f..2583edaf8 100644
--- a/src/esengine/resource/Environment.hpp
+++ b/src/esengine/resource/Environment.hpp
@@ -28,6 +28,10 @@ public:
resource::TextureHandle specular;
+ /** @brief The panorama the sky is drawn from: equirectangular, row 0 up, RGBM
+ * under maxRange. Invalid draws the sky from the atlas' mip 0 instead. */
+ resource::TextureHandle sky;
+
/** Edge length of mip 0's octahedral face, in texels. */
f32 faceSize = 0.0f;
u32 mipCount = 0;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index be6066aaf..2ced364ad 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -988,6 +988,10 @@ export const NOTED = {
{ note: 'A frame can be captured draw call by draw call, and replayed up to any one of them.' },
'feat(render): a frame capture lists every texture a draw bound':
{ note: 'A frame can be captured draw call by draw call, and replayed up to any one of them.' },
+ 'feat(render): the sky is drawn from the panorama it was imported from':
+ { note: 'A drawn sky is the panorama you imported, not a blur of it.' },
+ 'feat(editor): importing a panorama writes the sky it is drawn from':
+ { note: 'A drawn sky is the panorama you imported, not a blur of it.' },
'fix(render): a drawn sky fills the frame from every angle':
{ note: 'A drawn sky no longer vanishes, or half-vanishes, as the view turns.' },
'fix(render): the profiler and the draw-call count cover every camera of the frame':