@ignifx/core 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/{gtao-_nr0b6-E.js → gtao-Bpu5-0Ne.js} +2 -2
  2. package/dist/{gtao-_nr0b6-E.js.map → gtao-Bpu5-0Ne.js.map} +1 -1
  3. package/dist/{hdr-output-Dbv0lhFl.js → hdr-output-DBQwMphy.js} +2 -2
  4. package/dist/{hdr-output-Dbv0lhFl.js.map → hdr-output-DBQwMphy.js.map} +1 -1
  5. package/dist/index.d.ts +181 -21
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1616 -174
  8. package/dist/index.js.map +1 -1
  9. package/dist/{instanced-mesh-instance-BMhREEfx.js → instanced-mesh-instance-B-fXKSrY.js} +2 -2
  10. package/dist/{instanced-mesh-instance-BMhREEfx.js.map → instanced-mesh-instance-B-fXKSrY.js.map} +1 -1
  11. package/dist/{light-probes-DyLapYX9.js → light-probes-DDojYajw.js} +2 -2
  12. package/dist/{light-probes-DyLapYX9.js.map → light-probes-DDojYajw.js.map} +1 -1
  13. package/dist/lightmaps-BUUIIkt9.js +230 -0
  14. package/dist/lightmaps-BUUIIkt9.js.map +1 -0
  15. package/dist/{material-CGk5mAah.js → material-myMbl9mW.js} +37 -2
  16. package/dist/{material-CGk5mAah.js.map → material-myMbl9mW.js.map} +1 -1
  17. package/dist/{post-effect-CaiqDlhW.js → post-effect-Cu3Enpz7.js} +2 -2
  18. package/dist/{post-effect-CaiqDlhW.js.map → post-effect-Cu3Enpz7.js.map} +1 -1
  19. package/dist/{post-effect-compiler-jSvOVe0U.js → post-effect-compiler-cCq9lcHt.js} +2 -2
  20. package/dist/{post-effect-compiler-jSvOVe0U.js.map → post-effect-compiler-cCq9lcHt.js.map} +1 -1
  21. package/dist/{prefab-overrides-DRP2DcnC.js → prefab-overrides-C2GsgOQc.js} +24 -7
  22. package/dist/prefab-overrides-C2GsgOQc.js.map +1 -0
  23. package/dist/{prefab-overrides-CS8_cG66.d.ts → prefab-overrides-htDc_5Po.d.ts} +53 -12
  24. package/dist/prefab-overrides-htDc_5Po.d.ts.map +1 -0
  25. package/dist/prefab.d.ts +1 -1
  26. package/dist/prefab.js +1 -1
  27. package/dist/{reflection-probe-AS8d4uKv.js → reflection-probe-QkD1Fo_d.js} +79 -3
  28. package/dist/{reflection-probe-AS8d4uKv.js.map → reflection-probe-QkD1Fo_d.js.map} +1 -1
  29. package/dist/{reflection-probes-CUZcOjNW.js → reflection-probes-CAzSuqf8.js} +298 -21
  30. package/dist/reflection-probes-CAzSuqf8.js.map +1 -0
  31. package/dist/{shader-material-CuwK9tWC.js → shader-material-TM4f8eKA.js} +2 -2
  32. package/dist/{shader-material-CuwK9tWC.js.map → shader-material-TM4f8eKA.js.map} +1 -1
  33. package/dist/{ssgi-Dm-maZrc.js → ssgi-DSnhqotl.js} +2 -2
  34. package/dist/{ssgi-Dm-maZrc.js.map → ssgi-DSnhqotl.js.map} +1 -1
  35. package/dist/{surface-shader-DY9_aC9L.js → surface-shader-rpPpeosD.js} +4 -4
  36. package/dist/{surface-shader-DY9_aC9L.js.map → surface-shader-rpPpeosD.js.map} +1 -1
  37. package/dist/{vec3-Cc19wl4r.js → vec3-2C3LBZnt.js} +55 -3
  38. package/dist/vec3-2C3LBZnt.js.map +1 -0
  39. package/package.json +1 -1
  40. package/dist/lightmaps-LO6Ygtwe.js +0 -137
  41. package/dist/lightmaps-LO6Ygtwe.js.map +0 -1
  42. package/dist/prefab-overrides-CS8_cG66.d.ts.map +0 -1
  43. package/dist/prefab-overrides-DRP2DcnC.js.map +0 -1
  44. package/dist/reflection-probes-CUZcOjNW.js.map +0 -1
  45. package/dist/vec3-Cc19wl4r.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import { a as CORE_ERROR_MESSAGES, c as THIRD_PARTY_ERROR_PREFIX, i as isIgnifxError, l as isValidErrorCode, n as assertNever, o as CoreErrorCode, r as formatErrorMessage, s as ErrorRange, t as IgnifxError } from "./ignifx-error-DwIZKxA2.js";
2
- import { A as u32, B as readPickedMeshName, C as i32, D as quat, E as optional, F as createPickRay, G as INVALID_HANDLE, H as setPickRay, I as raycastScene, J as applyInit, K as toComponentHandle, L as raycastSceneWhere, M as vec3, N as vec4, O as record, P as FieldKind, Q as Signal, R as readOwnerTag, S as f64, T as map, U as Component, V as readPickedTag, W as componentInternals, X as createDefaults, Y as assertNoInheritedFieldNames, Z as defineSchema, _ as curve, b as enumOf, c as RenderTextureImpl, d as renderTextureUnusableError, f as array, g as componentRef, h as color, j as vec2, k as str, l as assertRenderTextureSize, m as bool, n as ReflectionProbe, o as EDITOR_ONLY_METADATA_KEY, p as asset, q as toEntityHandle, s as RENDER_TEXTURE_MAX_SIZE, t as REFLECTION_PROBE_REFRESH_MODES, u as bindFrameCameras, v as custom, w as layerMask, x as f32, y as entityRef, z as readPickedIdentity } from "./reflection-probe-AS8d4uKv.js";
3
- import { A as childPath, C as canonicalizeNumber, D as encodeValue, E as encodeProps, F as asJsonObject, G as splitFragment, H as joinRoot, I as setOwnJsonProperty, L as SchemaIssueCode, M as isArray, N as isPlainObject, O as COLOR_CHANNELS, P as asJsonArray, R as issue, S as toJsonSchema, T as decodeValue, U as matchExtension, V as isAbsoluteAddress, W as normalizeExtension, _ as describeSceneFileFormat, a as applyOverrides, b as stringifySceneFile, c as remapInstancePath, d as createSceneAsset, f as findSceneDependency, g as SCENE_FORMAT_VERSION, h as SCENE_FILE_FORMAT, i as resolveInstancePath, j as indexPath, k as VECTOR_COMPONENTS, l as SceneAssetToken, m as SCENE_FILE_EXTENSIONS, n as revertOverrides, o as parseOverridePath, p as SCENE_ASSET_TYPE, r as enumerateInstanceTargets, s as instancePathResolver, t as applyOverridesToAsset, u as computeSceneHash, v as isSceneFileHeader, w as decodeProps, x as describeSchema, y as sceneFileJsonSchema } from "./prefab-overrides-DRP2DcnC.js";
2
+ import { $ as Signal, A as str, B as readPickedIdentity, C as f64, D as optional, E as map, F as FieldKind, G as componentInternals, H as readPickedTag, I as createPickRay, J as toEntityHandle, K as INVALID_HANDLE, L as raycastScene, M as vec2, N as vec3, O as quat, P as vec4, Q as defineSchema, R as raycastSceneWhere, S as f32, T as layerMask, U as setPickRay, V as readPickedMeshName, W as Component, X as assertNoInheritedFieldNames, Y as applyInit, Z as createDefaults, _ as componentRef, b as entityRef, c as RENDER_TEXTURE_MAX_SIZE, d as bindFrameCameras, f as renderTextureUnusableError, g as color, h as bool, j as u32, k as record, l as RenderTextureImpl, m as asset, n as ReflectionProbe, p as array, q as toComponentHandle, s as EDITOR_ONLY_METADATA_KEY, t as REFLECTION_PROBE_REFRESH_MODES, u as assertRenderTextureSize, v as curve, w as i32, x as enumOf, y as custom, z as readOwnerTag } from "./reflection-probe-QkD1Fo_d.js";
3
+ import { A as childPath, C as canonicalizeNumber, D as encodeValue, E as encodeProps, F as asJsonObject, G as splitFragment, H as joinRoot, I as setOwnJsonProperty, L as SchemaIssueCode, M as isArray, N as isPlainObject, O as COLOR_CHANNELS, P as asJsonArray, R as issue, S as toJsonSchema, T as decodeValue, U as matchExtension, V as isAbsoluteAddress, W as normalizeExtension, _ as describeSceneFileFormat, a as applyOverrides, b as stringifySceneFile, c as remapInstancePath, d as createSceneAsset, f as findSceneDependency, g as SCENE_FORMAT_VERSION, h as SCENE_FILE_FORMAT, i as resolveInstancePath, j as indexPath, k as VECTOR_COMPONENTS, l as SceneAssetToken, m as SCENE_FILE_EXTENSIONS, n as revertOverrides, o as parseOverridePath, p as SCENE_ASSET_TYPE, r as enumerateInstanceTargets, s as instancePathResolver, t as applyOverridesToAsset, u as computeSceneHash, v as isSceneFileHeader, w as decodeProps, x as describeSchema, y as sceneFileJsonSchema } from "./prefab-overrides-C2GsgOQc.js";
4
4
  import { _ as smoothStep, a as clamp, c as deltaAngleDegrees, d as lerpAngleDegrees, f as moveTowards, g as sign, h as repeat, i as approximately, l as inverseLerp, m as radToDeg, n as EPSILON, o as clamp01, p as pingPong, r as RAD_TO_DEG, s as degToRad, t as DEG_TO_RAD, u as lerp, v as wrapAngleDegrees } from "./math-utils-BcDnL-gi.js";
5
5
  import { n as Mat4, r as basisToQuatToRef, t as MAT4_IDENTITY } from "./mat4-D6exvAuO.js";
6
6
  import { a as localRotation, d as setNodeName, f as setNodeSelfVisible, i as localPosition, l as readWorldMatrix, m as worldMatrixVersion, n as disposeNode, o as localScale, p as tagNode, r as linkParent, s as parentNode, t as createNode, u as reparentKeepingWorld } from "./node-DznSvwap.js";
7
7
  import { t as Color } from "./color-DrR6GFTd.js";
8
8
  import { a as readSceneImageProcessing, c as setSceneEnvironmentRotation, i as readSceneEnvironment, l as setSceneFog, n as installSceneEnvironment, o as setSceneClearColor, r as loadSceneEnvironment, s as setSceneEnvironmentBlur, t as TONE_MAPPING_NAMES, u as setSceneImageProcessingOptions } from "./environment-Bf4aphSb.js";
9
- import { a as markMaterialDirty, c as setPbrBaseColor, i as createStandardMaterialFromProps, l as setPbrMetallicRoughness, n as createDefaultMaterial, r as createPbrMaterialFromProps, s as setMaterialAlpha, t as MATERIAL_ALPHA_MODES } from "./material-CGk5mAah.js";
10
- import { A as setMeshReceiveShadows, C as overrideSubtreeMaterials, D as setMeshId, E as setMeshBounds, F as updateMeshPositions$1, I as updateMeshUvs$1, M as setMeshSubtreeVisible, N as updateMeshColors$1, O as setMeshMaterial, P as updateMeshNormals$1, S as disposeMeshTemplate, T as removeMeshFromScene, _ as createMeshFromGeometry, a as VEC3_ONE, b as createTorusMesh, c as VEC3_ZERO, d as cloneMeshUnderNode, f as collectSubtreeMeshes, g as createGroundMesh, h as createCylinderMesh, i as VEC3_LEFT, j as setMeshRenderOrder, k as setMeshPickable, l as Vec3, m as createCapsuleMesh, n as VEC3_DOWN, o as VEC3_RIGHT, p as createBoxMesh, r as VEC3_FORWARD, s as VEC3_UP, t as VEC3_BACKWARD, u as addMeshToScene, v as createPlaneMesh, w as recomputeMeshBounds, x as detachMeshBounds, y as createSphereMesh } from "./vec3-Cc19wl4r.js";
9
+ import { a as markMaterialDirty, c as setPbrBaseColor, i as createStandardMaterialFromProps, l as setPbrMetallicRoughness, n as createDefaultMaterial, r as createPbrMaterialFromProps, s as setMaterialAlpha, t as MATERIAL_ALPHA_MODES } from "./material-myMbl9mW.js";
10
+ import { A as setMeshPickable, C as overrideSubtreeMaterials, D as setMeshBounds, E as removeMeshFromScene, F as updateMeshNormals$1, I as updateMeshPositions$1, L as updateMeshUvs$1, M as setMeshRenderOrder, N as setMeshSubtreeVisible, O as setMeshId, P as updateMeshColors$1, S as disposeMeshTemplate, T as recomputeMeshBounds, _ as createMeshFromGeometry, a as VEC3_ONE, b as createTorusMesh, c as VEC3_ZERO, d as cloneMeshUnderNode, f as collectSubtreeMeshes, g as createGroundMesh, h as createCylinderMesh, i as VEC3_LEFT, j as setMeshReceiveShadows, k as setMeshMaterial, l as Vec3, m as createCapsuleMesh, n as VEC3_DOWN, o as VEC3_RIGHT, p as createBoxMesh, r as VEC3_FORWARD, s as VEC3_UP, t as VEC3_BACKWARD, u as addMeshToScene, v as createPlaneMesh, w as readMeshBakeSurface, x as detachMeshBounds, y as createSphereMesh } from "./vec3-2C3LBZnt.js";
11
11
  import { a as LightProbeAsset, c as readLightProbeFile, d as writeLightProbeFile, i as LIGHT_PROBE_FORMAT_VERSION, l as readLightProbeGrid, n as LIGHT_PROBE_FILE_EXTENSIONS, o as createLightProbeAsset, r as LIGHT_PROBE_FILE_FORMAT, t as LIGHT_PROBE_ASSET_TYPE, u as sampleLightProbes } from "./light-probe-asset-BqfSrJe9.js";
