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(lighting): a scene says how it is lit, and whether its light still describes it
esengineaa7aed244c97
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 072d0f9a7..99ca44376 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,24 @@ published separately; it ships inside the editor.### Added+- **A scene says how it is lit, and whether its light still describes it.** The+ bake's knobs — atlas size, density, bounces, samples — had no home: both doors+ fell back to the same defaults and neither could be told otherwise. A+ `BakedLighting` component is that home, on the shape `StreamedWorld` has, and+ both doors read it.++ It also records what the last bake READ, as a fingerprint of every value a bake+ takes: the meshes and where they stand, the lights, the volumes, the knobs.+ Comparing it to what the scene fingerprints to now answers "is this light out+ of date" without re-running the bake to find out — and both collectors+ fingerprint the REFS a document spells rather than the paths they resolve to,+ so a project in two checkouts fingerprints alike.++ A **Lighting panel** shows that answer, with what a bake would take and what it+ would refuse, and the knobs beside it. It is a view of the one component, not a+ second home for the numbers: editing there goes through the same write door as+ any inspector edit. `get_bake_status` is the same reading, for automation.+- **A bake now solves the probes too, and refuses to light what moves.** One passover one light field produces both: the atlas the surfaces read, and ninecoefficients at every point of each `LightProbeVolume`'s grid. A probe gathers@@ -63,6 +81,19 @@ published separately; it ships inside the editor.### Fixed+- **The command line bakes the meshes a scene actually names.** An asset ref is+ PROJECT-relative, and `bake-scene` resolved it against the scene's own folder —+ so every object drawing a real `.esmesh` fell out of the bake with "draws no+ mesh asset", and only scenes built from stock geometry came out lit. It now+ resolves against the project root and reads `@uuid:` refs out of the `.meta`+ index, which is what the editor's own collector does.++- **Both bake doors read a light the same way.** A spot's inner angle defaults to+ 30 degrees, and the command line filled an unstated one in with 45. One reading+ now serves both — the document's values over the component's own defaults —+ along with one transform compose and one `.esprobes` writer. Three places where+ the editor and CI could quietly disagree about the same scene.+- **A scene's ambient light reaches its bake.** `LightType.Ambient` is the thirdvalue of the enum and `Spot` the fourth, and both bake collectors read the thirdas a spot lamp — so the sky lit nothing it was not standing next to. An ambientdiff --git a/desktop b/desktopindex cb3b28b14..89b74039d 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit cb3b28b146211ed9add002c1a8ff1127c68977f3+Subproject commit 89b74039d21c455ea3e60dd1b4983380a1d6085ediff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex b919cb7ff..9ace8db32 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 114,"beta": 101,- "experimental": 1900,+ "experimental": 1909,"deprecated": 3},- "total": 2115,+ "total": 2124,"subsystems": [{"id": "ecs",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex ce3694b17..f3ad4184b 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -77,6 +77,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {MeshMorph: { category: 'graphics', summary: 'How far a MeshRenderer is blended towards each of the shapes its mesh carries — one weight per morph target.', doc: 'assets/models', anchor: 'morph-targets', anchorZh: 'morph-target' },MeshLightmap: { category: 'graphics', summary: 'Where a MeshRenderer\'s baked light comes from — the atlas, and the rectangle of it this object occupies.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },LightProbeVolume: { category: 'graphics', summary: 'A box of baked irradiance on a grid — what lights the things a lightmap cannot hold still, characters included.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },+ BakedLighting: { category: 'graphics', summary: 'How this scene is baked — atlas size, density, bounces — and a record of what the last bake read.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },StreamedWorld: { category: 'world', summary: 'Declares the scene a streamed world and how big the cook cuts its cells.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },WorldPersistent: { category: 'world', summary: 'Keeps an entity\'s whole subtree out of the partition — it belongs to the persistent world.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },WorldStreamingSource: { category: 'world', summary: 'Asks for the places near it to exist; several sources are unioned.', doc: 'world/streaming', anchor: 'asking-for-places-streaming-sources', anchorZh: '请求地方存在流送源' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex e1ccfb704..3b796e62c 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -173,6 +173,61 @@"priority"]},+ {+ "name": "BakedLighting",+ "source": "ts",+ "fields": [+ {+ "key": "atlasSize",+ "type": "number",+ "default": "1024",+ "doc": "Side of the square atlas, in texels.",+ "range": "≥ 64, step 64"+ },+ {+ "key": "texelsPerUnit",+ "type": "number",+ "default": "0.25",+ "doc": "How finely a surface is lit. A world unit is a design pixel.",+ "range": "≥ 0.01, step 0.05"+ },+ {+ "key": "bounces",+ "type": "number",+ "default": "2",+ "doc": "How many times light may reflect. 0 = direct only.",+ "range": "0–8"+ },+ {+ "key": "samples",+ "type": "number",+ "default": "64",+ "doc": "Rays each lumel gathers per bounce.",+ "range": "≥ 1"+ },+ {+ "key": "probeSamples",+ "type": "number",+ "default": "128",+ "doc": "Directions each probe gathers, over the whole sphere.",+ "range": "≥ 1"+ },+ {+ "key": "bakedFrom",+ "type": "string",+ "default": "empty",+ "doc": "Fingerprint of the inputs the last bake read.",+ "advanced": true+ }+ ],+ "animatable": [+ "atlasSize",+ "texelsPerUnit",+ "bounces",+ "samples",+ "probeSamples"+ ]+ },{"name": "BehaviorTreeAgent","source": "ts",diff --git a/examples/physics-3d/assets/scenes/main.esscene b/examples/physics-3d/assets/scenes/main.essceneindex 715dbd5fd..e7928a37a 100644--- a/examples/physics-3d/assets/scenes/main.esscene+++ b/examples/physics-3d/assets/scenes/main.esscene@@ -1507,6 +1507,26 @@}]},+ {+ "id": 49,+ "name": "Lighting",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "BakedLighting",+ "data": {+ "atlasSize": 1024,+ "texelsPerUnit": 0.25,+ "bounces": 2,+ "samples": 64,+ "probeSamples": 128,+ "bakedFrom": "d5774992810126ae"+ }+ }+ ]+ },{"id": 50,"name": "Probes",diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex e1a07a62a..61e570d11 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -3,7 +3,7 @@//// Package a project without the editor. `--help` states the options.import path from 'node:path';-import { existsSync, readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';+import { existsSync, readFileSync, readdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { createRequire } from 'node:module';import { installedTemplateDir, iosTemplateSources } from '../../build-tools/utils/nativeTemplate.js';@@ -118,33 +118,52 @@ const HOST_DESKTOP_OS = process.platform === 'darwin' ? 'macos'const BAKE_IDENTITY_Q = { x: 0, y: 0, z: 0, w: 1 };const BAKE_ONE = { x: 1, y: 1, z: 1 };const BAKE_ZERO = { x: 0, y: 0, z: 0 };-// LightType's own order. 2 is AMBIENT, which occupies no slot and no direction:-// it is light from everywhere, and a bake takes it as its ambient term rather-// than as a fourth kind of lamp.-const BAKE_LIGHT_KIND = { 0: 'point', 1: 'directional', 3: 'spot' };-const BAKE_LIGHT_AMBIENT = 2;const bakeComponent = (entity, type) => entity.components?.find((c) => c.type === type);-const bakeVec = (v, fallback) => ({ ...fallback, ...(v ?? {}) });-/** Column-major 4x4 from a document's Transform. Flat scenes only — see bakeScene. */-function bakeTransformOf(entity) {- const tf = bakeComponent(entity, 'Transform')?.data ?? {};- const p = bakeVec(tf.position, BAKE_ZERO);- const { x, y, z, w } = bakeVec(tf.rotation, BAKE_IDENTITY_Q);- const s = bakeVec(tf.scale, BAKE_ONE);- return [- (1 - 2 * (y * y + z * z)) * s.x, (2 * (x * y + z * w)) * s.x, (2 * (x * z - y * w)) * s.x, 0,- (2 * (x * y - z * w)) * s.y, (1 - 2 * (x * x + z * z)) * s.y, (2 * (y * z + x * w)) * s.y, 0,- (2 * (x * z + y * w)) * s.z, (2 * (y * z - x * w)) * s.z, (1 - 2 * (x * x + y * y)) * s.z, 0,- p.x, p.y, p.z, 1,- ];+/** The project a scene belongs to: the nearest ancestor holding a `.esproject`.+ * An asset ref is PROJECT-relative, which is what the editor resolves against. */+function bakeProjectRoot(sceneFile) {+ let dir = path.dirname(sceneFile);+ for (;;) {+ if (existsSync(path.join(dir, 'project.esproject'))) return dir;+ const up = path.dirname(dir);+ if (up === dir) return null;+ dir = up;+ }}-/** Where a light aims: -Z under its rotation, as the renderer reads it. */-function bakeForwardOf(q) {- const { x, y, z, w } = q;- return [-2 * (x * z + y * w), -2 * (y * z - x * w), -(1 - 2 * (x * x + y * y))];+/** uuid -> project-relative path, out of the `.meta` beside each asset. A scene+ * the editor saved names its assets by uuid and one a person wrote names them+ * by path; both have to reach the same file. */+function bakeAssetIndex(root) {+ const index = new Map();+ if (!root) return index;+ const walk = (dir) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const at = path.join(dir, entry.name);+ if (entry.isDirectory()) { if (entry.name[0] !== '.') walk(at); continue; }+ if (!entry.name.endsWith('.meta')) continue;+ try {+ const uuid = JSON.parse(readFileSync(at, 'utf8')).uuid;+ if (typeof uuid === 'string') {+ index.set(uuid, path.relative(root, at.slice(0, -'.meta'.length)).split(path.sep).join('/'));+ }+ } catch { /* a half-written .meta names nothing */ }+ }+ };+ walk(root);+ return index;+}+const bakeVec = (v, fallback) => ({ ...fallback, ...(v ?? {}) });++/** Column-major 4x4 from a document's Transform, through the SDK's own compose.+ * Flat scenes only — see bakeScene. */+function bakeTransformOf(baker, entity) {+ const tf = bakeComponent(entity, 'Transform')?.data ?? {};+ return baker.composeTRS(bakeVec(tf.position, BAKE_ZERO),+ bakeVec(tf.rotation, BAKE_IDENTITY_Q),+ bakeVec(tf.scale, BAKE_ONE));}/**@@ -166,10 +185,36 @@ async function bakeScene(baker, sceneFile, check) {return 1;}+ // The scene's own knobs, where it states them. Absent leaves the bake at its+ // defaults, which is what every scene got before the component existed.+ const declared = (scene.entities ?? [])+ .map((e) => bakeComponent(e, 'BakedLighting')).find(Boolean)?.data ?? {};+ const options = {+ atlasSize: declared.atlasSize, texelsPerUnit: declared.texelsPerUnit,+ bounces: declared.bounces, samples: declared.samples,+ probeSamples: declared.probeSamples,+ };+ for (const k of Object.keys(options)) if (typeof options[k] !== 'number') delete options[k];++ // Where an asset ref resolves to. Not relative to the SCENE: a ref is what the+ // project's asset browser shows, and the editor resolves it against the root.+ const projectRoot = bakeProjectRoot(sceneFile);+ const byUuid = bakeAssetIndex(projectRoot);+ const resolveRef = (ref) => {+ if (typeof ref !== 'string' || ref === '') return '';+ const relative = ref.startsWith('@uuid:') ? byUuid.get(ref.slice(6)) : ref;+ if (!relative) return '';+ return projectRoot ? path.resolve(projectRoot, relative) : path.resolve(sceneDir, relative);+ };+const surfaces = [];const lights = [];const volumes = [];const ambient = [0, 0, 0];+ // The REF as the document spells it, not the path it resolves to: the editor's+ // collector fingerprints the same string, and an absolute path would differ+ // between two checkouts of one project.+ const fingerprintSurfaces = [];for (const entity of scene.entities ?? []) {const tf = bakeComponent(entity, 'Transform')?.data ?? {};const mesh = bakeComponent(entity, 'MeshRenderer');@@ -187,46 +232,48 @@ async function bakeScene(baker, sceneFile, check) {if (mesh && mesh.data?.enabled !== false) {const ref = typeof mesh.data?.mesh === 'string' ? mesh.data.mesh : '';const builtin = ref.startsWith('builtin:') ? ref : undefined;- const file = builtin ? '' : path.resolve(sceneDir, ref);+ const file = builtin ? '' : resolveRef(ref);if (builtin || (ref && existsSync(file))) {const c = mesh.data?.color;const body = bakeComponent(entity, 'RigidBody3D');+ const textureRef = typeof mesh.data?.texture === 'string' ? mesh.data.texture : '';+ const textureFile = resolveRef(textureRef);+ const transform = bakeTransformOf(baker, entity);+ const holdsStill = baker.bakeHoldsStill({+ characterController: !!bakeComponent(entity, 'CharacterController3D'),+ bodyType: body ? (body.data?.bodyType ?? 2) : undefined,+ });+ const albedo = c ? [c.r ?? 1, c.g ?? 1, c.b ?? 1] : undefined;surfaces.push({entity: entity.id, label: entity.name ?? String(entity.id),- meshFile: file, builtinRef: builtin, transform: bakeTransformOf(entity),- baseColor: c ? [c.r ?? 1, c.g ?? 1, c.b ?? 1] : undefined,- holdsStill: baker.bakeHoldsStill({- characterController: !!bakeComponent(entity, 'CharacterController3D'),- bodyType: body ? (body.data?.bodyType ?? 2) : undefined,- }),+ meshFile: file, builtinRef: builtin, transform,+ baseColor: albedo, holdsStill,+ baseColorTexture: textureFile && existsSync(textureFile) ? textureFile : undefined,});+ fingerprintSurfaces.push({ mesh: ref, transform, albedo, texture: textureRef, holdsStill });}}- if (light && light.data?.enabled !== false) {- const d = light.data ?? {};+ if (light) {const p = bakeVec(tf.position, BAKE_ZERO);- if ((d.type ?? 0) === BAKE_LIGHT_AMBIENT) {- const i = d.intensity ?? 1;- ambient[0] += (d.color?.r ?? 1) * i;- ambient[1] += (d.color?.g ?? 1) * i;- ambient[2] += (d.color?.b ?? 1) * i;- continue;+ const made = baker.bakeLightOf(light.data, [p.x, p.y, p.z],+ bakeVec(tf.rotation, BAKE_IDENTITY_Q));+ if (made?.lamp) lights.push(made.lamp);+ else if (made?.ambient) {+ ambient[0] += made.ambient[0];+ ambient[1] += made.ambient[1];+ ambient[2] += made.ambient[2];}- const kind = BAKE_LIGHT_KIND[d.type ?? 0] ?? 'point';- const cos = (deg) => Math.cos(((deg ?? 45) * Math.PI) / 180 / 2);- lights.push({- kind, position: [p.x, p.y, p.z],- direction: bakeForwardOf(bakeVec(tf.rotation, BAKE_IDENTITY_Q)),- color: [d.color?.r ?? 1, d.color?.g ?? 1, d.color?.b ?? 1],- intensity: d.intensity ?? 1,- radius: kind === 'directional' ? undefined : (d.radius ?? 200),- innerCos: cos(d.innerAngle), outerCos: cos(d.outerAngle),- });}}+ const fingerprint = baker.bakeFingerprint({+ surfaces: fingerprintSurfaces, lights,+ volumes: volumes.map((v) => ({ center: v.center, halfExtents: v.halfExtents,+ spacing: v.spacing })),+ ambient, options,+ });const result = baker.bakeSceneLightmap({- surfaces, lights, probeVolumes: volumes, options: { ambient },+ surfaces, lights, probeVolumes: volumes, options: { ...options, ambient },});for (const w of result.warnings) console.warn(` ! ${w}`);@@ -241,9 +288,7 @@ async function bakeScene(baker, sceneFile, check) {if (!doc) return;grids.set(volumes[i].entity, {name: `${stem}_probes_${volumes[i].entity}.esprobes`,- text: `{\n "version": ${doc.version},\n`- + ` "resolution": ${JSON.stringify(doc.resolution)},\n`- + ` "irradiance": ${JSON.stringify(doc.irradiance)}\n}\n`,+ text: baker.probeDocumentText(doc),});});@@ -261,6 +306,14 @@ async function bakeScene(baker, sceneFile, check) {if (at >= 0) entity.components[at] = { type: 'MeshLightmap', data };else entity.components.push({ type: 'MeshLightmap', data });}+ for (const entity of scene.entities ?? []) {+ const at = entity.components.findIndex((c) => c.type === 'BakedLighting');+ if (at < 0) continue;+ entity.components[at] = {+ type: 'BakedLighting',+ data: { ...entity.components[at].data, bakedFrom: fingerprint },+ };+ }for (const entity of scene.entities ?? []) {const at = entity.components.findIndex((c) => c.type === 'LightProbeVolume');if (at < 0) continue;diff --git a/pipeline/src/assets/lightmapBake.ts b/pipeline/src/assets/lightmapBake.tsindex 8232b02f0..63856c456 100644--- a/pipeline/src/assets/lightmapBake.ts+++ b/pipeline/src/assets/lightmapBake.ts@@ -15,9 +15,11 @@ import { bakeLightmap, decodeMesh, unwrapLightmapUV, builtinMeshTemplate, MeshChtype ProbeGrid } from 'esengine';import { encodeRgbaPng } from './png';-// The rule a collector needs before it can fill in `holdsStill`, re-exported so-// the CLI reaches it through the one module it loads.-export { bakeHoldsStill, type BakeMobility } from 'esengine';+// What a collector needs to describe a surface, re-exported so the CLI reaches+// them through the one module it loads. composeTRS especially: a second+// implementation would put the two doors a rounding error apart.+export { bakeHoldsStill, bakeFingerprint, bakeLightOf, composeTRS, BAKE_DEFAULTS,+ type BakeMobility, type BakeInputs } from 'esengine';/** One placed object, as the editor's world describes it. */export interface SceneBakeSurface {@@ -109,6 +111,17 @@ export interface SceneBakeResult {* these say nothing a bake of it would reproduce anyway. */const round6 = (v: number): number => Number(v.toPrecision(6));+/**+ * An `.esprobes` document as its file. One line per member, because a grid is+ * hundreds of numbers and a diff of it is worth reading only if they stay put —+ * and ONE writer, so the two bake doors produce the same bytes.+ */+export function probeDocumentText(doc: ProbeVolumeDocument): string {+ return `{\n "version": ${doc.version},\n`+ + ` "resolution": ${JSON.stringify(doc.resolution)},\n`+ + ` "irradiance": ${JSON.stringify(doc.irradiance)}\n}\n`;+}+/** Stock geometry with a lightmap UV set, unwrapped once per bake. */function builtinGeometry(ref: string, cache: Map<string, MeshData | null>): MeshData | null {if (!cache.has(ref)) {diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 248c4b00e..4ccf3a39e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1739 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1748 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1284,6 +1284,17 @@ name: stringtype: "audio"```+## AuthoredLight — interface @experimental+```+color: { r?: number; g?: number; b?: number; } | undefined+enabled: boolean | undefined+innerAngle: number | undefined+intensity: number | undefined+outerAngle: number | undefined+radius: number | undefined+type: number | undefined+```+## Axis1D — const @public```(...bindings: Binding[]) => ActionDef@@ -1294,6 +1305,11 @@ type: "audio"(...bindings: Binding[]) => ActionDef```+## BAKE_DEFAULTS — const @experimental+```+{ atlasSize: number; texelsPerUnit: number; bounces: number; samples: number; ambient: readonly [number, number, number]; dilate: number; probeGrids: readonly ProbeGrid[]; probeSamples: number; }+```+## BUILTIN_AUDIO_BUSES — const @experimental```readonly [{ readonly name: "master"; readonly parent: null; readonly volume: 1; }, { readonly name: "music"; readonly parent: "master"; readonly volume: 0.8; }, { readonly name: "sfx"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "ui"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "voice"; readonly parent: "master"; readonly volume: 1; }]@@ -1332,6 +1348,15 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeInputs — interface @experimental+```+ambient: readonly [number, number, number] | undefined+lights: readonly BakeLight[]+options: BakeOptions | undefined+surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonly [number, number, number]; texture?: string; holdsStill?: boolean; }[]+volumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1344,6 +1369,12 @@ position: readonly [number, number, number] | undefinedradius: number | undefined```+## BakeLightContribution — type @experimental+```+| { lamp: BakeLight; ambient?: undefined }+ | { ambient: [number, number, number]; lamp?: undefined }+```+## BakeMobility — interface @experimental```bodyType: BodyType | undefined@@ -1378,6 +1409,21 @@ mesh: MeshDatatransform: ArrayLike<number>```+## BakedLighting — const @experimental+```+ComponentDef<BakedLightingData>+```++## BakedLightingData — interface @experimental+```+atlasSize: number+bakedFrom: string+bounces: number+probeSamples: number+samples: number+texelsPerUnit: number+```+## BatchBreak — enum @experimental```Blend = 4@@ -11041,11 +11087,26 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeFingerprint — function @experimental+```+(inputs: BakeInputs): string+```+## bakeHoldsStill — function @experimental```(mobility: BakeMobility): boolean```+## bakeLightForward — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number, number]+```++## bakeLightOf — function @experimental+```+(authored: AuthoredLight | undefined, position: readonly [number, number, number], rotation: { x: number; y: number; z: number; w: number; }): BakeLightContribution | null+```+## bakeLightmap — function @experimental```(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResultdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d84bd6bdc..39e996a4b 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 99 beta · 1758 experimental · 3 deprecated+Symbols: 114 public · 99 beta · 1767 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1284,6 +1284,17 @@ name: stringtype: "audio"```+## AuthoredLight — interface @experimental+```+color: { r?: number; g?: number; b?: number; } | undefined+enabled: boolean | undefined+innerAngle: number | undefined+intensity: number | undefined+outerAngle: number | undefined+radius: number | undefined+type: number | undefined+```+## Axis1D — const @public```(...bindings: Binding[]) => ActionDef@@ -1294,6 +1305,11 @@ type: "audio"(...bindings: Binding[]) => ActionDef```+## BAKE_DEFAULTS — const @experimental+```+{ atlasSize: number; texelsPerUnit: number; bounces: number; samples: number; ambient: readonly [number, number, number]; dilate: number; probeGrids: readonly ProbeGrid[]; probeSamples: number; }+```+## BUILTIN_AUDIO_BUSES — const @experimental```readonly [{ readonly name: "master"; readonly parent: null; readonly volume: 1; }, { readonly name: "music"; readonly parent: "master"; readonly volume: 0.8; }, { readonly name: "sfx"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "ui"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "voice"; readonly parent: "master"; readonly volume: 1; }]@@ -1332,6 +1348,15 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeInputs — interface @experimental+```+ambient: readonly [number, number, number] | undefined+lights: readonly BakeLight[]+options: BakeOptions | undefined+surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonly [number, number, number]; texture?: string; holdsStill?: boolean; }[]+volumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1344,6 +1369,12 @@ position: readonly [number, number, number] | undefinedradius: number | undefined```+## BakeLightContribution — type @experimental+```+| { lamp: BakeLight; ambient?: undefined }+ | { ambient: [number, number, number]; lamp?: undefined }+```+## BakeMobility — interface @experimental```bodyType: BodyType | undefined@@ -1378,6 +1409,21 @@ mesh: MeshDatatransform: ArrayLike<number>```+## BakedLighting — const @experimental+```+ComponentDef<BakedLightingData>+```++## BakedLightingData — interface @experimental+```+atlasSize: number+bakedFrom: string+bounces: number+probeSamples: number+samples: number+texelsPerUnit: number+```+## BatchBreak — enum @experimental```Blend = 4@@ -11249,11 +11295,26 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeFingerprint — function @experimental+```+(inputs: BakeInputs): string+```+## bakeHoldsStill — function @experimental```(mobility: BakeMobility): boolean```+## bakeLightForward — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number, number]+```++## bakeLightOf — function @experimental+```+(authored: AuthoredLight | undefined, position: readonly [number, number, number], rotation: { x: number; y: number; z: number; w: number; }): BakeLightContribution | null+```+## bakeLightmap — function @experimental```(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResultdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex df42adea8..232f81298 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 96 beta · 1738 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1747 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1279,6 +1279,17 @@ name: stringtype: "audio"```+## AuthoredLight — interface @experimental+```+color: { r?: number; g?: number; b?: number; } | undefined+enabled: boolean | undefined+innerAngle: number | undefined+intensity: number | undefined+outerAngle: number | undefined+radius: number | undefined+type: number | undefined+```+## Axis1D — const @public```(...bindings: Binding[]) => ActionDef@@ -1289,6 +1300,11 @@ type: "audio"(...bindings: Binding[]) => ActionDef```+## BAKE_DEFAULTS — const @experimental+```+{ atlasSize: number; texelsPerUnit: number; bounces: number; samples: number; ambient: readonly [number, number, number]; dilate: number; probeGrids: readonly ProbeGrid[]; probeSamples: number; }+```+## BUILTIN_AUDIO_BUSES — const @experimental```readonly [{ readonly name: "master"; readonly parent: null; readonly volume: 1; }, { readonly name: "music"; readonly parent: "master"; readonly volume: 0.8; }, { readonly name: "sfx"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "ui"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "voice"; readonly parent: "master"; readonly volume: 1; }]@@ -1327,6 +1343,15 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeInputs — interface @experimental+```+ambient: readonly [number, number, number] | undefined+lights: readonly BakeLight[]+options: BakeOptions | undefined+surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonly [number, number, number]; texture?: string; holdsStill?: boolean; }[]+volumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1339,6 +1364,12 @@ position: readonly [number, number, number] | undefinedradius: number | undefined```+## BakeLightContribution — type @experimental+```+| { lamp: BakeLight; ambient?: undefined }+ | { ambient: [number, number, number]; lamp?: undefined }+```+## BakeMobility — interface @experimental```bodyType: BodyType | undefined@@ -1373,6 +1404,21 @@ mesh: MeshDatatransform: ArrayLike<number>```+## BakedLighting — const @experimental+```+ComponentDef<BakedLightingData>+```++## BakedLightingData — interface @experimental+```+atlasSize: number+bakedFrom: string+bounces: number+probeSamples: number+samples: number+texelsPerUnit: number+```+## BatchBreak — enum @experimental```Blend = 4@@ -11036,11 +11082,26 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeFingerprint — function @experimental+```+(inputs: BakeInputs): string+```+## bakeHoldsStill — function @experimental```(mobility: BakeMobility): boolean```+## bakeLightForward — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number, number]+```++## bakeLightOf — function @experimental+```+(authored: AuthoredLight | undefined, position: readonly [number, number, number], rotation: { x: number; y: number; z: number; w: number; }): BakeLightContribution | null+```+## bakeLightmap — function @experimental```(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResultdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 258cddc79..6efab7db4 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1760 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1769 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1279,6 +1279,17 @@ name: stringtype: "audio"```+## AuthoredLight — interface @experimental+```+color: { r?: number; g?: number; b?: number; } | undefined+enabled: boolean | undefined+innerAngle: number | undefined+intensity: number | undefined+outerAngle: number | undefined+radius: number | undefined+type: number | undefined+```+## Axis1D — const @public```(...bindings: Binding[]) => ActionDef@@ -1289,6 +1300,11 @@ type: "audio"(...bindings: Binding[]) => ActionDef```+## BAKE_DEFAULTS — const @experimental+```+{ atlasSize: number; texelsPerUnit: number; bounces: number; samples: number; ambient: readonly [number, number, number]; dilate: number; probeGrids: readonly ProbeGrid[]; probeSamples: number; }+```+## BUILTIN_AUDIO_BUSES — const @experimental```readonly [{ readonly name: "master"; readonly parent: null; readonly volume: 1; }, { readonly name: "music"; readonly parent: "master"; readonly volume: 0.8; }, { readonly name: "sfx"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "ui"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "voice"; readonly parent: "master"; readonly volume: 1; }]@@ -1327,6 +1343,15 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeInputs — interface @experimental+```+ambient: readonly [number, number, number] | undefined+lights: readonly BakeLight[]+options: BakeOptions | undefined+surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonly [number, number, number]; texture?: string; holdsStill?: boolean; }[]+volumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1339,6 +1364,12 @@ position: readonly [number, number, number] | undefinedradius: number | undefined```+## BakeLightContribution — type @experimental+```+| { lamp: BakeLight; ambient?: undefined }+ | { ambient: [number, number, number]; lamp?: undefined }+```+## BakeMobility — interface @experimental```bodyType: BodyType | undefined@@ -1373,6 +1404,21 @@ mesh: MeshDatatransform: ArrayLike<number>```+## BakedLighting — const @experimental+```+ComponentDef<BakedLightingData>+```++## BakedLightingData — interface @experimental+```+atlasSize: number+bakedFrom: string+bounces: number+probeSamples: number+samples: number+texelsPerUnit: number+```+## BatchBreak — enum @experimental```Blend = 4@@ -11290,11 +11336,26 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeFingerprint — function @experimental+```+(inputs: BakeInputs): string+```+## bakeHoldsStill — function @experimental```(mobility: BakeMobility): boolean```+## bakeLightForward — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number, number]+```++## bakeLightOf — function @experimental+```+(authored: AuthoredLight | undefined, position: readonly [number, number, number], rotation: { x: number; y: number; z: number; w: number; }): BakeLightContribution | null+```+## bakeLightmap — function @experimental```(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResultdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 88cb663ed..2a75046eb 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1750 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1759 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1279,6 +1279,17 @@ name: stringtype: "audio"```+## AuthoredLight — interface @experimental+```+color: { r?: number; g?: number; b?: number; } | undefined+enabled: boolean | undefined+innerAngle: number | undefined+intensity: number | undefined+outerAngle: number | undefined+radius: number | undefined+type: number | undefined+```+## Axis1D — const @public```(...bindings: Binding[]) => ActionDef@@ -1289,6 +1300,11 @@ type: "audio"(...bindings: Binding[]) => ActionDef```+## BAKE_DEFAULTS — const @experimental+```+{ atlasSize: number; texelsPerUnit: number; bounces: number; samples: number; ambient: readonly [number, number, number]; dilate: number; probeGrids: readonly ProbeGrid[]; probeSamples: number; }+```+## BUILTIN_AUDIO_BUSES — const @experimental```readonly [{ readonly name: "master"; readonly parent: null; readonly volume: 1; }, { readonly name: "music"; readonly parent: "master"; readonly volume: 0.8; }, { readonly name: "sfx"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "ui"; readonly parent: "master"; readonly volume: 1; }, { readonly name: "voice"; readonly parent: "master"; readonly volume: 1; }]@@ -1327,6 +1343,15 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeInputs — interface @experimental+```+ambient: readonly [number, number, number] | undefined+lights: readonly BakeLight[]+options: BakeOptions | undefined+surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonly [number, number, number]; texture?: string; holdsStill?: boolean; }[]+volumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1339,6 +1364,12 @@ position: readonly [number, number, number] | undefinedradius: number | undefined```+## BakeLightContribution — type @experimental+```+| { lamp: BakeLight; ambient?: undefined }+ | { ambient: [number, number, number]; lamp?: undefined }+```+## BakeMobility — interface @experimental```bodyType: BodyType | undefined@@ -1373,6 +1404,21 @@ mesh: MeshDatatransform: ArrayLike<number>```+## BakedLighting — const @experimental+```+ComponentDef<BakedLightingData>+```++## BakedLightingData — interface @experimental+```+atlasSize: number+bakedFrom: string+bounces: number+probeSamples: number+samples: number+texelsPerUnit: number+```+## BatchBreak — enum @experimental```Blend = 4@@ -11064,11 +11110,26 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeFingerprint — function @experimental+```+(inputs: BakeInputs): string+```+## bakeHoldsStill — function @experimental```(mobility: BakeMobility): boolean```+## bakeLightForward — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number, number]+```++## bakeLightOf — function @experimental+```+(authored: AuthoredLight | undefined, position: readonly [number, number, number], rotation: { x: number; y: number; z: number; w: number; }): BakeLightContribution | null+```+## bakeLightmap — function @experimental```(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResultdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 2aafb88e7..67098438d 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -152,7 +152,18 @@ export {*/export {bakeLightmap, type BakeOptions, type BakeResult, type BakeSurface, type BakeLight,- type ProbeGrid, bakeHoldsStill, type BakeMobility,+ type ProbeGrid, bakeHoldsStill, type BakeMobility, BAKE_DEFAULTS,+} from './lightmap';+/**+ * What a scene declares about its baked light: the knobs, and the fingerprint of+ * what the last bake read. The engine never looks at it — a bake is a+ * creation-time act — but every door into one does.+ *+ * @experimental Pre-1.0: the knobs follow what a baker turns out to need.+ */+export {+ BakedLighting, type BakedLightingData, bakeFingerprint, type BakeInputs,+ bakeLightOf, bakeLightForward, type AuthoredLight, type BakeLightContribution,} from './lightmap';/*** Nine coefficients, as the shader reads them. A panorama import and a probediff --git a/sdk/src/lightmap/bake.ts b/sdk/src/lightmap/bake.tsindex e202dd6f4..ea4f2ea7b 100644--- a/sdk/src/lightmap/bake.ts+++ b/sdk/src/lightmap/bake.ts@@ -55,7 +55,9 @@ export interface BakeResult {probes: Float32Array[];}-const DEFAULTS = {+/** What a bake does where the caller says nothing — and what a scene's own+ * `BakedLighting` starts at, so the two cannot drift apart. */+export const BAKE_DEFAULTS = {atlasSize: 1024,texelsPerUnit: 0.25,bounces: 2,@@ -185,7 +187,7 @@ function dilate(radiance: Float32Array, solved: Uint8Array, size: number, rounds*/export function bakeLightmap(surfaces: readonly BakeSurface[], lights: readonly BakeLight[],options: BakeOptions = {}): BakeResult {- const opts = { ...DEFAULTS, ...options };+ const opts = { ...BAKE_DEFAULTS, ...options };const size = opts.atlasSize;const patches = layoutAtlas(surfaces, size, opts.texelsPerUnit);if (!patches) {diff --git a/sdk/src/lightmap/components.ts b/sdk/src/lightmap/components.tsnew file mode 100644index 000000000..17add1237--- /dev/null+++ b/sdk/src/lightmap/components.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file components.ts+ * @brief What a project AUTHORS about its baked light: how finely, and of what.+ *+ * @details One declaration and no policy, on the shape StreamedWorld has. The+ * engine never reads it — a bake is a creation-time act — so it is a+ * TypeScript component: what it carries are the knobs a baker takes and+ * the fingerprint of the last bake, which is how anything downstream+ * knows the scene has moved on since.+ */++import { defineComponent, type ComponentDef } from '../ecs/component';+import { BAKE_DEFAULTS } from './bake';++/** The fields of the `BakedLighting` component. @experimental */+export interface BakedLightingData {+ /** Side of the square atlas, in texels. */+ atlasSize: number;+ /** How finely a surface is lit, in texels per world unit. A world unit here+ * is a design pixel, so a room is hundreds of them across. */+ texelsPerUnit: number;+ /** How many times light is allowed to reflect. Zero is direct light only. */+ bounces: number;+ /** Rays each lumel gathers per bounce. */+ samples: number;+ /** Directions each probe gathers — over the whole sphere, so this buys less+ * per ray than a lumel's hemisphere does. */+ probeSamples: number;+ /** What the last bake was OF. Empty until one has run; different from what+ * the scene fingerprints to now means the light is out of date. The baker+ * writes it — not `readonly`, which means "the engine computes this and the+ * editor must not project it into the World", and this is neither. */+ bakedFrom: string;+}++/**+ * Declares how the scene carrying it is lit, and what its light was baked from.+ *+ * Presence is not the switch — a scene with nothing to light bakes to nothing+ * either way. It exists so the knobs have one home rather than one per door, and+ * so "out of date" can be asked without re-running the bake to find out.+ *+ * @experimental+ */+export const BakedLighting: ComponentDef<BakedLightingData> = defineComponent<BakedLightingData>(+ 'BakedLighting',+ {+ atlasSize: BAKE_DEFAULTS.atlasSize,+ texelsPerUnit: BAKE_DEFAULTS.texelsPerUnit,+ bounces: BAKE_DEFAULTS.bounces,+ samples: BAKE_DEFAULTS.samples,+ probeSamples: BAKE_DEFAULTS.probeSamples,+ bakedFrom: '',+ },+ {+ fields: {+ atlasSize: { min: 64, step: 64, tooltip: 'Side of the square atlas, in texels.' },+ texelsPerUnit: { min: 0.01, step: 0.05, unit: 'tx/wu',+ tooltip: 'How finely a surface is lit. A world unit is a design pixel.' },+ bounces: { min: 0, max: 8, tooltip: 'How many times light may reflect. 0 = direct only.' },+ samples: { min: 1, tooltip: 'Rays each lumel gathers per bounce.' },+ probeSamples: { min: 1, tooltip: 'Directions each probe gathers, over the whole sphere.' },+ bakedFrom: { advanced: true, tooltip: 'Fingerprint of the inputs the last bake read.' },+ },+ },+);diff --git a/sdk/src/lightmap/fingerprint.ts b/sdk/src/lightmap/fingerprint.tsnew file mode 100644index 000000000..d67e3581d--- /dev/null+++ b/sdk/src/lightmap/fingerprint.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file fingerprint.ts+ * @brief What a bake was OF, as one short string.+ *+ * @details Two collectors fill in the same shape — one from a document, one from+ * a world — and the rule for reducing it lives here, so they cannot+ * disagree about whether a scene has changed since it was lit. Order+ * does not count: the two walk their sources differently, and a scene+ * whose entities were reordered is the same scene to light.+ */++import type { BakeLight } from './solve';+import type { BakeOptions } from './bake';+import { BAKE_DEFAULTS } from './bake';++/** Everything a bake reads, at the grain a fingerprint is taken of. */+export interface BakeInputs {+ surfaces: ReadonlyArray<{+ /** The mesh's project path, or its `builtin:` ref — its identity, not its bytes. */+ mesh: string;+ /** Column-major 4x4 world transform. */+ transform: ArrayLike<number>;+ albedo?: readonly [number, number, number];+ /** The base colour texture's project path, where it has one. */+ texture?: string;+ /** False where the simulation moves it. */+ holdsStill?: boolean;+ }>;+ lights: readonly BakeLight[];+ volumes: ReadonlyArray<{+ center: readonly [number, number, number];+ halfExtents: readonly [number, number, number];+ spacing: number;+ }>;+ ambient?: readonly [number, number, number];+ options?: BakeOptions;+}++/** FNV-1a over UTF-16 code units. Two seeds, so the result is 64 bits wide. */+function fnv1a(text: string, seed: number): number {+ let h = seed >>> 0;+ for (let i = 0; i < text.length; i++) {+ h = (h ^ text.charCodeAt(i)) >>> 0;+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return h >>> 0;+}++const num = (v: number | undefined): string => (v === undefined ? '' : String(v));+const nums = (v: ArrayLike<number> | undefined): string =>+ (v === undefined ? '' : Array.from(v).join(','));++/**+ * The fingerprint of one bake's inputs.+ *+ * Every value a bake reads reaches this; nothing else does. A mesh is named by+ * its PATH rather than its bytes — a reimport that changes the geometry changes+ * the file, and the gate that rebakes byte for byte is what answers for that.+ */+export function bakeFingerprint(inputs: BakeInputs): string {+ const opts = { ...BAKE_DEFAULTS, ...inputs.options };+ const lines: string[] = [];+ for (const s of inputs.surfaces) {+ lines.push(`s|${s.mesh}|${nums(s.transform)}|${nums(s.albedo)}|${s.texture ?? ''}`+ + `|${s.holdsStill === false ? 0 : 1}`);+ }+ for (const l of inputs.lights) {+ lines.push(`l|${l.kind}|${nums(l.position)}|${nums(l.direction)}|${nums(l.color)}`+ + `|${num(l.intensity)}|${num(l.radius)}|${num(l.innerCos)}|${num(l.outerCos)}`);+ }+ for (const v of inputs.volumes) {+ lines.push(`v|${nums(v.center)}|${nums(v.halfExtents)}|${num(v.spacing)}`);+ }+ lines.sort();+ lines.push(`o|${opts.atlasSize}|${opts.texelsPerUnit}|${opts.bounces}|${opts.samples}`+ + `|${opts.probeSamples}|${opts.dilate}|${nums(inputs.ambient ?? opts.ambient)}`);+ const text = lines.join('\n');+ const hex = (v: number): string => v.toString(16).padStart(8, '0');+ return hex(fnv1a(text, 0x811c9dc5)) + hex(fnv1a(text, 0x9e3779b9));+}diff --git a/sdk/src/lightmap/index.ts b/sdk/src/lightmap/index.tsindex 7b59b751e..5de082e2c 100644--- a/sdk/src/lightmap/index.ts+++ b/sdk/src/lightmap/index.ts@@ -6,4 +6,9 @@ export type { BakeSurface } from './atlas';export type { BakeLight } from './solve';export { solveProbes, probeAt, type ProbeGrid } from './probes';export { bakeHoldsStill, type BakeMobility } from './mobility';+export { bakeFingerprint, type BakeInputs } from './fingerprint';+export { BakedLighting, type BakedLightingData } from './components';+export { bakeLightOf, bakeLightForward, type AuthoredLight, type BakeLightContribution }+ from './lights';+export { BAKE_DEFAULTS } from './bake';export { shBasis, convolveCosine, evalIrradianceSH, SH_BASIS_SCALE, SH_COSINE_BAND } from './sh';diff --git a/sdk/src/lightmap/lights.ts b/sdk/src/lightmap/lights.tsnew file mode 100644index 000000000..86a316c53--- /dev/null+++ b/sdk/src/lightmap/lights.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file lights.ts+ * @brief What a bake makes of one authored Light.+ *+ * @details A document states only what an author touched, so every collector has+ * to fill the rest in — and two of them filling it in separately is two+ * answers about a field nobody set. The defaults here are the+ * component's own, and the reading is one function both doors call.+ */++import { LightType } from '../wasm/wasm.generated';+import { COMPONENT_META } from './metaAccess';+import type { BakeLight } from './solve';++/** A Light's authored fields, as loosely as a document may state them. */+export interface AuthoredLight {+ type?: number;+ color?: { r?: number; g?: number; b?: number };+ intensity?: number;+ radius?: number;+ innerAngle?: number;+ outerAngle?: number;+ enabled?: boolean;+}++/** A lamp the bake places, or a contribution to the light from no direction. */+export type BakeLightContribution =+ | { lamp: BakeLight; ambient?: undefined }+ | { ambient: [number, number, number]; lamp?: undefined };++/** Where a light aims: -Z under its rotation, as the renderer reads it. */+export function bakeLightForward(q: { x: number; y: number; z: number; w: number }):+ [number, number, number] {+ const { x, y, z, w } = q;+ return [-2 * (x * z + y * w), -2 * (y * z - x * w), -(1 - 2 * (x * x + y * y))];+}++/**+ * One authored Light as the bake takes it, or null where it contributes nothing.+ *+ * An Ambient light is not a fourth kind of lamp: it occupies no slot and aims+ * nowhere, so it comes back as the term every surface receives.+ */+export function bakeLightOf(authored: AuthoredLight | undefined,+ position: readonly [number, number, number],+ rotation: { x: number; y: number; z: number; w: number }):+ BakeLightContribution | null {+ const meta = COMPONENT_META['Light'];+ const v = { ...(meta?.defaults as AuthoredLight | undefined),+ ...(meta?.editorDefaults as AuthoredLight | undefined),+ ...authored };+ const intensity = v.intensity ?? 1;+ if (v.enabled === false || !(intensity > 0)) return null;++ const rgb: [number, number, number] = [v.color?.r ?? 1, v.color?.g ?? 1, v.color?.b ?? 1];+ if ((v.type ?? 0) === LightType.Ambient) {+ return { ambient: [rgb[0] * intensity, rgb[1] * intensity, rgb[2] * intensity] };+ }++ const kind: BakeLight['kind'] = (v.type ?? 0) === LightType.Directional ? 'directional'+ : (v.type ?? 0) === LightType.Spot ? 'spot' : 'point';+ const cos = (deg: number): number => Math.cos((deg * Math.PI) / 360);+ return {+ lamp: {+ kind,+ position: [position[0], position[1], position[2]],+ direction: bakeLightForward(rotation),+ color: rgb,+ intensity,+ radius: kind === 'directional' ? undefined : (v.radius ?? 200),+ innerCos: cos(v.innerAngle ?? 30),+ outerCos: cos(v.outerAngle ?? 45),+ },+ };+}diff --git a/sdk/src/lightmap/metaAccess.ts b/sdk/src/lightmap/metaAccess.tsnew file mode 100644index 000000000..a643fbf96--- /dev/null+++ b/sdk/src/lightmap/metaAccess.ts@@ -0,0 +1,6 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** The generated component table, reached without importing the registry: a bake+ * runs where no World has been created, and needs only what a component's+ * fields default to. */+export { COMPONENT_META } from '../ecs/component.generated';diff --git a/sdk/tests/lightmap-fingerprint.test.ts b/sdk/tests/lightmap-fingerprint.test.tsnew file mode 100644index 000000000..f97e0ba38--- /dev/null+++ b/sdk/tests/lightmap-fingerprint.test.ts@@ -0,0 +1,101 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Whether a scene has moved on since it was lit. The claim is two-sided: every+ * value a bake reads has to change the fingerprint, and nothing a bake ignores+ * may — otherwise "out of date" is either a nag or a lie.+ */+import { describe, it, expect } from 'vitest';+import { bakeFingerprint, type BakeInputs } from '../src/lightmap';++const BASE: BakeInputs = {+ surfaces: [+ { mesh: 'assets/floor.esmesh', transform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],+ albedo: [0.5, 0.5, 0.5], texture: 'assets/wood.png', holdsStill: true },+ { mesh: 'builtin:cube', transform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 1],+ holdsStill: false },+ ],+ lights: [+ { kind: 'directional', direction: [0, -1, 0], color: [1, 1, 1], intensity: 1 },+ ],+ volumes: [{ center: [0, 0, 0], halfExtents: [100, 100, 100], spacing: 50 }],+ ambient: [0.1, 0.2, 0.3],+ options: { atlasSize: 512, texelsPerUnit: 0.25, bounces: 2, samples: 64, probeSamples: 128 },+};++/** BASE as something an edit can reach into: the same shape without the readonly+ * tuples, which a caller authoring a change does not have to satisfy. */+interface Draft {+ surfaces: Array<{+ mesh: string; transform: number[]; albedo?: number[]; texture?: string;+ holdsStill?: boolean;+ }>;+ lights: Array<{+ kind: string; position?: number[]; direction?: number[]; color: number[];+ intensity: number; radius?: number; innerCos?: number; outerCos?: number;+ }>;+ volumes: Array<{ center: number[]; halfExtents: number[]; spacing: number }>;+ ambient?: number[];+ options?: Record<string, number>;+}++/** BASE with one value replaced, as a caller would author the change. */+function changed(edit: (draft: Draft) => void): BakeInputs {+ const draft = JSON.parse(JSON.stringify(BASE)) as Draft;+ edit(draft);+ return draft as unknown as BakeInputs;+}++describe('a bake fingerprint', () => {+ it('is the same for the same inputs', () => {+ expect(bakeFingerprint(BASE)).toBe(bakeFingerprint(BASE));+ expect(bakeFingerprint(changed(() => {}))).toBe(bakeFingerprint(BASE));+ });++ it('does not depend on the order things were collected in', () => {+ // The document collector and the world collector walk their sources+ // differently, and a scene whose entities were reordered is the same+ // scene to light. If order counted, the two would disagree forever.+ const reversed = changed((d) => {+ d.surfaces = [...d.surfaces].reverse();+ d.lights = [...d.lights].reverse();+ });+ expect(bakeFingerprint(reversed)).toBe(bakeFingerprint(BASE));+ });++ it('changes for every value a bake actually reads', () => {+ const edits: Array<[string, (d: Draft) => void]> = [+ ['a mesh was swapped', (d) => { d.surfaces[0]!.mesh = 'assets/wall.esmesh'; }],+ ['something moved', (d) => { d.surfaces[0]!.transform[13] = 5; }],+ ['an albedo changed', (d) => { d.surfaces[0]!.albedo = [1, 0, 0]; }],+ ['a texture changed', (d) => { d.surfaces[0]!.texture = 'assets/tile.png'; }],+ ['something started moving', (d) => { d.surfaces[0]!.holdsStill = false; }],+ ['a light turned', (d) => { d.lights[0]!.direction = [1, -1, 0]; }],+ ['a light brightened', (d) => { d.lights[0]!.intensity = 2; }],+ ['a light was added', (d) => { d.lights.push({ kind: 'point', position: [0, 5, 0], color: [1, 1, 1], intensity: 3, radius: 20 }); }],+ ['a volume moved', (d) => { d.volumes[0]!.center = [0, 50, 0]; }],+ ['a volume was resized', (d) => { d.volumes[0]!.halfExtents = [200, 100, 100]; }],+ ['its density changed', (d) => { d.volumes[0]!.spacing = 25; }],+ ['the ambient changed', (d) => { d.ambient = [0, 0, 0]; }],+ ['the atlas was resized', (d) => { d.options = { ...d.options, atlasSize: 1024 }; }],+ ['the density changed', (d) => { d.options = { ...d.options, texelsPerUnit: 0.5 }; }],+ ['the bounces changed', (d) => { d.options = { ...d.options, bounces: 0 }; }],+ ['the samples changed', (d) => { d.options = { ...d.options, samples: 128 }; }],+ ['the probe samples changed', (d) => { d.options = { ...d.options, probeSamples: 64 }; }],+ ];+ const base = bakeFingerprint(BASE);+ for (const [what, edit] of edits) {+ expect(bakeFingerprint(changed(edit)), `${what}: the fingerprint did not move`)+ .not.toBe(base);+ }+ });++ it('fills an absent option from the same defaults a bake would', () => {+ // A scene that never set a knob and one that set it to the default are+ // the same bake, so they must fingerprint alike — otherwise adding the+ // component to a lit scene would report it out of date.+ const stated = changed((d) => { d.options = { ...d.options, dilate: 2 }; });+ const unstated = changed((d) => { delete d.options?.dilate; });+ expect(bakeFingerprint(stated)).toBe(bakeFingerprint(unstated));+ });+});diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex 8a4a7cfee..fe6407f78 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -134,6 +134,7 @@ const DISPOSITION = {'TrailRenderer.minVertexDistance': ['no-place', 'how far the entity moves before a point is kept — a sampling step'],// Not a length in world space at all.+ 'BakedLighting.atlasSize': ['not-world', 'the side of a TEXTURE in texels; what it covers in the world is every lightmapped surface at once'],'Canvas.matchWidthOrHeight': ['not-world', 'a 0..1 blend between two fits, not a length'],'UIDropdown.optionHeight': ['not-world', 'a row height inside a laid-out box, resolved by layout rather than placed'],'SpriteMask.rangeEndOrder': ['not-world', 'the last draw ORDER a mask reaches, not a distance it reaches over'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 283fef5ee..a9f04dbc2 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,11 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(lighting): a scene says how it is lit, and whether its light still describes it':+ { note: 'A scene says how it is lit, and whether its light still describes it.' },+ 'feat(lighting): a Lighting panel, and a scene that says whether its light is stale':+ { note: 'A scene says how it is lit, and whether its light still describes it.' },+'feat(render): a bake solves the probes in the light field it already has':{ note: 'A bake now solves the probes too, and refuses to light what moves.' },'feat(lighting): Bake Lighting solves the probes, and refuses to light what moves':