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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(assets): a panorama becomes an environment
esengine01aaeaf195fc
diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.tsindex 969b4f190..f6a673c8f 100644--- a/desktop/electron/importAssets.ts+++ b/desktop/electron/importAssets.ts@@ -16,6 +16,7 @@ import { capture } from './fileJournal';import { EXT_TO_TYPE, metaTypeFor, metaTypeForFile, mintMeta, writeMeta, adoptOrphan } from '../../pipeline/src/assets/assetMeta';import { CONTENT_TYPED_EXTENSIONS } from '../../tools/assetMetaTable.js';import { importModel, isModelSource } from './importModel';+import { importPanorama, isPanoramaSource } from './importEnvironment';/** The supported import extensions (no leading dot) — used by the file dialog filter.* The content-typed ones are offered too: a Spine JSON skeleton is a `.json`, and a@@ -119,8 +120,10 @@ export async function importAssets(root: string, destDir: string, sources: strin// A model produces the assets a scene references; the source itself is not one// of them, so importing one without this leaves a file nothing can draw.const produce = async (abs: string, dir: string, originDir?: string): Promise<void> => {- if (!isModelSource(abs)) return;- const result = await importModel(root, dir, abs, originDir);+ const result = isModelSource(abs) ? await importModel(root, dir, abs, originDir)+ : isPanoramaSource(abs) ? await importPanorama(root, dir, abs)+ : null;+ if (!result) return;imported.push(...result.products);warnings.push(...result.warnings.map((w) => `${path.basename(abs)}: ${w}`));};diff --git a/desktop/electron/importEnvironment.ts b/desktop/electron/importEnvironment.tsnew file mode 100644index 000000000..b8d20d494--- /dev/null+++ b/desktop/electron/importEnvironment.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Environment import: a `.hdr` panorama in the project produces the+ * `.esenv` a light can actually reference.+ *+ * The same shape as the model import — the engine loads no panorama format, so a+ * file that is only copied in leaves the user with something nothing can light+ * with. The convolutions happen here, once, rather than at every load.+ */+import { mkdir, writeFile } from 'node:fs/promises';+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { resolveInRoot } from './projectFs';+import { capture } from './fileJournal';+import { adoptOrphan } from '../../pipeline/src/assets/assetMeta';+import { importEnvironment } from '../../pipeline/src/assets/environmentImport';++export interface EnvironmentImportResult {+ /** Project-relative paths of everything written, in the order it was produced. */+ products: string[];+ warnings: string[];+}++export const PANORAMA_EXTENSIONS = ['.hdr'];++export function isPanoramaSource(file: string): boolean {+ return PANORAMA_EXTENSIONS.includes(path.extname(file).toLowerCase());+}++/**+ * Import `absSource` (already inside the project) into `destDir`, writing the+ * prefiltered atlas and the `.esenv` that names it.+ */+export async function importPanorama(root: string, destDir: string,+ absSource: string): Promise<EnvironmentImportResult> {+ const absDir = resolveInRoot(root, destDir);+ await mkdir(absDir, { recursive: true });+ const stem = path.basename(absSource).replace(/\.hdr$/i, '');+ const products: string[] = [];++ const write = async (name: string, bytes: Uint8Array | string,+ settings?: Record<string, unknown>): Promise<string> => {+ const rel = destDir ? `${destDir}/${name}` : name;+ await capture(rel, 'write');+ await writeFile(path.join(absDir, name), bytes);+ // keeps the uuid a re-import must not change+ await adoptOrphan(path.join(absDir, name), settings);+ products.push(rel);+ return rel;+ };++ const result = importEnvironment(new Uint8Array(readFileSync(absSource)), stem,+ panoramaOptions(absSource));++ // The atlas is not a picture: its channels are an RGBM encoding of radiance, so+ // sRGB would linearize what is already linear, and a block compressor would+ // quantize the shared multiplier along with the colour it scales.+ result.document.specular = await write(result.atlasName, result.atlasBytes,+ { sRGB: false, compress: false, wrapMode: 'clamp' });+ await write(`${stem}.esenv`, `${JSON.stringify(result.document, null, 2)}\n`);++ return { products, warnings: result.warnings };+}++/** The `.meta` settings that decide how finely this panorama is baked. */+function panoramaOptions(absSource: string): { faceSize?: number } {+ try {+ const meta = JSON.parse(readFileSync(`${absSource}.meta`, 'utf8')) as+ { importer?: { faceSize?: unknown } };+ const faceSize = meta.importer?.faceSize;+ return typeof faceSize === 'number' && faceSize >= 8 ? { faceSize } : {};+ } catch {+ return {};+ }+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 4b43f2a79..45a7cece1 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -37,6 +37,7 @@ import { cookAssets } from '../../pipeline/src/assets/cookAssets';import { startProjectWatch, stopProjectWatch } from './projectWatcher';import { importAssets, createAsset, IMPORT_EXTENSIONS } from './importAssets';import { importModel, isModelSource } from './importModel';+import { importPanorama, isPanoramaSource } from './importEnvironment';import { exportGame } from '../../pipeline/src/export/exportGame';import {iosSourcesFromTemplate, resolveNativeTemplate, installNativeTemplate, listNativeTemplates,@@ -1038,15 +1039,17 @@ ipcMain.handle('project:importFiles', async (_e, destDir: string, sources: strinreturn result;});-// Re-import a model already in the project: same products, same uuids, beside-// the source. This is how an edited `.gltf` — or an edited scale in its `.meta`-// — reaches the assets a scene references.-ipcMain.handle('project:reimportModel', async (_e, file: string) => {+// Re-import a source already in the project: same products, same uuids, beside+// the source. One door for every kind, because which converter runs is a property+// of the file rather than of the caller.+ipcMain.handle('project:reimportSource', async (_e, file: string) => {const root = requireRoot();const abs = resolveInRoot(root, file);- if (!isModelSource(abs)) return { products: [], warnings: [] };const dir = file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : '';- const result = await importModel(root, dir, abs);+ const result = isModelSource(abs) ? await importModel(root, dir, abs)+ : isPanoramaSource(abs) ? await importPanorama(root, dir, abs)+ : null;+ if (!result) return { products: [], warnings: [] };notifyFsChanged(result.products);return result;});diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex dc2bcb5ad..44398dd88 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -245,8 +245,8 @@ const api = {ipcRenderer.invoke('project:importFiles', destDir, sources),/** Re-run a model's import in place: the door an edited source, or an edited* import setting, reaches its products through. */- reimportModel: (file: string): Promise<{ products: string[]; warnings: string[] }> =>- ipcRenderer.invoke('project:reimportModel', file),+ reimportSource: (file: string): Promise<{ products: string[]; warnings: string[] }> =>+ ipcRenderer.invoke('project:reimportSource', file),/** Create a new asset file (+ .meta) from `content`; returns its project path. */createAsset: (destDir: string, baseName: string, content: string, type: string): Promise<string> =>ipcRenderer.invoke('project:createAsset', destDir, baseName, content, type),diff --git a/desktop/src/plugins/importers.ts b/desktop/src/plugins/importers.tsindex 12163934a..a3bda4cb7 100644--- a/desktop/src/plugins/importers.ts+++ b/desktop/src/plugins/importers.ts@@ -62,16 +62,21 @@ export async function runImporters(paths: readonly string[]): Promise<void> {}}-// The model import is the editor's own, but it is an importer like any other and-// is registered rather than special-cased — Reimport and the source watcher then-// reach it by the one rule, not by a second test for model extensions.-importerRegistry.register('core', {- id: 'core:model',- extensions: ['gltf', 'glb'],- run: async (path: string): Promise<void> => {- const result = await window.estella.project.reimportModel(path);- // The same notes a first import shows: what the source says that the engine- // cannot draw, and how big it arrived.- for (const warning of result.warnings) Toasts.push(`${path}: ${warning}`, 'warn');- },-});+// The model and panorama imports are the editor's own, but they are importers+// like any other and are registered rather than special-cased — Reimport and the+// source watcher reach them by the one rule.+for (const [id, extensions] of [+ ['core:model', ['gltf', 'glb']],+ ['core:panorama', ['hdr']],+] as const) {+ importerRegistry.register('core', {+ id,+ extensions,+ run: async (path: string): Promise<void> => {+ const result = await window.estella.project.reimportSource(path);+ // The same notes a first import shows: what the source says that the engine+ // cannot draw, and how it had to be reinterpreted.+ for (const warning of result.warnings) Toasts.push(`${path}: ${warning}`, 'warn');+ },+ });+}diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex d3c4a2cef..565287126 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -18,7 +18,7 @@*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Box, Boxes, Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles, Plug, Type,+ Box, Boxes, Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles, Plug, Type, Globe, Sun,type LucideIcon,} from 'lucide-react';import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';@@ -76,6 +76,10 @@ export const ASSET_TYPES: Record<BuiltinAssetType, AssetTypeDef> = {// none of these — offering one where a mesh is asked for is offering a ref// that cannot resolve.model: { extensions: ['gltf', 'glb'], badge: 'MDL', icon: Boxes, tint: '#8fa9b5' },+ // A baked environment (.esenv) and, in the same relation as model/mesh, the+ // panorama it was baked from — which the engine also cannot load.+ environment: { extensions: ['esenv'], badge: 'ENV', icon: Globe, tint: '#8fb5b0' },+ panorama: { extensions: ['hdr'], badge: 'HDR', icon: Sun, tint: '#c4b07f' },video: { extensions: ['mp4', 'm4v', 'mov'], badge: 'VID', icon: Video, tint: '#c08fb5' },prefab: { extensions: ['esprefab'], badge: 'PFB', icon: Component, tint: '#c2a274' },// .esmaterial is the real extension (the SDK MaterialAssetLoader only loads it);diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 1c20338a7..e127826f4 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -257,6 +257,8 @@ export type BuiltinAssetType =| 'font'| 'mesh'| 'model'+ | 'environment'+ | 'panorama'| 'file';/** A built-in asset type, or one a plugin contributed. */diff --git a/desktop/tests/environment-import.test.ts b/desktop/tests/environment-import.test.tsnew file mode 100644index 000000000..b1aaa75dc--- /dev/null+++ b/desktop/tests/environment-import.test.ts@@ -0,0 +1,264 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a `.hdr` panorama becomes: nine irradiance coefficients and a+ * prefiltered octahedral atlas.+ *+ * These are the claims a pixel gate cannot make. A rendered sphere says the+ * lighting changed; only arithmetic says it changed to the RIGHT value — and the+ * one identity the whole design rests on (a constant environment reconstructs as+ * that constant, which is what keeps existing scenes pixel-identical) is checked+ * here rather than inferred from a screenshot.+ */+import { describe, it, expect } from 'vitest';+import {+ decodeRadianceHdr, projectIrradianceSH, evalIrradianceSH, samplePanorama,+ octEncode, octDecode, encodeRgbm, decodeRgbm, atlasLayout, prefilterOctahedral,+ importEnvironment, ENV_MAX_RANGE,+ type Panorama,+} from '../../pipeline/src/assets/environmentImport';++/** A Radiance file in the flat (uncompressed) encoding, one RGBE per pixel. */+function flatHdr(width: number, height: number,+ pixel: (x: number, y: number) => [number, number, number]): Uint8Array {+ const header = Buffer.from(`#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y ${height} +X ${width}\n`);+ const body = Buffer.alloc(width * height * 4);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const [r, g, b] = pixel(x, y);+ const peak = Math.max(r, g, b);+ let e = 0;+ let scale = 0;+ if (peak > 1e-9) {+ e = Math.ceil(Math.log2(peak)) + 128;+ scale = 256 / Math.pow(2, e - 128);+ }+ const at = (y * width + x) * 4;+ body[at] = Math.min(255, Math.floor(r * scale));+ body[at + 1] = Math.min(255, Math.floor(g * scale));+ body[at + 2] = Math.min(255, Math.floor(b * scale));+ body[at + 3] = e;+ }+ }+ return new Uint8Array(Buffer.concat([header, body]));+}++/** The same panorama without the file round trip, for the convolution tests. */+function panorama(width: number, height: number,+ pixel: (x: number, y: number) => [number, number, number]): Panorama {+ const rgb = new Float32Array(width * height * 3);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const [r, g, b] = pixel(x, y);+ const at = (y * width + x) * 3;+ rgb[at] = r; rgb[at + 1] = g; rgb[at + 2] = b;+ }+ }+ return { width, height, rgb };+}++describe('Radiance decode', () => {+ it('reads a flat scanline back as the values it was given', () => {+ const env = decodeRadianceHdr(flatHdr(4, 2, (x, y) => [x + 1, y + 1, 0.5]));+ expect(env.width).toBe(4);+ expect(env.height).toBe(2);+ // RGBE is a shared 8-bit mantissa, so the round trip is close, not exact.+ expect(env.rgb[0]).toBeCloseTo(1, 1);+ expect(env.rgb[1]).toBeCloseTo(1, 1);+ expect(env.rgb[(1 * 4 + 3) * 3]).toBeCloseTo(4, 1);+ });++ it('reads the adaptive-RLE encoding as the same picture', () => {+ // 8 wide is the narrowest width the RLE header is legal at.+ const width = 8;+ const values = Array.from({ length: width }, (_, x) => 32 + x * 4);+ const header = Buffer.from(`#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 1 +X ${width}\n`);+ const rle: number[] = [2, 2, 0, width];+ for (let channel = 0; channel < 4; channel++) {+ rle.push(width);+ for (let x = 0; x < width; x++) rle.push(channel === 3 ? 128 : values[x]!);+ }+ const env = decodeRadianceHdr(new Uint8Array(Buffer.concat([header, Buffer.from(rle)])));+ expect(env.width).toBe(width);+ // e = 128 means a scale of 2^-8, so each stored byte reads back as byte/256.+ expect(env.rgb[0]).toBeCloseTo(32 / 256, 5);+ expect(env.rgb[(width - 1) * 3]).toBeCloseTo((32 + 7 * 4) / 256, 5);+ });++ it('refuses a file that is not Radiance', () => {+ expect(() => decodeRadianceHdr(new Uint8Array([1, 2, 3, 4]))).toThrow(/Radiance/);+ });+});++describe('irradiance coefficients', () => {+ // THE identity the design rests on: a constant environment must come back as+ // that same constant in every direction. If this drifts, every existing lit+ // scene changes brightness the day an environment is attached.+ it('reconstructs a constant environment as that constant', () => {+ const sh = projectIrradianceSH(panorama(64, 32, () => [0.25, 0.5, 0.75]));+ for (const [x, y, z] of [[0, 1, 0], [0, -1, 0], [1, 0, 0], [0, 0, 1],+ [0.577, 0.577, 0.577]] as const) {+ const [r, g, b] = evalIrradianceSH(sh, x, y, z);+ expect(r).toBeCloseTo(0.25, 2);+ expect(g).toBeCloseTo(0.5, 2);+ expect(b).toBeCloseTo(0.75, 2);+ }+ });++ it('puts a lit upper hemisphere above a dark lower one', () => {+ const sh = projectIrradianceSH(panorama(64, 32, (_x, y) => (y < 16 ? [1, 1, 1] : [0, 0, 0])));+ const up = evalIrradianceSH(sh, 0, 1, 0)[0];+ const down = evalIrradianceSH(sh, 0, -1, 0)[0];+ const side = evalIrradianceSH(sh, 1, 0, 0)[0];+ // Analytic: a white upper hemisphere gives E(up)/π = 1, E(side)/π = 0.5,+ // E(down)/π = 0. Order-2 SH rings, so the ends land near rather than on them.+ expect(up).toBeGreaterThan(0.9);+ expect(side).toBeCloseTo(0.5, 1);+ expect(down).toBeLessThan(0.1);+ expect(up).toBeGreaterThan(side);+ expect(side).toBeGreaterThan(down);+ });++ it('answers with the colour that lies in that direction, not the average', () => {+ // Red on the +Z half of the sphere (the image's centre column), green behind.+ const sh = projectIrradianceSH(panorama(64, 32,+ (x) => (x > 16 && x < 48 ? [1, 0, 0] : [0, 1, 0])));+ const front = evalIrradianceSH(sh, 0, 0, 1);+ const back = evalIrradianceSH(sh, 0, 0, -1);+ expect(front[0]).toBeGreaterThan(front[1]);+ expect(back[1]).toBeGreaterThan(back[0]);+ });+});++describe('octahedral mapping', () => {+ it('round-trips every direction it is given', () => {+ const third = 1 / Math.sqrt(3);+ for (const d of [[0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0], [0, 0, 1], [0, 0, -1],+ [third, third, third], [-third, -third, third]]) {+ const [u, v] = octEncode(d[0], d[1], d[2]);+ expect(u).toBeGreaterThanOrEqual(0);+ expect(u).toBeLessThanOrEqual(1);+ const back = octDecode(u, v);+ for (let i = 0; i < 3; i++) expect(back[i]).toBeCloseTo(d[i]!, 5);+ }+ });++ it('stays continuous just outside the square, which is what the border is for', () => {+ // The texel one step past the edge must be the direction its neighbour across+ // the fold sees — otherwise a bilinear tap at the seam blends in nothing.+ const inside = octDecode(0.02, 0.5);+ const outside = octDecode(-0.02, 0.5);+ const dot = inside[0] * outside[0] + inside[1] * outside[1] + inside[2] * outside[2];+ expect(dot).toBeGreaterThan(0.99);+ });+});++describe('RGBM', () => {+ it('round-trips values across the range within a percent of full scale', () => {+ for (const v of [0, 0.01, 0.1, 0.5, 1, 3, 7.9]) {+ const out = new Uint8Array(4);+ encodeRgbm(v, v * 0.5, 0, ENV_MAX_RANGE, out, 0);+ const [r, g, b] = decodeRgbm(out[0]!, out[1]!, out[2]!, out[3]!, ENV_MAX_RANGE);+ expect(Math.abs(r - v)).toBeLessThan(0.08);+ expect(Math.abs(g - v * 0.5)).toBeLessThan(0.08);+ expect(b).toBeCloseTo(0, 3);+ }+ });++ it('clamps rather than wrapping above the range', () => {+ const out = new Uint8Array(4);+ encodeRgbm(100, 100, 100, ENV_MAX_RANGE, out, 0);+ const [r] = decodeRgbm(out[0]!, out[1]!, out[2]!, out[3]!, ENV_MAX_RANGE);+ expect(r).toBeCloseTo(ENV_MAX_RANGE, 1);+ });+});++describe('prefiltered atlas', () => {+ it('stacks the mips with a border between them', () => {+ const { width, height, offsets } = atlasLayout(128, 6);+ expect(width).toBe(130);+ expect(height).toBe(130 + 66 + 34 + 18 + 10 + 6);+ expect(offsets[0]).toBe(0);+ expect(offsets[1]).toBe(130);+ // The closed form the shader uses instead of a loop.+ for (let mip = 0; mip < 6; mip++) {+ expect(offsets[mip]).toBe(2 * 128 * (1 - Math.pow(2, -mip)) + 2 * mip);+ }+ });++ it('reproduces the source in mip 0 and averages it away by the last', () => {+ // Sky above, ground below: a mirror sees the half it faces; a fully rough+ // surface sees the whole sphere at once.+ const env = panorama(64, 32, (_x, y) => (y < 16 ? [0, 0, 4] : [1, 0, 0]));+ const { width, rgba } = prefilterOctahedral(env, 16, 4, ENV_MAX_RANGE);+ const { offsets } = atlasLayout(16, 4);+ const read = (mip: number, dx: number, dy: number, dz: number): [number, number, number] => {+ const size = 16 >> mip;+ const [u, v] = octEncode(dx, dy, dz);+ const px = Math.min(size - 1, Math.floor(u * size)) + 1;+ const py = offsets[mip]! + Math.min(size - 1, Math.floor(v * size)) + 1;+ const at = (py * width + px) * 4;+ return decodeRgbm(rgba[at]!, rgba[at + 1]!, rgba[at + 2]!, rgba[at + 3]!, ENV_MAX_RANGE);+ };++ const mirrorUp = read(0, 0, 1, 0);+ expect(mirrorUp[2]).toBeGreaterThan(3);+ expect(mirrorUp[0]).toBeLessThan(0.2);+ const mirrorDown = read(0, 0, -1, 0);+ expect(mirrorDown[0]).toBeGreaterThan(0.8);+ expect(mirrorDown[2]).toBeLessThan(0.2);++ // The roughest mip has seen both halves from either side, so the two agree.+ const roughUp = read(3, 0, 1, 0);+ const roughDown = read(3, 0, -1, 0);+ expect(roughUp[2]).toBeGreaterThan(0.5);+ expect(roughDown[2]).toBeGreaterThan(0.5);+ expect(Math.abs(roughUp[2] - roughDown[2])).toBeLessThan(1.5);+ });++ it('fills the border with the neighbour across the fold', () => {+ const env = panorama(64, 32, (_x, y) => (y < 16 ? [0, 0, 4] : [1, 0, 0]));+ const { width, rgba } = prefilterOctahedral(env, 8, 1, ENV_MAX_RANGE);+ const texel = (x: number, y: number): [number, number, number] => {+ const at = (y * width + x) * 4;+ return decodeRgbm(rgba[at]!, rgba[at + 1]!, rgba[at + 2]!, rgba[at + 3]!, ENV_MAX_RANGE);+ };+ // Column 0 is the border; column 1 is the face's first real texel. Both look+ // outward along -X near the horizon, so neither is the untouched black an+ // unfilled border would be.+ for (let y = 1; y <= 8; y++) {+ const border = texel(0, y);+ expect(border[0] + border[1] + border[2]).toBeGreaterThan(0.1);+ }+ });+});++describe('importEnvironment', () => {+ it('produces a document and an atlas that describe each other', () => {+ const hdr = flatHdr(32, 16, (_x, y) => (y < 8 ? [2, 2, 2] : [0, 0, 0]));+ const result = importEnvironment(hdr, 'studio', { faceSize: 8, mipCount: 3 });+ expect(result.atlasName).toBe('studio_env.png');+ expect(result.document.irradiance).toHaveLength(27);+ expect(result.document.faceSize).toBe(8);+ expect(result.document.mipCount).toBe(3);+ expect(result.document.maxRange).toBe(ENV_MAX_RANGE);+ // A PNG, and one whose size the layout predicts.+ expect(Array.from(result.atlasBytes.subarray(1, 4))).toEqual([0x50, 0x4e, 0x47]);+ const up = evalIrradianceSH(result.document.irradiance, 0, 1, 0)[0];+ const down = evalIrradianceSH(result.document.irradiance, 0, -1, 0)[0];+ expect(up).toBeGreaterThan(down + 1);+ });+});++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]);+ const out = new Float32Array(3);+ samplePanorama(env, 0, 1, 0, out);+ expect(out[1]).toBeLessThan(0.5);+ samplePanorama(env, 0, -1, 0, out);+ expect(out[1]).toBeGreaterThan(2.5);+ samplePanorama(env, 0, 0, 1, out);+ expect(out[0]).toBeCloseTo(3.5, 1);+ });+});diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 63c15cc1f..c6736cc8a 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -15,6 +15,8 @@ const REPO = path.join(PIPELINE, '..');const USAGE = `usage: node pipeline/bin/estella.mjs export <projectDir> [options]node pipeline/bin/estella.mjs import-gltf <file.gltf|file.glb> [outDir][--project <dir>] [--scale <n>]+ node pipeline/bin/estella.mjs import-hdr <file.hdr> [outDir]+ [--project <dir>] [--face-size <n>]--platform <id> web | desktop | wechat | playable | android | ios (default web)--out <dir> output dir (default <projectDir>/dist-<platform>)@@ -40,7 +42,12 @@ each piece where the source's node tree puts it, with its image and tint. A glTFholds many primitives, so it is a source that PRODUCES assets rather than one theengine loads — the products are what a scene references. Asset refs areproject-relative, so the project is found above the source unless --project says-otherwise; --scale sizes the model, whose metres are world units otherwise.`;+otherwise; --scale sizes the model, whose metres are world units otherwise.++import-hdr bakes an equirectangular panorama into the two things a renderer asks+an environment for: nine irradiance coefficients (in the \`.esenv\`) and one+prefiltered octahedral atlas beside it. The panorama itself is not shipped —+a light references the \`.esenv\`.`;/** Options take a value; these do not — without the distinction a trailing flag* swallows nothing, ends the loop, and a CI job silently gets no gate. */@@ -52,18 +59,20 @@ function parseArgs(argv) {console.log(USAGE);process.exit(0);}- if (command === 'import-gltf') {+ if (command === 'import-gltf' || command === 'import-hdr') {if (!projectDir) {console.error(USAGE);process.exit(2);}const flag = rest.indexOf('--project');const scale = rest.indexOf('--scale');+ const faceSize = rest.indexOf('--face-size');const out = rest[0] && !rest[0].startsWith('--') ? path.resolve(rest[0]) : null;return {command, out, source: path.resolve(projectDir),project: flag >= 0 && rest[flag + 1] ? path.resolve(rest[flag + 1]) : null,scale: scale >= 0 ? Number(rest[scale + 1]) || 1 : 1,+ faceSize: faceSize >= 0 ? Number(rest[faceSize + 1]) || undefined : undefined,};}if (command !== 'export' || !projectDir) {@@ -260,6 +269,47 @@ if (opts.command === 'import-gltf') {process.exit(imported > 0 ? 0 : 1);}+if (opts.command === 'import-hdr') {+ const { mod: importer, cleanup } = await loadPipeline(+ path.join(PIPELINE, 'src', 'assets', 'environmentImport.ts'), 'environmentImport.mjs');+ const { mod: meta, cleanup: cleanupMeta } = await loadPipeline(+ path.join(PIPELINE, 'src', 'assets', 'assetMeta.ts'), 'assetMeta.mjs');+ try {+ const sourceDir = path.dirname(opts.source);+ const dir = opts.out ?? sourceDir;+ const stem = path.basename(opts.source).replace(/\.hdr$/i, '');+ const root = opts.project ?? findProjectRoot(sourceDir);+ const projectRef = (abs) => path.relative(root, abs).split(path.sep).join('/');+ const result = importer.importEnvironment(+ new Uint8Array(readFileSync(opts.source)), stem, { faceSize: opts.faceSize });+ for (const w of result.warnings) console.warn(` ! ${w}`);+ if (!root) {+ console.warn(' ! no project found above the source — the atlas ref is a bare file name'+ + ' (pass --project <dir>)');+ }+ const report = (file, what) =>+ console.log(`${path.relative(process.cwd(), file)}: ${what}`);++ 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' });+ report(atlasFile, `${result.document.mipCount} prefiltered mips`);++ result.document.specular = root ? projectRef(atlasFile) : result.atlasName;+ const envFile = path.join(dir, `${stem}.esenv`);+ writeFileSync(envFile, `${JSON.stringify(result.document, null, 2)}\n`);+ await meta.adoptOrphan(envFile);+ report(envFile, `irradiance + ${result.document.faceSize}px reflection`);+ } finally {+ cleanup();+ cleanupMeta();+ }+ process.exit(0);+}+const project = projectSettings(opts.projectDir);const platform = opts.platform;diff --git a/pipeline/src/assets/environmentImport.ts b/pipeline/src/assets/environmentImport.tsnew file mode 100644index 000000000..85b9c0b4b--- /dev/null+++ b/pipeline/src/assets/environmentImport.ts@@ -0,0 +1,473 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A Radiance `.hdr` panorama → the two things a renderer actually asks an+ * environment for: irradiance for the diffuse term, and a roughness-indexed+ * reflection for the specular one.+ *+ * Both are precomputed here rather than at load: the convolutions are the+ * expensive part and the answer never changes, so the product carries it.+ * The diffuse half becomes nine spherical-harmonic coefficients — no texture+ * at all — and the specular half one ordinary RGBA8 image, so nothing+ * downstream learns a cube map or a float format.+ */+import { PNG } from 'pngjs';++/** A panorama in linear light: equirectangular, row 0 = up (+Y). */+export interface Panorama {+ width: number;+ height: number;+ /** RGB triples, `width * height * 3` linear values. */+ rgb: Float32Array;+}++/** The `.esenv` document. `specular` is filled in by the importer, which is what+ * knows the atlas' project path. */+export interface EnvironmentAssetData {+ version: number;+ /** Nine RGB coefficients, already divided by π: evaluating them at N gives the+ * value that multiplies albedo directly, the way `ambient` does. */+ irradiance: number[];+ /** The octahedral mip atlas, as an `@uuid:` reference. */+ specular: string;+ /** Edge length of mip 0's octahedral face, in texels. */+ faceSize: number;+ /** How many mips the atlas holds; mip i is prefiltered for roughness i/(mipCount-1). */+ mipCount: number;+ /** The RGBM decode range: `rgb*rgb * (a * maxRange)` is the stored radiance. */+ maxRange: number;+}++export const ENVIRONMENT_FORMAT_VERSION = 1;++/** Mip 0's face size, and how many mips follow it. Six mips put roughness on a+ * 0.2 grid, which is finer than the prefilter's own error at the rough end. */+export const ENV_FACE_SIZE = 128;+export const ENV_MIP_COUNT = 6;+/** 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;++// =============================================================================+// Radiance (.hdr) decode+// =============================================================================++/**+ * Decode a Radiance RGBE file. Both the flat and the adaptive-RLE scanline+ * encodings appear in the wild; a decoder that handles one silently produces+ * garbage for the other, so both are here.+ */+export function decodeRadianceHdr(bytes: Uint8Array): Panorama {+ let at = 0;+ const line = (): string => {+ const start = at;+ while (at < bytes.length && bytes[at] !== 0x0a) at++;+ const text = new TextDecoder().decode(bytes.subarray(start, at));+ at++;+ return text;+ };++ const magic = line();+ if (!magic.startsWith('#?')) throw new Error('not a Radiance file: no #? signature');+ let format = '';+ for (;;) {+ if (at >= bytes.length) throw new Error('Radiance header ended before the resolution line');+ const text = line();+ if (text === '') break;+ if (text.startsWith('FORMAT=')) format = text.slice(7).trim();+ }+ if (format !== '' && format !== '32-bit_rle_rgbe') {+ throw new Error(`unsupported Radiance format ${format}`);+ }++ // Only the -Y +X orientation is produced by panorama tools; another one would+ // arrive mirrored, which is worse than refused.+ const resolution = /^-Y\s+(\d+)\s+\+X\s+(\d+)$/.exec(line().trim());+ if (!resolution) throw new Error('unsupported Radiance scanline order (want "-Y h +X w")');+ const height = Number(resolution[1]);+ const width = Number(resolution[2]);++ const rgb = new Float32Array(width * height * 3);+ const scanline = new Uint8Array(width * 4);+ for (let y = 0; y < height; y++) {+ at = readScanline(bytes, at, width, scanline);+ for (let x = 0; x < width; x++) {+ const e = scanline[x * 4 + 3]!;+ const scale = e === 0 ? 0 : Math.pow(2, e - 136);+ const o = (y * width + x) * 3;+ rgb[o] = scanline[x * 4]! * scale;+ rgb[o + 1] = scanline[x * 4 + 1]! * scale;+ rgb[o + 2] = scanline[x * 4 + 2]! * scale;+ }+ }+ return { width, height, rgb };+}++/** Read one scanline into `out` as RGBE quadruples; returns where it ended. */+function readScanline(bytes: Uint8Array, at: number, width: number, out: Uint8Array): number {+ const adaptive = width >= 8 && width < 32768+ && bytes[at] === 2 && bytes[at + 1] === 2+ && ((bytes[at + 2]! << 8) | bytes[at + 3]!) === width;+ if (!adaptive) {+ // Flat RGBE. The old run marker is (1,1,1,count) — NOT an all-255 pixel,+ // which is what a mid-grey encodes to and must stay.+ let x = 0;+ while (x < width) {+ const r = bytes[at]!, g = bytes[at + 1]!, b = bytes[at + 2]!, e = bytes[at + 3]!;+ at += 4;+ if (r === 1 && g === 1 && b === 1 && x > 0) {+ const from = (x - 1) * 4;+ for (let i = 0; i < e && x < width; i++, x++) {+ out.copyWithin(x * 4, from, from + 4);+ }+ continue;+ }+ out[x * 4] = r; out[x * 4 + 1] = g; out[x * 4 + 2] = b; out[x * 4 + 3] = e;+ x++;+ }+ return at;+ }++ at += 4;+ for (let channel = 0; channel < 4; channel++) {+ let x = 0;+ while (x < width) {+ const count = bytes[at++]!;+ if (count > 128) {+ const value = bytes[at++]!;+ for (let i = 0; i < count - 128; i++) out[(x++) * 4 + channel] = value;+ } else {+ for (let i = 0; i < count; i++) out[(x++) * 4 + channel] = bytes[at++]!;+ }+ }+ }+ return at;+}++// =============================================================================+// Directions+// =============================================================================++/** Bilinear lookup of the panorama along `d` (normalized). The image's centre+ * column is +Z — the direction a head-on camera reflects — and row 0 is +Y. */+export function samplePanorama(env: Panorama, dx: number, dy: number, dz: number,+ out: Float32Array): void {+ const u = 0.5 + Math.atan2(dx, dz) / (2 * Math.PI);+ const v = Math.acos(Math.max(-1, Math.min(1, dy))) / Math.PI;+ const fx = u * env.width - 0.5;+ const fy = v * env.height - 0.5;+ const x0 = Math.floor(fx), y0 = Math.floor(fy);+ const tx = fx - x0, ty = fy - y0;+ // u wraps (the seam is continuous); v clamps (there is nothing past a pole).+ const wrapX = (x: number): number => ((x % env.width) + env.width) % env.width;+ const clampY = (y: number): number => Math.max(0, Math.min(env.height - 1, y));+ const x1 = wrapX(x0 + 1), y1 = clampY(y0 + 1);+ const xa = wrapX(x0), ya = clampY(y0);+ for (let c = 0; c < 3; c++) {+ const a = env.rgb[(ya * env.width + xa) * 3 + c]!;+ const b = env.rgb[(ya * env.width + x1) * 3 + c]!;+ const d = env.rgb[(y1 * env.width + xa) * 3 + c]!;+ const e = env.rgb[(y1 * env.width + x1) * 3 + c]!;+ out[c] = (a * (1 - tx) + b * tx) * (1 - ty) + (d * (1 - tx) + e * tx) * ty;+ }+}++/** Octahedral unit square → direction, with +Y at the centre. Values slightly+ * outside [0,1] stay continuous, which is what makes the atlas' border texels+ * the neighbours a bilinear tap expects. */+export function octDecode(u: number, v: number): [number, number, number] {+ const fx = u * 2 - 1;+ const fz = v * 2 - 1;+ let x = fx;+ let z = fz;+ const y = 1 - Math.abs(fx) - Math.abs(fz);+ if (y < 0) {+ const sx = x >= 0 ? 1 : -1;+ const sz = z >= 0 ? 1 : -1;+ x = (1 - Math.abs(fz)) * sx;+ z = (1 - Math.abs(fx)) * sz;+ }+ const len = Math.hypot(x, y, z) || 1;+ return [x / len, y / len, z / len];+}++/** The inverse of {@link octDecode}. */+export function octEncode(dx: number, dy: number, dz: number): [number, number] {+ const norm = Math.abs(dx) + Math.abs(dy) + Math.abs(dz) || 1;+ let px = dx / norm;+ let pz = dz / norm;+ if (dy < 0) {+ const sx = px >= 0 ? 1 : -1;+ const sz = pz >= 0 ? 1 : -1;+ const ax = Math.abs(px);+ const az = Math.abs(pz);+ px = (1 - az) * sx;+ pz = (1 - ax) * sz;+ }+ return [px * 0.5 + 0.5, pz * 0.5 + 0.5];+}++// =============================================================================+// Diffuse: nine coefficients+// =============================================================================++const SH_BASIS_SCALE = [+ 0.282095,+ 0.488603, 0.488603, 0.488603,+ 1.092548, 1.092548, 0.315392, 1.092548, 0.546274,+];++/** The nine real SH basis functions at `d`, in the usual l/m order. */+export function shBasis(dx: number, dy: number, dz: number, out: Float32Array): void {+ out[0] = SH_BASIS_SCALE[0]!;+ out[1] = SH_BASIS_SCALE[1]! * dy;+ out[2] = SH_BASIS_SCALE[2]! * dz;+ out[3] = SH_BASIS_SCALE[3]! * dx;+ out[4] = SH_BASIS_SCALE[4]! * dx * dy;+ out[5] = SH_BASIS_SCALE[5]! * dy * dz;+ out[6] = SH_BASIS_SCALE[6]! * (3 * dz * dz - 1);+ out[7] = SH_BASIS_SCALE[7]! * dx * dz;+ out[8] = SH_BASIS_SCALE[8]! * (dx * dx - dy * dy);+}++/**+ * Project the panorama onto nine RGB coefficients, convolved with the clamped+ * cosine lobe and divided by π. That division is what makes a constant+ * environment come back as itself — a uniform radiance c integrates to πc — so+ * these land where the flat ambient term already sits.+ */+export function projectIrradianceSH(env: Panorama): Float32Array {+ const coefficients = new Float32Array(27);+ const basis = new Float32Array(9);+ const dPhi = (2 * Math.PI) / env.width;+ const dTheta = Math.PI / env.height;+ for (let y = 0; y < env.height; y++) {+ const theta = (y + 0.5) * dTheta;+ const sinTheta = Math.sin(theta);+ const cosTheta = Math.cos(theta);+ const solidAngle = sinTheta * dTheta * dPhi;+ for (let x = 0; x < env.width; x++) {+ const phi = ((x + 0.5) / env.width - 0.5) * 2 * Math.PI;+ shBasis(sinTheta * Math.sin(phi), cosTheta, sinTheta * Math.cos(phi), basis);+ const o = (y * env.width + x) * 3;+ for (let i = 0; i < 9; i++) {+ const weighted = basis[i]! * solidAngle;+ coefficients[i * 3] += env.rgb[o]! * weighted;+ coefficients[i * 3 + 1] += env.rgb[o + 1]! * weighted;+ coefficients[i * 3 + 2] += env.rgb[o + 2]! * weighted;+ }+ }+ }++ // Ramamoorthi & Hanrahan's cosine-lobe convolution, over π.+ const band = [1.0, 2 / 3, 2 / 3, 2 / 3, 0.25, 0.25, 0.25, 0.25, 0.25];+ for (let i = 0; i < 9; i++) {+ for (let c = 0; c < 3; c++) coefficients[i * 3 + c] *= band[i]!;+ }+ return coefficients;+}++/** Evaluate {@link projectIrradianceSH}'s output at `d` — the shader's own+ * reconstruction, in TypeScript, so a test can state what a pixel should be. */+export function evalIrradianceSH(coefficients: ArrayLike<number>,+ dx: number, dy: number, dz: number): [number, number, number] {+ const basis = new Float32Array(9);+ shBasis(dx, dy, dz, basis);+ const out: [number, number, number] = [0, 0, 0];+ for (let i = 0; i < 9; i++) {+ for (let c = 0; c < 3; c++) out[c] += coefficients[i * 3 + c]! * basis[i]!;+ }+ return out;+}++// =============================================================================+// Specular: one prefiltered octahedral atlas+// =============================================================================++/** The atlas' pixel size, and where each mip's face begins in it. Mips stack+ * downward, every face ringed by one texel so a bilinear tap at the edge of one+ * never reaches into the next. */+export function atlasLayout(faceSize: number, mipCount: number): {+ width: number; height: number; offsets: number[];+} {+ const offsets: number[] = [];+ let height = 0;+ for (let mip = 0; mip < mipCount; mip++) {+ offsets.push(height);+ height += (faceSize >> mip) + 2;+ }+ return { width: faceSize + 2, height, offsets };+}++/** Van der Corput radical inverse — the second half of a Hammersley pair. */+function radicalInverse(bits: number): number {+ let b = bits;+ b = ((b << 16) | (b >>> 16)) >>> 0;+ b = (((b & 0x55555555) << 1) | ((b & 0xaaaaaaaa) >>> 1)) >>> 0;+ b = (((b & 0x33333333) << 2) | ((b & 0xcccccccc) >>> 2)) >>> 0;+ b = (((b & 0x0f0f0f0f) << 4) | ((b & 0xf0f0f0f0) >>> 4)) >>> 0;+ b = (((b & 0x00ff00ff) << 8) | ((b & 0xff00ff00) >>> 8)) >>> 0;+ return b * 2.3283064365386963e-10;+}++/**+ * GGX-importance-sample the panorama around `N`, the standard prefilter with+ * V = N. That approximation drops the stretched grazing highlight, which is the+ * price every runtime prefilter pays; the split-sum term the shader applies on+ * top is derived under the same assumption, so the two agree.+ */+function prefilterDirection(env: Panorama, roughness: number, samples: number,+ nx: number, ny: number, nz: number,+ out: Float32Array, scratch: Float32Array): void {+ out[0] = 0; out[1] = 0; out[2] = 0;+ if (roughness <= 0) {+ samplePanorama(env, nx, ny, nz, out);+ return;+ }+ // A tangent frame around N; the branch keeps the helper axis off N.+ const ax = Math.abs(nz) < 0.999 ? 0 : 1;+ let tx = ax === 0 ? -ny : 0;+ let ty = ax === 0 ? nx : nz;+ let tz = ax === 0 ? 0 : -ny;+ const tl = Math.hypot(tx, ty, tz) || 1;+ tx /= tl; ty /= tl; tz /= tl;+ const bx = ny * tz - nz * ty;+ const by = nz * tx - nx * tz;+ const bz = nx * ty - ny * tx;++ const a = roughness * roughness;+ let weight = 0;+ for (let i = 0; i < samples; i++) {+ const u1 = (i + 0.5) / samples;+ const u2 = radicalInverse(i);+ const phi = 2 * Math.PI * u1;+ const cosTheta = Math.sqrt((1 - u2) / (1 + (a * a - 1) * u2));+ const sinTheta = Math.sqrt(Math.max(0, 1 - cosTheta * cosTheta));+ const hx = sinTheta * Math.cos(phi);+ const hy = sinTheta * Math.sin(phi);+ const wx = tx * hx + bx * hy + nx * cosTheta;+ const wy = ty * hx + by * hy + ny * cosTheta;+ const wz = tz * hx + bz * hy + nz * cosTheta;+ const vdoth = nx * wx + ny * wy + nz * wz;+ const lx = 2 * vdoth * wx - nx;+ const ly = 2 * vdoth * wy - ny;+ const lz = 2 * vdoth * wz - nz;+ const ndotl = nx * lx + ny * ly + nz * lz;+ if (ndotl <= 0) continue;+ samplePanorama(env, lx, ly, lz, scratch);+ out[0] += scratch[0]! * ndotl;+ out[1] += scratch[1]! * ndotl;+ out[2] += scratch[2]! * ndotl;+ weight += ndotl;+ }+ if (weight > 0) {+ out[0] /= weight; out[1] /= weight; out[2] /= weight;+ }+}++/** RGBM, gamma-2 in the colour channels: an 8-bit encoding whose channels each+ * interpolate the way the GPU is about to interpolate them. */+export function encodeRgbm(r: number, g: number, b: number, maxRange: number,+ out: Uint8Array, at: number): void {+ const sr = Math.sqrt(Math.max(0, r) / maxRange);+ const sg = Math.sqrt(Math.max(0, g) / maxRange);+ const sb = Math.sqrt(Math.max(0, b) / maxRange);+ const m = Math.min(1, Math.max(sr, sg, sb, 1 / 255));+ const a = Math.ceil(m * 255) / 255;+ out[at] = Math.round(Math.min(1, sr / a) * 255);+ out[at + 1] = Math.round(Math.min(1, sg / a) * 255);+ out[at + 2] = Math.round(Math.min(1, sb / a) * 255);+ out[at + 3] = Math.round(a * 255);+}++/** The inverse of {@link encodeRgbm} — the same expression the shader runs. */+export function decodeRgbm(r: number, g: number, b: number, a: number,+ maxRange: number): [number, number, number] {+ const f = (v: number): number => ((v / 255) * (a / 255)) ** 2 * maxRange;+ return [f(r), f(g), f(b)];+}++/** Prefilter `env` into the octahedral mip atlas, as RGBA8 rows top-first. */+export function prefilterOctahedral(env: Panorama, faceSize = ENV_FACE_SIZE,+ mipCount = ENV_MIP_COUNT,+ maxRange = ENV_MAX_RANGE): {+ width: number; height: number; rgba: Uint8Array;+} {+ const { width, height, offsets } = atlasLayout(faceSize, mipCount);+ const rgba = new Uint8Array(width * height * 4);+ const colour = new Float32Array(3);+ const scratch = new Float32Array(3);+ for (let mip = 0; mip < mipCount; mip++) {+ const size = faceSize >> mip;+ const roughness = mipCount > 1 ? mip / (mipCount - 1) : 0;+ // Fewer texels to fill as the lobe widens, so the sample count can climb+ // without the cost doing the same.+ const samples = mip === 0 ? 1 : Math.min(256, 64 << mip);+ for (let y = -1; y <= size; y++) {+ for (let x = -1; x <= size; x++) {+ const u = (x + 0.5) / size;+ const v = (y + 0.5) / size;+ const [dx, dy, dz] = octDecode(u, v);+ prefilterDirection(env, roughness, samples, dx, dy, dz, colour, scratch);+ const px = x + 1;+ const py = offsets[mip]! + y + 1;+ encodeRgbm(colour[0]!, colour[1]!, colour[2]!, maxRange,+ rgba, (py * width + px) * 4);+ }+ }+ }+ return { width, height, rgba };+}++/** Encode raw RGBA8 (row 0 = top) as PNG bytes. */+export function encodeAtlasPng(width: number, height: number, rgba: Uint8Array): Uint8Array {+ const png = new PNG({ width, height });+ png.data = Buffer.from(rgba);+ return new Uint8Array(PNG.sync.write(png));+}++/** 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;+ /** The `.esenv` document, with `specular` still empty. */+ document: EnvironmentAssetData;+ /** What the source says that this import had to reinterpret. */+ warnings: string[];+}++/**+ * 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.+ */+export function importEnvironment(bytes: Uint8Array, stem: string,+ options: { faceSize?: number; mipCount?: number } = {}):+ ImportedEnvironment {+ const faceSize = options.faceSize ?? ENV_FACE_SIZE;+ const mipCount = options.mipCount ?? ENV_MIP_COUNT;+ const panorama = decodeRadianceHdr(bytes);+ const warnings: string[] = [];+ // Equirectangular is 2:1 by construction. Another ratio still bakes, but the+ // sphere it wraps onto is not the one the file draws — said, not guessed at.+ if (Math.abs(panorama.width - panorama.height * 2) > 1) {+ warnings.push(`the panorama is ${panorama.width}x${panorama.height}, not the 2:1 an`+ + ' equirectangular projection is; it was wrapped as if it were');+ }+ const irradiance = projectIrradianceSH(panorama);+ const atlas = prefilterOctahedral(panorama, faceSize, mipCount, ENV_MAX_RANGE);+ return {+ atlasName: `${stem}_env.png`,+ atlasBytes: encodeAtlasPng(atlas.width, atlas.height, atlas.rgba),+ warnings,+ document: {+ version: ENVIRONMENT_FORMAT_VERSION,+ irradiance: Array.from(irradiance),+ specular: '',+ faceSize,+ mipCount,+ maxRange: ENV_MAX_RANGE,+ },+ };+}diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.tsindex 230f016a1..0843e0216 100644--- a/pipeline/src/project/importSettings.ts+++ b/pipeline/src/project/importSettings.ts@@ -137,10 +137,20 @@ const MODEL: ImporterFieldSpec[] = [},];+const PANORAMA: ImporterFieldSpec[] = [+ {+ key: 'faceSize', label: 'Reflection Size', type: 'enum', default: 128, category: 'Import',+ options: [32, 64, 128, 256].map((n) => ({ label: `${n} px`, value: n })),+ tooltip: 'Edge length of the sharpest prefiltered reflection. Larger keeps a mirror '+ + 'crisper and costs baking time; the diffuse half is nine numbers either way.',+ },+];+/** type → its import-setting field specs. Types absent here have no import* settings (only metadata) and get an empty defaults object. */export const IMPORTER_SCHEMAS: Record<string, ImporterFieldSpec[]> = {model: MODEL,+ panorama: PANORAMA,texture: TEXTURE,sprite: TEXTURE,spine: SPINE,diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex bb88f2a3c..ad888adfe 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -88,6 +88,10 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [{ extensions: ['esanimator'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// Behavior tree (registerBt / BtAssetLoader) — data-driven BT definition.{ extensions: ['esbt'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },+ // Prefiltered environment: nine irradiance coefficients inline, plus the path+ // of the octahedral atlas they were baked beside — hence the transitive dep,+ // without which the cook ships the document and culls the image it is half of.+ { extensions: ['esenv'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },];const MIME_MAP: Record<string, string> = {@@ -126,6 +130,7 @@ const MIME_MAP: Record<string, string> = {esfsm: 'application/json',esanimator: 'application/json',esbt: 'application/json',+ esenv: 'application/json',bmfont: 'application/json',fnt: 'text/plain',};diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex 09d896027..d43190e71 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -66,6 +66,10 @@ export const EXT_TO_TYPE = Object.freeze({// products for that reason — the engine loads no model format.'.gltf': 'model','.glb': 'model',+ // The same shape for lighting: a `.hdr` panorama is import-only and produces+ // the `.esenv` + atlas a scene references.+ '.hdr': 'panorama',+ '.esenv': 'environment','.esmesh': 'mesh','.esanim': 'animclip','.esanimclip': 'animclip',