12
- import { a as postEffectValuesCodec, i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, r as customEffect, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-CaiqDlhW.js";
12
+ import { a as postEffectValuesCodec, i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, r as customEffect, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-Cu3Enpz7.js";
13
13
  import { n as installOffscreenRenderPath } from "./render-path-D11i_7X8.js";
14
14
  import { a as SHADER_BLEND_MODES, c as SHADER_KINDS, d as SURFACE_HOOK_NAMES, f as SURFACE_UNIFORM_BLOCK, i as SHADER_ATTRIBUTE_NAMES, l as SHADER_TEXTURE_FALLBACKS, o as SHADER_CULL_MODES, r as LITE_SYSTEM_UNIFORM_NAMES, s as SHADER_INSTANCING_MODES, t as IGNIFX_UNIFORM_NAMES, u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
15
15
  import { a as defineMaterialPlugin, i as MATERIAL_PLUGIN_SAMPLER_BUDGET, n as MATERIAL_PLUGIN_DEFAULT_PRIORITY, o as isLiteMaterialPluginPoint, r as MATERIAL_PLUGIN_RESERVED_NAMES, t as LITE_MATERIAL_PLUGIN_POINTS } from "./material-plugin-DapJNj04.js";
@@ -3903,7 +3903,7 @@ function createServiceKey(name) {
3903
3903
  *
3904
3904
  * @public
3905
3905
  */
3906
- const VERSION = "0.19.0";
3906
+ const VERSION = "0.20.0";
3907
3907
  //#endregion
3908
3908
  //#region src/assets/delivery-system.ts
3909
3909
  /**
@@ -5349,7 +5349,7 @@ var Environment = class Environment extends Component {
5349
5349
  const askedForSize = skybox.size !== SKYBOX_SIZE_DEFAULT && skybox.size !== definition.skyboxSize;
5350
5350
  if (!askedForEnabled && !askedForSize) return;
5351
5351
  this.#hasWarnedAboutSkybox = true;
5352
- renderer.app.log.warn(`${CoreErrorCode.skyboxFixedAtLoad}: {entity} asks for skybox {requested}, but {asset} was loaded with {loaded} and Babylon Lite builds the background when the environment loads, with no handle to change it afterwards. Declare skyboxEnabled and skyboxSize in the .environment.json instead.`, this.entity.name, `{ enabled: ${String(skybox.enabled)}, size: ${String(skybox.size)} }`, installed.address, `{ enabled: ${String(definition.skyboxEnabled)}, size: ${String(definition.skyboxSize)} }`);
5352
+ renderer.app.log.warn(`${CoreErrorCode.skyboxFixedAtLoad}: ${JSON.stringify(this.entity.name)} asks for skybox { enabled: ${String(skybox.enabled)}, size: ${String(skybox.size)} }, but ${installed.address} was loaded with { enabled: ${String(definition.skyboxEnabled)}, size: ${String(definition.skyboxSize)} } and Babylon Lite builds the background when the environment loads, with no handle to change it afterwards. Declare skyboxEnabled and skyboxSize in the .environment.json instead.`);
5353
5353
  }
5354
5354
  /**
5355
5355
  * Fires the asynchronous image-processing update, at most one at a time.
@@ -5466,7 +5466,7 @@ let layer$1 = null;
5466
5466
  * @internal
5467
5467
  */
5468
5468
  async function loadInstancedMeshSupport() {
5469
- const loaded = layer$1 ?? await import("./instanced-mesh-instance-BMhREEfx.js");
5469
+ const loaded = layer$1 ?? await import("./instanced-mesh-instance-B-fXKSrY.js");
5470
5470
  layer$1 = loaded;
5471
5471
  return loaded;
5472
5472
  }
@@ -5494,7 +5494,7 @@ let surfaceLayer = null;
5494
5494
  * @internal
5495
5495
  */
5496
5496
  async function loadShaderSupport() {
5497
- const loaded = shaderLayer ?? await import("./shader-material-CuwK9tWC.js").then((n) => n.n);
5497
+ const loaded = shaderLayer ?? await import("./shader-material-TM4f8eKA.js").then((n) => n.n);
5498
5498
  shaderLayer = loaded;
5499
5499
  await loaded.loadShaderMaterialAdapter();
5500
5500
  return loaded;
@@ -5517,7 +5517,7 @@ function shaderSupport() {
5517
5517
  * @internal
5518
5518
  */
5519
5519
  async function loadSurfaceShaderSupport() {
5520
- const loaded = surfaceLayer ?? await import("./surface-shader-DY9_aC9L.js");
5520
+ const loaded = surfaceLayer ?? await import("./surface-shader-rpPpeosD.js");
5521
5521
  surfaceLayer = loaded;
5522
5522
  return loaded;
5523
5523
  }
@@ -6653,6 +6653,7 @@ var MeshAsset = class {
6653
6653
  #scene;
6654
6654
  #geometry;
6655
6655
  #engine;
6656
+ #primitive;
6656
6657
  #mesh;
6657
6658
  #isDisposed = false;
6658
6659
  /**
@@ -6666,15 +6667,17 @@ var MeshAsset = class {
6666
6667
  * {@link MeshAsset.fromData}; `null` for a primitive, whose arrays Lite generated and never
6667
6668
  * handed back. It is what makes the `update*` methods legal.
6668
6669
  * @param engine - The engine an update writes through, or `null` under a headless app.
6670
+ * @param primitive - The primitive and options it was built from, or `null` for data.
6669
6671
  *
6670
6672
  * @internal
6671
6673
  */
6672
- constructor(name, mesh, scene, geometry = null, engine = null) {
6674
+ constructor(name, mesh, scene, geometry = null, engine = null, primitive = null) {
6673
6675
  this.name = name;
6674
6676
  this.#mesh = mesh;
6675
6677
  this.#scene = scene;
6676
6678
  this.#geometry = geometry;
6677
6679
  this.#engine = engine;
6680
+ this.#primitive = primitive;
6678
6681
  }
6679
6682
  /**
6680
6683
  * The Babylon Lite objects the asset owns. Unstable escape hatch
@@ -6704,6 +6707,17 @@ var MeshAsset = class {
6704
6707
  return this.#geometry;
6705
6708
  }
6706
6709
  /**
6710
+ * The primitive and options the asset was built from, so a light-probe bake can rebuild its
6711
+ * triangles on the CPU.
6712
+ *
6713
+ * @returns The definition, or `null` for a mesh built with {@link MeshAsset.fromData}.
6714
+ *
6715
+ * @internal
6716
+ */
6717
+ get primitive() {
6718
+ return this.#primitive;
6719
+ }
6720
+ /**
6707
6721
  * How many vertices the geometry has.
6708
6722
  *
6709
6723
  * @remarks
@@ -7041,7 +7055,7 @@ function copyRange(source, target, components, vertexOffset, count) {
7041
7055
  */
7042
7056
  function createPrimitiveMeshAsset(app, name, definition) {
7043
7057
  const handles = buildMeshTemplate(app.isHeadless, app.lite.scene, app.lite.engine, (engine) => buildPrimitiveTemplate(engine, definition));
7044
- return new MeshAsset(name, handles.mesh, handles.scene, null, handles.engine);
7058
+ return new MeshAsset(name, handles.mesh, handles.scene, null, handles.engine, definition);
7045
7059
  }
7046
7060
  /**
7047
7061
  * Builds a primitive and registers it as an in-memory asset named after the primitive.
@@ -8585,7 +8599,7 @@ var LightProbeHost = class {
8585
8599
  }
8586
8600
  if (volumes.length === 0 || this.#isLoading || this.#isDisposed) return;
8587
8601
  this.#isLoading = true;
8588
- import("./light-probes-DyLapYX9.js").then((module) => module.createLightProbeRuntime(this.#engine, this.#scene)).then((created) => {
8602
+ import("./light-probes-DDojYajw.js").then((module) => module.createLightProbeRuntime(this.#engine, this.#scene)).then((created) => {
8589
8603
  if (this.#isDisposed) {
8590
8604
  created.dispose();
8591
8605
  return;
@@ -8650,10 +8664,12 @@ const IDENTITY_LIGHTMAP_PLACEMENT = Object.freeze({
8650
8664
  * A loaded lightmap: a texture and where each entity's UV2 square sits in it.
8651
8665
  *
8652
8666
  * @remarks
8653
- * A `MeshRenderer` names it in its `lightmap` record. Only placements equal to
8654
- * {@link IDENTITY_LIGHTMAP_PLACEMENT} are honoured for now: Babylon Lite 1.34's lightmap fragment
8655
- * samples `uv2` without a transform, so a renderer with another placement logs `IGX-0735` once and
8656
- * samples the whole texture until the atlas transform lands (GI plan §5, spike P2).
8667
+ * A `MeshRenderer` names it in its `lightmap` record. Many renderers can share one atlas
8668
+ * texture: each samples it at `uv2 · scale + offset`, with its entity's entry as the placement, in
8669
+ * the same UV space as an entity without one (so a V flip the texture asks for applies to the
8670
+ * placed coordinate too). A placement other than {@link IDENTITY_LIGHTMAP_PLACEMENT} needs the
8671
+ * renderer's `lightmap.uv2` on and a mesh with `uvs2`; otherwise it logs `IGX-0735` once and
8672
+ * samples the whole texture. Each distinct placement compiles its own pipeline variant.
8657
8673
  *
8658
8674
  * @example
8659
8675
  * ```ts
@@ -8776,9 +8792,9 @@ function readLightmapEntries(value, address) {
8776
8792
  const entries = {};
8777
8793
  for (const id of Object.keys(record)) {
8778
8794
  const entry = asRecord$1(record[id]);
8779
- const scale = entry === null ? null : readVec2(entry["scale"], IDENTITY_LIGHTMAP_PLACEMENT.scale, (n) => n > 0);
8780
- const offset = entry === null ? null : readVec2(entry["offset"], IDENTITY_LIGHTMAP_PLACEMENT.offset, () => true);
8781
- if (id === "" || scale === null || offset === null) throw invalid(address, `entries["${id}"] must be { scale?: { x, y }, offset?: { x, y } } with finite numbers and a scale above 0`);
8795
+ const scale = entry === null ? null : readVec2(entry["scale"], IDENTITY_LIGHTMAP_PLACEMENT.scale, (n) => n > 0 && n <= MAX_PLACEMENT_MAGNITUDE);
8796
+ const offset = entry === null ? null : readVec2(entry["offset"], IDENTITY_LIGHTMAP_PLACEMENT.offset, (n) => Math.abs(n) <= MAX_PLACEMENT_MAGNITUDE);
8797
+ if (id === "" || scale === null || offset === null) throw invalid(address, `entries["${id}"] must be { scale?: { x, y }, offset?: { x, y } } with finite numbers, a scale above 0 and every component within ±${String(MAX_PLACEMENT_MAGNITUDE)}`);
8782
8798
  entries[id] = {
8783
8799
  scale,
8784
8800
  offset
@@ -8787,7 +8803,7 @@ function readLightmapEntries(value, address) {
8787
8803
  return entries;
8788
8804
  }
8789
8805
  /**
8790
- * Whether a placement is the identity, the only one Babylon Lite 1.34 can draw (GI plan §5, P2).
8806
+ * Whether a placement is the identity, which needs no atlas transform.
8791
8807
  *
8792
8808
  * @param placement - The placement.
8793
8809
  * @returns `true` for scale `(1, 1)` and offset `(0, 0)`.
@@ -8799,6 +8815,12 @@ function isIdentityLightmapPlacement(placement) {
8799
8815
  return scale.x === 1 && scale.y === 1 && offset.x === 0 && offset.y === 0;
8800
8816
  }
8801
8817
  /**
8818
+ * The largest magnitude a placement component may have. Atlas coordinates live near `0..1`; the
8819
+ * bound keeps every value well inside `f32`, since the placement is written into WGSL as a constant
8820
+ * and an out-of-range literal fails shader creation.
8821
+ */
8822
+ const MAX_PLACEMENT_MAGNITUDE = 1e6;
8823
+ /**
8802
8824
  * Reads `{ x, y }` whose components are finite and pass a check, or takes a default when absent.
8803
8825
  *
8804
8826
  * @param value - The candidate, `undefined` when the field is absent.
@@ -8891,7 +8913,10 @@ var LightmapHost = class {
8891
8913
  * @remarks
8892
8914
  * A renderer samples its lightmap when its `lightmap.asset` is loaded, its entity is static and its
8893
8915
  * material is PBR; otherwise it draws with `base`, and a static or PBR mismatch logs `IGX-0735`
8894
- * once. A placement other than the identity also logs `IGX-0735`, and the whole texture is used.
8916
+ * once. Its entry's placement (scale and offset) moves its UV2 into its square of the atlas. A
8917
+ * placement other than the identity needs `uv2: true` and a mesh with `uvs2`, since the first UV
8918
+ * set also drives the material's own textures; without them it logs `IGX-0735` once and samples
8919
+ * the whole texture.
8895
8920
  *
8896
8921
  * @param owner - The renderer.
8897
8922
  * @param base - The material it declares (or the default material).
@@ -8914,13 +8939,24 @@ var LightmapHost = class {
8914
8939
  this.release(owner);
8915
8940
  return base.lite.material;
8916
8941
  }
8917
- if (!isIdentityLightmapPlacement(lightmap.placementOf(entity.uid))) this.#report(owner, "its lightmap entry has a scale or offset, which is not applied yet; it samples the whole texture");
8942
+ const placement = lightmap.placementOf(entity.uid);
8943
+ let atlas = null;
8944
+ if (!isIdentityLightmapPlacement(placement)) {
8945
+ const mesh = owner.mesh;
8946
+ if (mesh === null || mesh.state !== "loaded") {
8947
+ this.release(owner);
8948
+ return base.lite.material;
8949
+ }
8950
+ if (!settings.uv2) this.#report(owner, "its lightmap entry has a scale or offset, which needs uv2: true (the first UV set also maps the material's textures); it samples the whole texture");
8951
+ else if (!hasSecondUvSet(owner)) this.#report(owner, "its lightmap entry has a scale or offset, but its mesh has no uvs2; it samples the whole texture with the first UV set");
8952
+ else atlas = placement;
8953
+ }
8918
8954
  const runtime = this.#runtime;
8919
8955
  if (runtime === null) {
8920
8956
  this.#load();
8921
8957
  return base.lite.material;
8922
8958
  }
8923
- return runtime.materialFor(owner, base, lightmap, settings);
8959
+ return runtime.materialFor(owner, base, lightmap, settings, atlas);
8924
8960
  }
8925
8961
  /**
8926
8962
  * Drops a renderer's lightmapped clone, if it has one.
@@ -8944,7 +8980,7 @@ var LightmapHost = class {
8944
8980
  #load() {
8945
8981
  if (this.#isLoading || this.#isDisposed) return;
8946
8982
  this.#isLoading = true;
8947
- import("./lightmaps-LO6Ygtwe.js").then((module) => module.createLightmapRuntime(this.#app, this.#scene)).then((created) => {
8983
+ import("./lightmaps-BUUIIkt9.js").then((module) => module.createLightmapRuntime(this.#app, this.#scene)).then((created) => {
8948
8984
  if (this.#isDisposed) {
8949
8985
  created.dispose();
8950
8986
  return;
@@ -8961,9 +8997,24 @@ var LightmapHost = class {
8961
8997
  #report(owner, problem) {
8962
8998
  if (this.#reported.get(owner) === problem) return;
8963
8999
  this.#reported.set(owner, problem);
8964
- this.#app.log.warn(`${CoreErrorCode.lightmapNotApplied}: {entity}'s MeshRenderer lightmap: ${problem}.`, owner.entity.name);
9000
+ this.#app.log.warn(`${CoreErrorCode.lightmapNotApplied}: the MeshRenderer lightmap of ${JSON.stringify(owner.entity.name)}: ${problem}.`);
8965
9001
  }
8966
9002
  };
9003
+ /**
9004
+ * Whether a renderer's mesh has a second UV set, which Lite turns into the `uv2` varying an atlas
9005
+ * placement rewrites.
9006
+ *
9007
+ * @remarks
9008
+ * Only a mesh built with `MeshAsset.fromData` and `uvs2` has one; Lite's primitives make none.
9009
+ *
9010
+ * @param owner - The renderer.
9011
+ * @returns `true` when its loaded mesh carries `uvs2`.
9012
+ */
9013
+ function hasSecondUvSet(owner) {
9014
+ const mesh = owner.mesh;
9015
+ const uvs2 = mesh?.state === "loaded" ? mesh.value.cpuGeometry?.uvs2 : void 0;
9016
+ return uvs2 !== void 0 && uvs2.length > 0;
9017
+ }
8967
9018
  //#endregion
8968
9019
  //#region src/render/gpu/reflection-probe-host.ts
8969
9020
  /**
@@ -8981,13 +9032,15 @@ var ReflectionProbeHost = class {
8981
9032
  #runtime = null;
8982
9033
  #isLoading = false;
8983
9034
  #isDisposed = false;
9035
+ /** Set from a device loss until Lite's recovery; no frame work runs in between. */
9036
+ #isDeviceLost = false;
8984
9037
  /**
8985
9038
  * Creates the host; nothing loads until a probe exists.
8986
9039
  *
8987
9040
  * @param engine - The engine.
8988
9041
  * @param scene - The registered render scene.
8989
9042
  * @param onError - Where a failed chunk load goes.
8990
- * @param warn - Where a probe's warning goes: a message with an `{entity}` slot, and the name.
9043
+ * @param warn - Where a probe's warning goes, with the entity's name already in the message.
8991
9044
  */
8992
9045
  constructor(engine, scene, onError, warn) {
8993
9046
  this.#engine = engine;
@@ -9014,13 +9067,14 @@ var ReflectionProbeHost = class {
9014
9067
  * not even loaded, since a probe needs the map's lighting tables.
9015
9068
  */
9016
9069
  update(world, probes, isHdr, tier, hasEnvironment) {
9070
+ if (this.#isDeviceLost) return;
9017
9071
  if (this.#runtime !== null) {
9018
9072
  this.#runtime.update(world, probes, isHdr, tier, hasEnvironment);
9019
9073
  return;
9020
9074
  }
9021
9075
  if (probes.length === 0 || !hasEnvironment || this.#isLoading || this.#isDisposed) return;
9022
9076
  this.#isLoading = true;
9023
- import("./reflection-probes-CUZcOjNW.js").then(async (module) => module.createReflectionProbeRuntime(this.#engine, this.#scene, this.#warn)).then((created) => {
9077
+ import("./reflection-probes-CAzSuqf8.js").then(async (module) => module.createReflectionProbeRuntime(this.#engine, this.#scene, this.#warn)).then((created) => {
9024
9078
  if (this.#isDisposed) {
9025
9079
  created.dispose();
9026
9080
  return;
@@ -9033,8 +9087,14 @@ var ReflectionProbeHost = class {
9033
9087
  * recovery rebuilds the materials; they capture again once frames resume.
9034
9088
  */
9035
9089
  handleDeviceLost() {
9090
+ this.#isDeviceLost = true;
9036
9091
  this.#runtime?.handleDeviceLost();
9037
9092
  }
9093
+ /** Resumes probe work once Lite rebuilt the scene (`app.events.onDeviceRecovered`). */
9094
+ handleDeviceRecovered() {
9095
+ this.#isDeviceLost = false;
9096
+ this.#runtime?.handleDeviceRecovered();
9097
+ }
9038
9098
  /** Frees every probe. Idempotent. */
9039
9099
  dispose() {
9040
9100
  this.#isDisposed = true;
@@ -10108,7 +10168,7 @@ var RendererImpl = class {
10108
10168
  #ambientOcclusion = null;
10109
10169
  /** The reflection probes' host, created on the first frame of a canvas-backed app (GI B1). */
10110
10170
  #reflectionProbes = null;
10111
- /** Detaches the reflection probes' `app.events.onDeviceLost` handler. */
10171
+ /** Detaches the reflection probes' `onDeviceLost` and `onDeviceRecovered` handlers. */
10112
10172
  #disconnectProbeDeviceLoss = null;
10113
10173
  /** The light probes' host, created with the reflection probes' one (GI B2). */
10114
10174
  #lightProbes = null;
@@ -10906,7 +10966,7 @@ var RendererImpl = class {
10906
10966
  */
10907
10967
  async #installAmbientOcclusion() {
10908
10968
  const settings = resolveAmbientOcclusion(this.settings.ambientOcclusion);
10909
- const [module, inputs] = await Promise.all([import("./gtao-_nr0b6-E.js"), this.acquireSceneInputs()]);
10969
+ const [module, inputs] = await Promise.all([import("./gtao-Bpu5-0Ne.js"), this.acquireSceneInputs()]);
10910
10970
  if (inputs === null) return;
10911
10971
  if (this.#isDisposed) {
10912
10972
  inputs.release();
@@ -10978,13 +11038,20 @@ var RendererImpl = class {
10978
11038
  });
10979
11039
  };
10980
11040
  if (this.#reflectionProbes === null) {
10981
- const host = new ReflectionProbeHost(this.engine, this.scene, onError, (message, entityName) => {
10982
- this.#app.log.warn(message, entityName);
11041
+ const host = new ReflectionProbeHost(this.engine, this.scene, onError, (message) => {
11042
+ this.#app.log.warn(message);
10983
11043
  });
10984
11044
  this.#reflectionProbes = host;
10985
- this.#disconnectProbeDeviceLoss = this.#app.events.onDeviceLost.connect(() => {
11045
+ const disconnectLost = this.#app.events.onDeviceLost.connect(() => {
10986
11046
  host.handleDeviceLost();
10987
11047
  });
11048
+ const disconnectRecovered = this.#app.events.onDeviceRecovered.connect(() => {
11049
+ host.handleDeviceRecovered();
11050
+ });
11051
+ this.#disconnectProbeDeviceLoss = () => {
11052
+ disconnectLost();
11053
+ disconnectRecovered();
11054
+ };
10988
11055
  }
10989
11056
  this.#lightProbes ??= new LightProbeHost(this.engine, this.scene, onError);
10990
11057
  this.#reflectionProbes.update(world, probes, (this.#presenter?.hdr ?? null) !== null, this.qualityPreset, readSceneEnvironment(this.scene) !== null);
@@ -11685,7 +11752,7 @@ var InstancedMeshRenderer = class InstancedMeshRenderer extends Component {
11685
11752
  #warnAboutLateSetting(field) {
11686
11753
  if (this.#hasWarnedAboutLateSetting) return;
11687
11754
  this.#hasWarnedAboutLateSetting = true;
11688
- this.app.log.warn(`${CoreErrorCode.instancingSettingTooLate}: {entity} changed {field} on an InstancedMeshRenderer after the scene was registered; the value in use was kept. Set capacity, gpuCulling and lod.mesh before app.start().`, this.entity.name, field);
11755
+ this.app.log.warn(`${CoreErrorCode.instancingSettingTooLate}: ${JSON.stringify(this.entity.name)} changed ${field} on an InstancedMeshRenderer after the scene was registered; the value in use was kept. Set capacity, gpuCulling and lod.mesh before app.start().`);
11689
11756
  }
11690
11757
  /**
11691
11758
  * Says once, at warning level, that a LOD partner was declared with GPU culling off. Lite picks
@@ -11696,7 +11763,7 @@ var InstancedMeshRenderer = class InstancedMeshRenderer extends Component {
11696
11763
  #warnAboutLodWithoutCulling(lod) {
11697
11764
  if (this.#hasWarnedAboutLodWithoutCulling || this.gpuCulling || lod === null || lod.mesh === null) return;
11698
11765
  this.#hasWarnedAboutLodWithoutCulling = true;
11699
- this.app.log.warn(`${CoreErrorCode.instancingLodWithoutCulling}: {entity} declares an InstancedMeshRenderer lod with gpuCulling off; the LOD mesh never draws. Turn gpuCulling on.`, this.entity.name);
11766
+ this.app.log.warn(`${CoreErrorCode.instancingLodWithoutCulling}: ${JSON.stringify(this.entity.name)} declares an InstancedMeshRenderer lod with gpuCulling off; the LOD mesh never draws. Turn gpuCulling on.`);
11700
11767
  }
11701
11768
  /**
11702
11769
  * Builds or rebuilds the meshes when the template or a baked setting changed.
@@ -12565,6 +12632,16 @@ const LIGHT_TYPES = [
12565
12632
  "spot",
12566
12633
  "hemispheric"
12567
12634
  ];
12635
+ /**
12636
+ * How a light takes part in baked lighting (`docs/architecture/07-rendering.md` §2.15).
12637
+ *
12638
+ * @beta
12639
+ */
12640
+ const LIGHT_BAKE_MODES = [
12641
+ "realtime",
12642
+ "mixed",
12643
+ "baked"
12644
+ ];
12568
12645
  /** How many elements a 4x4 matrix has. */
12569
12646
  const MATRIX_LENGTH$1 = 16;
12570
12647
  /** Where the world-space up axis starts inside a column-major world matrix. */
@@ -12583,6 +12660,8 @@ const TRANSLATION_COLUMN = 12;
12583
12660
  *
12584
12661
  * A disabled light, or one on an inactive entity, contributes nothing: its intensity reaches Lite
12585
12662
  * as `0` and its shadow generator is released. Enabling it again restores both on the next frame.
12663
+ * A light whose `bakeMode` is `"baked"` is dimmed the same way: its light reaches the scene only
12664
+ * through a light-probe bake (`bakeLightProbes`).
12586
12665
  *
12587
12666
  * @example
12588
12667
  * ```ts
@@ -12760,7 +12839,8 @@ var Light = class Light extends Component {
12760
12839
  }
12761
12840
  }
12762
12841
  /**
12763
- * The intensity Lite should use: the field, or `0` while the component or its entity is disabled.
12842
+ * The intensity Lite should use: the field, or `0` while the component or its entity is disabled
12843
+ * or the light is `"baked"`.
12764
12844
  *
12765
12845
  * @remarks
12766
12846
  * Dimming keeps the light in the scene. Removing it would change the light count every compiled
@@ -12769,7 +12849,7 @@ var Light = class Light extends Component {
12769
12849
  * @returns The intensity to apply.
12770
12850
  */
12771
12851
  #effectiveIntensity() {
12772
- return this.isEnabledInHierarchy ? this.intensity : 0;
12852
+ return this.isEnabledInHierarchy && this.bakeMode !== "baked" ? this.intensity : 0;
12773
12853
  }
12774
12854
  /**
12775
12855
  * Rebuilds the include and exclude mesh-id sets when either list changed length.
@@ -12803,7 +12883,7 @@ var Light = class Light extends Component {
12803
12883
  */
12804
12884
  #applyShadows(renderer) {
12805
12885
  const light = this.#light;
12806
- const wanted = this.shadows.enabled && this.isEnabledInHierarchy && renderer.features.shadows && !renderer.isHeadless;
12886
+ const wanted = this.shadows.enabled && this.isEnabledInHierarchy && this.bakeMode !== "baked" && renderer.features.shadows && !renderer.isHeadless;
12807
12887
  const isStale = wanted && !sameShadowSettings(this.#appliedShadowSettings, this.shadows);
12808
12888
  if (light === null || wanted === this.#appliedShadows && !isStale) {
12809
12889
  this.#warnAboutShadows(renderer);
@@ -12826,7 +12906,7 @@ var Light = class Light extends Component {
12826
12906
  #warnAboutShadows(renderer) {
12827
12907
  if (this.#hasWarnedAboutShadows || !this.shadows.enabled || renderer.features.shadows) return;
12828
12908
  this.#hasWarnedAboutShadows = true;
12829
- renderer.app.log.warn("{entity} asks for shadows, but the rendering.features.shadows opt-in is off, so it casts none.", this.entity.name);
12909
+ renderer.app.log.warn(`${JSON.stringify(this.entity.name)} asks for shadows, but the rendering.features.shadows opt-in is off, so it casts none.`);
12830
12910
  }
12831
12911
  /**
12832
12912
  * Writes the entity's world pose onto the unparented Lite light, in any frame in which the entity
@@ -13036,7 +13116,8 @@ function lightSchema() {
13036
13116
  })
13037
13117
  }, { tooltip: "Shadow casting; point and hemispheric lights cannot cast (IGX-0703)." }),
13038
13118
  includeOnly: array(entityRef(), [], { tooltip: "Light only these entities' renderers." }),
13039
- exclude: array(entityRef(), [], { tooltip: "Never light these entities' renderers." })
13119
+ exclude: array(entityRef(), [], { tooltip: "Never light these entities' renderers." }),
13120
+ bakeMode: enumOf(LIGHT_BAKE_MODES, "realtime", { tooltip: "Baked lighting: realtime and mixed draw at run time (a probe bake keeps their bounce); baked draws only through the bake." })
13040
13121
  });
13041
13122
  }
13042
13123
  //#endregion
@@ -14713,7 +14794,7 @@ function readMeshFile(parsed, address) {
14713
14794
  for (const key of Object.keys(file)) if (!Object.hasOwn(MESH_FILE_FIELDS, key)) throw invalidMesh(address, `"${key}" is not a mesh file field`);
14714
14795
  const name = file["name"];
14715
14796
  if (name !== void 0 && typeof name !== "string") throw invalidMesh(address, "\"name\" must be a string");
14716
- const primitive = readPrimitive(file["primitive"], address);
14797
+ const primitive = readPrimitive$1(file["primitive"], address);
14717
14798
  const definition = {
14718
14799
  primitive,
14719
14800
  options: readOptions(file["options"], primitive, address)
@@ -14806,7 +14887,7 @@ function asObject(value) {
14806
14887
  * @returns The primitive.
14807
14888
  * @throws IgnifxError with code `IGX-0507` when it is not one of {@link MESH_PRIMITIVES}.
14808
14889
  */
14809
- function readPrimitive(value, address) {
14890
+ function readPrimitive$1(value, address) {
14810
14891
  for (const primitive of MESH_PRIMITIVES) if (value === primitive) return primitive;
14811
14892
  throw invalidMesh(address, `"primitive" is ${JSON.stringify(value ?? null)}; expected one of ${MESH_PRIMITIVES.join(", ")}`);
14812
14893
  }
@@ -15277,9 +15358,9 @@ function decoderLeftOut(address, group) {
15277
15358
  });
15278
15359
  }
15279
15360
  /** `glTF` in ASCII, little-endian: the first four bytes of a `.glb`. */
15280
- const GLB_MAGIC = 1179937895;
15361
+ const GLB_MAGIC$1 = 1179937895;
15281
15362
  /** `JSON` in ASCII, little-endian: the type of a `.glb`'s first chunk. */
15282
- const GLB_JSON_CHUNK = 1313821514;
15363
+ const GLB_JSON_CHUNK$1 = 1313821514;
15283
15364
  /**
15284
15365
  * The extension names a glTF file declares in `extensionsUsed` and `extensionsRequired`.
15285
15366
  *
@@ -15291,9 +15372,9 @@ const GLB_JSON_CHUNK = 1313821514;
15291
15372
  function gltfExtensionsUsed(bytes) {
15292
15373
  let text;
15293
15374
  const view = new DataView(bytes);
15294
- if (bytes.byteLength >= 20 && view.getUint32(0, true) === GLB_MAGIC) {
15375
+ if (bytes.byteLength >= 20 && view.getUint32(0, true) === GLB_MAGIC$1) {
15295
15376
  const length = view.getUint32(12, true);
15296
- if (view.getUint32(16, true) !== GLB_JSON_CHUNK || 20 + length > bytes.byteLength) return [];
15377
+ if (view.getUint32(16, true) !== GLB_JSON_CHUNK$1 || 20 + length > bytes.byteLength) return [];
15297
15378
  text = new TextDecoder().decode(new Uint8Array(bytes, 20, length));
15298
15379
  } else text = new TextDecoder().decode(bytes);
15299
15380
  let document;
@@ -15313,6 +15394,445 @@ function gltfExtensionsUsed(bytes) {
15313
15394
  return names;
15314
15395
  }
15315
15396
  //#endregion
15397
+ //#region src/render/light-probe-bake-gltf.ts
15398
+ /**
15399
+ * A minimal glTF 2.0 reader for the light-probe bake (`docs/architecture/07-rendering.md` §2.15):
15400
+ * the triangles of every mesh the default scene places, in the model's own space, with each
15401
+ * primitive's flat base colour. No device, no Lite.
15402
+ *
15403
+ * - **Containers.** A `.glb` (its JSON and BIN chunks) or a `.gltf` whose buffers are embedded as
15404
+ * `data:` URIs. A buffer at any other URI cannot be read from the bytes alone, so its primitives
15405
+ * are skipped with a reason.
15406
+ * - **Geometry.** `POSITION` (float, or the integer types `KHR_mesh_quantization` allows) and the
15407
+ * indices (or none) of every primitive drawn as triangles, strips or fans; points and lines draw no
15408
+ * surface. Node transforms (matrix or TRS) are composed down the default scene, and then X is
15409
+ * mirrored, as Babylon Lite 1.34.0's loader does with its `__root__` node (scale `(-1, 1, 1)`,
15410
+ * `lib/loader-gltf/load-gltf.js`), so the triangles land where the model draws. Skinned meshes
15411
+ * are read in their bind pose and morph targets are ignored.
15412
+ * - **Compression.** `KHR_draco_mesh_compression` primitives and `EXT_meshopt_compression` buffer
15413
+ * views need Lite's decoders; they are skipped with a reason. Sparse accessors are skipped too.
15414
+ * - **Colour.** `pbrMetallicRoughness.baseColorFactor` (linear) times `1 − metallicFactor` when no
15415
+ * metallic-roughness texture overrides the factor; textures are not sampled.
15416
+ */
15417
+ /** `glTF` in ASCII, little-endian: a `.glb`'s magic. */
15418
+ const GLB_MAGIC = 1179937895;
15419
+ /** `JSON` in ASCII, little-endian: the type of a `.glb`'s first chunk. */
15420
+ const GLB_JSON_CHUNK = 1313821514;
15421
+ /** `BIN\0` in ASCII, little-endian: the type of a `.glb`'s binary chunk. */
15422
+ const GLB_BIN_CHUNK = 5130562;
15423
+ /** Primitive modes the bake can turn into triangles. */
15424
+ const MODE_TRIANGLES = 4;
15425
+ const MODE_TRIANGLE_STRIP = 5;
15426
+ const MODE_TRIANGLE_FAN = 6;
15427
+ /** The largest `byteStride` glTF allows. */
15428
+ const MAX_BYTE_STRIDE = 252;
15429
+ /** The most node visits one file may cost; a strict tree visits each node once. */
15430
+ const MAX_NODE_VISITS = 65536;
15431
+ /** A failure to read one primitive, carried as a reason rather than thrown to the caller. */
15432
+ var SkipPrimitive = class extends Error {};
15433
+ /**
15434
+ * Reads the triangles of a `.glb` or self-contained `.gltf`.
15435
+ *
15436
+ * @param bytes - The file.
15437
+ * @returns The primitives and the reasons for those left out.
15438
+ * @throws Error when the bytes are not a glTF document at all; the bake reports it as the model's
15439
+ * skip reason.
15440
+ *
15441
+ * @internal
15442
+ */
15443
+ function readGltfTriangles(bytes) {
15444
+ const { json, bin } = splitContainer(bytes);
15445
+ const buffers = (json.buffers ?? []).map((buffer, index) => resolveBuffer(buffer.uri, index, bin));
15446
+ const primitives = [];
15447
+ const skipped = [];
15448
+ const mirror = [
15449
+ -1,
15450
+ 0,
15451
+ 0,
15452
+ 0,
15453
+ 0,
15454
+ 1,
15455
+ 0,
15456
+ 0,
15457
+ 0,
15458
+ 0,
15459
+ 1,
15460
+ 0,
15461
+ 0,
15462
+ 0,
15463
+ 0,
15464
+ 1
15465
+ ];
15466
+ const roots = item(item(json.scenes, json.scene ?? 0)?.nodes, "all") ?? [];
15467
+ const visited = /* @__PURE__ */ new Set();
15468
+ const visit = (nodeIndex, parent, depth) => {
15469
+ const node = item(json.nodes, nodeIndex);
15470
+ if (node === void 0 || typeof nodeIndex !== "number" || depth > 256) return;
15471
+ if (visited.has(nodeIndex) || visited.size >= MAX_NODE_VISITS) {
15472
+ skipped.push(`node ${String(nodeIndex)} is reached twice or past the node budget; glTF nodes form a tree`);
15473
+ return;
15474
+ }
15475
+ visited.add(nodeIndex);
15476
+ const world = multiply(parent, localMatrix(node));
15477
+ const mesh = node.mesh === void 0 ? void 0 : item(json.meshes, node.mesh);
15478
+ for (const [index, primitive] of (item(mesh?.primitives, "all") ?? []).entries()) try {
15479
+ const read = readPrimitive(json, buffers, primitive, world);
15480
+ if (read !== null) primitives.push(read);
15481
+ } catch (error) {
15482
+ const reason = error instanceof SkipPrimitive ? error.message : String(error);
15483
+ skipped.push(`mesh ${String(node.mesh)} primitive ${String(index)}: ${reason}`);
15484
+ }
15485
+ for (const child of item(node.children, "all") ?? []) visit(child, world, depth + 1);
15486
+ };
15487
+ for (const root of roots) visit(root, mirror, 0);
15488
+ return {
15489
+ primitives,
15490
+ skipped
15491
+ };
15492
+ }
15493
+ /**
15494
+ * The flat linear albedo of each named material of a `.glb` or `.gltf`, as the bake reads
15495
+ * materials. Only the JSON is parsed.
15496
+ *
15497
+ * @param bytes - The file.
15498
+ * @returns The albedos by material name; empty when the file cannot be read or names none.
15499
+ *
15500
+ * @internal
15501
+ */
15502
+ function readGltfMaterialAlbedos(bytes) {
15503
+ const out = /* @__PURE__ */ new Map();
15504
+ try {
15505
+ const { json } = splitContainer(bytes);
15506
+ for (const material of item(json.materials, "all") ?? []) if (typeof material.name === "string" && !out.has(material.name)) out.set(material.name, materialAlbedo$1(material));
15507
+ } catch {}
15508
+ return out;
15509
+ }
15510
+ /**
15511
+ * Splits a `.glb` into its JSON and BIN chunks, or parses a `.gltf`.
15512
+ *
15513
+ * @param bytes - The file.
15514
+ * @returns The document and the binary chunk, if any.
15515
+ * @throws Error for anything else.
15516
+ */
15517
+ function splitContainer(bytes) {
15518
+ const view = new DataView(bytes);
15519
+ if (bytes.byteLength >= 20 && view.getUint32(0, true) === GLB_MAGIC) {
15520
+ const jsonLength = view.getUint32(12, true);
15521
+ if (view.getUint32(16, true) !== GLB_JSON_CHUNK || 20 + jsonLength > bytes.byteLength) throw new Error("the .glb has no JSON chunk");
15522
+ const json = parseJson(new Uint8Array(bytes, 20, jsonLength));
15523
+ let bin = null;
15524
+ const binStart = 20 + jsonLength;
15525
+ if (binStart + 8 <= bytes.byteLength && view.getUint32(binStart + 4, true) === GLB_BIN_CHUNK) {
15526
+ const binLength = Math.min(view.getUint32(binStart, true), bytes.byteLength - binStart - 8);
15527
+ bin = new Uint8Array(bytes, binStart + 8, binLength);
15528
+ }
15529
+ return {
15530
+ json,
15531
+ bin
15532
+ };
15533
+ }
15534
+ return {
15535
+ json: parseJson(new Uint8Array(bytes)),
15536
+ bin: null
15537
+ };
15538
+ }
15539
+ /**
15540
+ * Parses a glTF JSON document.
15541
+ *
15542
+ * @param text - Its UTF-8 bytes.
15543
+ * @returns The document.
15544
+ * @throws Error when it is not a JSON object.
15545
+ */
15546
+ function parseJson(text) {
15547
+ const value = JSON.parse(new TextDecoder().decode(text));
15548
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("the glTF document is not a JSON object");
15549
+ return value;
15550
+ }
15551
+ /**
15552
+ * The bytes of one buffer, or why there are none.
15553
+ *
15554
+ * @param uri - The buffer's URI, or `undefined` for the `.glb` chunk.
15555
+ * @param index - The buffer's index.
15556
+ * @param bin - The `.glb`'s binary chunk.
15557
+ * @returns The bytes, or the reason as a string.
15558
+ */
15559
+ function resolveBuffer(uri, index, bin) {
15560
+ if (uri === void 0) return index === 0 && bin !== null ? bin : `buffer ${String(index)} has no data`;
15561
+ const comma = uri.indexOf(",");
15562
+ if (uri.startsWith("data:") && comma > 0 && uri.slice(0, comma).endsWith(";base64")) {
15563
+ const text = atob(uri.slice(comma + 1));
15564
+ const out = new Uint8Array(text.length);
15565
+ for (let i = 0; i < text.length; i += 1) out[i] = text.charCodeAt(i);
15566
+ return out;
15567
+ }
15568
+ return `buffer ${String(index)} is a separate file (${uri.slice(0, 80)}), which the bake cannot read`;
15569
+ }
15570
+ /**
15571
+ * Reads one primitive into model space.
15572
+ *
15573
+ * @param json - The document.
15574
+ * @param buffers - The resolved buffers.
15575
+ * @param primitive - The primitive.
15576
+ * @param world - Its node's transform, mirror included.
15577
+ * @returns The triangles, or `null` for points and lines.
15578
+ * @throws SkipPrimitive with the reason it cannot be read.
15579
+ */
15580
+ function readPrimitive(json, buffers, primitive, world) {
15581
+ if (primitive.extensions?.["KHR_draco_mesh_compression"] !== void 0) throw new SkipPrimitive("Draco-compressed (KHR_draco_mesh_compression)");
15582
+ const mode = primitive.mode ?? MODE_TRIANGLES;
15583
+ if (mode !== MODE_TRIANGLES && mode !== MODE_TRIANGLE_STRIP && mode !== MODE_TRIANGLE_FAN) return null;
15584
+ const positionIndex = primitive.attributes?.["POSITION"];
15585
+ if (positionIndex === void 0) throw new SkipPrimitive("no POSITION attribute");
15586
+ const local = readAccessor(json, buffers, positionIndex, 3);
15587
+ const vertexCount = local.length / 3;
15588
+ const positions = new Float32Array(local.length);
15589
+ for (let v = 0; v < vertexCount; v += 1) {
15590
+ const x = local[v * 3] ?? 0;
15591
+ const y = local[v * 3 + 1] ?? 0;
15592
+ const z = local[v * 3 + 2] ?? 0;
15593
+ positions[v * 3] = at(world, 0) * x + at(world, 4) * y + at(world, 8) * z + at(world, 12);
15594
+ positions[v * 3 + 1] = at(world, 1) * x + at(world, 5) * y + at(world, 9) * z + at(world, 13);
15595
+ positions[v * 3 + 2] = at(world, 2) * x + at(world, 6) * y + at(world, 10) * z + at(world, 14);
15596
+ }
15597
+ const raw = primitive.indices === void 0 ? Uint32Array.from({ length: vertexCount }, (_, index) => index) : Uint32Array.from(readAccessor(json, buffers, primitive.indices, 1));
15598
+ for (const index of raw) if (index >= vertexCount) throw new SkipPrimitive("an index past the last vertex");
15599
+ const material = primitive.material === void 0 ? void 0 : item(json.materials, primitive.material);
15600
+ return {
15601
+ positions,
15602
+ indices: toTriangleList(raw, mode),
15603
+ albedo: materialAlbedo$1(material),
15604
+ materialName: material?.name ?? null
15605
+ };
15606
+ }
15607
+ /**
15608
+ * Reads an accessor's elements as plain numbers, normalised when it says so.
15609
+ *
15610
+ * @param json - The document.
15611
+ * @param buffers - The resolved buffers.
15612
+ * @param index - The accessor's index.
15613
+ * @param components - The components per element the caller needs.
15614
+ * @returns `count × components` numbers.
15615
+ * @throws SkipPrimitive when it cannot be read.
15616
+ */
15617
+ function readAccessor(json, buffers, index, components) {
15618
+ const accessor = item(json.accessors, index);
15619
+ if (accessor === void 0) throw new SkipPrimitive(`accessor ${String(index)} does not exist`);
15620
+ if (accessor.sparse !== void 0) throw new SkipPrimitive("a sparse accessor");
15621
+ const width = typeComponents(accessor.type);
15622
+ const size = componentBytes(accessor.componentType);
15623
+ const count = accessor.count ?? 0;
15624
+ if (width !== components || size === void 0 || !isWhole(count)) throw new SkipPrimitive(`accessor ${String(index)} is not a ${String(components)}-component number array`);
15625
+ const view = accessor.bufferView === void 0 ? void 0 : item(json.bufferViews, accessor.bufferView);
15626
+ if (view === void 0) throw new SkipPrimitive(`accessor ${String(index)} has no buffer view`);
15627
+ if (view.extensions?.["EXT_meshopt_compression"] !== void 0) throw new SkipPrimitive("meshopt-compressed (EXT_meshopt_compression)");
15628
+ const buffer = item(buffers, view.buffer ?? 0);
15629
+ if (buffer === void 0 || typeof buffer === "string") throw new SkipPrimitive(buffer ?? `buffer ${String(view.buffer)} does not exist`);
15630
+ const elementBytes = size * width;
15631
+ const stride = view.byteStride ?? elementBytes;
15632
+ const viewOffset = view.byteOffset ?? 0;
15633
+ const viewLength = view.byteLength;
15634
+ const accessorOffset = accessor.byteOffset ?? 0;
15635
+ if (!isWhole(stride) || stride < elementBytes || stride > Math.max(MAX_BYTE_STRIDE, elementBytes)) throw new SkipPrimitive(`buffer view ${String(accessor.bufferView)} has a byteStride outside ${String(elementBytes)}–252`);
15636
+ if (!isWhole(viewOffset) || !isWhole(viewLength) || !isWhole(accessorOffset)) throw new SkipPrimitive(`accessor ${String(index)} or its view has a negative or fractional offset or length`);
15637
+ if (viewOffset + viewLength > buffer.byteLength) throw new SkipPrimitive(`buffer view ${String(accessor.bufferView)} runs past its buffer`);
15638
+ if (count > 0 && accessorOffset + stride * (count - 1) + elementBytes > viewLength) throw new SkipPrimitive(`accessor ${String(index)} runs past its buffer view`);
15639
+ const start = buffer.byteOffset + viewOffset + accessorOffset;
15640
+ const data = new DataView(buffer.buffer, 0, buffer.byteOffset + buffer.byteLength);
15641
+ const out = new Float64Array(count * width);
15642
+ const type = accessor.componentType ?? 0;
15643
+ const normalized = accessor.normalized === true;
15644
+ for (let element = 0; element < count; element += 1) for (let c = 0; c < width; c += 1) out[element * width + c] = readComponent(data, start + element * stride + c * size, type, normalized);
15645
+ return out;
15646
+ }
15647
+ /**
15648
+ * Reads one component.
15649
+ *
15650
+ * @param data - The buffer.
15651
+ * @param offset - Its byte offset.
15652
+ * @param type - The glTF component type.
15653
+ * @param normalized - Whether an integer maps to `[-1, 1]` or `[0, 1]`.
15654
+ * @returns The number.
15655
+ */
15656
+ function readComponent(data, offset, type, normalized) {
15657
+ switch (type) {
15658
+ case 5120: return normalized ? Math.max(data.getInt8(offset) / 127, -1) : data.getInt8(offset);
15659
+ case 5121: return normalized ? data.getUint8(offset) / 255 : data.getUint8(offset);
15660
+ case 5122: return normalized ? Math.max(data.getInt16(offset, true) / 32767, -1) : data.getInt16(offset, true);
15661
+ case 5123: return normalized ? data.getUint16(offset, true) / 65535 : data.getUint16(offset, true);
15662
+ case 5125: return data.getUint32(offset, true);
15663
+ default: return data.getFloat32(offset, true);
15664
+ }
15665
+ }
15666
+ /**
15667
+ * Turns strip or fan indices into a triangle list.
15668
+ *
15669
+ * @param indices - The primitive's indices.
15670
+ * @param mode - Its mode.
15671
+ * @returns Three indices per triangle.
15672
+ */
15673
+ function toTriangleList(indices, mode) {
15674
+ if (mode === MODE_TRIANGLES) return indices.length % 3 === 0 ? indices : indices.slice(0, indices.length - indices.length % 3);
15675
+ const out = [];
15676
+ for (let i = 2; i < indices.length; i += 1) {
15677
+ const a = indices[i - 2] ?? 0;
15678
+ const b = indices[i - 1] ?? 0;
15679
+ const c = indices[i] ?? 0;
15680
+ if (mode === MODE_TRIANGLE_FAN) out.push(indices[0] ?? 0, b, c);
15681
+ else if (i % 2 === 0) out.push(a, b, c);
15682
+ else out.push(b, a, c);
15683
+ }
15684
+ return Uint32Array.from(out);
15685
+ }
15686
+ /**
15687
+ * A material's flat diffuse colour.
15688
+ *
15689
+ * @param material - The material, or `undefined` for glTF's default (white, metallic 1 — which
15690
+ * the bake reads as white, since an untextured default material is meant as plain white).
15691
+ * @returns Linear RGB.
15692
+ */
15693
+ function materialAlbedo$1(material) {
15694
+ const pbr = material?.pbrMetallicRoughness;
15695
+ if (material === void 0) return [
15696
+ 1,
15697
+ 1,
15698
+ 1
15699
+ ];
15700
+ const base = pbr?.baseColorFactor ?? [
15701
+ 1,
15702
+ 1,
15703
+ 1,
15704
+ 1
15705
+ ];
15706
+ const keep = 1 - (pbr?.metallicRoughnessTexture === void 0 ? clamp01$1(pbr?.metallicFactor ?? 1) : 0);
15707
+ return [
15708
+ clamp01$1(base[0] ?? 1) * keep,
15709
+ clamp01$1(base[1] ?? 1) * keep,
15710
+ clamp01$1(base[2] ?? 1) * keep
15711
+ ];
15712
+ }
15713
+ /**
15714
+ * Clamps a number to `[0, 1]`, `NaN` to 0.
15715
+ *
15716
+ * @param value - The number.
15717
+ * @returns It, clamped.
15718
+ */
15719
+ function clamp01$1(value) {
15720
+ return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;
15721
+ }
15722
+ /**
15723
+ * A node's local transform, column-major.
15724
+ *
15725
+ * @param node - The node.
15726
+ * @returns Sixteen numbers.
15727
+ */
15728
+ function localMatrix(node) {
15729
+ if (node.matrix?.length === 16) return [...node.matrix];
15730
+ const [tx = 0, ty = 0, tz = 0] = node.translation ?? [];
15731
+ const [qx = 0, qy = 0, qz = 0, qw = 1] = node.rotation ?? [];
15732
+ const [sx = 1, sy = 1, sz = 1] = node.scale ?? [];
15733
+ const xx = qx * qx;
15734
+ const yy = qy * qy;
15735
+ const zz = qz * qz;
15736
+ const xy = qx * qy;
15737
+ const xz = qx * qz;
15738
+ const yz = qy * qz;
15739
+ const wx = qw * qx;
15740
+ const wy = qw * qy;
15741
+ const wz = qw * qz;
15742
+ return [
15743
+ (1 - 2 * (yy + zz)) * sx,
15744
+ 2 * (xy + wz) * sx,
15745
+ 2 * (xz - wy) * sx,
15746
+ 0,
15747
+ 2 * (xy - wz) * sy,
15748
+ (1 - 2 * (xx + zz)) * sy,
15749
+ 2 * (yz + wx) * sy,
15750
+ 0,
15751
+ 2 * (xz + wy) * sz,
15752
+ 2 * (yz - wx) * sz,
15753
+ (1 - 2 * (xx + yy)) * sz,
15754
+ 0,
15755
+ tx,
15756
+ ty,
15757
+ tz,
15758
+ 1
15759
+ ];
15760
+ }
15761
+ /**
15762
+ * Multiplies two column-major 4×4 matrices: `a · b`.
15763
+ *
15764
+ * @param a - The parent.
15765
+ * @param b - The child.
15766
+ * @returns The product.
15767
+ */
15768
+ function multiply(a, b) {
15769
+ const out = Array.from({ length: 16 }, () => 0);
15770
+ for (let column = 0; column < 4; column += 1) for (let row = 0; row < 4; row += 1) {
15771
+ let sum = 0;
15772
+ for (let k = 0; k < 4; k += 1) sum += at(a, k * 4 + row) * at(b, column * 4 + k);
15773
+ out[column * 4 + row] = sum;
15774
+ }
15775
+ return out;
15776
+ }
15777
+ /**
15778
+ * Reads one number of an array, `0` past its end.
15779
+ *
15780
+ * @param values - The array.
15781
+ * @param index - The index.
15782
+ * @returns The number.
15783
+ */
15784
+ function at(values, index) {
15785
+ return values[index] ?? 0;
15786
+ }
15787
+ /**
15788
+ * Whether a value is a whole, non-negative, safe number: what glTF offsets, lengths and counts are.
15789
+ *
15790
+ * @param value - The value.
15791
+ * @returns `true` for 0, 1, 2…
15792
+ */
15793
+ function isWhole(value) {
15794
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
15795
+ }
15796
+ function item(list, index) {
15797
+ const given = list;
15798
+ if (list === void 0 || !Array.isArray(given)) return;
15799
+ if (index === "all") return list;
15800
+ return isWhole(index) && index < list.length ? list[index] : void 0;
15801
+ }
15802
+ /**
15803
+ * Bytes per component of a glTF `componentType`, compared by value so that no inherited key of a
15804
+ * lookup object (`"toString"`) can match.
15805
+ *
15806
+ * @param type - The document's value.
15807
+ * @returns 1, 2 or 4, or `undefined` for anything else.
15808
+ */
15809
+ function componentBytes(type) {
15810
+ switch (type) {
15811
+ case 5120:
15812
+ case 5121: return 1;
15813
+ case 5122:
15814
+ case 5123: return 2;
15815
+ case 5125:
15816
+ case 5126: return 4;
15817
+ default: return;
15818
+ }
15819
+ }
15820
+ /**
15821
+ * Components per element of a glTF accessor `type`, compared by value.
15822
+ *
15823
+ * @param type - The document's value.
15824
+ * @returns 1 to 4, or `undefined` for anything else.
15825
+ */
15826
+ function typeComponents(type) {
15827
+ switch (type) {
15828
+ case "SCALAR": return 1;
15829
+ case "VEC2": return 2;
15830
+ case "VEC3": return 3;
15831
+ case "VEC4": return 4;
15832
+ default: return;
15833
+ }
15834
+ }
15835
+ //#endregion
15316
15836
  //#region src/render/model-asset.ts
15317
15837
  /**
15318
15838
  * `ModelAsset` (`docs/architecture/05-assets-and-loading.md` §5 and §6,
@@ -15398,6 +15918,8 @@ var ModelAsset = class {
15398
15918
  #scene;
15399
15919
  #container;
15400
15920
  #instances = 0;
15921
+ #sourceBytes;
15922
+ #bakeAlbedos = null;
15401
15923
  /**
15402
15924
  * Wraps a loaded container. The `model` loader constructs these.
15403
15925
  *
@@ -15406,15 +15928,52 @@ var ModelAsset = class {
15406
15928
  * @param animations - The clips taken off the container.
15407
15929
  * @param skeletons - The skeletons the loader found.
15408
15930
  * @param scene - The scene the container is released through, or `null` when headless.
15931
+ * @param sourceBytes - The file's bytes, kept by a headless load for the light-probe bake; `null`
15932
+ * otherwise.
15409
15933
  *
15410
15934
  * @internal
15411
15935
  */
15412
- constructor(address, container, animations, skeletons, scene) {
15936
+ constructor(address, container, animations, skeletons, scene, sourceBytes = null) {
15413
15937
  this.address = address;
15414
15938
  this.#container = container;
15415
15939
  this.animations = animations;
15416
15940
  this.skeletons = skeletons;
15417
15941
  this.#scene = scene;
15942
+ this.#sourceBytes = sourceBytes;
15943
+ }
15944
+ /**
15945
+ * The `.glb` or `.gltf` bytes a headless load kept, which `bakeLightProbes` reads its triangles
15946
+ * from. A load with a device keeps none: the container already holds the model, and holding the
15947
+ * file as well would double what a game keeps in memory.
15948
+ *
15949
+ * @returns The bytes, or `null`.
15950
+ *
15951
+ * @internal
15952
+ */
15953
+ get sourceBytes() {
15954
+ return this.#sourceBytes;
15955
+ }
15956
+ /**
15957
+ * The flat linear albedo of each named glTF material, which a load with a device records for the
15958
+ * light-probe bake: Lite bakes an untextured material's `baseColorFactor` into a 1×1 texture
15959
+ * (`lib/loader-gltf/gltf-pbr-builder.js`), so the drawn material cannot tell its colour.
15960
+ *
15961
+ * @returns The albedos by material name, or `null` when none were recorded.
15962
+ *
15963
+ * @internal
15964
+ */
15965
+ get bakeAlbedos() {
15966
+ return this.#bakeAlbedos;
15967
+ }
15968
+ /**
15969
+ * Records {@link ModelAsset.bakeAlbedos}. The `model` loader calls it.
15970
+ *
15971
+ * @param albedos - The albedos by material name.
15972
+ *
15973
+ * @internal
15974
+ */
15975
+ recordBakeAlbedos(albedos) {
15976
+ this.#bakeAlbedos = albedos;
15418
15977
  }
15419
15978
  /**
15420
15979
  * The Babylon Lite objects the asset owns. Unstable escape hatch.
@@ -15470,6 +16029,7 @@ var ModelAsset = class {
15470
16029
  const container = this.#container;
15471
16030
  const scene = this.#scene;
15472
16031
  this.#container = null;
16032
+ this.#sourceBytes = null;
15473
16033
  if (container !== null && scene !== null) removeContainerFromScene(scene, container);
15474
16034
  }
15475
16035
  /** Releases the template when the asset leaves a `using` block. */
@@ -15483,12 +16043,13 @@ var ModelAsset = class {
15483
16043
  * @param address - The address it was loaded from.
15484
16044
  * @param container - The container, or `null` when the app is headless.
15485
16045
  * @param scene - The scene the container is released through, or `null` when headless.
16046
+ * @param sourceBytes - The file's bytes, kept only by a headless load (see `ModelAsset.sourceBytes`).
15486
16047
  * @returns The asset.
15487
16048
  *
15488
16049
  * @internal
15489
16050
  */
15490
- function createModelAsset(address, container, scene) {
15491
- if (container === null) return new ModelAsset(address, null, [], [], null);
16051
+ function createModelAsset(address, container, scene, sourceBytes = null) {
16052
+ if (container === null) return new ModelAsset(address, null, [], [], null, sourceBytes);
15492
16053
  return new ModelAsset(address, container, takeAnimationGroups(container), container.skeletons ?? [], scene);
15493
16054
  }
15494
16055
  //#endregion
@@ -15524,7 +16085,8 @@ function createModelAsset(address, container, scene) {
15524
16085
  * `engine._device` (ADR-0002 Validation). So a headless load skips it entirely and produces an
15525
16086
  * asset with no container — the `gpu: null` shape §5 requires — rather than failing. The bytes are
15526
16087
  * still fetched, so a headless test still exercises the address, the manifest, and the byte
15527
- * counters.
16088
+ * counters, and the asset keeps them for `bakeLightProbes`, which reads a model's triangles from
16089
+ * the file because a headless app has no container to read them from.
15528
16090
  */
15529
16091
  /**
15530
16092
  * Builds the loader for `.glb` and `.gltf` addresses.
@@ -15545,10 +16107,12 @@ function createModelLoader() {
15545
16107
  async load(ctx) {
15546
16108
  const bytes = await ctx.fetchBytes();
15547
16109
  assertModelDecodersIncluded(ctx.app, ctx.address, bytes);
15548
- if (ctx.app.isHeadless) return createModelAsset(ctx.address, null, null);
16110
+ if (ctx.app.isHeadless) return createModelAsset(ctx.address, null, null, bytes);
15549
16111
  await configureDecoders(ctx.app);
15550
16112
  const container = await loadGltfFromBytes(ctx.lite.engine, bytes);
15551
- return createModelAsset(ctx.address, container, ctx.app.lite.scene);
16113
+ const asset = createModelAsset(ctx.address, container, ctx.app.lite.scene);
16114
+ asset.recordBakeAlbedos(readGltfMaterialAlbedos(bytes));
16115
+ return asset;
15552
16116
  },
15553
16117
  unload(value) {
15554
16118
  value.dispose();
@@ -15569,7 +16133,7 @@ let effectLayer = null;
15569
16133
  * @internal
15570
16134
  */
15571
16135
  async function loadPostEffectSupport() {
15572
- const [compiler, effects] = await Promise.all([compilerLayer ?? import("./post-effect-compiler-jSvOVe0U.js"), effectLayer ?? import("./effect-task-CMbuO6Kb.js")]);
16136
+ const [compiler, effects] = await Promise.all([compilerLayer ?? import("./post-effect-compiler-cCq9lcHt.js"), effectLayer ?? import("./effect-task-CMbuO6Kb.js")]);
15573
16137
  compilerLayer = compiler;
15574
16138
  effectLayer = effects;
15575
16139
  }
@@ -16204,7 +16768,10 @@ var MeshRenderer = class MeshRenderer extends Component {
16204
16768
  sync(renderer) {
16205
16769
  const changed = this.#ensureClone(renderer);
16206
16770
  const instance = this.#instance;
16207
- if (instance === null) return changed;
16771
+ if (instance === null) {
16772
+ renderer.releaseLightmap(this);
16773
+ return changed;
16774
+ }
16208
16775
  instance.applyMaterial(renderer.lightmapMaterial(this, this.#materialAsset(renderer)));
16209
16776
  instance.applyDisplacement(this.#displacement(), this.entity.transform);
16210
16777
  instance.applyFlags(this.receiveShadows, this.renderOrder, this.pickable && !this.#displayHidden);
@@ -16619,6 +17186,16 @@ var Model = class Model extends Component {
16619
17186
  return { root: this.#instance?.root ?? null };
16620
17187
  }
16621
17188
  /**
17189
+ * The meshes of the instantiated subtree, for the light-probe bake under an app with a device.
17190
+ *
17191
+ * @returns The meshes, or `null` while nothing is instantiated (headless, or not synced yet).
17192
+ *
17193
+ * @internal
17194
+ */
17195
+ get instanceMeshes() {
17196
+ return this.#instance?.meshes ?? null;
17197
+ }
17198
+ /**
16622
17199
  * Parents an entity under one of the model's glTF nodes — the "weapon in hand" case
16623
17200
  * (`docs/architecture/07-rendering.md` §2.4).
16624
17201
  *
@@ -17622,7 +18199,7 @@ var ScreenSpaceEffects = class {
17622
18199
  renderer.acquireSceneInputs(),
17623
18200
  import("./scene-color-passes-B93qTOka.js"),
17624
18201
  contact === null ? null : import("./contact-shadows-T523EXaP.js"),
17625
- ssgi === null ? null : import("./ssgi-Dm-maZrc.js")
18202
+ ssgi === null ? null : import("./ssgi-DSnhqotl.js")
17626
18203
  ]);
17627
18204
  const presenter = renderer.presenter;
17628
18205
  const camera = renderer.isHeadless ? null : renderer.scene.camera;
@@ -17845,7 +18422,7 @@ var PostProcessStack = class PostProcessStack extends Component {
17845
18422
  #reportHdrBloomFailure(renderer, failure) {
17846
18423
  if (this.#hdrBloomFailed) return;
17847
18424
  this.#hdrBloomFailed = true;
17848
- renderer.app.log.error(`HDR bloom could not be loaded, so {entity} renders without it. ${String(failure)}`, this.entity.name);
18425
+ renderer.app.log.error(`HDR bloom could not be loaded, so ${JSON.stringify(this.entity.name)} renders without it. ${String(failure)}`);
17849
18426
  }
17850
18427
  /**
17851
18428
  * Replaces the chain with one that holds the effects the fields currently ask for.
@@ -17891,7 +18468,7 @@ var PostProcessStack = class PostProcessStack extends Component {
17891
18468
  #warnAboutFeature(renderer, requestedEffects) {
17892
18469
  if (this.#hasWarnedAboutFeature || requestedEffects === 0 || renderer.features.postProcessing) return;
17893
18470
  this.#hasWarnedAboutFeature = true;
17894
- renderer.app.log.warn(`${CoreErrorCode.postProcessingFeatureOff}: {entity} asks for post-processing, but the rendering.features.postProcessing opt-in is off, so the stack is inert. Declare it in the rendering.features block of createApp() or ignifx.config.ts.`, this.entity.name);
18471
+ renderer.app.log.warn(`${CoreErrorCode.postProcessingFeatureOff}: ${JSON.stringify(this.entity.name)} asks for post-processing, but the rendering.features.postProcessing opt-in is off, so the stack is inert. Declare it in the rendering.features block of createApp() or ignifx.config.ts.`);
17895
18472
  }
17896
18473
  /**
17897
18474
  * The enabled effects, first to last, with the tuning each one needs.
@@ -17965,7 +18542,7 @@ var PostProcessStack = class PostProcessStack extends Component {
17965
18542
  if (!this.#failedShaders.has(shader.address)) {
17966
18543
  this.#failedShaders.add(shader.address);
17967
18544
  const message = isIgnifxError(failure) ? failure.message : String(failure);
17968
- renderer.app.log.error(`${CoreErrorCode.shaderCompileFailed}: {asset} could not be recorded as a custom post effect. ${message}`, shader.address);
18545
+ renderer.app.log.error(`${CoreErrorCode.shaderCompileFailed}: ${shader.address} could not be recorded as a custom post effect. ${message}`);
17969
18546
  }
17970
18547
  return null;
17971
18548
  }
@@ -18403,7 +18980,7 @@ var RenderSyncSystem = class {
18403
18980
  }
18404
18981
  if (enabledCount > 1 && !this.#hasLoggedMultipleEnvironments) {
18405
18982
  this.#hasLoggedMultipleEnvironments = true;
18406
- world.app.log.warn("IGX-0705: {count} Environment components are enabled in this world; the most recent one wins.", enabledCount);
18983
+ world.app.log.warn(`IGX-0705: ${String(enabledCount)} Environment components are enabled in this world; the most recent one wins.`);
18407
18984
  }
18408
18985
  if (enabledCount <= 1) this.#hasLoggedMultipleEnvironments = false;
18409
18986
  if (winner !== null && winner !== (this.#lastEnvironment.get(world) ?? null)) winner.reclaim();
@@ -18506,7 +19083,7 @@ var RenderSyncSystem = class {
18506
19083
  }
18507
19084
  if (hasEsmLight && !this.#esmSkipReported.has(renderer)) {
18508
19085
  this.#esmSkipReported.add(renderer);
18509
- renderer.entity.world.app.log.warn(`${CoreErrorCode.shaderMaterialEsmCasterSkipped}: {entity} uses a shader material under ESM shadows; Babylon Lite 1.27.0 cannot render it into an ESM map, so it casts no shadow there. Use pcf shadows or castShadows: false.`, renderer.entity.name);
19086
+ renderer.entity.world.app.log.warn(`${CoreErrorCode.shaderMaterialEsmCasterSkipped}: ${JSON.stringify(renderer.entity.name)} uses a shader material under ESM shadows; Babylon Lite 1.27.0 cannot render it into an ESM map, so it casts no shadow there. Use pcf shadows or castShadows: false.`);
18510
19087
  }
18511
19088
  }
18512
19089
  /**
@@ -20126,7 +20703,7 @@ var SettingsStore = class {
20126
20703
  },
20127
20704
  hint: "Check the section against the schema the owning extension registered."
20128
20705
  });
20129
- this.#log.warn("The {section} settings section is invalid and was replaced by its defaults: {issues}", name, detail);
20706
+ this.#log.warn(`The ${name} settings section is invalid and was replaced by its defaults: ${detail}`);
20130
20707
  return defaults;
20131
20708
  }
20132
20709
  };
@@ -23691,7 +24268,7 @@ var ExtensionHost = class {
23691
24268
  const dependency = byName.get(name);
23692
24269
  if (dependency === void 0) continue;
23693
24270
  if (state.get(name) === Visit.visiting) {
23694
- if (this.#options.mode === "development") this.#options.log.debug("Dropped the optional dependency {extension} -> {optional} because it would form a cycle.", extension.name, name);
24271
+ if (this.#options.mode === "development") this.#options.log.debug(`Dropped the optional dependency ${extension.name} -> ${name} because it would form a cycle.`);
23695
24272
  continue;
23696
24273
  }
23697
24274
  this.#visit(dependency, byName, state, stack, sorted);
@@ -25018,7 +25595,7 @@ async function createRenderEngine(canvas, options, features) {
25018
25595
  if (hdr) {
25019
25596
  const knobs = features.autoExposure ?? null;
25020
25597
  const exposure = knobs === null ? null : await import("./auto-exposure-uzPn0beO.js");
25021
- presenter = (await import("./hdr-output-Dbv0lhFl.js")).installHdrRenderPath(engine, scene, exposure === null || knobs === null ? void 0 : (hdrTexture) => exposure.installAutoExposure(engine, scene, hdrTexture, knobs));
25598
+ presenter = (await import("./hdr-output-DBQwMphy.js")).installHdrRenderPath(engine, scene, exposure === null || knobs === null ? void 0 : (hdrTexture) => exposure.installAutoExposure(engine, scene, hdrTexture, knobs));
25022
25599
  } else if (offscreen) presenter = installOffscreenRenderPath(engine, scene);
25023
25600
  return {
25024
25601
  engine,
@@ -30261,15 +30838,23 @@ function expandScene(asset, options) {
30261
30838
  };
30262
30839
  if (options.asInstance === true) {
30263
30840
  const key = nextInstanceKey(state);
30264
- instances.push({
30841
+ const entry = {
30265
30842
  key,
30266
30843
  address: asset.address,
30267
30844
  asset: null,
30268
30845
  scene: asset,
30269
30846
  rootUid: null,
30270
- root: null
30271
- });
30847
+ root: null,
30848
+ nestedBaseline: null,
30849
+ nestedRootSourceUids: null
30850
+ };
30851
+ instances.push(entry);
30852
+ const start = entities.length;
30272
30853
  expandFile(asset, null, key, true, [asset.address], state, null);
30854
+ entry.nestedBaseline = nestedBaseline(state, start, key, null);
30855
+ const rootUid = singleRoot(asset)?.uid;
30856
+ const rootEntity = entities.find((entity, index) => index >= start && entity.instanceKey === key && entity.sourceUid === rootUid);
30857
+ entry.nestedRootSourceUids = rootEntity === void 0 ? null : nestedRootSources(state, 1, rootEntity.data.uid);
30273
30858
  return {
30274
30859
  entities,
30275
30860
  instances,
@@ -30422,15 +31007,25 @@ function expandInstance(asset, instance, carrier, chain, state) {
30422
31007
  componentSourceUids: merge.componentSourceUids
30423
31008
  };
30424
31009
  }
30425
- state.instances.push({
31010
+ const entry = {
30426
31011
  key,
30427
31012
  address,
30428
31013
  asset: resolved.handle,
30429
31014
  scene: resolved.value,
30430
31015
  rootUid,
30431
- root
30432
- });
31016
+ root,
31017
+ nestedBaseline: null,
31018
+ nestedRootSourceUids: null
31019
+ };
31020
+ const at = state.instances.length;
31021
+ state.instances.push(entry);
31022
+ const start = state.entities.length;
30433
31023
  const produced = expandFile(resolved.value, rootUid, key, true, [...chain, address], state, merge);
31024
+ entry.nestedRootSourceUids = single === null ? null : nestedRootSources(state, at + 1, rootUid);
31025
+ entry.nestedBaseline = nestedBaseline(state, start, key, entry.nestedRootSourceUids === null ? null : {
31026
+ carrier,
31027
+ uids: entry.nestedRootSourceUids
31028
+ });
30434
31029
  const overrides = instance.overrides;
30435
31030
  if (overrides !== void 0 && overrides.length > 0) applyOverrides(overrides, produced, (message) => {
30436
31031
  state.options.report(CoreErrorCode.instanceHashMismatch, `${asset.address}: ${message}`);
@@ -30464,6 +31059,63 @@ function nestedResolver(produced, state) {
30464
31059
  };
30465
31060
  }
30466
31061
  /**
31062
+ * Collects the component records an instance's nested prefabs produced, before the instance's own
31063
+ * overrides run: every component of an entity a deeper instance produced, and every component a
31064
+ * nested single root merged into an entity of the instanced file.
31065
+ *
31066
+ * @param state - The expansion so far.
31067
+ * @param start - The index of the instance's first entity in `state.entities`.
31068
+ * @param key - The instance's key.
31069
+ * @param root - The carrier and the components the instanced root's own nested instances merged
31070
+ * into it, or `null` when there are none.
31071
+ * @returns Expanded component uid to its record, or `null` when there is none.
31072
+ */
31073
+ function nestedBaseline(state, start, key, root) {
31074
+ let baseline = null;
31075
+ if (root !== null) {
31076
+ for (const component of root.carrier.components) if (root.uids.has(component.uid)) {
31077
+ baseline ??= /* @__PURE__ */ new Map();
31078
+ baseline.set(component.uid, component);
31079
+ }
31080
+ }
31081
+ for (let index = start; index < state.entities.length; index += 1) {
31082
+ const entity = state.entities[index];
31083
+ if (entity === void 0) continue;
31084
+ const merged = entity.instanceKey === key ? state.merged.get(entity.data.uid) : void 0;
31085
+ if (entity.instanceKey === key && merged === void 0) continue;
31086
+ const components = entity.data.components;
31087
+ for (let inner = 0; inner < components.length; inner += 1) {
31088
+ const component = components[inner];
31089
+ if (component !== void 0 && (merged === void 0 || merged.has(component.uid))) {
31090
+ baseline ??= /* @__PURE__ */ new Map();
31091
+ baseline.set(component.uid, component);
31092
+ }
31093
+ }
31094
+ }
31095
+ return baseline;
31096
+ }
31097
+ /**
31098
+ * The components the scenes a single root instances merged into the same carrier: every instance
31099
+ * expanded after `from` whose root is the carrier and merged a single root into it.
31100
+ *
31101
+ * @param state - The expansion so far.
31102
+ * @param from - The index in `state.instances` of the first instance the root's file produced.
31103
+ * @param carrierUid - The carrier's expanded uid.
31104
+ * @returns Expanded component uid to the uid its own file gives it, or `null` when there is none.
31105
+ */
31106
+ function nestedRootSources(state, from, carrierUid) {
31107
+ let found = null;
31108
+ for (let index = from; index < state.instances.length; index += 1) {
31109
+ const instance = state.instances[index];
31110
+ if (instance?.rootUid !== carrierUid || instance.root === null) continue;
31111
+ for (const [uid, sourceUid] of instance.root.componentSourceUids) {
31112
+ found ??= /* @__PURE__ */ new Map();
31113
+ found.set(uid, sourceUid);
31114
+ }
31115
+ }
31116
+ return found;
31117
+ }
31118
+ /**
30467
31119
  * Reports, or throws, an `IGX-0604` hash mismatch.
30468
31120
  *
30469
31121
  * @param address - The instanced scene.
@@ -31048,7 +31700,9 @@ function ownedInstance(context, entity, source, rootOfInstance, handle) {
31048
31700
  address: instance.address,
31049
31701
  asset: instance.rootUid === null ? handle : instance.asset,
31050
31702
  scene: instance.scene,
31051
- root: instancedRoot(context, instance, source)
31703
+ root: instancedRoot(context, instance, source),
31704
+ nestedBaseline: instance.nestedBaseline,
31705
+ nestedRootSourceUids: instance.nestedRootSourceUids
31052
31706
  };
31053
31707
  }
31054
31708
  return null;
@@ -33520,20 +34174,347 @@ var Vec4 = class Vec4 {
33520
34174
  }
33521
34175
  };
33522
34176
  //#endregion
34177
+ //#region src/render/gpu/light-probe-bake-model.ts
34178
+ /** The albedo of a mesh whose material says nothing usable. */
34179
+ const MID_GREY = Object.freeze([
34180
+ .5,
34181
+ .5,
34182
+ .5
34183
+ ]);
34184
+ /**
34185
+ * Adds the triangles of a model's live instance, when the bake should read it: the asset kept no
34186
+ * file bytes and the instance exists. Each mesh is coloured by its material, or by the model's
34187
+ * override for that material's name.
34188
+ *
34189
+ * @param model - The model.
34190
+ * @param sink - Where the triangles go.
34191
+ * @param albedo - Reads an override's albedo.
34192
+ * @param skip - Records a mesh left out, or a model that gave nothing.
34193
+ * @param signal - Stops the collection between meshes.
34194
+ * @returns `null` when the model is read from its file instead (or has no instance to read), else
34195
+ * `1` when it gave no triangles at all and `0` when it gave some.
34196
+ *
34197
+ * @internal
34198
+ */
34199
+ function traceLiveModel(model, sink, albedo, skip, signal) {
34200
+ const handle = model.model;
34201
+ const asset = handle === null || handle.state !== "loaded" ? null : handle.value;
34202
+ const meshes = asset === null || asset.sourceBytes !== null ? null : model.instanceMeshes;
34203
+ if (asset === null || meshes === null) return null;
34204
+ const fileAlbedos = asset.bakeAlbedos;
34205
+ const matrix = Array.from({ length: 16 }, () => 0);
34206
+ let traced = 0;
34207
+ let reasons = 0;
34208
+ for (const mesh of meshes) {
34209
+ signal?.throwIfAborted();
34210
+ const surface = readMeshBakeSurface(mesh);
34211
+ if (surface === null) {
34212
+ reasons += 1;
34213
+ skip(model.entity, Model.typeId, `mesh "${mesh.name}" keeps no CPU triangles`);
34214
+ continue;
34215
+ }
34216
+ const override = surface.materialName === null ? void 0 : model.materialOverrides[surface.materialName];
34217
+ const fromFile = surface.materialName === null ? void 0 : fileAlbedos?.get(surface.materialName);
34218
+ const rgb = override !== void 0 && override !== null ? albedo(override) : fromFile ?? surface.albedo ?? MID_GREY;
34219
+ traced += sink.add(surface.positions, surface.indices, readWorldMatrix(mesh, matrix), rgb);
34220
+ }
34221
+ if (traced > 0) return 0;
34222
+ if (reasons === 0) skip(model.entity, Model.typeId, "the model's instance draws no triangles");
34223
+ return 1;
34224
+ }
34225
+ /**
34226
+ * Builds the triangles of a primitive as Lite would size and place it.
34227
+ *
34228
+ * @param definition - The primitive and its options, as `MeshAsset`'s factories and `.mesh.json` take them.
34229
+ * @returns Its local-space triangles.
34230
+ *
34231
+ * @internal
34232
+ */
34233
+ function primitiveTriangles(definition) {
34234
+ switch (definition.primitive) {
34235
+ case "box": {
34236
+ const size = definition.options.size ?? 1;
34237
+ return boxTriangles(definition.options.width ?? size, definition.options.height ?? size, definition.options.depth ?? size);
34238
+ }
34239
+ case "sphere": {
34240
+ const radius = (definition.options.diameter ?? 1) / 2;
34241
+ const rings = clampSegments(Math.max(3, definition.options.segments ?? 32));
34242
+ const profile = [];
34243
+ for (let ring = 0; ring <= rings; ring += 1) {
34244
+ const angle = Math.PI * (1 - ring / rings);
34245
+ profile.push([Math.sin(angle) * radius, Math.cos(angle) * radius]);
34246
+ }
34247
+ return revolve(profile, rings * 2);
34248
+ }
34249
+ case "plane": {
34250
+ const size = definition.options.size ?? 1;
34251
+ const hw = (definition.options.width ?? size) / 2;
34252
+ const hh = (definition.options.height ?? size) / 2;
34253
+ return quad([
34254
+ -hw,
34255
+ -hh,
34256
+ 0,
34257
+ hw,
34258
+ -hh,
34259
+ 0,
34260
+ hw,
34261
+ hh,
34262
+ 0,
34263
+ -hw,
34264
+ hh,
34265
+ 0
34266
+ ]);
34267
+ }
34268
+ case "ground": {
34269
+ const hw = (definition.options.width ?? 1) / 2;
34270
+ const hd = (definition.options.height ?? 1) / 2;
34271
+ return quad([
34272
+ -hw,
34273
+ 0,
34274
+ -hd,
34275
+ hw,
34276
+ 0,
34277
+ -hd,
34278
+ hw,
34279
+ 0,
34280
+ hd,
34281
+ -hw,
34282
+ 0,
34283
+ hd
34284
+ ]);
34285
+ }
34286
+ case "cylinder": {
34287
+ const options = definition.options;
34288
+ const height = options.height ?? 2;
34289
+ const top = (options.diameterTop ?? options.diameter ?? 1) / 2;
34290
+ const bottom = (options.diameterBottom ?? options.diameter ?? 1) / 2;
34291
+ return revolve([
34292
+ [0, -height / 2],
34293
+ [bottom, -height / 2],
34294
+ [top, height / 2],
34295
+ [0, height / 2]
34296
+ ], clampSegments(Math.max(3, options.tessellation ?? 24)));
34297
+ }
34298
+ case "capsule": {
34299
+ const options = definition.options;
34300
+ const height = Math.max(orDefault(options.height, 1), 0);
34301
+ const radius = Math.max(orDefault(options.radius, .25), 0);
34302
+ const half = Math.max(height / 2 - radius, 0);
34303
+ const arc = 8;
34304
+ const profile = [];
34305
+ for (let step = 0; step <= arc; step += 1) {
34306
+ const angle = Math.PI / 2 * (step / arc);
34307
+ profile.push([Math.sin(angle) * radius, -half - Math.cos(angle) * radius]);
34308
+ }
34309
+ for (let step = 0; step <= arc; step += 1) {
34310
+ const angle = Math.PI / 2 * (step / arc);
34311
+ profile.push([Math.cos(angle) * radius, half + Math.sin(angle) * radius]);
34312
+ }
34313
+ return revolve(profile, clampSegments(Math.max(3, orDefault(options.tessellation, 16))));
34314
+ }
34315
+ case "torus": {
34316
+ const options = definition.options;
34317
+ return torusTriangles((options.diameter ?? 1) / 2, (options.thickness ?? .5) / 2, clampSegments(Math.max(3, options.tessellation ?? 16)));
34318
+ }
34319
+ default: return assertNever(definition, "mesh primitive");
34320
+ }
34321
+ }
34322
+ /**
34323
+ * An option Lite reads with `||`: missing or `0` takes the default.
34324
+ *
34325
+ * @param value - The option.
34326
+ * @param fallback - Lite's default.
34327
+ * @returns The value to use.
34328
+ */
34329
+ function orDefault(value, fallback) {
34330
+ return value === void 0 || value === 0 || Number.isNaN(value) ? fallback : value;
34331
+ }
34332
+ /**
34333
+ * Caps a segment count at {@link MAX_BAKE_SEGMENTS}.
34334
+ *
34335
+ * @param segments - What the options asked for.
34336
+ * @returns A whole count from 3 to the cap.
34337
+ */
34338
+ function clampSegments(segments) {
34339
+ return Math.min(16, Math.max(3, Math.floor(segments)));
34340
+ }
34341
+ /**
34342
+ * An axis-aligned box centred on the origin.
34343
+ *
34344
+ * @param width - Its size along X.
34345
+ * @param height - Its size along Y.
34346
+ * @param depth - Its size along Z.
34347
+ * @returns Twelve triangles.
34348
+ */
34349
+ function boxTriangles(width, height, depth) {
34350
+ const x = width / 2;
34351
+ const y = height / 2;
34352
+ const z = depth / 2;
34353
+ return {
34354
+ positions: Float32Array.from([
34355
+ -x,
34356
+ -y,
34357
+ -z,
34358
+ x,
34359
+ -y,
34360
+ -z,
34361
+ x,
34362
+ y,
34363
+ -z,
34364
+ -x,
34365
+ y,
34366
+ -z,
34367
+ -x,
34368
+ -y,
34369
+ z,
34370
+ x,
34371
+ -y,
34372
+ z,
34373
+ x,
34374
+ y,
34375
+ z,
34376
+ -x,
34377
+ y,
34378
+ z
34379
+ ]),
34380
+ indices: Uint32Array.from([
34381
+ 0,
34382
+ 1,
34383
+ 2,
34384
+ 0,
34385
+ 2,
34386
+ 3,
34387
+ 4,
34388
+ 6,
34389
+ 5,
34390
+ 4,
34391
+ 7,
34392
+ 6,
34393
+ 0,
34394
+ 4,
34395
+ 5,
34396
+ 0,
34397
+ 5,
34398
+ 1,
34399
+ 3,
34400
+ 2,
34401
+ 6,
34402
+ 3,
34403
+ 6,
34404
+ 7,
34405
+ 0,
34406
+ 3,
34407
+ 7,
34408
+ 0,
34409
+ 7,
34410
+ 4,
34411
+ 1,
34412
+ 5,
34413
+ 6,
34414
+ 1,
34415
+ 6,
34416
+ 2
34417
+ ])
34418
+ };
34419
+ }
34420
+ /**
34421
+ * Two triangles over four corners given in order around the quad.
34422
+ *
34423
+ * @param corners - Twelve floats.
34424
+ * @returns The quad.
34425
+ */
34426
+ function quad(corners) {
34427
+ return {
34428
+ positions: Float32Array.from(corners),
34429
+ indices: Uint32Array.from([
34430
+ 0,
34431
+ 1,
34432
+ 2,
34433
+ 0,
34434
+ 2,
34435
+ 3
34436
+ ])
34437
+ };
34438
+ }
34439
+ /**
34440
+ * Revolves a `(radius, y)` profile around the Y axis.
34441
+ *
34442
+ * @param profile - The profile, bottom to top.
34443
+ * @param slices - Segments around the axis.
34444
+ * @returns The surface; a zero radius makes degenerate triangles, which the trace skips.
34445
+ */
34446
+ function revolve(profile, slices) {
34447
+ const positions = [];
34448
+ for (const [radius, y] of profile) for (let slice = 0; slice <= slices; slice += 1) {
34449
+ const angle = 2 * Math.PI * slice / slices;
34450
+ positions.push(Math.cos(angle) * radius, y, Math.sin(angle) * radius);
34451
+ }
34452
+ return {
34453
+ positions: Float32Array.from(positions),
34454
+ indices: gridIndices(profile.length - 1, slices)
34455
+ };
34456
+ }
34457
+ /**
34458
+ * A torus in the XZ plane.
34459
+ *
34460
+ * @param ring - The distance from the centre to the tube's centre.
34461
+ * @param tube - The tube's radius.
34462
+ * @param segments - Segments around the ring and around the tube.
34463
+ * @returns The surface.
34464
+ */
34465
+ function torusTriangles(ring, tube, segments) {
34466
+ const positions = [];
34467
+ for (let i = 0; i <= segments; i += 1) {
34468
+ const outer = 2 * Math.PI * i / segments;
34469
+ for (let j = 0; j <= segments; j += 1) {
34470
+ const inner = 2 * Math.PI * j / segments;
34471
+ const distance = ring + Math.cos(inner) * tube;
34472
+ positions.push(Math.cos(outer) * distance, Math.sin(inner) * tube, -Math.sin(outer) * distance);
34473
+ }
34474
+ }
34475
+ return {
34476
+ positions: Float32Array.from(positions),
34477
+ indices: gridIndices(segments, segments)
34478
+ };
34479
+ }
34480
+ /**
34481
+ * The triangles of a `(rows + 1) × (columns + 1)` vertex grid.
34482
+ *
34483
+ * @param rows - Quads along the first axis.
34484
+ * @param columns - Quads along the second.
34485
+ * @returns Six indices per quad.
34486
+ */
34487
+ function gridIndices(rows, columns) {
34488
+ const indices = [];
34489
+ const stride = columns + 1;
34490
+ for (let row = 0; row < rows; row += 1) for (let column = 0; column < columns; column += 1) {
34491
+ const a = row * stride + column;
34492
+ const b = a + stride;
34493
+ indices.push(a, b, a + 1, a + 1, b, b + 1);
34494
+ }
34495
+ return Uint32Array.from(indices);
34496
+ }
34497
+ //#endregion
33523
34498
  //#region src/render/light-probe-bake.ts
33524
34499
  /**
33525
34500
  * The CPU light-probe bake (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B4): one bounce
33526
34501
  * of diffuse light, needing no device, so it runs headless, in a tool, or in a test.
33527
34502
  *
33528
- * - **Geometry.** Triangles of every enabled `MeshRenderer` whose mesh was built with
33529
- * `MeshAsset.fromData`, moved to world space. Primitives and glTF models keep their triangles on
33530
- * the GPU side only and are skipped; {@link LightProbeBakeResult.skipped} counts them.
34503
+ * - **Geometry.** Triangles of every enabled `MeshRenderer` (a `MeshAsset.fromData` mesh's own
34504
+ * arrays, or a primitive rebuilt on the CPU by `light-probe-bake-primitives.ts`) and every enabled
34505
+ * `Model` — read from the glTF file a headless app loaded (`light-probe-bake-gltf.ts`), or, under
34506
+ * an app with a device, from its instance's meshes (Lite's `getMeshTriangles`) — moved to world
34507
+ * space. What
34508
+ * cannot be read is listed in {@link LightProbeBakeResult.skips}. Each mesh keeps a world bounding
34509
+ * box, so a ray tests the triangles of the meshes it passes through only.
33531
34510
  * - **Per probe.** `rays` directions on a Fibonacci sphere. A hit returns the surface's albedo (the
33532
34511
  * material's base or diffuse colour, decoded to linear) times the direct light there, with a
33533
- * shadow ray per directional, point or spot light and the hemispheric lights unshadowed. A miss
33534
- * returns `sky` plus the hemispheric lights. With `directLight: "include"`, the directional, point
33535
- * and spot lights the probe sees are added exactly, as clamped-cosine lobes; by default they are
33536
- * left out, because those lights still light the scene in real time. Spot cones are ignored.
34512
+ * shadow ray per directional, point or spot light and the hemispheric lights unshadowed: every
34513
+ * light bounces. A miss returns the sky. The light a probe receives straight from a light is
34514
+ * added only for a light whose rule says so ({@link lightBakeTerms}): a `"baked"` light always, a
34515
+ * `"mixed"` light never, a `"realtime"` light only with `directLight: "include"` — a hemispheric
34516
+ * light as part of what a miss sees, the others exactly, as clamped-cosine lobes. Spot cones are
34517
+ * ignored.
33537
34518
  * - **Units.** Lite's: a white surface lit by the result shows `c0 + c1·n.y + c2·n.z + c3·n.x`, so a
33538
34519
  * uniform sky of radiance `L` bakes to `c0 = L`, and an included directional light of intensity
33539
34520
  * `I` to `c0 = I/4` and a first-order term of `I/2` along its direction.
@@ -33548,15 +34529,52 @@ const GOLDEN_ANGLE = 2.399963229728653;
33548
34529
  const MAX_RAYS = 4096;
33549
34530
  /** How long the bake works before it yields to the host, in milliseconds (half a 60 Hz frame). */
33550
34531
  const YIELD_BUDGET_MS = 8;
34532
+ /** Floats per mesh in {@link TraceScene.meshes}. */
34533
+ const MESH_STRIDE = 8;
34534
+ /**
34535
+ * What one light gives a light-probe bake, by its `bakeMode` and the bake's `directLight`.
34536
+ *
34537
+ * @remarks
34538
+ * Every light bounces: the light it puts on surfaces is traced back to the probes. Whether a probe
34539
+ * also stores the light it receives straight from it depends on who draws that light at run time:
34540
+ * a `"baked"` light is not drawn, so the probe holds it; a `"mixed"` light is drawn, so the probe
34541
+ * never does; a `"realtime"` light is drawn too, and `directLight: "include"` is how a bake asks
34542
+ * for its direct light anyway (to read a probe's total light).
34543
+ *
34544
+ * @param bakeMode - The light's `bakeMode`.
34545
+ * @param directLight - The bake's `directLight` option.
34546
+ * @returns Whether the probes store its direct light, and whether its bounce is baked.
34547
+ *
34548
+ * @beta
34549
+ */
34550
+ function lightBakeTerms(bakeMode, directLight) {
34551
+ if (bakeMode === "baked") return {
34552
+ direct: true,
34553
+ bounce: true
34554
+ };
34555
+ if (bakeMode === "mixed") return {
34556
+ direct: false,
34557
+ bounce: true
34558
+ };
34559
+ return {
34560
+ direct: directLight === "include",
34561
+ bounce: true
34562
+ };
34563
+ }
33551
34564
  /**
33552
34565
  * Bakes a light-probe grid from a world's mesh renderers and lights, on the CPU.
33553
34566
  *
33554
34567
  * @remarks
33555
- * One bounce, first-order harmonics, deterministic. Only meshes built with `MeshAsset.fromData`
33556
- * cast and bounce light (see {@link LightProbeBakeResult.skipped}). By default a probe holds the
33557
- * bounce but not the direct light of directional, point and spot lights, which keep lighting the
33558
- * scene in real time (see {@link LightProbeBakeOptions.directLight}). Cost grows with probes × rays ×
33559
- * triangles; it is meant for small scenes and tools, not for every frame.
34568
+ * One bounce, first-order harmonics, deterministic. `MeshRenderer` meshes (built from data, or
34569
+ * primitives) and `Model` glTF files cast and bounce light; a model is read from the file a
34570
+ * headless app loaded, or, under an app with a device, from the CPU triangles Lite keeps on its
34571
+ * instance's meshes once the model has been drawn (a model not instantiated yet is listed in
34572
+ * {@link LightProbeBakeResult.skips}). Draco- and meshopt-compressed glTF primitives are skipped
34573
+ * headless. By
34574
+ * default a probe holds every light's bounce but the direct light of `"baked"` lights only, since
34575
+ * the others keep lighting the scene in real time (see {@link LightProbeBakeOptions.directLight} and
34576
+ * `Light.bakeMode`). Cost grows with probes × rays × triangles (each mesh's bounding box culls its
34577
+ * triangles); it is meant for tools, not for every frame.
33560
34578
  *
33561
34579
  * The bake is asynchronous: it yields to the host after every ~8 ms of work, reports progress
33562
34580
  * through `onProgress` after each probe, and stops at the next probe once `signal` aborts.
@@ -33567,7 +34585,9 @@ const YIELD_BUDGET_MS = 8;
33567
34585
  * @throws IgnifxError with code `IGX-0734`, before tracing anything, for a grid the `.probes.json`
33568
34586
  * format cannot hold (whole counts, `counts.x` ≤ 1024, `counts.y × counts.z` ≤ 4096, finite
33569
34587
  * `origin` and positive `cellSize`), `rays` outside 1–4096, a `maxDistance` that is not finite
33570
- * and positive, or a `directLight` other than `"include"` or `"exclude"`. The promise rejects with `signal.reason` when the bake is aborted.
34588
+ * and positive, a `directLight` other than `"include"` or `"exclude"`, or a `sky` that is not a
34589
+ * finite colour, gradient or 27 finite harmonics. The promise rejects with `signal.reason` when the
34590
+ * bake is aborted.
33571
34591
  *
33572
34592
  * @example
33573
34593
  * ```ts
@@ -33584,8 +34604,8 @@ const YIELD_BUDGET_MS = 8;
33584
34604
  async function bakeLightProbes(world, options) {
33585
34605
  const settings = readBakeOptions(options);
33586
34606
  options.signal?.throwIfAborted();
33587
- const { scene, skipped } = collectTriangles(world);
33588
- const lights = collectLights(world);
34607
+ const { scene, skipped, skips } = collectTriangles(world, options.signal);
34608
+ const lights = collectLights(world, settings.includeDirect ? "include" : "exclude");
33589
34609
  const { origin, cellSize, counts } = settings.grid;
33590
34610
  const total = counts.x * counts.y * counts.z;
33591
34611
  const coefficients = [];
@@ -33612,7 +34632,8 @@ async function bakeLightProbes(world, options) {
33612
34632
  coefficients
33613
34633
  },
33614
34634
  triangles: scene.count,
33615
- skipped
34635
+ skipped,
34636
+ skips
33616
34637
  };
33617
34638
  }
33618
34639
  /**
@@ -33639,15 +34660,85 @@ function readBakeOptions(options) {
33639
34660
  grid,
33640
34661
  rays,
33641
34662
  maxDistance,
33642
- sky: linearRgb(options.sky ?? {
33643
- r: 0,
33644
- g: 0,
33645
- b: 0,
33646
- a: 1
33647
- }, false),
34663
+ sky: readSky(options.sky),
33648
34664
  includeDirect: directLight === "include"
33649
34665
  };
33650
34666
  }
34667
+ /** The real SH basis constants for bands 0–2. */
34668
+ const SH_C0 = .2820947917738781;
34669
+ const SH_C1 = .4886025119029199;
34670
+ const SH_C2 = 1.0925484305920792;
34671
+ const SH_C3 = .31539156525252005;
34672
+ const SH_C4 = .5462742152960396;
34673
+ /**
34674
+ * Checks the `sky` option and turns it into a radiance function.
34675
+ *
34676
+ * @param sky - The option.
34677
+ * @returns The function.
34678
+ * @throws IgnifxError with code `IGX-0734` for a non-finite colour or the wrong harmonics.
34679
+ */
34680
+ function readSky(sky) {
34681
+ if (sky === void 0) return (_dx, _dy, _dz, out) => {
34682
+ out.fill(0);
34683
+ };
34684
+ const given = sky;
34685
+ if (typeof given !== "object" || given === null) throw fail("sky must be a colour, a gradient or harmonics");
34686
+ if (!("kind" in sky)) {
34687
+ const flat = checkedColor(sky, "sky");
34688
+ return (_dx, _dy, _dz, out) => {
34689
+ for (let channel = 0; channel < 3; channel += 1) out[channel] = read(flat, channel);
34690
+ };
34691
+ }
34692
+ const kind = sky.kind;
34693
+ if (kind === "gradient" && sky.kind === "gradient") {
34694
+ const up = checkedColor(sky.sky, "sky.sky");
34695
+ const horizon = checkedColor(sky.horizon, "sky.horizon");
34696
+ const down = checkedColor(sky.ground, "sky.ground");
34697
+ return (_dx, dy, _dz, out) => {
34698
+ const end = dy >= 0 ? up : down;
34699
+ const t = Math.min(1, Math.abs(dy));
34700
+ for (let channel = 0; channel < 3; channel += 1) out[channel] = read(horizon, channel) * (1 - t) + read(end, channel) * t;
34701
+ };
34702
+ }
34703
+ if (kind === "sh9" && sky.kind === "sh9") {
34704
+ const c = sky.coefficients;
34705
+ if (!Array.isArray(c) || c.length !== 27 || !c.every((value) => Number.isFinite(value))) throw fail("sky.coefficients must be 27 finite numbers (nine RGB triples)");
34706
+ return (x, y, z, out) => {
34707
+ const basis = [
34708
+ SH_C0,
34709
+ SH_C1 * y,
34710
+ SH_C1 * z,
34711
+ SH_C1 * x,
34712
+ SH_C2 * x * y,
34713
+ SH_C2 * y * z,
34714
+ SH_C3 * (3 * z * z - 1),
34715
+ SH_C2 * x * z,
34716
+ SH_C4 * (x * x - y * y)
34717
+ ];
34718
+ for (let channel = 0; channel < 3; channel += 1) {
34719
+ let sum = 0;
34720
+ for (let term = 0; term < 9; term += 1) sum += read(c, term * 3 + channel) * read(basis, term);
34721
+ out[channel] = Math.max(0, sum);
34722
+ }
34723
+ };
34724
+ }
34725
+ throw fail("sky.kind must be \"gradient\" or \"sh9\"");
34726
+ }
34727
+ /**
34728
+ * A linear colour option's three channels, checked.
34729
+ *
34730
+ * @param colour - The colour.
34731
+ * @param name - The option's name, for the error.
34732
+ * @returns Linear RGB.
34733
+ * @throws IgnifxError with code `IGX-0734` when a channel is not finite.
34734
+ */
34735
+ function checkedColor(colour, name) {
34736
+ const given = colour;
34737
+ if (typeof given !== "object" || given === null) throw fail(`${name} must be a colour with finite channels`);
34738
+ const rgb = linearRgb(colour, false);
34739
+ if (!rgb.every((channel) => Number.isFinite(channel))) throw fail(`${name} must be a colour with finite channels`);
34740
+ return rgb;
34741
+ }
33651
34742
  /**
33652
34743
  * The error for a bake option.
33653
34744
  *
@@ -33705,7 +34796,7 @@ function bakeProbe(scene, lights, px, py, pz, settings) {
33705
34796
  sh[9 + channel] = read(sh, 9 + channel) + BAND1_PER_SAMPLE * value * dx / rays;
33706
34797
  }
33707
34798
  }
33708
- if (settings.includeDirect) addDirectLobes(scene, lights, px, py, pz, sh);
34799
+ addDirectLobes(scene, lights, px, py, pz, sh);
33709
34800
  return sh;
33710
34801
  }
33711
34802
  /**
@@ -33725,53 +34816,175 @@ function fibonacciDirection(index, count) {
33725
34816
  Math.sin(angle) * radius
33726
34817
  ];
33727
34818
  }
34819
+ /** Collects world-space meshes into a {@link TraceScene}. */
34820
+ var SceneBuilder = class {
34821
+ vertices = [];
34822
+ albedo = [];
34823
+ meshes = [];
34824
+ /**
34825
+ * Adds one mesh.
34826
+ *
34827
+ * @param positions - Three floats per vertex, in the space `matrix` maps from.
34828
+ * @param indices - Three indices per triangle.
34829
+ * @param matrix - A column-major world matrix.
34830
+ * @param rgb - The mesh's linear albedo.
34831
+ * @returns How many triangles it added.
34832
+ */
34833
+ add(positions, indices, matrix, rgb) {
34834
+ const first = this.albedo.length / 3;
34835
+ const min = [
34836
+ Number.POSITIVE_INFINITY,
34837
+ Number.POSITIVE_INFINITY,
34838
+ Number.POSITIVE_INFINITY
34839
+ ];
34840
+ const max = [
34841
+ Number.NEGATIVE_INFINITY,
34842
+ Number.NEGATIVE_INFINITY,
34843
+ Number.NEGATIVE_INFINITY
34844
+ ];
34845
+ const m = matrix;
34846
+ const triangles = Math.floor(indices.length / 3);
34847
+ for (let index = 0; index < triangles * 3; index += 1) {
34848
+ const vertex = read(indices, index) * 3;
34849
+ const x = read(positions, vertex);
34850
+ const y = read(positions, vertex + 1);
34851
+ const z = read(positions, vertex + 2);
34852
+ const world = [
34853
+ read(m, 0) * x + read(m, 4) * y + read(m, 8) * z + read(m, 12),
34854
+ read(m, 1) * x + read(m, 5) * y + read(m, 9) * z + read(m, 13),
34855
+ read(m, 2) * x + read(m, 6) * y + read(m, 10) * z + read(m, 14)
34856
+ ];
34857
+ for (let axis = 0; axis < 3; axis += 1) {
34858
+ const value = read(world, axis);
34859
+ this.vertices.push(value);
34860
+ min[axis] = Math.min(read(min, axis), value);
34861
+ max[axis] = Math.max(read(max, axis), value);
34862
+ }
34863
+ if (index % 3 === 2) this.albedo.push(...rgb);
34864
+ }
34865
+ if (triangles > 0) this.meshes.push(first, triangles, ...min, ...max);
34866
+ return triangles;
34867
+ }
34868
+ /**
34869
+ * The finished scene.
34870
+ *
34871
+ * @returns It.
34872
+ */
34873
+ build() {
34874
+ return {
34875
+ vertices: Float64Array.from(this.vertices),
34876
+ albedo: Float64Array.from(this.albedo),
34877
+ count: this.albedo.length / 3,
34878
+ meshes: Float64Array.from(this.meshes),
34879
+ meshCount: this.meshes.length / MESH_STRIDE
34880
+ };
34881
+ }
34882
+ };
33728
34883
  /**
33729
- * Gathers the world-space triangles of every enabled mesh renderer with CPU geometry.
34884
+ * Gathers the world-space triangles of every enabled mesh renderer and model the bake can read.
33730
34885
  *
33731
34886
  * @param world - The world.
33732
- * @returns The triangles and how many renderers had none.
34887
+ * @param signal - Stops the collection between meshes, models and glTF primitives.
34888
+ * @returns The triangles, how many components gave none, and why each part was left out.
33733
34889
  */
33734
- function collectTriangles(world) {
33735
- const vertices = [];
33736
- const albedo = [];
34890
+ function collectTriangles(world, signal) {
34891
+ const builder = new SceneBuilder();
34892
+ const skips = [];
33737
34893
  let skipped = 0;
34894
+ const gltfCache = /* @__PURE__ */ new Map();
34895
+ const skip = (entity, component, reason) => {
34896
+ skips.push({
34897
+ entity: entity.name,
34898
+ uid: entity.uid,
34899
+ component,
34900
+ reason
34901
+ });
34902
+ };
33738
34903
  for (const renderer of world.components(MeshRenderer)) {
34904
+ signal?.throwIfAborted();
33739
34905
  if (!renderer.isEnabledInHierarchy) continue;
33740
34906
  const handle = renderer.mesh;
33741
- const geometry = handle !== null && handle.state === "loaded" ? handle.value.cpuGeometry : null;
34907
+ const mesh = handle !== null && handle.state === "loaded" ? handle.value : null;
34908
+ const geometry = mesh === null ? null : mesh.cpuGeometry ?? primitiveOrNull(mesh.primitive);
33742
34909
  if (geometry === null) {
33743
34910
  skipped += 1;
34911
+ skip(renderer.entity, MeshRenderer.typeId, mesh === null ? "its mesh is not loaded" : "its mesh has no CPU triangles");
33744
34912
  continue;
33745
34913
  }
33746
- const rgb = surfaceAlbedo(renderer);
33747
- const m = renderer.entity.transform.worldMatrix;
33748
- const { positions, indices } = geometry;
33749
- for (let index = 0; index < indices.length; index += 1) {
33750
- const vertex = read(indices, index) * 3;
33751
- const x = read(positions, vertex);
33752
- const y = read(positions, vertex + 1);
33753
- const z = read(positions, vertex + 2);
33754
- vertices.push(read(m, 0) * x + read(m, 4) * y + read(m, 8) * z + read(m, 12), read(m, 1) * x + read(m, 5) * y + read(m, 9) * z + read(m, 13), read(m, 2) * x + read(m, 6) * y + read(m, 10) * z + read(m, 14));
33755
- if (index % 3 === 2) albedo.push(...rgb);
34914
+ builder.add(geometry.positions, geometry.indices, renderer.entity.transform.worldMatrix, materialAlbedo(renderer.materials[0] ?? null));
34915
+ }
34916
+ for (const model of world.components(Model)) {
34917
+ signal?.throwIfAborted();
34918
+ if (!model.isEnabledInHierarchy) continue;
34919
+ const live = traceLiveModel(model, builder, materialAlbedo, skip, signal);
34920
+ if (live !== null) {
34921
+ skipped += live;
34922
+ continue;
34923
+ }
34924
+ const gltf = readModel(model.model, gltfCache);
34925
+ if (typeof gltf === "string") {
34926
+ skipped += 1;
34927
+ skip(model.entity, Model.typeId, gltf);
34928
+ continue;
34929
+ }
34930
+ let traced = 0;
34931
+ for (const primitive of gltf.primitives) {
34932
+ signal?.throwIfAborted();
34933
+ const override = primitive.materialName === null ? void 0 : model.materialOverrides[primitive.materialName];
34934
+ const rgb = override === void 0 || override === null ? primitive.albedo : materialAlbedo(override);
34935
+ traced += builder.add(primitive.positions, primitive.indices, model.entity.transform.worldMatrix, rgb);
34936
+ }
34937
+ for (const reason of gltf.skipped) skip(model.entity, Model.typeId, reason);
34938
+ if (traced === 0) {
34939
+ skipped += 1;
34940
+ if (gltf.skipped.length === 0) skip(model.entity, Model.typeId, "the model's default scene draws no triangles");
33756
34941
  }
33757
34942
  }
33758
34943
  return {
33759
- scene: {
33760
- vertices: Float64Array.from(vertices),
33761
- albedo: Float64Array.from(albedo),
33762
- count: albedo.length / 3
33763
- },
33764
- skipped
34944
+ scene: builder.build(),
34945
+ skipped,
34946
+ skips
33765
34947
  };
33766
34948
  }
33767
34949
  /**
33768
- * A renderer's diffuse colour: its first material's base (PBR) or diffuse (Standard) colour.
34950
+ * A primitive's CPU triangles.
33769
34951
  *
33770
- * @param renderer - The renderer.
34952
+ * @param definition - The primitive, or `null`.
34953
+ * @returns The triangles, or `null`.
34954
+ */
34955
+ function primitiveOrNull(definition) {
34956
+ return definition === null ? null : primitiveTriangles(definition);
34957
+ }
34958
+ /**
34959
+ * A model's glTF triangles, read once per asset.
34960
+ *
34961
+ * @param handle - The `Model.model` field.
34962
+ * @param gltfCache - What this bake already read, by asset.
34963
+ * @returns The geometry, or why there is none.
34964
+ */
34965
+ function readModel(handle, gltfCache) {
34966
+ if (handle === null || handle.state !== "loaded") return "its model is not loaded";
34967
+ const asset = handle.value;
34968
+ const cached = gltfCache.get(asset);
34969
+ if (cached !== void 0) return cached;
34970
+ const bytes = asset.sourceBytes;
34971
+ let result;
34972
+ if (bytes === null) result = "its model has no instance to read yet (it is read once a frame has drawn it)";
34973
+ else try {
34974
+ result = readGltfTriangles(bytes);
34975
+ } catch (error) {
34976
+ result = `its glTF could not be read: ${error instanceof Error ? error.message : String(error)}`;
34977
+ }
34978
+ gltfCache.set(asset, result);
34979
+ return result;
34980
+ }
34981
+ /**
34982
+ * A material's diffuse colour: its base (PBR, times `1 − metallic`) or diffuse (Standard) colour.
34983
+ *
34984
+ * @param handle - The material, or `null`.
33771
34985
  * @returns Linear RGB; mid grey when the material says nothing usable.
33772
34986
  */
33773
- function surfaceAlbedo(renderer) {
33774
- const handle = renderer.materials[0] ?? null;
34987
+ function materialAlbedo(handle) {
33775
34988
  const definition = handle !== null && handle.state === "loaded" ? handle.value.definition : null;
33776
34989
  if (definition?.kind === "pbr") return linearRgb(definition.baseColor, true).map((channel) => channel * (1 - definition.metallic));
33777
34990
  if (definition?.kind === "standard") return linearRgb(definition.diffuse, true);
@@ -33782,15 +34995,17 @@ function surfaceAlbedo(renderer) {
33782
34995
  ];
33783
34996
  }
33784
34997
  /**
33785
- * Collects the enabled lights, in linear RGB times intensity.
34998
+ * Collects the enabled lights, in linear RGB times intensity, with what each gives the bake.
33786
34999
  *
33787
35000
  * @param world - The world.
35001
+ * @param directLight - The bake's `directLight` option.
33788
35002
  * @returns The lights.
33789
35003
  */
33790
- function collectLights(world) {
35004
+ function collectLights(world, directLight) {
33791
35005
  const out = [];
33792
35006
  for (const light of world.components(Light)) {
33793
35007
  if (!light.isEnabledInHierarchy || light.intensity <= 0) continue;
35008
+ const { direct } = lightBakeTerms(light.bakeMode, directLight);
33794
35009
  const rgb = linearRgb(light.color, true).map((channel) => channel * light.intensity);
33795
35010
  const transform = light.entity.transform;
33796
35011
  if (light.type === "directional") {
@@ -33802,7 +35017,8 @@ function collectLights(world) {
33802
35017
  -forward.y,
33803
35018
  -forward.z
33804
35019
  ],
33805
- rgb
35020
+ rgb,
35021
+ direct
33806
35022
  });
33807
35023
  } else if (light.type === "hemispheric") {
33808
35024
  const up = transform.up;
@@ -33815,7 +35031,8 @@ function collectLights(world) {
33815
35031
  up.z
33816
35032
  ],
33817
35033
  sky: rgb,
33818
- ground
35034
+ ground,
35035
+ direct
33819
35036
  });
33820
35037
  } else {
33821
35038
  const at = transform.position;
@@ -33827,14 +35044,15 @@ function collectLights(world) {
33827
35044
  at.z
33828
35045
  ],
33829
35046
  range: light.range,
33830
- rgb
35047
+ rgb,
35048
+ direct
33831
35049
  });
33832
35050
  }
33833
35051
  }
33834
35052
  return out;
33835
35053
  }
33836
35054
  /**
33837
- * The radiance a surface hit sends back: albedo times the direct light there.
35055
+ * The radiance a surface hit sends back: albedo times the direct light there, from every light.
33838
35056
  *
33839
35057
  * @param scene - The triangles.
33840
35058
  * @param lights - The lights.
@@ -33873,24 +35091,26 @@ function shadeHit(scene, lights, hit, x, y, z, out) {
33873
35091
  for (let channel = 0; channel < 3; channel += 1) out[channel] = read(out, channel) * read(scene.albedo, base + channel);
33874
35092
  }
33875
35093
  /**
33876
- * The radiance of a ray that hit nothing: the sky and the hemispheric lights.
35094
+ * The radiance of a ray that hit nothing: the sky, plus the hemispheric lights whose direct light
35095
+ * the probes store.
33877
35096
  *
33878
35097
  * @param lights - The lights.
33879
- * @param sky - The sky's linear RGB.
35098
+ * @param sky - The sky.
33880
35099
  * @param dx - The ray's X.
33881
35100
  * @param dy - The ray's Y.
33882
35101
  * @param dz - The ray's Z.
33883
35102
  * @param out - Receives linear RGB.
33884
35103
  */
33885
35104
  function missRadiance(lights, sky, dx, dy, dz, out) {
33886
- for (let channel = 0; channel < 3; channel += 1) out[channel] = read(sky, channel);
33887
- for (const light of lights) if (light.kind === "hemispheric") {
35105
+ sky(dx, dy, dz, out);
35106
+ for (const light of lights) if (light.kind === "hemispheric" && light.direct) {
33888
35107
  const above = dx * light.up[0] + dy * light.up[1] + dz * light.up[2] >= 0;
33889
35108
  for (let channel = 0; channel < 3; channel += 1) out[channel] = read(out, channel) + read(above ? light.sky : light.ground, channel);
33890
35109
  }
33891
35110
  }
33892
35111
  /**
33893
- * Adds the directional, point and spot lights a probe sees as clamped-cosine lobes.
35112
+ * Adds the directional, point and spot lights whose direct light the probes store, as
35113
+ * clamped-cosine lobes.
33894
35114
  *
33895
35115
  * @param scene - The triangles.
33896
35116
  * @param lights - The lights.
@@ -33908,7 +35128,7 @@ function addDirectLobes(scene, lights, x, y, z, sh) {
33908
35128
  triangle: -1
33909
35129
  };
33910
35130
  for (const light of lights) {
33911
- if (light.kind === "hemispheric") continue;
35131
+ if (light.kind === "hemispheric" || !light.direct) continue;
33912
35132
  const toward = towardLight(light, x, y, z);
33913
35133
  if (toward === null) continue;
33914
35134
  const [lx, ly, lz, distance, falloff] = toward;
@@ -33953,7 +35173,53 @@ function towardLight(light, x, y, z) {
33953
35173
  ];
33954
35174
  }
33955
35175
  /**
33956
- * Finds the nearest triangle a ray hits (Möller–Trumbore, both faces).
35176
+ * The distance at which a ray enters an axis-aligned box (slab test).
35177
+ *
35178
+ * @param meshes - The scene's mesh table.
35179
+ * @param base - The mesh's first float in it.
35180
+ * @param ox - The ray origin's X.
35181
+ * @param oy - The ray origin's Y.
35182
+ * @param oz - The ray origin's Z.
35183
+ * @param ix - `1 / dx`.
35184
+ * @param iy - `1 / dy`.
35185
+ * @param iz - `1 / dz`.
35186
+ * @param nearest - How far the nearest hit so far is.
35187
+ * @returns Whether the ray meets the box before `nearest`.
35188
+ */
35189
+ function meetsBox(meshes, base, ox, oy, oz, ix, iy, iz, nearest) {
35190
+ let near = 0;
35191
+ let far = nearest;
35192
+ const origin = [
35193
+ ox,
35194
+ oy,
35195
+ oz
35196
+ ];
35197
+ const inverse = [
35198
+ ix,
35199
+ iy,
35200
+ iz
35201
+ ];
35202
+ for (let axis = 0; axis < 3; axis += 1) {
35203
+ const o = read(origin, axis);
35204
+ const inv = read(inverse, axis);
35205
+ const lo = read(meshes, base + 2 + axis) - 1e-6;
35206
+ const hi = read(meshes, base + 5 + axis) + 1e-6;
35207
+ let t0 = (lo - o) * inv;
35208
+ let t1 = (hi - o) * inv;
35209
+ if (Number.isNaN(t0) || Number.isNaN(t1)) {
35210
+ if (o < lo || o > hi) return false;
35211
+ continue;
35212
+ }
35213
+ if (t0 > t1) [t0, t1] = [t1, t0];
35214
+ near = Math.max(near, t0);
35215
+ far = Math.min(far, t1);
35216
+ if (near > far) return false;
35217
+ }
35218
+ return true;
35219
+ }
35220
+ /**
35221
+ * Finds the nearest triangle a ray hits (Möller–Trumbore, both faces), testing only the meshes
35222
+ * whose world box it passes through.
33957
35223
  *
33958
35224
  * @param scene - The triangles.
33959
35225
  * @param ox - The ray origin's X.
@@ -33968,39 +35234,49 @@ function towardLight(light, x, y, z) {
33968
35234
  */
33969
35235
  function trace(scene, ox, oy, oz, dx, dy, dz, maxDistance, out) {
33970
35236
  const v = scene.vertices;
35237
+ const meshes = scene.meshes;
35238
+ const ix = 1 / dx;
35239
+ const iy = 1 / dy;
35240
+ const iz = 1 / dz;
33971
35241
  let nearest = maxDistance;
33972
35242
  let found = -1;
33973
- for (let triangle = 0; triangle < scene.count; triangle += 1) {
33974
- const b = triangle * 9;
33975
- const ax = read(v, b);
33976
- const ay = read(v, b + 1);
33977
- const az = read(v, b + 2);
33978
- const e1x = read(v, b + 3) - ax;
33979
- const e1y = read(v, b + 4) - ay;
33980
- const e1z = read(v, b + 5) - az;
33981
- const e2x = read(v, b + 6) - ax;
33982
- const e2y = read(v, b + 7) - ay;
33983
- const e2z = read(v, b + 8) - az;
33984
- const px = dy * e2z - dz * e2y;
33985
- const py = dz * e2x - dx * e2z;
33986
- const pz = dx * e2y - dy * e2x;
33987
- const det = e1x * px + e1y * py + e1z * pz;
33988
- if (Math.abs(det) < 1e-12) continue;
33989
- const inv = 1 / det;
33990
- const tx = ox - ax;
33991
- const ty = oy - ay;
33992
- const tz = oz - az;
33993
- const u = (tx * px + ty * py + tz * pz) * inv;
33994
- if (u < 0 || u > 1) continue;
33995
- const qx = ty * e1z - tz * e1y;
33996
- const qy = tz * e1x - tx * e1z;
33997
- const qz = tx * e1y - ty * e1x;
33998
- const w = (dx * qx + dy * qy + dz * qz) * inv;
33999
- if (w < 0 || u + w > 1) continue;
34000
- const distance = (e2x * qx + e2y * qy + e2z * qz) * inv;
34001
- if (distance > 1e-6 && distance < nearest) {
34002
- nearest = distance;
34003
- found = triangle;
35243
+ for (let mesh = 0; mesh < scene.meshCount; mesh += 1) {
35244
+ const base = mesh * MESH_STRIDE;
35245
+ if (!meetsBox(meshes, base, ox, oy, oz, ix, iy, iz, nearest)) continue;
35246
+ const first = read(meshes, base);
35247
+ const end = first + read(meshes, base + 1);
35248
+ for (let triangle = first; triangle < end; triangle += 1) {
35249
+ const b = triangle * 9;
35250
+ const ax = read(v, b);
35251
+ const ay = read(v, b + 1);
35252
+ const az = read(v, b + 2);
35253
+ const e1x = read(v, b + 3) - ax;
35254
+ const e1y = read(v, b + 4) - ay;
35255
+ const e1z = read(v, b + 5) - az;
35256
+ const e2x = read(v, b + 6) - ax;
35257
+ const e2y = read(v, b + 7) - ay;
35258
+ const e2z = read(v, b + 8) - az;
35259
+ const px = dy * e2z - dz * e2y;
35260
+ const py = dz * e2x - dx * e2z;
35261
+ const pz = dx * e2y - dy * e2x;
35262
+ const det = e1x * px + e1y * py + e1z * pz;
35263
+ if (Math.abs(det) < 1e-12) continue;
35264
+ const inv = 1 / det;
35265
+ const tx = ox - ax;
35266
+ const ty = oy - ay;
35267
+ const tz = oz - az;
35268
+ const u = (tx * px + ty * py + tz * pz) * inv;
35269
+ if (u < 0 || u > 1) continue;
35270
+ const qx = ty * e1z - tz * e1y;
35271
+ const qy = tz * e1x - tx * e1z;
35272
+ const qz = tx * e1y - ty * e1x;
35273
+ const w = (dx * qx + dy * qy + dz * qz) * inv;
35274
+ if (w < 0 || u + w > 1) continue;
35275
+ const distance = (e2x * qx + e2y * qy + e2z * qz) * inv;
35276
+ if (distance > 1e-6 && distance < nearest) {
35277
+ nearest = distance;
35278
+ found = triangle;
35279
+ }
34004
35280
  }
34005
35281
  }
34006
35282
  if (found < 0) return false;
@@ -34568,7 +35844,7 @@ function describeLightmapFileFormat() {
34568
35844
  entries: {
34569
35845
  kind: "map",
34570
35846
  default: {},
34571
- description: "Per entity uid, { scale: { x, y }, offset: { x, y } }: the entity's UV2 square in the texture (sampled at uv2 · scale + offset; scale above 0). Missing halves and missing entities take scale 1, offset 0. Only the identity is drawn until the atlas transform lands."
35847
+ description: "Per entity uid, { scale: { x, y }, offset: { x, y } }: the entity's UV2 square in the texture (sampled at uv2 · scale + offset; scale above 0). Missing halves and missing entities take scale 1, offset 0. A placement other than the identity needs the renderer's lightmap.uv2 on and a mesh with uvs2; each distinct placement is its own pipeline variant."
34572
35848
  }
34573
35849
  }
34574
35850
  };
@@ -35045,11 +36321,14 @@ function writeInstance(root, origin, references, report) {
35045
36321
  * Diffs every direct member of an instance against the record the instanced file holds for it.
35046
36322
  *
35047
36323
  * @remarks
35048
- * Only entities the instanced file itself declares are diffed. Content that came from a scene the
35049
- * instanced scene itself instanced is not diffed: an override can address a nested prefab's
35050
- * component by instance path, but the diff would need the nested file with the outer prefab's own
35051
- * overrides applied, so deep edits inside a nested prefab are not written back; `flatten: true` is
35052
- * the escape hatch.
36324
+ * Entities the instanced file itself declares are diffed field by field. Components that came
36325
+ * from a scene the instanced scene itself instanced are diffed against the records the expansion
36326
+ * kept for them (`EntityInstanceLink.nestedBaseline`: the nested file with the outer prefab's own
36327
+ * overrides applied), and a changed prop or `enabled` flag, or a removed component, is written as
36328
+ * an override whose component segment is an instance path; so are the components a scene the
36329
+ * instanced single root itself instances merged into the instance root. Nested entities' own
36330
+ * fields are not written back; a component added to a nested entity and a nested entity destroyed
36331
+ * at run time cannot be, and are reported (`IGX-0609`). `flatten: true` is the escape hatch.
35053
36332
  *
35054
36333
  * An instance root that stands for its scene's single root is diffed against that root's record
35055
36334
  * too, but only for the components the scene put on it: its name, transform, and other entity
@@ -35086,9 +36365,167 @@ function computeOverrides(root, link, references, report) {
35086
36365
  }
35087
36366
  diffEntity(entity, record, overrides, references, report, localize);
35088
36367
  }
36368
+ const baseline = link.nestedBaseline;
36369
+ if (baseline !== null) {
36370
+ const nested = {
36371
+ root,
36372
+ baseline,
36373
+ overrides,
36374
+ references,
36375
+ report,
36376
+ covered: /* @__PURE__ */ new Set()
36377
+ };
36378
+ if (single !== null && link.nestedRootSourceUids !== null) diffNestedComponents(root, single.sourceUid, link.nestedRootSourceUids, nested);
36379
+ markLive(root, nested);
36380
+ diffNestedMembers(root, nested);
36381
+ reportLostNestedComponents(root, nested);
36382
+ }
35089
36383
  return overrides;
35090
36384
  }
35091
36385
  /**
36386
+ * Reports the nested-prefab components no live entity of the instance accounts for: their entity
36387
+ * was destroyed at run time (or sits where an override cannot address it), and an override cannot
36388
+ * say so, so the saved file brings them back.
36389
+ *
36390
+ * @param root - The instance root.
36391
+ * @param nested - The diff state.
36392
+ */
36393
+ function reportLostNestedComponents(root, nested) {
36394
+ let lost = 0;
36395
+ for (const uid of nested.baseline.keys()) if (!nested.covered.has(uid)) lost += 1;
36396
+ if (lost > 0) nested.report(CoreErrorCode.invalidOverridePath, `${String(lost)} component(s) of a prefab nested in the instance ${JSON.stringify(root.name)} belong to an entity destroyed at run time; an override cannot remove a nested entity, so the saved file keeps it. Destroy it in the nested prefab, or save with flatten: true.`);
36397
+ }
36398
+ /**
36399
+ * Diffs the components an instance's nested prefabs produced against their baseline records, below
36400
+ * one entity of the instance, and reports the components added at run time to an entity a nested
36401
+ * prefab declares, which an override cannot add.
36402
+ *
36403
+ * @param entity - Where to walk from.
36404
+ * @param nested - The diff state.
36405
+ */
36406
+ function diffNestedMembers(entity, nested) {
36407
+ const root = nested.root;
36408
+ const children = entity.children;
36409
+ for (let index = 0; index < children.length; index += 1) {
36410
+ const child = children[index];
36411
+ if (child === void 0 || child.isDestroyed || !belongsToInstance(child, root)) continue;
36412
+ markLive(child, nested);
36413
+ const origin = entityInternals(child).origin;
36414
+ const inside = origin?.instanceRoot ?? null;
36415
+ if (origin !== null && inside !== null && inside !== root) {
36416
+ const prefix = nestedPathOf(inside, root);
36417
+ if (prefix !== null) diffNestedComponents(child, prefix, origin.componentSourceUids, nested);
36418
+ reportAddedToNested(child, origin, nested);
36419
+ }
36420
+ const link = origin?.instanced ?? null;
36421
+ const merged = link?.root ?? null;
36422
+ if (link !== null && merged !== null) {
36423
+ const prefix = nestedPathOf(child, root);
36424
+ if (prefix !== null) {
36425
+ diffNestedComponents(child, prefix, merged.componentSourceUids, nested);
36426
+ if (link.nestedRootSourceUids !== null) diffNestedComponents(child, prefix, link.nestedRootSourceUids, nested);
36427
+ }
36428
+ }
36429
+ diffNestedMembers(child, nested);
36430
+ }
36431
+ }
36432
+ /**
36433
+ * Counts an entity's live components that have a baseline record as accounted for, so only the
36434
+ * components of a destroyed entity are reported lost.
36435
+ *
36436
+ * @param entity - The entity.
36437
+ * @param nested - The diff state.
36438
+ */
36439
+ function markLive(entity, nested) {
36440
+ const components = entity.components;
36441
+ for (let index = 0; index < components.length; index += 1) {
36442
+ const component = components[index];
36443
+ if (component !== void 0 && !component.isDestroyed && nested.baseline.has(component.uid)) nested.covered.add(component.uid);
36444
+ }
36445
+ }
36446
+ /**
36447
+ * Reports the components added at run time to an entity a nested prefab declares: an override
36448
+ * reaches a nested entity's components only by instance path, which an added component has none
36449
+ * of, so the saved file drops it.
36450
+ *
36451
+ * @param entity - The nested entity.
36452
+ * @param origin - Its origin.
36453
+ * @param nested - The diff state.
36454
+ */
36455
+ function reportAddedToNested(entity, origin, nested) {
36456
+ const fromFiles = origin.instanced?.root?.components;
36457
+ const components = entity.components;
36458
+ for (let index = 0; index < components.length; index += 1) {
36459
+ const component = components[index];
36460
+ if (component === void 0 || component === entity.transform || component.isDestroyed || origin.componentSourceUids.has(component.uid) || fromFiles?.has(component.uid) === true || nested.baseline.has(component.uid)) continue;
36461
+ const typeId = component.world.registry.describe(component.constructor).typeId ?? component.constructor.name;
36462
+ nested.report(CoreErrorCode.invalidOverridePath, `${typeId} was added at run time to ${JSON.stringify(entity.name)}, which a prefab nested in the instance ${JSON.stringify(nested.root.name)} declares; an override cannot add a component there, so it is not saved. Add it in the nested prefab, or save with flatten: true.`);
36463
+ }
36464
+ }
36465
+ /**
36466
+ * The instance path, from an outer instance, of a nested instance root inside it: the uids each
36467
+ * enclosing file gives the entities carrying the nested `instance` entries.
36468
+ *
36469
+ * @param entity - The nested instance root.
36470
+ * @param root - The outer instance root.
36471
+ * @returns `"<uidInTheOuterFile>/…/<uid>"`, or `null` when the entity is not inside `root`.
36472
+ */
36473
+ function nestedPathOf(entity, root) {
36474
+ const segments = [];
36475
+ let current = entity;
36476
+ const limit = 64;
36477
+ while (current !== null && segments.length < limit) {
36478
+ const origin = entityInternals(current).origin;
36479
+ if (origin === null) return null;
36480
+ segments.push(origin.sourceUid);
36481
+ if (origin.instanceRoot === root) return segments.toReversed().join("/");
36482
+ current = origin.instanceRoot;
36483
+ }
36484
+ return null;
36485
+ }
36486
+ /**
36487
+ * Diffs one entity's nested-prefab components against their baseline records.
36488
+ *
36489
+ * @param entity - The entity; a baseline component it no longer has is written as a `remove`.
36490
+ * @param prefix - The instance path of the nested instance the components' uids are local to.
36491
+ * @param sourceUids - Runtime component uid to the uid that nested file gives it.
36492
+ * @param nested - The diff state.
36493
+ */
36494
+ function diffNestedComponents(entity, prefix, sourceUids, nested) {
36495
+ const { baseline, overrides, references, report } = nested;
36496
+ const head = prefix.split("/")[0] ?? prefix;
36497
+ for (const [uid, sourceUid] of sourceUids) {
36498
+ const before = baseline.get(uid);
36499
+ if (before === void 0) continue;
36500
+ nested.covered.add(uid);
36501
+ const component = entity.components.find((candidate) => candidate.uid === uid && !candidate.isDestroyed);
36502
+ if (component === void 0) {
36503
+ overrides.push({
36504
+ op: "remove",
36505
+ path: `${head}/components/${prefix}/${sourceUid}`
36506
+ });
36507
+ continue;
36508
+ }
36509
+ const registry = component.world.registry;
36510
+ if (registry.describe(component.constructor).typeId === null) continue;
36511
+ const comparable = serializeComponent(component, ownUidEncoder());
36512
+ const written = serializeComponent(component, references, (issue) => {
36513
+ report(issue.code, issue.message);
36514
+ });
36515
+ const schema = registry.describe(component.constructor).schema;
36516
+ diffProps(head, `${prefix}/${sourceUid}`, before, comparable, schema, overrides, identity, written);
36517
+ }
36518
+ }
36519
+ /**
36520
+ * Returns its argument, for a diff whose two sides already share one uid space.
36521
+ *
36522
+ * @param value - The JSON.
36523
+ * @returns `value`.
36524
+ */
36525
+ function identity(value) {
36526
+ return value;
36527
+ }
36528
+ /**
35092
36529
  * Collects the entities of an instance that the instanced file itself declared, keyed by the uid it
35093
36530
  * gave them.
35094
36531
  *
@@ -35266,21 +36703,24 @@ function diffComponents(entity, record, diff, overrides, references, report) {
35266
36703
  * @param schema - The component's declared fields, so an omitted prop compares against its default.
35267
36704
  * @param overrides - Where patches are appended.
35268
36705
  * @param localize - Rewrites `after`'s references into the instanced file's uids for the comparison.
36706
+ * @param emitted - What the overrides' values are taken from, when it is not `after` (the same
36707
+ * component written with other references).
35269
36708
  */
35270
- function diffProps(entityUid, componentUid, before, after, schema, overrides, localize) {
36709
+ function diffProps(entityUid, componentUid, before, after, schema, overrides, localize, emitted = after) {
35271
36710
  if ((before.enabled ?? true) !== (after.enabled ?? true)) overrides.push({
35272
36711
  path: `${entityUid}/components/${componentUid}/enabled`,
35273
36712
  value: after.enabled ?? true
35274
36713
  });
35275
36714
  const beforeProps = before.props ?? {};
35276
36715
  const afterProps = after.props ?? {};
36716
+ const emittedProps = emitted.props ?? {};
35277
36717
  const references = ownUidEncoder();
35278
36718
  for (const name of Object.keys(afterProps)) {
35279
36719
  const next = afterProps[name] ?? null;
35280
36720
  const field = schema?.[name];
35281
36721
  if (!sameJson(beforeProps[name] ?? (field === void 0 ? null : encodeValue(field, field.createDefault(), references)), localize(next))) overrides.push({
35282
36722
  path: `${entityUid}/components/${componentUid}/props/${name}`,
35283
- value: next
36723
+ value: emittedProps[name] ?? next
35284
36724
  });
35285
36725
  }
35286
36726
  }
@@ -35442,7 +36882,9 @@ function componentPackage(registry, typeId) {
35442
36882
  * Describes every component an app has registered, the engine's, its extensions' and the game's,
35443
36883
  * the way {@link describeSchema} describes one, plus what only the registry knows: whether an
35444
36884
  * entity may hold more than one (`allowMultiple`), which package registered it (`package`), and
35445
- * which components it adds when they are missing (`requires`, its classes' type ids).
36885
+ * which components it adds when they are missing (`requires`, its classes' type ids; `null` for a
36886
+ * class that declares no `typeId` of its own, such as an unregistered subclass that only inherits
36887
+ * its parent's, because naming the parent would describe a different component).
35446
36888
  * This is what an external inspector, such as the ignifx editor, is generated from.
35447
36889
  *
35448
36890
  * @remarks
@@ -35490,7 +36932,7 @@ function describeRegisteredSchemas(registry, curated) {
35490
36932
  allowMultiple: info.allowMultiple,
35491
36933
  package: componentPackage(registry, typeId),
35492
36934
  ...builtIn ? { builtIn } : {},
35493
- ...info.requires.length === 0 ? {} : { requires: info.requires.map((required) => required.typeId ?? null) }
36935
+ ...info.requires.length === 0 ? {} : { requires: info.requires.map((required) => Object.hasOwn(required, "typeId") ? required.typeId ?? null : null) }
35494
36936
  });
35495
36937
  }
35496
36938
  return described;
@@ -36038,6 +37480,6 @@ function settingsJsonSchema(app) {
36038
37480
  };
36039
37481
  }
36040
37482
  //#endregion
36041
- export { AMBIENT_OCCLUSION_QUALITIES, ASSET_DIAGNOSTICS_COUNTERS, ASSET_DIAGNOSTICS_GROUP, ASSET_MANIFEST_FORMAT, ASSET_MANIFEST_VERSION, AssetLoadError, CANVAS_ALPHA_MODES, CORE_ERROR_MESSAGES, Camera, Color, Component, ComponentRegistry, CoreErrorCode, DEFAULT_ASSET_CONCURRENCY, DEFAULT_ASSET_ROOT, DEFAULT_BRDF_LUT_ADDRESS, DEFAULT_LAYER, DEFAULT_MEMORY_SINK_LIMIT, DEFAULT_STORAGE_NAMESPACE, DEG_TO_RAD, Diagnostics, EASINGS, EASING_NAMES, EDITOR_ONLY_METADATA_KEY, EMPTY_ASSET_MANIFEST, ENVIRONMENT_ASSET_TYPE, ENVIRONMENT_FILE_EXTENSION, ENVIRONMENT_FILE_EXTENSIONS, ENVIRONMENT_FILE_FORMAT, ENVIRONMENT_FORMAT_VERSION, EPSILON, Entity, Environment, EnvironmentAsset, ErrorRange, FOG_MODE_NAMES, FONT_ASSET_TYPE, FONT_FILE_EXTENSIONS, FRAME_HISTORY_LENGTH, FieldKind, FontAsset, IDENTITY_LIGHTMAP_PLACEMENT, IGNIFX_UNIFORM_NAMES, INVALID_HANDLE, IgnifxError, IndexedDbStorageBackend, InstancedMeshRenderer, LIGHTMAP_ASSET_TYPE, LIGHTMAP_FILE_EXTENSIONS, LIGHTMAP_FILE_FORMAT, LIGHTMAP_FORMAT_VERSION, LIGHTMAP_MODES, LIGHT_PROBE_ASSET_TYPE, LIGHT_PROBE_FILE_EXTENSIONS, LIGHT_PROBE_FILE_FORMAT, LIGHT_PROBE_FORMAT_VERSION, LIGHT_TYPES, LITE_MATERIAL_PLUGIN_POINTS, LITE_SYSTEM_UNIFORM_NAMES, LOG_LEVEL_SEVERITY, LayerMask, LayerTable, Light, LightProbeAsset, LightProbeVolume, LightmapAsset, LogLevel, MAT4_IDENTITY, MATERIAL_ALPHA_MODES, MATERIAL_ASSET_TYPE, MATERIAL_FILE_EXTENSION, MATERIAL_FILE_FORMAT, MATERIAL_FORMAT_VERSION, MATERIAL_KINDS, MATERIAL_PLUGIN_DEFAULT_PRIORITY, MATERIAL_PLUGIN_RESERVED_NAMES, MATERIAL_PLUGIN_SAMPLER_BUDGET, MAX_LAYERS, MAX_ULID_TIME_MS, MESH_ASSET_TYPE, MESH_FILE_EXTENSION, MESH_FILE_FORMAT, MESH_FORMAT_VERSION, MESH_PRIMITIVES, MESH_PRIMITIVE_OPTIONS, MODEL_ASSET_TYPE, MODEL_FILE_EXTENSIONS, Mat4, MaterialAsset, MemoryStorageBackend, MeshAsset, MeshRenderer, Model, ModelAsset, NAMESPACE_SEGMENT_MAX_LENGTH, PBR_TEXTURE_SLOTS, PHASES, PHASE_COUNT, PHASE_NAMES, POST_EFFECT_BUILTIN_UNIFORMS, POST_EFFECT_FUNCTION, PROJECTIONS, Phase, PhysicsCallbackName, PostProcessStack, QUAT_IDENTITY, Quat, RAD_TO_DEG, REFLECTION_PROBE_REFRESH_MODES, RENDERING_QUALITIES, RENDERING_SETTINGS_SECTION, RENDER_DIAGNOSTICS_COUNTERS, RENDER_DIAGNOSTICS_GROUP, RENDER_TEXTURE_MAX_SIZE, RESERVED_LAYER_NAMES, ReflectionProbe, SCENE_ASSET_TYPE, SCENE_FILE_EXTENSIONS, SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION, SETTINGS_DESCRIPTION_FORMAT, SHADER_ASSET_TYPE, SHADER_ATTRIBUTE_NAMES, SHADER_BLEND_MODES, SHADER_CULL_MODES, SHADER_FILE_EXTENSIONS, SHADER_INSTANCING_MODES, SHADER_KINDS, SHADER_TEXTURE_FALLBACKS, SHADER_UNIFORM_TYPES, SHADOW_TECHNIQUES, STANDARD_TEXTURE_SLOTS, STORAGE_BUFFER_ASSET_TYPE, STORAGE_KEY_MAX_LENGTH, SURFACE_HOOK_NAMES, SURFACE_UNIFORM_BLOCK, SceneAssetToken, SceneInstance, SchemaIssueCode, Script, ScriptCallbackKind, ShaderAsset, Signal, StorageBufferAsset, TEXTURE_ASSET_TYPE, THIRD_PARTY_ERROR_PREFIX, TONE_MAPPING_NAMES, TWEEN_LOOP_FOREVER, TWEEN_SYSTEM_ORDER, TWEEN_VALUE_KINDS, TagSet, TextureAsset, Transform, Tween, UidRemap, VEC2_ONE, VEC2_ZERO, VEC3_BACKWARD, VEC3_DOWN, VEC3_FORWARD, VEC3_LEFT, VEC3_ONE, VEC3_RIGHT, VEC3_UP, VEC3_ZERO, VERSION, Vec2, Vec3, Vec4, World, addComponentFromRecord, applyInit, applyOverridesToAsset, approximately, array, assertNever, assertSceneDependenciesLoaded, asset, assetRef, bakeLightProbes, binaryAssetLoader, bool, canonicalizeNumber, clamp, clamp01, color, componentRef, computeSceneHash, coreExtension, createApp, createAssetManifest, createConsoleSink, createCryptoRandom, createDefaults, createDiagnosticsGroup, createEnvironmentLoader, createErrorCodeRegistry, createFileStorageBackend, createFontLoader, createFrameSample, createLayerTable, createLightProbeAsset, createLightProbeLoader, createLightmapAsset, createLightmapLoader, createLogger, createManualClock, createMaterialAsset, createMaterialLoader, createMemorySink, createMeshLoader, createModelLoader, createPerformanceClock, createRay, createSceneAsset, createSceneLoader, createSeededRandom, createServiceKey, createShaderLoader, createStorageBufferAsset, createTextureLoader, createUlidFactory, curve, custom, customEffect, decodeProps, decodeValue, defaultAutoExposureSettings, defaultRenderingSettings, defineExtension, defineMaterialPlugin, defineSchema, degToRad, deltaAngleDegrees, describeEnvironmentFileFormat, describeLightProbeFileFormat, describeLightmapFileFormat, describeMaterialFileFormat, describeMeshFileFormat, describeRegisteredSchemas, describeSceneFileFormat, describeSchema, describeSchemas, describeSettings, encodeProps, encodeValue, entityRef, enumOf, enumerateInstanceTargets, environmentDefinition, f32, f64, forceRendererDeviceLossForTesting, formatErrorMessage, generateUlid, i32, instanceComponentAt, instanceEntityAt, instantiateScene, inverseLerp, isAssetRef, isIgnifxError, isLiteMaterialPluginPoint, isSceneFileHeader, isUlid, isValidErrorCode, isWebGpuAvailable, jsonAssetLoader, layerMask, lerp, lerpAngleDegrees, loadSceneDependencies, map, meshFileJsonSchema, moveTowards, optional, parseOverridePath, pbrMaterialDefinition, pingPong, platformInternals, quat, radToDeg, record, repeat, resetFrameSample, resolveEase, resolveInstancePath, revertOverrides, sampleLightProbes, sceneFileJsonSchema, serializeComponent, serializeEntity, serializeScene, settingsJsonSchema, shaderMaterialDefinition, sign, smoothStep, standardMaterialDefinition, storageInternals, str, stringifySceneFile, textAssetLoader, toJsonSchema, transformSchema, u32, validateProps, validateSceneFile, validateValue, vec2, vec3, vec4, waitFixedUpdate, waitSeconds, waitSecondsRealtime, waitUntil, waitWhile, wrapAngleDegrees, writeLightProbeFile, writeLightmapFile };
37483
+ export { AMBIENT_OCCLUSION_QUALITIES, ASSET_DIAGNOSTICS_COUNTERS, ASSET_DIAGNOSTICS_GROUP, ASSET_MANIFEST_FORMAT, ASSET_MANIFEST_VERSION, AssetLoadError, CANVAS_ALPHA_MODES, CORE_ERROR_MESSAGES, Camera, Color, Component, ComponentRegistry, CoreErrorCode, DEFAULT_ASSET_CONCURRENCY, DEFAULT_ASSET_ROOT, DEFAULT_BRDF_LUT_ADDRESS, DEFAULT_LAYER, DEFAULT_MEMORY_SINK_LIMIT, DEFAULT_STORAGE_NAMESPACE, DEG_TO_RAD, Diagnostics, EASINGS, EASING_NAMES, EDITOR_ONLY_METADATA_KEY, EMPTY_ASSET_MANIFEST, ENVIRONMENT_ASSET_TYPE, ENVIRONMENT_FILE_EXTENSION, ENVIRONMENT_FILE_EXTENSIONS, ENVIRONMENT_FILE_FORMAT, ENVIRONMENT_FORMAT_VERSION, EPSILON, Entity, Environment, EnvironmentAsset, ErrorRange, FOG_MODE_NAMES, FONT_ASSET_TYPE, FONT_FILE_EXTENSIONS, FRAME_HISTORY_LENGTH, FieldKind, FontAsset, IDENTITY_LIGHTMAP_PLACEMENT, IGNIFX_UNIFORM_NAMES, INVALID_HANDLE, IgnifxError, IndexedDbStorageBackend, InstancedMeshRenderer, LIGHTMAP_ASSET_TYPE, LIGHTMAP_FILE_EXTENSIONS, LIGHTMAP_FILE_FORMAT, LIGHTMAP_FORMAT_VERSION, LIGHTMAP_MODES, LIGHT_BAKE_MODES, LIGHT_PROBE_ASSET_TYPE, LIGHT_PROBE_FILE_EXTENSIONS, LIGHT_PROBE_FILE_FORMAT, LIGHT_PROBE_FORMAT_VERSION, LIGHT_TYPES, LITE_MATERIAL_PLUGIN_POINTS, LITE_SYSTEM_UNIFORM_NAMES, LOG_LEVEL_SEVERITY, LayerMask, LayerTable, Light, LightProbeAsset, LightProbeVolume, LightmapAsset, LogLevel, MAT4_IDENTITY, MATERIAL_ALPHA_MODES, MATERIAL_ASSET_TYPE, MATERIAL_FILE_EXTENSION, MATERIAL_FILE_FORMAT, MATERIAL_FORMAT_VERSION, MATERIAL_KINDS, MATERIAL_PLUGIN_DEFAULT_PRIORITY, MATERIAL_PLUGIN_RESERVED_NAMES, MATERIAL_PLUGIN_SAMPLER_BUDGET, MAX_LAYERS, MAX_ULID_TIME_MS, MESH_ASSET_TYPE, MESH_FILE_EXTENSION, MESH_FILE_FORMAT, MESH_FORMAT_VERSION, MESH_PRIMITIVES, MESH_PRIMITIVE_OPTIONS, MODEL_ASSET_TYPE, MODEL_FILE_EXTENSIONS, Mat4, MaterialAsset, MemoryStorageBackend, MeshAsset, MeshRenderer, Model, ModelAsset, NAMESPACE_SEGMENT_MAX_LENGTH, PBR_TEXTURE_SLOTS, PHASES, PHASE_COUNT, PHASE_NAMES, POST_EFFECT_BUILTIN_UNIFORMS, POST_EFFECT_FUNCTION, PROJECTIONS, Phase, PhysicsCallbackName, PostProcessStack, QUAT_IDENTITY, Quat, RAD_TO_DEG, REFLECTION_PROBE_REFRESH_MODES, RENDERING_QUALITIES, RENDERING_SETTINGS_SECTION, RENDER_DIAGNOSTICS_COUNTERS, RENDER_DIAGNOSTICS_GROUP, RENDER_TEXTURE_MAX_SIZE, RESERVED_LAYER_NAMES, ReflectionProbe, SCENE_ASSET_TYPE, SCENE_FILE_EXTENSIONS, SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION, SETTINGS_DESCRIPTION_FORMAT, SHADER_ASSET_TYPE, SHADER_ATTRIBUTE_NAMES, SHADER_BLEND_MODES, SHADER_CULL_MODES, SHADER_FILE_EXTENSIONS, SHADER_INSTANCING_MODES, SHADER_KINDS, SHADER_TEXTURE_FALLBACKS, SHADER_UNIFORM_TYPES, SHADOW_TECHNIQUES, STANDARD_TEXTURE_SLOTS, STORAGE_BUFFER_ASSET_TYPE, STORAGE_KEY_MAX_LENGTH, SURFACE_HOOK_NAMES, SURFACE_UNIFORM_BLOCK, SceneAssetToken, SceneInstance, SchemaIssueCode, Script, ScriptCallbackKind, ShaderAsset, Signal, StorageBufferAsset, TEXTURE_ASSET_TYPE, THIRD_PARTY_ERROR_PREFIX, TONE_MAPPING_NAMES, TWEEN_LOOP_FOREVER, TWEEN_SYSTEM_ORDER, TWEEN_VALUE_KINDS, TagSet, TextureAsset, Transform, Tween, UidRemap, VEC2_ONE, VEC2_ZERO, VEC3_BACKWARD, VEC3_DOWN, VEC3_FORWARD, VEC3_LEFT, VEC3_ONE, VEC3_RIGHT, VEC3_UP, VEC3_ZERO, VERSION, Vec2, Vec3, Vec4, World, addComponentFromRecord, applyInit, applyOverridesToAsset, approximately, array, assertNever, assertSceneDependenciesLoaded, asset, assetRef, bakeLightProbes, binaryAssetLoader, bool, canonicalizeNumber, clamp, clamp01, color, componentRef, computeSceneHash, coreExtension, createApp, createAssetManifest, createConsoleSink, createCryptoRandom, createDefaults, createDiagnosticsGroup, createEnvironmentLoader, createErrorCodeRegistry, createFileStorageBackend, createFontLoader, createFrameSample, createLayerTable, createLightProbeAsset, createLightProbeLoader, createLightmapAsset, createLightmapLoader, createLogger, createManualClock, createMaterialAsset, createMaterialLoader, createMemorySink, createMeshLoader, createModelLoader, createPerformanceClock, createRay, createSceneAsset, createSceneLoader, createSeededRandom, createServiceKey, createShaderLoader, createStorageBufferAsset, createTextureLoader, createUlidFactory, curve, custom, customEffect, decodeProps, decodeValue, defaultAutoExposureSettings, defaultRenderingSettings, defineExtension, defineMaterialPlugin, defineSchema, degToRad, deltaAngleDegrees, describeEnvironmentFileFormat, describeLightProbeFileFormat, describeLightmapFileFormat, describeMaterialFileFormat, describeMeshFileFormat, describeRegisteredSchemas, describeSceneFileFormat, describeSchema, describeSchemas, describeSettings, encodeProps, encodeValue, entityRef, enumOf, enumerateInstanceTargets, environmentDefinition, f32, f64, forceRendererDeviceLossForTesting, formatErrorMessage, generateUlid, i32, instanceComponentAt, instanceEntityAt, instantiateScene, inverseLerp, isAssetRef, isIgnifxError, isLiteMaterialPluginPoint, isSceneFileHeader, isUlid, isValidErrorCode, isWebGpuAvailable, jsonAssetLoader, layerMask, lerp, lerpAngleDegrees, lightBakeTerms, loadSceneDependencies, map, meshFileJsonSchema, moveTowards, optional, parseOverridePath, pbrMaterialDefinition, pingPong, platformInternals, quat, radToDeg, record, repeat, resetFrameSample, resolveEase, resolveInstancePath, revertOverrides, sampleLightProbes, sceneFileJsonSchema, serializeComponent, serializeEntity, serializeScene, settingsJsonSchema, shaderMaterialDefinition, sign, smoothStep, standardMaterialDefinition, storageInternals, str, stringifySceneFile, textAssetLoader, toJsonSchema, transformSchema, u32, validateProps, validateSceneFile, validateValue, vec2, vec3, vec4, waitFixedUpdate, waitSeconds, waitSecondsRealtime, waitUntil, waitWhile, wrapAngleDegrees, writeLightProbeFile, writeLightmapFile };
36042
37484
 
36043
37485
  //# sourceMappingURL=index.js.map