@ignifx/editor-host 0.10.0 → 0.12.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as isEditorOrigin, t as EditorHostErrorCode } from "./error-codes.js";
2
- import { Camera, IgnifxError, Phase, SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION, Script, Transform, VERSION, addComponentFromRecord, canonicalizeNumber, clamp, createApp, createFrameSample, createRay, createSceneAsset, decodeProps, decodeValue, degToRad, describeRegisteredSchemas, describeSchemas, describeSettings, encodeProps, encodeValue, instantiateScene, isIgnifxError, loadSceneDependencies, parseOverridePath, serializeScene, settingsJsonSchema, toJsonSchema, transformSchema, validateSceneFile } from "@ignifx/core";
2
+ import { Camera, Component, CoreErrorCode, IgnifxError, Phase, SCENE_ASSET_TYPE, SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION, Script, Transform, VERSION, addComponentFromRecord, canonicalizeNumber, clamp, createApp, createFrameSample, createRay, createSceneAsset, decodeProps, decodeValue, degToRad, describeRegisteredSchemas, describeSchemas, describeSettings, encodeProps, encodeValue, instantiateScene, isIgnifxError, loadSceneDependencies, parseOverridePath, serializeScene, settingsJsonSchema, toJsonSchema, transformSchema, validateSceneFile } from "@ignifx/core";
3
3
  import { addToScene, attachPositionGizmoToNode, attachRotationGizmoToNode, attachScaleGizmoToNode, createLines, createPositionGizmo, createRotationGizmo, createScaleGizmo, isGizmoDragging, isGizmoInteracting, isGizmoPickPending, onBeforeRender, setPositionGizmoLocalCoordinates, setRotationGizmoLocalCoordinates, setScaleGizmoLocalCoordinates } from "@babylonjs/lite";
4
4
  //#region src/protocol/rpc.ts
5
5
  /**
@@ -213,6 +213,59 @@ const HostCapability = {
213
213
  hotReloadDefaults: "hotReloadDefaults"
214
214
  };
215
215
  /**
216
+ * The longest string, in UTF-16 code units, the editor accepts from a host in `ready` (the engine
217
+ * version, each capability name) and in the reports `log`, `hostError` (with `AppErrorData`) and
218
+ * `hotReloaded` (messages, codes, scopes, stacks, type ids). A message holding a longer one fails
219
+ * its guard and is dropped whole. It is far above what the Console keeps (which clips a message or
220
+ * a stack it shows), so it only stops a runaway report from crossing the editor's processes. The
221
+ * host does not clip to it.
222
+ *
223
+ * @public
224
+ */
225
+ const HOST_TEXT_MAX_LENGTH = 1048576;
226
+ /**
227
+ * The longest list the editor accepts from a host in `ready` (the capabilities) and in a
228
+ * `hotReloaded` report (the type ids, the errors). A message holding a longer one fails its guard
229
+ * and is dropped whole.
230
+ *
231
+ * @public
232
+ */
233
+ const HOST_LIST_MAX_LENGTH = 4096;
234
+ /**
235
+ * Tells whether a value is a string no longer than {@link HOST_TEXT_MAX_LENGTH}.
236
+ *
237
+ * @param value - The value to test.
238
+ * @returns True for such a string.
239
+ *
240
+ * @internal
241
+ */
242
+ function isHostText(value) {
243
+ return typeof value === "string" && value.length <= 1048576;
244
+ }
245
+ /**
246
+ * Tells whether a value is `null` or a string no longer than {@link HOST_TEXT_MAX_LENGTH}.
247
+ *
248
+ * @param value - The value to test.
249
+ * @returns True for `null` or such a string.
250
+ *
251
+ * @internal
252
+ */
253
+ function isHostTextOrNull(value) {
254
+ return value === null || isHostText(value);
255
+ }
256
+ /**
257
+ * Tells whether a value is a list of at most {@link HOST_LIST_MAX_LENGTH} passing items.
258
+ *
259
+ * @param value - The value to test.
260
+ * @param item - The test for one item.
261
+ * @returns True for such a list.
262
+ *
263
+ * @internal
264
+ */
265
+ function isHostList(value, item) {
266
+ return Array.isArray(value) && value.length <= 4096 && value.every((entry) => item(entry));
267
+ }
268
+ /**
216
269
  * Tells whether a value is a protocol version: two non-negative integers.
217
270
  *
218
271
  * @param value - The value to test.
@@ -230,14 +283,15 @@ function isProtocolVersion(value) {
230
283
  *
231
284
  * @param value - The received `result`.
232
285
  * @returns True when it has a string `engineVersion`, a protocol version, an array of capability
233
- * strings, and a known `hostKind`.
286
+ * strings, and a known `hostKind`; the strings and the list within {@link HOST_TEXT_MAX_LENGTH}
287
+ * and {@link HOST_LIST_MAX_LENGTH}.
234
288
  *
235
289
  * @public
236
290
  */
237
291
  function isReadyResult(value) {
238
292
  if (!isRecord(value)) return false;
239
293
  const { capabilities, hostKind } = value;
240
- return typeof value["engineVersion"] === "string" && isProtocolVersion(value["protocol"]) && Array.isArray(capabilities) && capabilities.every((name) => typeof name === "string") && Object.values(HostKind).some((kind) => kind === hostKind);
294
+ return isHostText(value["engineVersion"]) && isProtocolVersion(value["protocol"]) && isHostList(capabilities, isHostText) && Object.values(HostKind).some((kind) => kind === hostKind);
241
295
  }
242
296
  /**
243
297
  * Checks the `data` of an `incompatibleProtocol` answer to `hello`.
@@ -826,7 +880,25 @@ const SceneMethod = {
826
880
  */
827
881
  describeSettings: "describeSettings",
828
882
  /** Switches the view between the 3D and the 2D editor camera. Answers `null`. */
829
- setViewMode: "setViewMode"
883
+ setViewMode: "setViewMode",
884
+ /**
885
+ * Turns the editor's "animate materials" toggle on or off: whether the shader clock runs in the
886
+ * scene view. Answers `null`. The host starts with it on, after every load. A host from before it
887
+ * answers `RpcErrorCode.methodNotFound`. Additive in 0.3.
888
+ */
889
+ setAnimateMaterials: "setAnimateMaterials",
890
+ /**
891
+ * Outlines the colliders of entities of the open scene, as world-space line segments, for the
892
+ * editor's collider gizmos. Answers {@link ColliderOutlineSet}. A host from before it answers
893
+ * `RpcErrorCode.methodNotFound`. Additive in 0.3.
894
+ */
895
+ getColliderOutlines: "getColliderOutlines",
896
+ /**
897
+ * Poses an entity's `Animator` at one point of one state without playing it (engine ADR-0028,
898
+ * amendment 2026-10-20). Answers {@link SampleAnimationResult}. A host from before it answers
899
+ * `RpcErrorCode.methodNotFound`. Additive in 0.3.
900
+ */
901
+ sampleAnimation: "sampleAnimation"
830
902
  };
831
903
  /**
832
904
  * Scene host → editor: the notifications of protocol 0.3. None has an answer.
@@ -879,6 +951,36 @@ const TRANSFORM_DRAGGING_INTERVAL_MS = 50;
879
951
  */
880
952
  const SCREENSHOT_MAX_SIZE = 2048;
881
953
  /**
954
+ * The most entities one `getColliderOutlines` request outlines; the rest of a longer list are left
955
+ * out and the answer says `truncated`.
956
+ *
957
+ * @public
958
+ */
959
+ const COLLIDER_OUTLINES_MAX_ENTITIES = 256;
960
+ /**
961
+ * The most numbers all the `lines` of one `getColliderOutlines` answer hold together, 100 000
962
+ * segments: an outline that would pass it is left out, with every one after it, and the answer
963
+ * says `truncated`.
964
+ *
965
+ * @public
966
+ */
967
+ const COLLIDER_OUTLINES_MAX_NUMBERS = 6e5;
968
+ /**
969
+ * The most parameter values one `sampleAnimation` request may carry. A request with more fails
970
+ * with `invalidParams`.
971
+ *
972
+ * @public
973
+ */
974
+ const SAMPLE_ANIMATION_MAX_PARAMETERS = 64;
975
+ /**
976
+ * The longest `entity`, `state` or parameter name, in UTF-16 code units, one `sampleAnimation`
977
+ * request may carry. A request with a longer one fails with `invalidParams`. It also bounds the
978
+ * names an error message echoes back.
979
+ *
980
+ * @public
981
+ */
982
+ const SAMPLE_ANIMATION_MAX_NAME_LENGTH = 256;
983
+ /**
882
984
  * Why the host could not apply one op.
883
985
  *
884
986
  * @remarks
@@ -1087,12 +1189,13 @@ function isApplyOpFailure(value) {
1087
1189
  * Checks the result of `applyOps`.
1088
1190
  *
1089
1191
  * @param value - The received `result`.
1090
- * @returns True for a count of applied ops and a list of failures with known codes.
1192
+ * @returns True for a count of applied ops, a list of failures with known codes, and an optional
1193
+ * list of issues.
1091
1194
  *
1092
1195
  * @public
1093
1196
  */
1094
1197
  function isApplyOpsResult(value) {
1095
- return isRecord(value) && isCount(value["applied"]) && isArrayOf(value["failures"], isApplyOpFailure);
1198
+ return isRecord(value) && isCount(value["applied"]) && isArrayOf(value["failures"], isApplyOpFailure) && optionalField(value, "warnings", (warnings) => isArrayOf(warnings, isSceneIssue));
1096
1199
  }
1097
1200
  /**
1098
1201
  * Checks the parameters of `readBack`.
@@ -1233,10 +1336,10 @@ function isSchemaFieldDescription(value) {
1233
1336
  *
1234
1337
  * @param value - The value to test.
1235
1338
  * @returns True for `{ title, format, description?, fields, allowMultiple?, package?, builtIn?,
1236
- * propsSchema? }`, ignoring members it does not declare.
1339
+ * requires?, extends?, propsSchema? }`, ignoring members it does not declare.
1237
1340
  */
1238
1341
  function isSchemaDescription(value) {
1239
- return isRecord(value) && isString(value["title"]) && isString(value["format"]) && optionalField(value, "description", isString) && isRecord(value["fields"]) && Object.values(value["fields"]).every((field) => isSchemaFieldDescription(field)) && optionalField(value, "allowMultiple", isBoolean) && optionalField(value, "package", isString) && optionalField(value, "builtIn", isBoolean) && optionalField(value, "propsSchema", isJsonObject);
1342
+ return isRecord(value) && isString(value["title"]) && isString(value["format"]) && optionalField(value, "description", isString) && isRecord(value["fields"]) && Object.values(value["fields"]).every((field) => isSchemaFieldDescription(field)) && optionalField(value, "allowMultiple", isBoolean) && optionalField(value, "package", isString) && optionalField(value, "builtIn", isBoolean) && optionalField(value, "requires", (ids) => Array.isArray(ids) && ids.every((id) => isStringOrNull(id))) && optionalField(value, "extends", (ids) => isArrayOf(ids, isString)) && optionalField(value, "propsSchema", isJsonObject);
1240
1343
  }
1241
1344
  /**
1242
1345
  * Checks the result of `getSchemas` and the parameters of `schemasChanged`.
@@ -1276,6 +1379,90 @@ function isSetViewModeParams(value) {
1276
1379
  return isRecord(value) && isOneOf(ViewMode, value["mode"]);
1277
1380
  }
1278
1381
  /**
1382
+ * Checks the parameters of `setAnimateMaterials`.
1383
+ *
1384
+ * @param value - The received `params`.
1385
+ * @returns True for a boolean `enabled`.
1386
+ *
1387
+ * @public
1388
+ */
1389
+ function isSetAnimateMaterialsParams(value) {
1390
+ return isRecord(value) && isBoolean(value["enabled"]);
1391
+ }
1392
+ /**
1393
+ * Checks one record of `getColliderOutlines`.
1394
+ *
1395
+ * @param value - The value to test.
1396
+ * @returns True for two uids, a boolean, and a list of finite numbers whose length is a multiple of
1397
+ * six.
1398
+ *
1399
+ * @public
1400
+ */
1401
+ function isColliderOutlineRecord(value) {
1402
+ if (!isRecord(value)) return false;
1403
+ const lines = value["lines"];
1404
+ return isUidString(value["entity"]) && isUidString(value["component"]) && isBoolean(value["isTrigger"]) && isArrayOf(lines, isFiniteNumber) && lines.length % 6 === 0;
1405
+ }
1406
+ /**
1407
+ * Checks the result of `getColliderOutlines`.
1408
+ *
1409
+ * @param value - The received `result`.
1410
+ * @returns True for a list of outline records and a boolean `truncated`.
1411
+ *
1412
+ * @public
1413
+ */
1414
+ function isColliderOutlineSet(value) {
1415
+ return isRecord(value) && isArrayOf(value["outlines"], isColliderOutlineRecord) && isBoolean(value["truncated"]);
1416
+ }
1417
+ /**
1418
+ * Checks the parameters of `sampleAnimation`.
1419
+ *
1420
+ * @param value - The received `params`.
1421
+ * @returns True for a uid, a state name, a finite time, and optional parameter values that are
1422
+ * finite numbers or booleans, within {@link SAMPLE_ANIMATION_MAX_NAME_LENGTH} and
1423
+ * {@link SAMPLE_ANIMATION_MAX_PARAMETERS}.
1424
+ *
1425
+ * @public
1426
+ */
1427
+ function isSampleAnimationParams(value) {
1428
+ return isRecord(value) && isUidString(value["entity"]) && isBoundedName(value["entity"]) && isBoundedName(value["state"]) && isFiniteNumber(value["normalizedTime"]) && optionalField(value, "parameters", isSampleParameters);
1429
+ }
1430
+ /**
1431
+ * Tells whether a value is a string no longer than {@link SAMPLE_ANIMATION_MAX_NAME_LENGTH}.
1432
+ *
1433
+ * @param value - The value to test.
1434
+ * @returns True for such a string.
1435
+ */
1436
+ function isBoundedName(value) {
1437
+ return isString(value) && value.length <= 256;
1438
+ }
1439
+ /**
1440
+ * Checks the `parameters` of `sampleAnimation`.
1441
+ *
1442
+ * @param value - The value to test.
1443
+ * @returns True for at most {@link SAMPLE_ANIMATION_MAX_PARAMETERS} bounded names, each with a
1444
+ * finite number or a boolean.
1445
+ */
1446
+ function isSampleParameters(value) {
1447
+ if (!isRecord(value)) return false;
1448
+ const names = Object.keys(value);
1449
+ return names.length <= 64 && names.every((name) => {
1450
+ const entry = value[name];
1451
+ return name.length <= 256 && (isFiniteNumber(entry) || isBoolean(entry));
1452
+ });
1453
+ }
1454
+ /**
1455
+ * Checks the result of `sampleAnimation`.
1456
+ *
1457
+ * @param value - The received `result`.
1458
+ * @returns True for `{ posed: boolean }`.
1459
+ *
1460
+ * @public
1461
+ */
1462
+ function isSampleAnimationResult(value) {
1463
+ return isRecord(value) && isBoolean(value["posed"]);
1464
+ }
1465
+ /**
1279
1466
  * Checks the parameters of `sceneOpened`.
1280
1467
  *
1281
1468
  * @param value - The received `params`.
@@ -1300,13 +1487,14 @@ const HOT_RELOAD_KINDS = {
1300
1487
  * Checks the parameters of `hotReloaded`.
1301
1488
  *
1302
1489
  * @param value - The received `params`.
1303
- * @returns True for `{ report }` with a known kind, type ids, counts and JSON errors.
1490
+ * @returns True for `{ report }` with a known kind, type ids, counts and JSON errors, its strings and
1491
+ * lists within `HOST_TEXT_MAX_LENGTH` and `HOST_LIST_MAX_LENGTH`.
1304
1492
  *
1305
1493
  * @public
1306
1494
  */
1307
1495
  function isHotReloadedParams(value) {
1308
1496
  const report = isRecord(value) ? value["report"] : void 0;
1309
- return isRecord(report) && isOneOf(HOT_RELOAD_KINDS, report["kind"]) && isArrayOf(report["typeIds"], isString) && isCount(report["instances"]) && isNonNegative(report["durationMs"]) && isArrayOf(report["errors"], (error) => isRecord(error) && isString(error["message"]) && isStringOrNull(error["code"]) && optionalField(error, "stack", isStringOrNull));
1497
+ return isRecord(report) && isOneOf(HOT_RELOAD_KINDS, report["kind"]) && isHostList(report["typeIds"], isHostText) && isCount(report["instances"]) && isNonNegative(report["durationMs"]) && isHostList(report["errors"], (error) => isRecord(error) && isHostText(error["message"]) && isHostTextOrNull(error["code"]) && optionalField(error, "stack", isHostTextOrNull));
1310
1498
  }
1311
1499
  /**
1312
1500
  * Checks the parameters of `assetReloaded`.
@@ -1351,24 +1539,26 @@ function isTransformDraggedParams(value) {
1351
1539
  * Checks the parameters of `hostError`.
1352
1540
  *
1353
1541
  * @param value - The received `params`.
1354
- * @returns True for a code or `null`, a message and optional JSON data.
1542
+ * @returns True for a code or `null`, a message and optional JSON data, the strings within
1543
+ * `HOST_TEXT_MAX_LENGTH`.
1355
1544
  *
1356
1545
  * @public
1357
1546
  */
1358
1547
  function isHostErrorParams(value) {
1359
- return isRecord(value) && isStringOrNull(value["code"]) && isString(value["message"]) && optionalField(value, "data", (data) => isJsonValue(data));
1548
+ return isRecord(value) && isHostTextOrNull(value["code"]) && isHostText(value["message"]) && optionalField(value, "data", (data) => isJsonValue(data));
1360
1549
  }
1361
1550
  /**
1362
1551
  * Checks the `data` of a `hostError` for an error the app reported.
1363
1552
  *
1364
1553
  * @param value - The received `data`.
1365
1554
  * @returns True for a boundary name, a phase or `null`, an entity uid or `null`, and, when present,
1366
- * a phase name, an entity name, a component and a stack, each a string or `null`.
1555
+ * a phase name, an entity name, a component and a stack, each a string or `null`; the strings within
1556
+ * `HOST_TEXT_MAX_LENGTH`.
1367
1557
  *
1368
1558
  * @public
1369
1559
  */
1370
1560
  function isAppErrorData(value) {
1371
- return isRecord(value) && isString(value["source"]) && (value["phase"] === null || isCount(value["phase"])) && (value["entity"] === null || isUidString(value["entity"])) && optionalField(value, "phaseName", isStringOrNull) && optionalField(value, "entityName", isStringOrNull) && optionalField(value, "component", isStringOrNull) && optionalField(value, "stack", isStringOrNull);
1561
+ return isRecord(value) && isHostText(value["source"]) && (value["phase"] === null || isCount(value["phase"])) && (value["entity"] === null || isUidString(value["entity"])) && optionalField(value, "phaseName", isHostTextOrNull) && optionalField(value, "entityName", isHostTextOrNull) && optionalField(value, "component", isHostTextOrNull) && optionalField(value, "stack", isHostTextOrNull);
1372
1562
  }
1373
1563
  /** The severities of a log line. */
1374
1564
  const LOG_LEVELS = {
@@ -1381,12 +1571,13 @@ const LOG_LEVELS = {
1381
1571
  * Checks the parameters of `log`.
1382
1572
  *
1383
1573
  * @param value - The received `params`.
1384
- * @returns True for a known level, a scope or `null`, a message and a finite time.
1574
+ * @returns True for a known level, a scope or `null`, a message and a finite time, the strings
1575
+ * within `HOST_TEXT_MAX_LENGTH`.
1385
1576
  *
1386
1577
  * @public
1387
1578
  */
1388
1579
  function isLogParams(value) {
1389
- return isRecord(value) && isOneOf(LOG_LEVELS, value["level"]) && isStringOrNull(value["scope"]) && isString(value["message"]) && isFiniteNumber(value["timeMs"]) && optionalField(value, "error", (error) => isRecord(error) && isString(error["message"]) && isStringOrNull(error["code"]) && isStringOrNull(error["stack"]));
1580
+ return isRecord(value) && isOneOf(LOG_LEVELS, value["level"]) && isHostTextOrNull(value["scope"]) && isHostText(value["message"]) && isFiniteNumber(value["timeMs"]) && optionalField(value, "error", (error) => isRecord(error) && isHostText(error["message"]) && isHostTextOrNull(error["code"]) && isHostTextOrNull(error["stack"]));
1390
1581
  }
1391
1582
  //#endregion
1392
1583
  //#region src/protocol/version.ts
@@ -1554,7 +1745,7 @@ function send(port, message) {
1554
1745
  * period that is not a positive finite number.
1555
1746
  */
1556
1747
  function checkChannelOptions(editorOrigin, heartbeatIntervalMs) {
1557
- if (!isEditorOrigin(editorOrigin)) throw new IgnifxError(EditorHostErrorCode.invalidEditorOrigin, `"${editorOrigin}" is not an origin the editor can be served from.`, { hint: "Pass the editor's origin exactly as the browser reports it, for example \"ignifx://app\"." });
1748
+ if (!isEditorOrigin(editorOrigin)) throw new IgnifxError(EditorHostErrorCode.invalidEditorOrigin, `"${editorOrigin}" is not an origin the editor can be served from.`, { hint: "Pass the editor's origin exactly as the browser reports it, for example \"ignifx-editor://app\"." });
1558
1749
  const interval = heartbeatIntervalMs ?? 1e3;
1559
1750
  if (!Number.isFinite(interval) || interval <= 0) throw new IgnifxError(EditorHostErrorCode.invalidOption, `heartbeatIntervalMs must be a positive number of milliseconds; got ${String(interval)}.`, { context: { option: "heartbeatIntervalMs" } });
1560
1751
  return interval;
@@ -1755,6 +1946,41 @@ function openChannel(options) {
1755
1946
  * The app's reports as the editor's Console reads them: log lines, `app.onError` reports and hot
1756
1947
  * reloads, made JSON. The scene view and the play view relay the same shapes.
1757
1948
  */
1949
+ /** What ends a string {@link clipHostText} cut. */
1950
+ const CLIPPED_MARKER = "… [clipped]";
1951
+ /**
1952
+ * Cuts a string to `HOST_TEXT_MAX_LENGTH`, the longest the editor accepts in a report: the editor
1953
+ * drops a whole report holding a longer one.
1954
+ *
1955
+ * @param text - The string.
1956
+ * @returns It unchanged when short enough, else its start and {@link CLIPPED_MARKER}, exactly
1957
+ * `HOST_TEXT_MAX_LENGTH` long or one shorter (a surrogate pair is never split).
1958
+ */
1959
+ function clipHostText(text) {
1960
+ if (text.length <= 1048576) return text;
1961
+ let end = 1048565;
1962
+ const last = text.charCodeAt(end - 1);
1963
+ if (last >= 55296 && last <= 56319) end -= 1;
1964
+ return `${text.slice(0, end)}${CLIPPED_MARKER}`;
1965
+ }
1966
+ /**
1967
+ * Like {@link clipHostText}, passing `null` through.
1968
+ *
1969
+ * @param text - The string, or `null`.
1970
+ * @returns The clipped string, or `null`.
1971
+ */
1972
+ function clipHostTextOrNull(text) {
1973
+ return text === null ? null : clipHostText(text);
1974
+ }
1975
+ /**
1976
+ * Keeps the first `HOST_LIST_MAX_LENGTH` items of a list, the most the editor accepts in a report.
1977
+ *
1978
+ * @param items - The list.
1979
+ * @returns It, or its start when longer.
1980
+ */
1981
+ function clipHostList(items) {
1982
+ return items.length <= 4096 ? items : items.slice(0, HOST_LIST_MAX_LENGTH);
1983
+ }
1758
1984
  /**
1759
1985
  * Names one of the engine's phases.
1760
1986
  *
@@ -1765,59 +1991,60 @@ function phaseName(phase) {
1765
1991
  return Object.entries(Phase).find(([, value]) => value === phase)?.[0] ?? null;
1766
1992
  }
1767
1993
  /**
1768
- * Reads a thrown value's message.
1994
+ * Reads a thrown value's message, clipped by {@link clipHostText}.
1769
1995
  *
1770
1996
  * @param error - Whatever was thrown.
1771
1997
  * @returns Its message, or the value as a string when it is not an `Error`.
1772
1998
  */
1773
1999
  function messageOf(error) {
1774
- return error instanceof Error ? error.message : String(error);
2000
+ return clipHostText(error instanceof Error ? error.message : String(error));
1775
2001
  }
1776
2002
  /**
1777
- * Reads a thrown value's stack.
2003
+ * Reads a thrown value's stack, clipped by {@link clipHostText}.
1778
2004
  *
1779
2005
  * @param error - Whatever was thrown.
1780
2006
  * @returns Its `stack` when it is an `Error` with one, else `null`.
1781
2007
  */
1782
2008
  function stackOf(error) {
1783
- return error instanceof Error && typeof error.stack === "string" && error.stack !== "" ? error.stack : null;
2009
+ return error instanceof Error && typeof error.stack === "string" && error.stack !== "" ? clipHostText(error.stack) : null;
1784
2010
  }
1785
2011
  /**
1786
- * Reads a thrown value's `IGX-` code.
2012
+ * Reads a thrown value's `IGX-` code, clipped by {@link clipHostText}.
1787
2013
  *
1788
2014
  * @param error - Whatever was thrown.
1789
2015
  * @returns The code of an `IgnifxError`, else `null`.
1790
2016
  */
1791
2017
  function codeOf(error) {
1792
- return isIgnifxError(error) ? error.code : null;
2018
+ return isIgnifxError(error) ? clipHostText(error.code) : null;
1793
2019
  }
1794
2020
  /**
1795
2021
  * Names a component for the editor: its `typeId`, else its class name.
1796
2022
  *
1797
2023
  * @param component - The component.
1798
- * @returns The name.
2024
+ * @returns The name, clipped by {@link clipHostText}.
1799
2025
  */
1800
2026
  function componentName(component) {
1801
2027
  const typeId = Reflect.get(component.constructor, "typeId");
1802
- return typeof typeId === "string" && typeId !== "" ? typeId : component.constructor.name;
2028
+ return clipHostText(typeof typeId === "string" && typeId !== "" ? typeId : component.constructor.name);
1803
2029
  }
1804
2030
  /**
1805
2031
  * Builds the parameters of `log` from one record.
1806
2032
  *
1807
2033
  * @param record - The record the app's logger wrote.
1808
- * @returns The level, scope, message and time, and the first `Error` among the extras.
2034
+ * @returns The level, scope, message and time, and the first `Error` among the extras; each string
2035
+ * clipped by {@link clipHostText}.
1809
2036
  */
1810
2037
  function logParamsOf(record) {
1811
2038
  const params = {
1812
2039
  level: record.level,
1813
- scope: record.scope,
1814
- message: record.message,
2040
+ scope: clipHostTextOrNull(record.scope),
2041
+ message: clipHostText(record.message),
1815
2042
  timeMs: record.timeMs
1816
2043
  };
1817
2044
  const error = record.data.find((value) => value instanceof Error);
1818
2045
  if (error === void 0) return params;
1819
2046
  const logged = {
1820
- message: error.message,
2047
+ message: messageOf(error),
1821
2048
  code: codeOf(error),
1822
2049
  stack: stackOf(error)
1823
2050
  };
@@ -1830,15 +2057,16 @@ function logParamsOf(record) {
1830
2057
  * Builds the parameters of `hostError` from one `app.onError` report.
1831
2058
  *
1832
2059
  * @param report - The report.
1833
- * @returns The thrown error's code and message, and where it was caught.
2060
+ * @returns The thrown error's code and message, and where it was caught; each string clipped by
2061
+ * {@link clipHostText}.
1834
2062
  */
1835
2063
  function hostErrorParamsOf(report) {
1836
2064
  const data = {
1837
- source: report.source,
2065
+ source: clipHostText(report.source),
1838
2066
  phase: report.phase,
1839
2067
  phaseName: report.phase === null ? null : phaseName(report.phase),
1840
2068
  entity: report.entity?.uid ?? null,
1841
- entityName: report.entity?.name ?? null,
2069
+ entityName: clipHostTextOrNull(report.entity?.name ?? null),
1842
2070
  component: report.component === null ? null : componentName(report.component),
1843
2071
  stack: stackOf(report.error)
1844
2072
  };
@@ -1852,15 +2080,16 @@ function hostErrorParamsOf(report) {
1852
2080
  * Builds the parameters of `hotReloaded` from one report.
1853
2081
  *
1854
2082
  * @param report - What `app.hotReload` did.
1855
- * @returns The report, with its errors made JSON.
2083
+ * @returns The report, with its errors made JSON; each string clipped by {@link clipHostText} and
2084
+ * each list cut to `HOST_LIST_MAX_LENGTH` items.
1856
2085
  */
1857
2086
  function hotReloadedParamsOf(report) {
1858
2087
  return { report: {
1859
2088
  kind: report.kind,
1860
- typeIds: report.typeIds,
2089
+ typeIds: clipHostList(report.typeIds).map((typeId) => clipHostText(typeId)),
1861
2090
  instances: report.instances,
1862
2091
  durationMs: report.durationMs,
1863
- errors: report.errors.map((error) => ({
2092
+ errors: clipHostList(report.errors).map((error) => ({
1864
2093
  message: messageOf(error),
1865
2094
  code: codeOf(error),
1866
2095
  stack: stackOf(error)
@@ -2295,124 +2524,117 @@ function outermostRoots(index, roots) {
2295
2524
  });
2296
2525
  }
2297
2526
  //#endregion
2298
- //#region src/scene/defaults.ts
2527
+ //#region src/scene/collider-outlines.ts
2299
2528
  /**
2300
- * Defaults that a script's hot reload changes (engine ask E25): which fields of which component
2301
- * types took a new default, and the live world brought in line with the document for them. A field
2302
- * a document component's record leaves out takes the new default; a field it sets keeps its value;
2303
- * a prefab instance whose members hold such a field is rebuilt from its prefab, with its overrides
2304
- * (`docs/architecture/17-editor-host.md` §6.1).
2529
+ * `getColliderOutlines`: the physics extensions' collider outlines, made JSON. The host reads
2530
+ * `app.physics.colliderOutlines` and `app.physics2d.colliderOutlines` by shape, as `@ignifx/devtools`
2531
+ * reads `app.physics`, so a project without physics costs the host nothing and the host depends on
2532
+ * neither package (ADR-0028, amendment of 2026-10-20).
2305
2533
  */
2306
- /** Defaults hold no reference to anything in a file. */
2307
- const NO_REFERENCES = {
2308
- entityUid: () => null,
2309
- componentUid: () => null
2310
- };
2534
+ /** How many decimal places a coordinate keeps on the wire: a hundredth of a millimetre. */
2535
+ const WIRE_PRECISION = 1e5;
2311
2536
  /**
2312
- * Reads a component type's field defaults as the file format writes them; `transient` fields,
2313
- * which no file holds, are left out.
2537
+ * Finds `colliderOutlines` on one of the app's physics services.
2314
2538
  *
2315
- * @param app - The scene view's app.
2316
- * @param type - The registered type.
2317
- * @returns The defaults, or `null` for a type without a schema.
2539
+ * @param app - The app.
2540
+ * @param property - `"physics"` or `"physics2d"`.
2541
+ * @returns A function that outlines an entity's colliders, or `null` when the project does not
2542
+ * register that extension (or registers one from before the method).
2318
2543
  */
2319
- function defaultsOf(app, type) {
2320
- const schema = app.world.registry.describe(type).schema;
2321
- if (schema === null) return null;
2322
- const encoded = encodeProps(schema, {}, NO_REFERENCES);
2323
- return new Map(Object.entries(encoded).map(([name, value]) => [name, JSON.stringify(value)]));
2544
+ function outlinerOf(app, property) {
2545
+ const service = Reflect.get(app, property);
2546
+ if (typeof service !== "object" || service === null) return null;
2547
+ const method = Reflect.get(service, "colliderOutlines");
2548
+ if (typeof method !== "function") return null;
2549
+ return (entity) => {
2550
+ const answer = Reflect.apply(method, service, [entity]);
2551
+ return Array.isArray(answer) ? answer.filter(isOutlineLike) : [];
2552
+ };
2324
2553
  }
2325
- /** The field defaults of every registered type, as the host last saw them. */
2326
- var DefaultsTracker = class {
2327
- #app;
2328
- #known = /* @__PURE__ */ new Map();
2329
- /**
2330
- * Reads the defaults of every type registered now.
2331
- *
2332
- * @param app - The scene view's app, started.
2333
- */
2334
- constructor(app) {
2335
- this.#app = app;
2336
- for (const [typeId, type] of app.world.registry.registrations()) this.#known.set(typeId, defaultsOf(app, type));
2337
- }
2338
- /**
2339
- * Compares the defaults of reloaded types with the ones seen before, and keeps the new ones.
2340
- *
2341
- * @param typeIds - The type ids a hot reload replaced; any other id is ignored.
2342
- * @returns The fields whose default changed or which are new, by type id. A type seen for the
2343
- * first time has no change: no document component was built from it.
2344
- */
2345
- changed(typeIds) {
2346
- const changed = /* @__PURE__ */ new Map();
2347
- const registry = this.#app.world.registry;
2348
- for (const typeId of typeIds) {
2349
- const type = registry.get(typeId);
2350
- if (type === null) continue;
2351
- const next = defaultsOf(this.#app, type);
2352
- const previous = this.#known.get(typeId);
2353
- this.#known.set(typeId, next);
2354
- if (previous === void 0 || next === null) continue;
2355
- const fields = [...next].filter(([name, value]) => previous?.get(name) !== value).map(([name]) => name);
2356
- if (fields.length > 0) changed.set(typeId, fields);
2357
- }
2358
- return changed;
2359
- }
2360
- };
2361
2554
  /**
2362
- * The type id of a live component.
2555
+ * Tells whether a value has an outline's shape.
2363
2556
  *
2364
- * @param app - The scene view's app.
2365
- * @param component - The component.
2366
- * @returns Its registered type id, or `null`.
2557
+ * @param value - The value.
2558
+ * @returns True for a component, a boolean, and a `Float32Array`.
2367
2559
  */
2368
- function typeIdOf(app, component) {
2369
- return app.world.registry.describe(component.constructor).typeId;
2560
+ function isOutlineLike(value) {
2561
+ return typeof value === "object" && value !== null && Reflect.get(value, "collider") instanceof Component && typeof Reflect.get(value, "isTrigger") === "boolean" && Reflect.get(value, "lines") instanceof Float32Array;
2370
2562
  }
2371
2563
  /**
2372
- * Gives every document component the new default of each changed field its record leaves out. A
2373
- * component the mirror has no record of is left alone.
2564
+ * Rounds a coordinate for the wire, which also drops the float32 noise (`0.30000001192092896`).
2374
2565
  *
2375
- * @param app - The scene view's app.
2376
- * @param mirror - The open document.
2377
- * @param index - Its index.
2378
- * @param changed - The changed fields, by type id.
2566
+ * @param value - The coordinate.
2567
+ * @returns The rounded coordinate.
2379
2568
  */
2380
- function applyDefaults(app, mirror, index, changed) {
2381
- for (const [uid, component] of index.components) {
2382
- const fields = changed.get(typeIdOf(app, component) ?? "");
2383
- const set = mirror.propsSetBy(uid);
2384
- const schema = app.world.registry.describe(component.constructor).schema;
2385
- if (fields === void 0 || set === null || schema === null) continue;
2386
- for (const name of fields) {
2387
- const field = Object.hasOwn(schema, name) ? schema[name] : void 0;
2388
- if (field !== void 0 && !set.has(name)) Reflect.set(component, name, field.createDefault());
2389
- }
2390
- }
2569
+ function wireNumber(value) {
2570
+ return Math.round(value * WIRE_PRECISION) / WIRE_PRECISION;
2391
2571
  }
2392
2572
  /**
2393
- * The document's instance roots whose members (not the document's own components) include a
2394
- * component of a changed type, in document order.
2573
+ * Turns 3D segments into wire numbers.
2574
+ *
2575
+ * @param lines - `x, y, z` per end.
2576
+ * @returns The same segments, rounded.
2577
+ */
2578
+ function lines3D(lines) {
2579
+ return Array.from(lines, wireNumber);
2580
+ }
2581
+ /**
2582
+ * Turns 2D segments into 3D wire numbers at a depth.
2583
+ *
2584
+ * @param lines - `x, y` per end.
2585
+ * @param z - The entity's world `z`.
2586
+ * @returns `x, y, z` per end, rounded.
2587
+ */
2588
+ function lines2D(lines, z) {
2589
+ const out = [];
2590
+ for (let index = 0; index + 1 < lines.length; index += 2) out.push(wireNumber(lines[index] ?? 0), wireNumber(lines[index + 1] ?? 0), wireNumber(z));
2591
+ return out;
2592
+ }
2593
+ /**
2594
+ * Outlines the colliders of document entities, 3D first and then 2D for each entity, within the
2595
+ * protocol's caps: at most `COLLIDER_OUTLINES_MAX_ENTITIES` entities and
2596
+ * `COLLIDER_OUTLINES_MAX_NUMBERS` numbers of lines. What passes a cap is left out, whole, and the
2597
+ * answer says `truncated`.
2395
2598
  *
2396
2599
  * @param app - The scene view's app.
2397
- * @param index - The open document's index.
2398
- * @param changed - The changed fields, by type id.
2399
- * @returns The roots' uids.
2600
+ * @param requested - The requested entities, as many as asked, before any is looked up.
2601
+ * @param resolve - Finds a requested uid's entity in the open scene, or `undefined`.
2602
+ * @returns The answer to `getColliderOutlines`.
2400
2603
  */
2401
- function instancesHolding(app, index, changed) {
2402
- const roots = /* @__PURE__ */ new Set();
2403
- for (const record of index.file.entities) {
2404
- const root = index.entities.get(record.uid);
2405
- if (record.instance === void 0 || root === void 0) continue;
2406
- const pending = [root];
2407
- for (let entity = pending.pop(); entity !== void 0; entity = pending.pop()) {
2408
- if (entity.components.some((component) => !index.components.has(component.uid) && changed.has(typeIdOf(app, component) ?? ""))) {
2409
- roots.add(record.uid);
2410
- break;
2604
+ function colliderOutlinesOf(app, requested, resolve) {
2605
+ const outline3D = outlinerOf(app, "physics");
2606
+ const outline2D = outlinerOf(app, "physics2d");
2607
+ const outlines = [];
2608
+ const uids = [...new Set(requested)];
2609
+ let truncated = uids.length > 256;
2610
+ let numbers = 0;
2611
+ for (const uid of uids.slice(0, 256)) {
2612
+ const entity = resolve(uid);
2613
+ if (entity === void 0) continue;
2614
+ const z = entity.transform.position.z;
2615
+ const found = [...(outline3D?.(entity) ?? []).map((outline) => [outline, false]), ...(outline2D?.(entity) ?? []).map((outline) => [outline, true])];
2616
+ for (const [outline, is2D] of found) {
2617
+ const count = is2D ? outline.lines.length / 2 * 3 : outline.lines.length;
2618
+ if (numbers + count > 6e5) {
2619
+ truncated = true;
2620
+ return {
2621
+ outlines,
2622
+ truncated
2623
+ };
2411
2624
  }
2412
- pending.push(...entity.children);
2625
+ numbers += count;
2626
+ outlines.push({
2627
+ entity: uid,
2628
+ component: outline.collider.uid,
2629
+ isTrigger: outline.isTrigger,
2630
+ lines: is2D ? lines2D(outline.lines, z) : lines3D(outline.lines)
2631
+ });
2413
2632
  }
2414
2633
  }
2415
- return roots;
2634
+ return {
2635
+ outlines,
2636
+ truncated
2637
+ };
2416
2638
  }
2417
2639
  /** Milliseconds in one second. */
2418
2640
  const MILLISECONDS_PER_SECOND = 1e3;
@@ -2494,38 +2716,144 @@ function copyJson(value) {
2494
2716
  * @param component - The component.
2495
2717
  * @param props - The `props` object.
2496
2718
  * @param references - How references resolve.
2719
+ * @param only - The fields to assign, if not every one; only their problems are returned.
2720
+ * @returns The decoding problems, as `{ code, message }`.
2721
+ */
2722
+ function assignProps(component, props, references, only) {
2723
+ const decoded = decodeComponentProps(component, props, references, only);
2724
+ for (const [name, value] of decoded.values) Reflect.set(component, name, value);
2725
+ return decoded.issues;
2726
+ }
2727
+ /**
2728
+ * The problems {@link assignProps} would return, without assigning anything.
2729
+ *
2730
+ * @param component - The component.
2731
+ * @param props - The `props` object.
2732
+ * @param references - How references resolve.
2733
+ * @param only - The fields to decode, if not every one.
2497
2734
  * @returns The decoding problems, as `{ code, message }`.
2498
2735
  */
2499
- function assignProps(component, props, references) {
2736
+ function propIssues(component, props, references, only) {
2737
+ return decodeComponentProps(component, props, references, only).issues;
2738
+ }
2739
+ /**
2740
+ * Decodes a component's props from JSON, every schema field the JSON leaves out taking its default.
2741
+ *
2742
+ * @param component - The component.
2743
+ * @param props - The `props` object.
2744
+ * @param references - How references resolve.
2745
+ * @param only - The fields to keep, if not every one.
2746
+ * @returns The kept fields' values, and their problems as `{ code, message }`.
2747
+ */
2748
+ function decodeComponentProps(component, props, references, only) {
2500
2749
  const schema = component.world.registry.describe(component.constructor).schema;
2501
- if (schema === null) return [];
2750
+ if (schema === null) return {
2751
+ values: /* @__PURE__ */ new Map(),
2752
+ issues: []
2753
+ };
2502
2754
  const decoded = decodeProps(schema, props, references);
2503
- const values = new Map(Object.entries(decoded.value));
2504
- for (const name of Object.keys(schema)) Reflect.set(component, name, values.get(name));
2505
- return decoded.issues.map((issue) => ({
2506
- code: issue.code,
2507
- message: `${component.uid}.${issue.path}: ${issue.message}`
2508
- }));
2755
+ const all = new Map(Object.entries(decoded.value));
2756
+ const values = /* @__PURE__ */ new Map();
2757
+ for (const name of Object.keys(schema)) if (only === void 0 || only.has(name)) values.set(name, all.get(name));
2758
+ return {
2759
+ values,
2760
+ issues: decoded.issues.filter((issue) => only === void 0 || only.has(issue.path.split(/[.[]/u, 1)[0] ?? "")).map((issue) => ({
2761
+ code: issue.code,
2762
+ message: `${component.uid}.${issue.path}: ${issue.message}`
2763
+ }))
2764
+ };
2509
2765
  }
2510
- /** The live mirror of the editor's open scene document. */
2511
- var DocumentMirror = class {
2512
- #app;
2513
- #scene = null;
2514
- #address = null;
2515
- #name = "";
2516
- #settings = null;
2517
- #index = null;
2518
- /**
2519
- * The fields each document component's record sets, by component uid: the keys of its `props` as
2520
- * the file and the ops since have written them. A field left out takes the schema's default.
2521
- */
2522
- #explicit = /* @__PURE__ */ new Map();
2523
- /**
2524
- * Each instance root's override list as the document holds it, by root uid. The serializer
2525
- * recomputes overrides by diffing the live members with their scene, which after a hot reload
2526
- * that changed a default reads every stale member value as an override.
2527
- */
2766
+ /**
2767
+ * Tells a component that the host changed some of its fields, through its `onValidate` hook
2768
+ * (`ComponentHooks`), so one that builds something from them (a physics body) rebuilds it.
2769
+ *
2770
+ * @param component - The component.
2771
+ * @param fields - The fields that changed; nothing is called when the list is empty.
2772
+ */
2773
+ function validateFields(component, fields) {
2774
+ const hook = Reflect.get(component, "onValidate");
2775
+ if (fields.length > 0 && typeof hook === "function") Reflect.apply(hook, component, [fields]);
2776
+ }
2777
+ /**
2778
+ * An override in the form the scene file writes it, which editor-core's document holds: an op
2779
+ * sent as `{ op: "replace" }` or a transform value with more than six decimals still reads back
2780
+ * as the document has it.
2781
+ *
2782
+ * @param override - The override as an op or a file carried it.
2783
+ * @returns The canonical override.
2784
+ */
2785
+ function canonicalOverride(override) {
2786
+ const op = override.op ?? "replace";
2787
+ const value = op === "remove" ? void 0 : canonicalOverrideValue(override.path, override.value);
2788
+ return {
2789
+ ...op === "replace" ? {} : { op },
2790
+ path: override.path,
2791
+ ...value === void 0 ? {} : { value }
2792
+ };
2793
+ }
2794
+ /**
2795
+ * A transform override's value with each number canonical; any other value as it is.
2796
+ *
2797
+ * @param path - The override's path.
2798
+ * @param value - Its value.
2799
+ * @returns The value to keep.
2800
+ */
2801
+ function canonicalOverrideValue(path, value) {
2802
+ const list = value;
2803
+ if (!Array.isArray(list) || !isTransformPath(path)) return value;
2804
+ const items = list;
2805
+ const numbers = [];
2806
+ for (const item of items) {
2807
+ if (typeof item !== "number") return value;
2808
+ numbers.push(canonicalizeNumber(item));
2809
+ }
2810
+ return numbers;
2811
+ }
2812
+ /**
2813
+ * Whether an override path names a transform field.
2814
+ *
2815
+ * @param path - The path.
2816
+ * @returns `false` too for a path the engine's grammar refuses.
2817
+ */
2818
+ function isTransformPath(path) {
2819
+ try {
2820
+ return parseOverridePath(path).kind === "transform";
2821
+ } catch {
2822
+ return false;
2823
+ }
2824
+ }
2825
+ /** The live mirror of the editor's open scene document. */
2826
+ var DocumentMirror = class {
2827
+ #app;
2828
+ #scene = null;
2829
+ #address = null;
2830
+ #name = "";
2831
+ #settings = null;
2832
+ #index = null;
2833
+ /**
2834
+ * The fields each document component's record sets, by component uid: the keys of its `props` as
2835
+ * the file and the ops since have written them. A field left out takes the schema's default.
2836
+ */
2837
+ #explicit = /* @__PURE__ */ new Map();
2838
+ /**
2839
+ * Each instance root's override list as the document holds it, by root uid. The serializer
2840
+ * recomputes overrides by diffing the live members with their scene, which after a hot reload
2841
+ * that changed a default reads every stale member value as an override.
2842
+ */
2528
2843
  #overrides = /* @__PURE__ */ new Map();
2844
+ /**
2845
+ * Each instance root's overrides as the serializer read them right after the host built the root,
2846
+ * as JSON text, by root uid. While the serializer still reads the same, the members are as the
2847
+ * document's list built them, and `readBack` writes that list.
2848
+ */
2849
+ #builtAs = /* @__PURE__ */ new Map();
2850
+ /**
2851
+ * Where an `add` puts a component on each instance root itself (`<root>/components` of a one-root
2852
+ * scene), or `null`, by root uid, read from the scene the root was last built from. A reload that
2853
+ * changes the scene's roots replaces the scene in the cache before the root is rebuilt, while the
2854
+ * serializer still writes the root as that build made it.
2855
+ */
2856
+ #rootPaths = /* @__PURE__ */ new Map();
2529
2857
  /** Assets loaded for ops, held until the document closes. */
2530
2858
  #handles = [];
2531
2859
  /**
@@ -2584,27 +2912,59 @@ var DocumentMirror = class {
2584
2912
  */
2585
2913
  async open(file, address) {
2586
2914
  await this.close();
2915
+ const where = address ?? "memory:scene/unsaved";
2587
2916
  const warnings = [];
2588
- const scene = await this.#app.world.loadSceneFile(file, {
2589
- address: address ?? "memory:scene/unsaved",
2590
- onIssue: (issue) => {
2591
- warnings.push({
2592
- code: issue.code,
2593
- message: issue.message
2594
- });
2595
- }
2596
- });
2917
+ const held = await this.#loadDoubledScenes(file.entities);
2918
+ let scene;
2919
+ let entities;
2920
+ try {
2921
+ entities = withoutDoubleAdds(this.#app, file.entities, where, warnings);
2922
+ scene = await this.#app.world.loadSceneFile({
2923
+ ...file,
2924
+ entities
2925
+ }, {
2926
+ address: where,
2927
+ onIssue: (issue) => {
2928
+ warnings.push({
2929
+ code: issue.code,
2930
+ message: issue.message
2931
+ });
2932
+ }
2933
+ });
2934
+ } finally {
2935
+ for (const handle of held) handle.release();
2936
+ }
2597
2937
  this.#scene = scene;
2598
2938
  this.#address = address;
2599
2939
  this.#name = file.name;
2600
2940
  this.#settings = file.settings === void 0 ? null : copyJson(file.settings);
2601
- this.recordComponents(file.entities.flatMap((record) => record.components ?? []));
2602
- this.recordInstances(file.entities);
2941
+ this.recordComponents(entities.flatMap((record) => record.components ?? []));
2942
+ this.recordInstances(entities);
2943
+ this.invalidate();
2603
2944
  return {
2604
2945
  entityCount: countEntities(scene),
2605
2946
  warnings
2606
2947
  };
2607
2948
  }
2949
+ /**
2950
+ * Loads the scenes of the instance roots whose records may hold the old double form of an added
2951
+ * component, so {@link withoutDoubleAdds} can tell where each scene's root is.
2952
+ *
2953
+ * @param records - The file's entity records.
2954
+ * @returns The handles, each with one holder the caller releases.
2955
+ */
2956
+ async #loadDoubledScenes(records) {
2957
+ const handles = [];
2958
+ for (const record of records) {
2959
+ const instance = record.instance;
2960
+ const own = new Set((record.components ?? []).map((component) => component.uid));
2961
+ const adds = (instance?.overrides ?? []).flatMap((override) => addedUids(override));
2962
+ if (instance === void 0 || !adds.some((uid) => own.has(uid))) continue;
2963
+ handles.push(this.#app.assets.load(instance.scene.$asset, { type: instance.scene.type ?? SCENE_ASSET_TYPE }));
2964
+ }
2965
+ await Promise.allSettled(handles.map(async (handle) => handle.promise));
2966
+ return handles;
2967
+ }
2608
2968
  /** Unloads the open document, if any, and releases the assets its ops loaded. */
2609
2969
  async close() {
2610
2970
  const scene = this.#scene;
@@ -2615,6 +2975,8 @@ var DocumentMirror = class {
2615
2975
  this.#index = null;
2616
2976
  this.#explicit.clear();
2617
2977
  this.#overrides.clear();
2978
+ this.#builtAs.clear();
2979
+ this.#rootPaths.clear();
2618
2980
  if (scene !== null) await this.#app.world.unloadScene(scene);
2619
2981
  for (const handle of this.#handles.splice(0)) handle.release();
2620
2982
  }
@@ -2669,21 +3031,47 @@ var DocumentMirror = class {
2669
3031
  return this.#explicit.get(uid) ?? null;
2670
3032
  }
2671
3033
  /**
2672
- * Records the override lists of the instance roots among some entity records.
3034
+ * Records the override lists of the instance roots among some entity records the host has just
3035
+ * built, and what the serializer reads from those roots now, before anything else can change
3036
+ * their members.
2673
3037
  *
2674
3038
  * @param records - The records, as a file or an op carries them.
2675
3039
  */
2676
3040
  recordInstances(records) {
2677
- for (const record of records) if (record.instance !== void 0) this.recordOverrides(record.uid, record.instance.overrides ?? []);
3041
+ const roots = records.filter((record) => record.instance !== void 0);
3042
+ for (const record of roots) {
3043
+ this.recordOverrides(record.uid, record.instance?.overrides ?? []);
3044
+ this.#rootPaths.set(record.uid, record.instance === void 0 ? null : rootComponentsPath(this.#app, record.instance));
3045
+ }
3046
+ if (roots.length === 0) return;
3047
+ this.#index = null;
3048
+ const index = this.index();
3049
+ for (const record of roots) {
3050
+ const read = index?.records.get(record.uid)?.instance;
3051
+ if (read === void 0) this.#builtAs.delete(record.uid);
3052
+ else this.#builtAs.set(record.uid, JSON.stringify(read.overrides ?? []));
3053
+ }
2678
3054
  }
2679
3055
  /**
2680
- * Records an instance root's override list.
3056
+ * Records an instance root's override list, each override in the form the scene file writes and
3057
+ * editor-core's document holds: no `op` for a `replace`, no value for a `remove`, and a
3058
+ * transform's numbers canonical.
2681
3059
  *
2682
3060
  * @param uid - The root's uid.
2683
3061
  * @param overrides - The list.
2684
3062
  */
2685
3063
  recordOverrides(uid, overrides) {
2686
- this.#overrides.set(uid, structuredClone(overrides));
3064
+ this.#overrides.set(uid, structuredClone(overrides).map(canonicalOverride));
3065
+ }
3066
+ /**
3067
+ * Where an `add` override puts a component on an instance root itself, in the scene the root was
3068
+ * last built from.
3069
+ *
3070
+ * @param uid - The root's uid.
3071
+ * @returns `<scene root uid>/components` when that scene has one root, or `null`.
3072
+ */
3073
+ rootPathOf(uid) {
3074
+ return this.#rootPaths.get(uid) ?? null;
2687
3075
  }
2688
3076
  /**
2689
3077
  * An instance root's override list as the document holds it.
@@ -2699,7 +3087,10 @@ var DocumentMirror = class {
2699
3087
  this.#index = null;
2700
3088
  }
2701
3089
  /**
2702
- * The document as the live world holds it, serialized once and cached until the next change.
3090
+ * The document as the live world holds it, serialized once and cached until an op, `open` or
3091
+ * `readBack` drops it; the next call serializes the world again. Every lookup (selection, picks,
3092
+ * the ops' references) reads this cache, so a lookup after a `readBack` sees the world as that
3093
+ * `readBack` did.
2703
3094
  *
2704
3095
  * @returns The index, or `null` while no document is open.
2705
3096
  */
@@ -2712,16 +3103,27 @@ var DocumentMirror = class {
2712
3103
  /**
2713
3104
  * Serializes the requested entities as the live world has them (protocol `readBack`).
2714
3105
  *
3106
+ * @remarks
3107
+ * The world is serialized again on every call, not read from the cache, because a `"run"`
3108
+ * system or a `runInEditMode` script can change it outside an op.
3109
+ *
3110
+ * An instance root's overrides are the list the document holds, in its order, while the
3111
+ * serializer still reads its members as they were built from that list. The serializer's own
3112
+ * list is a diff in file order that writes an added component whole and leaves out an override
3113
+ * equal to the instanced scene's value, so it never equals the document's; it is written instead
3114
+ * once the members read differently, so a change the document did not make still shows.
3115
+ *
2715
3116
  * @param params - The uids to read, or none for all.
2716
3117
  * @returns The records in file order, the uids not found, the settings, and the serializer's issues.
2717
3118
  */
2718
3119
  readBack(params) {
3120
+ this.invalidate();
2719
3121
  const index = this.index();
2720
3122
  if (index === null) return null;
2721
3123
  const requested = params.entities;
2722
3124
  const wanted = requested === void 0 ? null : new Set(requested);
2723
3125
  return {
2724
- entities: index.file.entities.filter((record) => wanted === null || wanted.has(record.uid)),
3126
+ entities: index.file.entities.filter((record) => wanted === null || wanted.has(record.uid)).map((record) => this.#withDocumentOverrides(record)),
2725
3127
  missing: requested === void 0 ? [] : [...new Set(requested)].filter((uid) => !index.records.has(uid)),
2726
3128
  settings: index.file.settings ?? null,
2727
3129
  issues: index.issues
@@ -2742,6 +3144,7 @@ var DocumentMirror = class {
2742
3144
  }
2743
3145
  /**
2744
3146
  * How references in props resolve: document uids first, then the uids of a subtree just built,
3147
+ * then the components instances' `add` overrides gave their members, as a reopen resolves them;
2745
3148
  * and assets already loaded in the app's cache.
2746
3149
  *
2747
3150
  * @param built - The uid table of a subtree an op just built, if any.
@@ -2752,7 +3155,7 @@ var DocumentMirror = class {
2752
3155
  const assets = this.#app.assets;
2753
3156
  return {
2754
3157
  entity: (uid) => index?.entities.get(uid) ?? built?.entity(uid) ?? null,
2755
- component: (uid) => index?.components.get(uid) ?? built?.component(uid) ?? null,
3158
+ component: (uid) => index?.components.get(uid) ?? built?.component(uid) ?? index?.added.get(uid) ?? null,
2756
3159
  asset: (address, type) => {
2757
3160
  const handle = assets.get(address);
2758
3161
  return handle !== null && handle.state === "loaded" && (type === null || handle.type === type) ? handle : null;
@@ -2760,6 +3163,24 @@ var DocumentMirror = class {
2760
3163
  };
2761
3164
  }
2762
3165
  /**
3166
+ * An entity's record with the document's override list, when it is an instance root whose
3167
+ * members still read as they were built from that list.
3168
+ *
3169
+ * @param record - The record as the serializer wrote it.
3170
+ * @returns The record to read back.
3171
+ */
3172
+ #withDocumentOverrides(record) {
3173
+ const read = record.instance;
3174
+ const listed = this.#overrides.get(record.uid);
3175
+ const built = this.#builtAs.get(record.uid);
3176
+ if (read === void 0 || listed === void 0 || JSON.stringify(read.overrides ?? []) !== built) return record;
3177
+ return withOverrideList(record, {
3178
+ scene: read.scene,
3179
+ ...read.hash === void 0 ? {} : { hash: read.hash },
3180
+ ...listed.length === 0 ? {} : { overrides: structuredClone(listed) }
3181
+ }, this.rootPathOf(record.uid));
3182
+ }
3183
+ /**
2763
3184
  * Serializes the document and indexes its entities and components.
2764
3185
  *
2765
3186
  * @param scene - The document's scene instance.
@@ -2781,6 +3202,7 @@ var DocumentMirror = class {
2781
3202
  const entities = /* @__PURE__ */ new Map();
2782
3203
  const records = /* @__PURE__ */ new Map();
2783
3204
  const components = /* @__PURE__ */ new Map();
3205
+ const added = /* @__PURE__ */ new Map();
2784
3206
  for (const record of file.entities) {
2785
3207
  const entity = world.getEntity(record.uid);
2786
3208
  if (entity === null) continue;
@@ -2788,16 +3210,259 @@ var DocumentMirror = class {
2788
3210
  records.set(record.uid, record);
2789
3211
  const uids = new Set((record.components ?? []).map((component) => component.uid));
2790
3212
  for (const component of entity.components) if (uids.has(component.uid) && !component.isDestroyed) components.set(component.uid, component);
3213
+ const adds = new Set((record.instance?.overrides ?? []).flatMap((override) => addedUids(override)));
3214
+ if (adds.size > 0) collectComponents(entity, adds, added);
2791
3215
  }
2792
3216
  return {
2793
3217
  file,
2794
3218
  issues,
2795
3219
  entities,
2796
3220
  records,
2797
- components
3221
+ components,
3222
+ added
2798
3223
  };
2799
3224
  }
2800
3225
  };
3226
+ /**
3227
+ * A file's entity records without the old double form of an added component: before `readBack`
3228
+ * wrote each `add` override once, it also wrote one that adds to the root of a one-root scene as
3229
+ * the root's own component, with the same uid, so a reopen built it twice. Each is kept once, as the
3230
+ * override list adds it, so `readBack` reads the same from the first frame. Only an `add` to the
3231
+ * root's component list counts: one on another member that reuses a uid of the root's own
3232
+ * components is not the old form, so both are built, with a warning of its own.
3233
+ *
3234
+ * @param app - The scene view's app, whose cache holds the instanced scenes.
3235
+ * @param records - The file's entity records.
3236
+ * @param address - The document's address, for the warnings.
3237
+ * @param warnings - Gets one `IGX-0608` warning when a record had the double form, and one when a
3238
+ * record's list adds to a member with a uid of the root's own components.
3239
+ * @returns The records, each collapsed one replaced.
3240
+ */
3241
+ function withoutDoubleAdds(app, records, address, warnings) {
3242
+ const doubled = [];
3243
+ const reused = [];
3244
+ const collapsed = records.map((record) => {
3245
+ const instance = record.instance;
3246
+ if (instance === void 0 || record.components === void 0) return record;
3247
+ const single = withOverrideList(record, instance, rootComponentsPath(app, instance));
3248
+ const kept = new Set((single.components ?? []).map((component) => component.uid));
3249
+ const adds = new Set((instance.overrides ?? []).flatMap((override) => addedUids(override)));
3250
+ for (const component of record.components) if (!kept.has(component.uid)) doubled.push(`${record.uid}/${component.uid}`);
3251
+ else if (adds.has(component.uid)) reused.push(`${record.uid}/${component.uid}`);
3252
+ return single;
3253
+ });
3254
+ if (reused.length > 0) warnings.push({
3255
+ code: CoreErrorCode.sceneFileInvalid,
3256
+ message: `${address}: ${reused.join(", ")}: each of these uids names both an instance root's own component and one an add override in its list gives a member; both are built.`
3257
+ });
3258
+ if (doubled.length > 0) warnings.push({
3259
+ code: CoreErrorCode.sceneFileInvalid,
3260
+ message: `${address}: ${doubled.join(", ")}: an older editor wrote each of these components both as an instance root's own and in its override list, with one uid; each is kept once, as the list adds it.`
3261
+ });
3262
+ return collapsed;
3263
+ }
3264
+ /**
3265
+ * An instance root's record with an instance entry whose override list replaces the serializer's.
3266
+ * The serializer writes a component that an `add` override gives the root of a one-root scene as
3267
+ * the root's own, so the record leaves out each component the list adds there; a rebuild or a
3268
+ * reopen would otherwise add it twice.
3269
+ *
3270
+ * @param record - The record as the serializer wrote it.
3271
+ * @param instance - The instance entry, with the document's list.
3272
+ * @param path - `<scene root uid>/components` of the scene the record was written against, when
3273
+ * that scene has one root, or `null`.
3274
+ * @returns The record.
3275
+ */
3276
+ function withOverrideList(record, instance, path) {
3277
+ const adds = new Set((instance.overrides ?? []).filter((override) => override.path === path).flatMap((override) => addedUids(override)));
3278
+ const own = record.components ?? [];
3279
+ const components = own.filter((component) => !adds.has(component.uid));
3280
+ if (components.length === own.length) return {
3281
+ ...record,
3282
+ instance
3283
+ };
3284
+ const { components: _written, ...rest } = record;
3285
+ return {
3286
+ ...rest,
3287
+ instance,
3288
+ ...components.length === 0 ? {} : { components }
3289
+ };
3290
+ }
3291
+ /**
3292
+ * The override path of the component list of an instanced scene's root, when the scene has one
3293
+ * root: a component an `add` there gives is the instance root's own.
3294
+ *
3295
+ * @param app - The scene view's app.
3296
+ * @param instance - The instance entry.
3297
+ * @returns `<root uid>/components`, or `null` for a scene with several roots or none, or one the
3298
+ * cache does not hold loaded as a scene.
3299
+ */
3300
+ function rootComponentsPath(app, instance) {
3301
+ const handle = app.assets.get(instance.scene.$asset);
3302
+ if (handle === null || handle.state !== "loaded" || handle.type !== SCENE_ASSET_TYPE) return null;
3303
+ const roots = handle.value.file.entities.filter((entity) => entity.parent === null);
3304
+ const root = roots.length === 1 ? roots[0] : void 0;
3305
+ return root === void 0 ? null : `${root.uid}/components`;
3306
+ }
3307
+ /**
3308
+ * The uid of the component an `add` override of a component list adds, as a list.
3309
+ *
3310
+ * @param override - The override.
3311
+ * @returns The uid, or nothing.
3312
+ */
3313
+ function addedUids(override) {
3314
+ const value = override.value;
3315
+ const uid = override.op === "add" && typeof value === "object" && value !== null ? Reflect.get(value, "uid") : null;
3316
+ return typeof uid === "string" ? [uid] : [];
3317
+ }
3318
+ /**
3319
+ * Finds the live components with some uids in a subtree.
3320
+ *
3321
+ * @param entity - The subtree's root.
3322
+ * @param uids - The uids.
3323
+ * @param into - Filled with each one found, by uid.
3324
+ */
3325
+ function collectComponents(entity, uids, into) {
3326
+ for (const component of entity.components) if (uids.has(component.uid) && !component.isDestroyed) into.set(component.uid, component);
3327
+ for (const child of entity.children) collectComponents(child, uids, into);
3328
+ }
3329
+ //#endregion
3330
+ //#region src/scene/defaults.ts
3331
+ /**
3332
+ * Defaults that a script's hot reload changes (engine ask E25): which fields of which component
3333
+ * types took a new default, and the live world brought in line with the document for them. A field
3334
+ * a document component's record leaves out takes the new default; a field it sets keeps its value;
3335
+ * a prefab instance whose members hold such a field is rebuilt from its prefab, with its overrides
3336
+ * (`docs/architecture/17-editor-host.md` §6.1).
3337
+ */
3338
+ /** Defaults hold no reference to anything in a file. */
3339
+ const NO_REFERENCES = {
3340
+ entityUid: () => null,
3341
+ componentUid: () => null
3342
+ };
3343
+ /**
3344
+ * Reads a component type's field defaults as the file format writes them; `transient` fields,
3345
+ * which no file holds, are left out.
3346
+ *
3347
+ * @param app - The scene view's app.
3348
+ * @param type - The registered type.
3349
+ * @returns The defaults, or `null` for a type without a schema.
3350
+ */
3351
+ function defaultsOf(app, type) {
3352
+ const schema = app.world.registry.describe(type).schema;
3353
+ if (schema === null) return null;
3354
+ const encoded = encodeProps(schema, {}, NO_REFERENCES);
3355
+ return new Map(Object.entries(encoded).map(([name, value]) => [name, JSON.stringify(value)]));
3356
+ }
3357
+ /** The field defaults of every registered type, as the host last saw them. */
3358
+ var DefaultsTracker = class {
3359
+ #app;
3360
+ #known = /* @__PURE__ */ new Map();
3361
+ /**
3362
+ * Reads the defaults of every type registered now.
3363
+ *
3364
+ * @param app - The scene view's app, started.
3365
+ */
3366
+ constructor(app) {
3367
+ this.#app = app;
3368
+ for (const [typeId, type] of app.world.registry.registrations()) this.#known.set(typeId, defaultsOf(app, type));
3369
+ }
3370
+ /**
3371
+ * Compares the defaults of reloaded types with the ones seen before, and keeps the new ones.
3372
+ *
3373
+ * @param typeIds - The type ids a hot reload replaced; any other id is ignored.
3374
+ * @returns The fields whose default changed or which are new, by type id. A type seen for the
3375
+ * first time has no change: no document component was built from it.
3376
+ */
3377
+ changed(typeIds) {
3378
+ const changed = /* @__PURE__ */ new Map();
3379
+ const registry = this.#app.world.registry;
3380
+ for (const typeId of typeIds) {
3381
+ const type = registry.get(typeId);
3382
+ if (type === null) continue;
3383
+ const next = defaultsOf(this.#app, type);
3384
+ const previous = this.#known.get(typeId);
3385
+ this.#known.set(typeId, next);
3386
+ if (previous === void 0 || next === null) continue;
3387
+ const fields = [...next].filter(([name, value]) => previous?.get(name) !== value).map(([name]) => name);
3388
+ if (fields.length > 0) changed.set(typeId, fields);
3389
+ }
3390
+ return changed;
3391
+ }
3392
+ };
3393
+ /**
3394
+ * The type id of a live component.
3395
+ *
3396
+ * @param app - The scene view's app.
3397
+ * @param component - The component.
3398
+ * @returns Its registered type id, or `null`.
3399
+ */
3400
+ function typeIdOf(app, component) {
3401
+ return app.world.registry.describe(component.constructor).typeId;
3402
+ }
3403
+ /**
3404
+ * Gives every document component the new default of each changed field its record leaves out. A
3405
+ * component the mirror has no record of is left alone. A component whose setter or `onValidate`
3406
+ * throws is handed to `failed`, and the others still get their defaults.
3407
+ *
3408
+ * @param app - The scene view's app.
3409
+ * @param mirror - The open document.
3410
+ * @param index - Its index.
3411
+ * @param changed - The changed fields, by type id.
3412
+ * @param failed - Called with each component that threw, its type id, and what it threw.
3413
+ */
3414
+ function applyDefaults(app, mirror, index, changed, failed) {
3415
+ for (const [uid, component] of index.components) {
3416
+ const typeId = typeIdOf(app, component) ?? "";
3417
+ const fields = changed.get(typeId);
3418
+ const set = mirror.propsSetBy(uid);
3419
+ const schema = app.world.registry.describe(component.constructor).schema;
3420
+ if (fields === void 0 || set === null || schema === null) continue;
3421
+ const assigned = [];
3422
+ try {
3423
+ for (const name of fields) {
3424
+ const field = Object.hasOwn(schema, name) ? schema[name] : void 0;
3425
+ if (field !== void 0 && !set.has(name)) {
3426
+ Reflect.set(component, name, field.createDefault());
3427
+ assigned.push(name);
3428
+ }
3429
+ }
3430
+ validateFields(component, assigned);
3431
+ } catch (error) {
3432
+ failed(component, typeId, error);
3433
+ }
3434
+ }
3435
+ }
3436
+ /**
3437
+ * The document's instance roots whose members (not the document's own components) include a
3438
+ * component of a changed type, in document order. A component the index lists but the mirror has
3439
+ * no record of is a member too: one an `add` override gives the root of a one-root prefab, which
3440
+ * the serializer writes as the root's own. So every component under a root either takes its new
3441
+ * defaults from {@link applyDefaults} or is rebuilt.
3442
+ *
3443
+ * @param app - The scene view's app.
3444
+ * @param mirror - The open document.
3445
+ * @param index - Its index.
3446
+ * @param changed - The changed fields, by type id.
3447
+ * @returns The roots' uids.
3448
+ */
3449
+ function instancesHolding(app, mirror, index, changed) {
3450
+ const isMember = (component) => !index.components.has(component.uid) || mirror.propsSetBy(component.uid) === null;
3451
+ const roots = /* @__PURE__ */ new Set();
3452
+ for (const record of index.file.entities) {
3453
+ const root = index.entities.get(record.uid);
3454
+ if (record.instance === void 0 || root === void 0) continue;
3455
+ const pending = [root];
3456
+ for (let entity = pending.pop(); entity !== void 0; entity = pending.pop()) {
3457
+ if (entity.components.some((component) => isMember(component) && changed.has(typeIdOf(app, component) ?? ""))) {
3458
+ roots.add(record.uid);
3459
+ break;
3460
+ }
3461
+ pending.push(...entity.children);
3462
+ }
3463
+ }
3464
+ return roots;
3465
+ }
2801
3466
  //#endregion
2802
3467
  //#region src/scene/editor-camera.ts
2803
3468
  /**
@@ -3668,49 +4333,544 @@ var EditorCamera2D = class extends Script {
3668
4333
  }
3669
4334
  };
3670
4335
  //#endregion
3671
- //#region src/scene/ops.ts
4336
+ //#region src/scene/view-math.ts
3672
4337
  /**
3673
- * `applyOps`: the thirteen scene ops of protocol 0.3, applied to the open document's live world.
3674
- *
3675
- * Each op changes the world the way the editor's `applyOp` changes the document, so that a mirror
3676
- * that started exact stays exact: `readBack` then returns the document's own records. An op that
3677
- * the world disagrees with fails with one of editor-core's codes; the host does not roll back,
3678
- * because the editor reopens the scene after any failure.
4338
+ * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and
4339
+ * plane point a `pick` answers with, the `screenshot` size rule, the transform the drag
4340
+ * notifications carry, and gizmo snapping. Each is a pure function, so the headless tests check it
4341
+ * directly.
3679
4342
  */
3680
- /** The address the subtrees ops build are named by, in the engine's diagnostics. */
3681
- const SUBTREE_ADDRESS = "memory:scene/editor-op";
3682
- /** Why one op failed, as `applyOps` reports it. */
3683
- var OpFailure = class extends Error {
3684
- /** The failure code. */
3685
- code;
3686
- /** The engine's diagnostic code, when there is one. */
3687
- diagnostic;
3688
- /**
3689
- * Creates the failure.
3690
- *
3691
- * @param code - The failure code.
3692
- * @param message - An actionable sentence.
3693
- * @param diagnostic - The engine's `IGX-` code, if any.
3694
- */
3695
- constructor(code, message, diagnostic = null) {
3696
- super(message);
3697
- this.name = "OpFailure";
3698
- this.code = code;
3699
- this.diagnostic = diagnostic;
3700
- }
3701
- };
3702
4343
  /**
3703
- * Applies one command's ops in order, never stopping at a failure.
3704
- *
4344
+ * Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its
4345
+ * backing pixels.
4346
+ *
4347
+ * @param surface - The canvas.
4348
+ * @returns The sizes.
4349
+ */
4350
+ function viewSurfaceOf(surface) {
4351
+ const clientWidth = Reflect.get(surface, "clientWidth");
4352
+ const clientHeight = Reflect.get(surface, "clientHeight");
4353
+ return {
4354
+ width: surface.width,
4355
+ height: surface.height,
4356
+ clientWidth: typeof clientWidth === "number" && clientWidth > 0 ? clientWidth : surface.width,
4357
+ clientHeight: typeof clientHeight === "number" && clientHeight > 0 ? clientHeight : surface.height
4358
+ };
4359
+ }
4360
+ /**
4361
+ * Converts a `pick` point to the backing-store pixels `app.renderer.pickAsync` takes (protocol 0.3,
4362
+ * "The pick unit rule"; engine ask E3). This is the host's one conversion: the renderer converts
4363
+ * on to the CSS pixels Lite's picker wants.
4364
+ *
4365
+ * @param params - The point and its unit.
4366
+ * @param surface - The canvas's sizes.
4367
+ * @returns The point in backing-store pixels, or `null` when it is outside the canvas (a miss).
4368
+ */
4369
+ function toBackingPixels(params, surface) {
4370
+ const x = params.unit === PickUnit.backing ? params.x : params.x * surface.width / surface.clientWidth;
4371
+ const y = params.unit === PickUnit.backing ? params.y : params.y * surface.height / surface.clientHeight;
4372
+ if (x < 0 || y < 0 || x >= surface.width || y >= surface.height) return null;
4373
+ return {
4374
+ x,
4375
+ y
4376
+ };
4377
+ }
4378
+ /**
4379
+ * Turns a camera ray into a `pick` answer's `ray` and `plane` members (protocol 0.3, additive): the
4380
+ * ray as it is, and the point where it meets the 2D world plane `z = 0`. The plane point is
4381
+ * computed before rounding, and its `z` is exactly `0`.
4382
+ *
4383
+ * @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.
4384
+ * @returns The members, every number rounded with `canonicalizeNumber`.
4385
+ */
4386
+ function pickRayMembers(ray) {
4387
+ const c = canonicalizeNumber;
4388
+ const { origin, direction } = ray;
4389
+ const members = { ray: {
4390
+ origin: [
4391
+ c(origin.x),
4392
+ c(origin.y),
4393
+ c(origin.z)
4394
+ ],
4395
+ direction: [
4396
+ c(direction.x),
4397
+ c(direction.y),
4398
+ c(direction.z)
4399
+ ]
4400
+ } };
4401
+ const t = direction.z === 0 ? NaN : -origin.z / direction.z;
4402
+ if (!Number.isFinite(t) || t < 0) return members;
4403
+ return {
4404
+ ...members,
4405
+ plane: [
4406
+ c(origin.x + direction.x * t),
4407
+ c(origin.y + direction.y * t),
4408
+ 0
4409
+ ]
4410
+ };
4411
+ }
4412
+ /**
4413
+ * Rounds an image side and keeps it from 1 to {@link SCREENSHOT_MAX_SIZE}.
4414
+ *
4415
+ * @param side - The side, in pixels.
4416
+ * @returns The whole side in range.
4417
+ */
4418
+ function clampSide(side) {
4419
+ return Math.min(SCREENSHOT_MAX_SIZE, Math.max(1, Math.round(side)));
4420
+ }
4421
+ /**
4422
+ * The size of a `screenshot`: the request's, or the view's backing size scaled down, keeping its
4423
+ * aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.
4424
+ *
4425
+ * @param params - The request; its sizes are already checked to be 1 to 2048.
4426
+ * @param view - The captured frame's size.
4427
+ * @returns The image size, each side at least 1 and at most 2048.
4428
+ */
4429
+ function screenshotSize(params, view) {
4430
+ const aspect = view.height > 0 ? view.width / view.height : 1;
4431
+ const { width, height } = params;
4432
+ if (width !== void 0 && height !== void 0) return {
4433
+ width,
4434
+ height
4435
+ };
4436
+ if (width !== void 0) return {
4437
+ width,
4438
+ height: clampSide(width / aspect)
4439
+ };
4440
+ if (height !== void 0) return {
4441
+ width: clampSide(height * aspect),
4442
+ height
4443
+ };
4444
+ const fit = Math.min(1, SCREENSHOT_MAX_SIZE / Math.max(view.width, view.height, 1));
4445
+ return {
4446
+ width: clampSide(view.width * fit),
4447
+ height: clampSide(view.height * fit)
4448
+ };
4449
+ }
4450
+ /**
4451
+ * Reads an entity's local transform as the scene file writes it, numbers canonicalized.
4452
+ *
4453
+ * @param entity - The entity.
4454
+ * @returns The transform.
4455
+ */
4456
+ function readLocalTransform(entity) {
4457
+ const { localPosition: p, localRotation: r, localScale: s } = entity.transform;
4458
+ const c = canonicalizeNumber;
4459
+ return {
4460
+ position: [
4461
+ c(p.x),
4462
+ c(p.y),
4463
+ c(p.z)
4464
+ ],
4465
+ rotation: [
4466
+ c(r.x),
4467
+ c(r.y),
4468
+ c(r.z),
4469
+ c(r.w)
4470
+ ],
4471
+ scale: [
4472
+ c(s.x),
4473
+ c(s.y),
4474
+ c(s.z)
4475
+ ]
4476
+ };
4477
+ }
4478
+ /**
4479
+ * Rounds a value to a step; a step of 0 leaves it alone.
4480
+ *
4481
+ * @param value - The value.
4482
+ * @param step - The step.
4483
+ * @returns The snapped value.
4484
+ */
4485
+ function snapTo(value, step) {
4486
+ return step > 0 ? Math.round(value / step) * step : value;
4487
+ }
4488
+ /**
4489
+ * Snaps a gizmo drag after Lite has applied each move (S0.2 §3.4, post-correction). The raw, unsnapped
4490
+ * value is kept apart from the node, so the snapped steps do not accumulate rounding.
4491
+ */
4492
+ var DragSnapper = class {
4493
+ #mode;
4494
+ #snap;
4495
+ #start;
4496
+ #raw;
4497
+ #written;
4498
+ /**
4499
+ * Starts snapping one drag.
4500
+ *
4501
+ * @param mode - The drag's mode.
4502
+ * @param snap - The snapping steps.
4503
+ * @param entity - The dragged entity, at drag start.
4504
+ */
4505
+ constructor(mode, snap, entity) {
4506
+ this.#mode = mode;
4507
+ this.#snap = snap;
4508
+ this.#start = this.#read(entity);
4509
+ this.#raw = [...this.#start];
4510
+ this.#written = [...this.#start];
4511
+ }
4512
+ /**
4513
+ * Folds the move Lite just wrote into the raw value and writes the snapped value back.
4514
+ *
4515
+ * @param entity - The dragged entity.
4516
+ */
4517
+ apply(entity) {
4518
+ const now = this.#read(entity);
4519
+ if (this.#mode === "rotate") {
4520
+ this.#applyRotation(entity, now);
4521
+ return;
4522
+ }
4523
+ const step = this.#mode === "translate" ? this.#snap.translate : this.#snap.scale;
4524
+ if (step <= 0) return;
4525
+ this.#raw = this.#raw.map((value, index) => value + (now[index] ?? 0) - (this.#written[index] ?? 0));
4526
+ const snapped = this.#raw.map((value, index) => (this.#start[index] ?? 0) + snapTo(value - (this.#start[index] ?? 0), step));
4527
+ (this.#mode === "translate" ? entity.transform.localPosition : entity.transform.localScale).set(snapped[0] ?? 0, snapped[1] ?? 0, snapped[2] ?? 0);
4528
+ this.#written = snapped;
4529
+ }
4530
+ /**
4531
+ * Snaps a rotation drag: a ring turns about one axis, so the turn since drag start is one angle,
4532
+ * which is rounded to the step.
4533
+ *
4534
+ * @param entity - The dragged entity.
4535
+ * @param now - Its rotation now, as Lite wrote it.
4536
+ */
4537
+ #applyRotation(entity, now) {
4538
+ const step = this.#snap.rotate;
4539
+ if (step <= 0) return;
4540
+ this.#raw = multiply(multiply(now, conjugate(this.#written)), this.#raw);
4541
+ const turn = multiply(this.#raw, conjugate(this.#start));
4542
+ const sine = Math.hypot(turn[0] ?? 0, turn[1] ?? 0, turn[2] ?? 0);
4543
+ if (sine < 1e-9) return;
4544
+ const half = snapTo(2 * Math.atan2(sine, turn[3] ?? 1) * 180 / Math.PI, step) * Math.PI / 180 / 2;
4545
+ const scale = Math.sin(half) / sine;
4546
+ const result = multiply([
4547
+ (turn[0] ?? 0) * scale,
4548
+ (turn[1] ?? 0) * scale,
4549
+ (turn[2] ?? 0) * scale,
4550
+ Math.cos(half)
4551
+ ], this.#start);
4552
+ entity.transform.localRotation.set(result[0] ?? 0, result[1] ?? 0, result[2] ?? 0, result[3] ?? 1);
4553
+ this.#written = result;
4554
+ }
4555
+ /**
4556
+ * Reads the channels this drag moves.
4557
+ *
4558
+ * @param entity - The entity.
4559
+ * @returns Position, scale, or the rotation quaternion.
4560
+ */
4561
+ #read(entity) {
4562
+ const t = entity.transform;
4563
+ if (this.#mode === "rotate") return [
4564
+ t.localRotation.x,
4565
+ t.localRotation.y,
4566
+ t.localRotation.z,
4567
+ t.localRotation.w
4568
+ ];
4569
+ const v = this.#mode === "translate" ? t.localPosition : t.localScale;
4570
+ return [
4571
+ v.x,
4572
+ v.y,
4573
+ v.z
4574
+ ];
4575
+ }
4576
+ };
4577
+ /**
4578
+ * Multiplies two quaternions, `a · b`.
4579
+ *
4580
+ * @param a - The left operand, `[x, y, z, w]`.
4581
+ * @param b - The right operand.
4582
+ * @returns The product.
4583
+ */
4584
+ function multiply(a, b) {
4585
+ const [ax = 0, ay = 0, az = 0, aw = 1] = a;
4586
+ const [bx = 0, by = 0, bz = 0, bw = 1] = b;
4587
+ return [
4588
+ aw * bx + ax * bw + ay * bz - az * by,
4589
+ aw * by - ax * bz + ay * bw + az * bx,
4590
+ aw * bz + ax * by - ay * bx + az * bw,
4591
+ aw * bw - ax * bx - ay * by - az * bz
4592
+ ];
4593
+ }
4594
+ /**
4595
+ * A unit quaternion's inverse.
4596
+ *
4597
+ * @param q - The quaternion.
4598
+ * @returns Its conjugate.
4599
+ */
4600
+ function conjugate(q) {
4601
+ return [
4602
+ -(q[0] ?? 0),
4603
+ -(q[1] ?? 0),
4604
+ -(q[2] ?? 0),
4605
+ q[3] ?? 1
4606
+ ];
4607
+ }
4608
+ //#endregion
4609
+ //#region src/scene/gizmo-drag.ts
4610
+ /**
4611
+ * Turns one gizmo drag into the scene view's drag notifications. It needs no GPU: the view calls
4612
+ * it with each part of the gesture, and the headless tests call it directly.
4613
+ */
4614
+ /**
4615
+ * Sends `transformDragging` and `transformDragged` for gizmo drags, one drag at a time.
4616
+ *
4617
+ * @remarks
4618
+ * Every drag opens with a `transformDragging` and closes with a `transformDragged`, even one that
4619
+ * ends where it started, so the editor can hold its undo from pointer-down to pointer-up.
4620
+ */
4621
+ var GizmoDragRelay = class {
4622
+ #notify;
4623
+ #now;
4624
+ #drag = null;
4625
+ /**
4626
+ * Makes a relay.
4627
+ *
4628
+ * @param notify - Sends one notification to the editor.
4629
+ * @param now - The clock, in milliseconds; `performance.now` by default.
4630
+ */
4631
+ constructor(notify, now = () => performance.now()) {
4632
+ this.#notify = notify;
4633
+ this.#now = now;
4634
+ }
4635
+ /**
4636
+ * Starts a drag and sends its first `transformDragging`, the transform at drag start. A drag in
4637
+ * progress is dropped without a `transformDragged`.
4638
+ *
4639
+ * @param entity - The dragged entity.
4640
+ * @param mode - The drag's mode.
4641
+ * @param snap - The snapping steps, or `null`.
4642
+ */
4643
+ start(entity, mode, snap) {
4644
+ const before = readLocalTransform(entity);
4645
+ this.#drag = {
4646
+ entity,
4647
+ mode,
4648
+ before,
4649
+ snapper: snap === null ? null : new DragSnapper(mode, snap, entity),
4650
+ lastSentMs: this.#now()
4651
+ };
4652
+ this.#notify(SceneNotification.transformDragging, {
4653
+ entity: entity.uid,
4654
+ mode,
4655
+ after: before
4656
+ });
4657
+ }
4658
+ /** Snaps the move the gizmo just made and sends `transformDragging`, at most every 50 ms. */
4659
+ move() {
4660
+ const state = this.#drag;
4661
+ if (state === null) return;
4662
+ state.snapper?.apply(state.entity);
4663
+ const now = this.#now();
4664
+ if (now - state.lastSentMs >= 50) {
4665
+ state.lastSentMs = now;
4666
+ this.#notify(SceneNotification.transformDragging, {
4667
+ entity: state.entity.uid,
4668
+ mode: state.mode,
4669
+ after: readLocalTransform(state.entity)
4670
+ });
4671
+ }
4672
+ }
4673
+ /** Ends the drag and sends `transformDragged`, whether or not the transform changed. */
4674
+ end() {
4675
+ const state = this.#drag;
4676
+ if (state === null) return;
4677
+ this.#drag = null;
4678
+ this.#notify(SceneNotification.transformDragged, {
4679
+ entity: state.entity.uid,
4680
+ mode: state.mode,
4681
+ before: state.before,
4682
+ after: readLocalTransform(state.entity)
4683
+ });
4684
+ }
4685
+ /** Forgets a drag that has no entity, so its moves and end send nothing. */
4686
+ clear() {
4687
+ this.#drag = null;
4688
+ }
4689
+ };
4690
+ //#endregion
4691
+ //#region src/scene/json.ts
4692
+ /**
4693
+ * The uid of a referenced entity or component.
4694
+ *
4695
+ * @param target - The field's value.
4696
+ * @returns Its uid, or `null` for anything without one.
4697
+ */
4698
+ function uidOf(target) {
4699
+ const uid = typeof target === "object" && target !== null ? Reflect.get(target, "uid") : null;
4700
+ return typeof uid === "string" ? uid : null;
4701
+ }
4702
+ /**
4703
+ * Narrows JSON to an object. `Array.isArray` does not remove a readonly array from the union, so the
4704
+ * discrimination lives here once.
4705
+ *
4706
+ * @param value - The JSON.
4707
+ * @returns The object, or `null` for anything else.
4708
+ */
4709
+ function asJsonObject(value) {
4710
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
4711
+ return value;
4712
+ }
4713
+ /**
4714
+ * Narrows JSON to an array.
4715
+ *
4716
+ * @param value - The JSON.
4717
+ * @returns The array, or `null`.
4718
+ */
4719
+ function asJsonArray(value) {
4720
+ return Array.isArray(value) ? value : null;
4721
+ }
4722
+ /**
4723
+ * Tells whether JSON references an entity or component of a set.
4724
+ *
4725
+ * @param value - The JSON.
4726
+ * @param entities - The entity uids.
4727
+ * @param components - The component uids.
4728
+ * @returns True when a `$entity` or `$component` names one of them.
4729
+ */
4730
+ function pointsInto(value, entities, components) {
4731
+ const array = asJsonArray(value);
4732
+ if (array !== null) return array.some((item) => pointsInto(item, entities, components));
4733
+ const object = asJsonObject(value);
4734
+ if (object === null) return false;
4735
+ const entity = object["$entity"];
4736
+ const component = object["$component"];
4737
+ return typeof entity === "string" && entities.has(entity) || typeof component === "string" && components.has(component) || Object.values(object).some((item) => pointsInto(item, entities, components));
4738
+ }
4739
+ //#endregion
4740
+ //#region src/scene/held-references.ts
4741
+ /**
4742
+ * What instance members outside a subtree that is about to be rebuilt hold in it: the reference
4743
+ * fields another instance's overrides aimed at the subtree, read from the live world before the
4744
+ * subtree is destroyed, so the rebuild can point them at the new objects.
4745
+ */
4746
+ /**
4747
+ * The reference fields of instance members outside a subtree that point into it, read from the live
4748
+ * world as JSON: what another instance's overrides aimed at the subtree's document entities, or at
4749
+ * the components its `add` overrides give. A member is not in the document, so only its live
4750
+ * component knows the field; a document component and an added one are read from the document. Only
4751
+ * the instances whose override lists point into the subtree are read.
4752
+ *
4753
+ * @param app - The scene view's app.
4754
+ * @param mirror - The open document.
4755
+ * @param index - The document, read before the subtree is destroyed.
4756
+ * @param subtree - The subtree's root.
4757
+ * @param entities - The subtree's document entity uids.
4758
+ * @param components - The uids of its document components and the components its overrides add.
4759
+ * @returns The fields, and the objects they held.
4760
+ */
4761
+ function heldByMembers(app, mirror, index, subtree, entities, components) {
4762
+ const fields = /* @__PURE__ */ new Map();
4763
+ const heldEntities = /* @__PURE__ */ new Map();
4764
+ const heldComponents = /* @__PURE__ */ new Map();
4765
+ const registry = app.world.registry;
4766
+ const visit = (entity) => {
4767
+ if (entity === subtree) return;
4768
+ for (const component of entity.components) {
4769
+ const uid = component.uid;
4770
+ if (index.components.get(uid) === component || index.added.get(uid) === component) continue;
4771
+ const props = {};
4772
+ for (const [name, field] of Object.entries(registry.describe(component.constructor).schema ?? {})) {
4773
+ if (!holdsReferences(field)) continue;
4774
+ const targets = [];
4775
+ const json = encodeValue(field, Reflect.get(component, name), {
4776
+ entityUid: (value) => remember(targets, heldEntities, value),
4777
+ componentUid: (value) => remember(targets, heldComponents, value)
4778
+ });
4779
+ if (pointsInto(json, entities, components)) {
4780
+ props[name] = json;
4781
+ for (const [into, target, value] of targets) into.set(target, value);
4782
+ }
4783
+ }
4784
+ if (Object.keys(props).length > 0) fields.set(component, props);
4785
+ }
4786
+ for (const child of entity.children) visit(child);
4787
+ };
4788
+ for (const record of index.file.entities) {
4789
+ const root = index.entities.get(record.uid);
4790
+ const aims = (mirror.overridesOf(record.uid) ?? []).some((override) => (override.op ?? "replace") === "replace" && pointsInto(override.value, entities, components));
4791
+ if (root !== void 0 && !entities.has(record.uid) && aims) visit(root);
4792
+ }
4793
+ return {
4794
+ fields,
4795
+ entities: heldEntities,
4796
+ components: heldComponents
4797
+ };
4798
+ }
4799
+ /**
4800
+ * Notes a referenced object by its uid, to keep if its field turns out to point into a subtree.
4801
+ *
4802
+ * @param targets - The field's notes.
4803
+ * @param into - Where the note goes if it is kept.
4804
+ * @param value - The referenced object.
4805
+ * @returns Its uid, or `null` for anything without one.
4806
+ */
4807
+ function remember(targets, into, value) {
4808
+ const uid = uidOf(value);
4809
+ if (uid !== null) targets.push([
4810
+ into,
4811
+ uid,
4812
+ value
4813
+ ]);
4814
+ return uid;
4815
+ }
4816
+ /**
4817
+ * Tells whether a field's value can hold an entity or component reference.
4818
+ *
4819
+ * @param field - The field.
4820
+ * @returns True for a reference, or a list, record, map or optional of one.
4821
+ */
4822
+ function holdsReferences(field) {
4823
+ const spec = field.spec;
4824
+ if (spec.kind === "entityRef" || spec.kind === "componentRef") return true;
4825
+ if (spec.kind === "array") return holdsReferences(spec.item);
4826
+ if (spec.kind === "record") return Object.values(spec.fields).some((inner) => holdsReferences(inner));
4827
+ if (spec.kind === "map") return holdsReferences(spec.value);
4828
+ return spec.kind === "optional" && holdsReferences(spec.inner);
4829
+ }
4830
+ //#endregion
4831
+ //#region src/scene/ops.ts
4832
+ /**
4833
+ * `applyOps`: the thirteen scene ops of protocol 0.3, applied to the open document's live world.
4834
+ *
4835
+ * Each op changes the world the way the editor's `applyOp` changes the document, so that a mirror
4836
+ * that started exact stays exact: `readBack` then returns the document's own records. An op that
4837
+ * the world disagrees with fails with one of editor-core's codes; the host does not roll back,
4838
+ * because the editor reopens the scene after any failure.
4839
+ */
4840
+ /** Why one op failed, as `applyOps` reports it. */
4841
+ var OpFailure = class extends Error {
4842
+ /** The failure code. */
4843
+ code;
4844
+ /** The engine's diagnostic code, when there is one. */
4845
+ diagnostic;
4846
+ /**
4847
+ * Creates the failure.
4848
+ *
4849
+ * @param code - The failure code.
4850
+ * @param message - An actionable sentence.
4851
+ * @param diagnostic - The engine's `IGX-` code, if any.
4852
+ */
4853
+ constructor(code, message, diagnostic = null) {
4854
+ super(message);
4855
+ this.name = "OpFailure";
4856
+ this.code = code;
4857
+ this.diagnostic = diagnostic;
4858
+ }
4859
+ };
4860
+ /**
4861
+ * Applies one command's ops in order, never stopping at a failure.
4862
+ *
3705
4863
  * @param app - The scene view's app.
3706
4864
  * @param mirror - The open document.
3707
4865
  * @param params - The ops and the command they belong to.
3708
- * @returns How many applied, and the failures in order.
4866
+ * @returns How many applied, the failures in order, and the build problems the ops met, in order.
3709
4867
  */
3710
4868
  async function applyOps(app, mirror, params) {
4869
+ const warnings = [];
3711
4870
  const context = {
3712
4871
  app,
3713
- mirror
4872
+ mirror,
4873
+ warnings
3714
4874
  };
3715
4875
  const failures = [];
3716
4876
  let applied = 0;
@@ -3726,7 +4886,8 @@ async function applyOps(app, mirror, params) {
3726
4886
  }
3727
4887
  return {
3728
4888
  applied,
3729
- failures
4889
+ failures,
4890
+ warnings
3730
4891
  };
3731
4892
  }
3732
4893
  /**
@@ -3920,21 +5081,28 @@ function requireFreeUids(context, records) {
3920
5081
  }
3921
5082
  }
3922
5083
  /**
3923
- * Tells whether JSON holds an entity or component reference anywhere.
5084
+ * Checks that new entity records form a scene file `validateSceneFile` accepts, before anything is
5085
+ * built: the protocol guard checks their shapes, and this adds the file's rules over them, among
5086
+ * them that no instance entry holds two overrides with one identity, which `setOverride` and
5087
+ * `removeOverride` could then reach only one of.
3924
5088
  *
3925
- * @param value - The JSON.
3926
- * @returns True when a `$entity` or `$component` object is in it.
5089
+ * @param records - The new entity records, parents first.
3927
5090
  */
3928
- function hasReferences(value) {
3929
- const array = asJsonArray(value);
3930
- if (array !== null) return array.some((item) => hasReferences(item));
3931
- const object = asJsonObject(value);
3932
- return object !== null && ("$entity" in object || "$component" in object || Object.values(object).some((item) => hasReferences(item)));
5091
+ function requireValidRecords(records) {
5092
+ const issue = validateSceneFile({
5093
+ format: SCENE_FILE_FORMAT,
5094
+ formatVersion: SCENE_FORMAT_VERSION,
5095
+ name: "",
5096
+ entities: records
5097
+ })[0];
5098
+ if (issue !== void 0) throw new OpFailure(ApplyOpFailureCode.invalidValue, `${issue.path}: ${issue.message}`, "IGX-0608");
3933
5099
  }
3934
5100
  /**
3935
5101
  * Builds a subtree from entity records under a live parent, with the records' uids, loading the
3936
- * assets they reference first; then resolves references to the rest of the document, which a
3937
- * subtree built on its own cannot see.
5102
+ * assets they reference first. A reference to a uid the subtree does not declare resolves against
5103
+ * the rest of the document, as it would in the whole file: one a document component holds, and one
5104
+ * an instance's overrides hold (an added component's, or a member's overridden field). The build's
5105
+ * problems are logged as warnings ({@link reportBuildIssues}).
3938
5106
  *
3939
5107
  * @param context - The app and the document.
3940
5108
  * @param records - The subtree's records, parents first; the first is its root.
@@ -3957,23 +5125,49 @@ async function buildSubtree(context, records, parent, index) {
3957
5125
  };
3958
5126
  const dependencies = await loadSceneDependencies(context.app.assets, file);
3959
5127
  context.mirror.retain(dependencies);
3960
- const asset = await createSceneAsset(SUBTREE_ADDRESS, file, dependencies);
5128
+ const asset = await createSceneAsset(documentAddress(context), file, dependencies);
5129
+ const outsideReferences = context.mirror.decoder();
3961
5130
  const built = instantiateScene(context.app.world, asset, {
3962
5131
  scene,
5132
+ outsideReferences,
3963
5133
  ...parent === null ? {} : { parent }
3964
5134
  });
3965
5135
  context.mirror.invalidate();
3966
- const references = context.mirror.decoder(built.remap);
3967
- for (const record of file.entities) for (const component of record.components ?? []) {
3968
- const live = built.remap.component(component.uid);
3969
- if (live !== null && hasReferences(component.props)) assignProps(live, component.props ?? {}, references);
3970
- }
5136
+ reportBuildIssues(context, built.issues);
3971
5137
  const root = built.roots[0] ?? built.remap.entity(top.uid);
3972
5138
  if (root === null) throw new OpFailure(ApplyOpFailureCode.engineError, `The engine built no entity for ${top.uid}.`);
3973
5139
  placeAmongSiblings(context, root, index);
3974
5140
  return root;
3975
5141
  }
3976
5142
  /**
5143
+ * The open document's address, which names the subtrees ops build.
5144
+ *
5145
+ * @param context - The app and the document.
5146
+ * @returns Where the document is saved, or `memory:scene/unsaved`.
5147
+ */
5148
+ function documentAddress(context) {
5149
+ return context.mirror.address ?? "memory:scene/unsaved";
5150
+ }
5151
+ /**
5152
+ * Writes a subtree build's recoverable problems to the app log, one warning each, the way
5153
+ * `world.loadSceneFile` writes a scene's (so a reopen of the document writes the same lines); the
5154
+ * host relays them to the editor as `log`. A stale override met while an instance is rebuilt is one.
5155
+ * Inside `applyOps` each also goes to the command's `warnings`, as `openScene` reports a build's.
5156
+ *
5157
+ * @param context - The app and the document.
5158
+ * @param issues - The problems, in the order found.
5159
+ */
5160
+ function reportBuildIssues(context, issues) {
5161
+ const address = documentAddress(context);
5162
+ for (const issue of issues) {
5163
+ context.app.log.warn(`${issue.code}: ${address}: ${issue.message}`);
5164
+ context.warnings?.push({
5165
+ code: issue.code,
5166
+ message: issue.message
5167
+ });
5168
+ }
5169
+ }
5170
+ /**
3977
5171
  * Applies `createEntity`: the entity and its descendants, with their uids and components.
3978
5172
  *
3979
5173
  * @param context - The app and the document.
@@ -3984,6 +5178,7 @@ async function createEntity(context, op) {
3984
5178
  const parent = requireParent(context, op.entity.parent);
3985
5179
  checkIndex(op.index, documentSiblings(context, parent, null).length);
3986
5180
  requireFreeUids(context, records);
5181
+ requireValidRecords(records);
3987
5182
  const inside = /* @__PURE__ */ new Set([op.entity.uid]);
3988
5183
  for (const record of op.descendants ?? []) {
3989
5184
  if (record.parent === null || !inside.has(record.parent)) throw new OpFailure(ApplyOpFailureCode.invalidParent, `${record.uid} must be the child of an entity created before it in the same op.`);
@@ -4143,20 +5338,11 @@ async function instantiate(context, op) {
4143
5338
  instance: op.instance
4144
5339
  };
4145
5340
  requireFreeUids(context, [record]);
5341
+ requireValidRecords([record]);
4146
5342
  await buildSubtree(context, [record], parent, op.index);
4147
5343
  context.mirror.recordInstances([record]);
4148
5344
  }
4149
5345
  /**
4150
- * The uid of a referenced entity or component.
4151
- *
4152
- * @param target - The field's value.
4153
- * @returns Its uid, or `null` for anything without one.
4154
- */
4155
- function uidOf(target) {
4156
- const uid = typeof target === "object" && target !== null ? Reflect.get(target, "uid") : null;
4157
- return typeof uid === "string" ? uid : null;
4158
- }
4159
- /**
4160
5346
  * Reads a schema field's current value as JSON, references written as the uids they point at.
4161
5347
  *
4162
5348
  * @param field - The field.
@@ -4170,26 +5356,6 @@ function encodeLive(field, value) {
4170
5356
  });
4171
5357
  }
4172
5358
  /**
4173
- * Narrows JSON to an object. `Array.isArray` does not remove a readonly array from the union, so the
4174
- * discrimination lives here once.
4175
- *
4176
- * @param value - The JSON.
4177
- * @returns The object, or `null` for anything else.
4178
- */
4179
- function asJsonObject(value) {
4180
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
4181
- return value;
4182
- }
4183
- /**
4184
- * Narrows JSON to an array.
4185
- *
4186
- * @param value - The JSON.
4187
- * @returns The array, or `null`.
4188
- */
4189
- function asJsonArray(value) {
4190
- return Array.isArray(value) ? value : null;
4191
- }
4192
- /**
4193
5359
  * Returns JSON with the value at a path set, or removed, leaving the input unchanged.
4194
5360
  *
4195
5361
  * @param container - The JSON the path starts in.
@@ -4213,7 +5379,7 @@ function withValueAt(container, path, value) {
4213
5379
  const object = asJsonObject(container);
4214
5380
  if (object !== null && typeof step === "string") {
4215
5381
  if (rest.length > 0) {
4216
- const next = object[step];
5382
+ const next = Object.hasOwn(object, step) ? object[step] : void 0;
4217
5383
  if (next === void 0) throw invalidPath(path);
4218
5384
  return {
4219
5385
  ...object,
@@ -4253,6 +5419,7 @@ async function setProp(context, op) {
4253
5419
  if (props === null) throw new OpFailure(ApplyOpFailureCode.invalidValue, "props must be an object.");
4254
5420
  rejectIssues(assignProps(component, props, references));
4255
5421
  context.mirror.recordProps(op.component, Object.keys(props));
5422
+ validateFields(component, Object.keys(schema));
4256
5423
  return;
4257
5424
  }
4258
5425
  const field = typeof name === "string" && Object.hasOwn(schema, name) ? schema[name] : void 0;
@@ -4260,6 +5427,7 @@ async function setProp(context, op) {
4260
5427
  if (rest.length === 0 && op.value === void 0) {
4261
5428
  Reflect.set(component, name, field.createDefault());
4262
5429
  context.mirror.recordProp(op.component, name, false);
5430
+ validateFields(component, [name]);
4263
5431
  return;
4264
5432
  }
4265
5433
  const json = rest.length > 0 ? withValueAt(encodeLive(field, Reflect.get(component, name)), rest, op.value) : op.value;
@@ -4270,6 +5438,7 @@ async function setProp(context, op) {
4270
5438
  })));
4271
5439
  Reflect.set(component, name, decoded.value);
4272
5440
  context.mirror.recordProp(op.component, name, true);
5441
+ validateFields(component, [name]);
4273
5442
  }
4274
5443
  /**
4275
5444
  * Fails the op on the first decoding problem: the value the field got is not the document's.
@@ -4343,53 +5512,52 @@ function findOverride(overrides, path, op, added) {
4343
5512
  * Rebuilds an instance root's subtree with an edited override list: the live world has no way to
4344
5513
  * re-apply one override, so the root and its document children are serialized, destroyed and built
4345
5514
  * again from the instanced scene with the new list. References from the rest of the document into
4346
- * the rebuilt subtree are resolved again.
5515
+ * the rebuilt subtree, the ones other instances' overrides hold included, are resolved again.
5516
+ *
5517
+ * The root and the instance roots under it are built with the override lists the document holds, and
5518
+ * the edit applies to the root's: the serializer recomputes a list by diffing the live members with
5519
+ * their scene, which writes an added component as its whole record and drops an override that
5520
+ * matches the scene, so a list read from it no longer follows a default or a prefab the document
5521
+ * leaves to them.
4347
5522
  *
4348
5523
  * @param context - The app and the document.
4349
5524
  * @param uid - The instance root.
4350
- * @param edit - Returns the new override list from the current one.
4351
- * @param documentOverrides - Whether the root and the instance roots under it are rebuilt with the
4352
- * override lists the document holds rather than the ones the serializer recomputes from the live
4353
- * members, which a hot reload that changed a default has left stale.
5525
+ * @param edit - Returns the new override list from the document's current one.
5526
+ * @param keepHashes - Whether the instances keep the hashes they were built against; without them
5527
+ * they build from their scenes' current files without an `IGX-0604` mismatch, as after a reload.
4354
5528
  */
4355
- async function rebuildInstance(context, uid, edit, documentOverrides = false) {
5529
+ async function rebuildInstance(context, uid, edit, keepHashes = true) {
4356
5530
  const index = indexOf(context);
4357
5531
  const root = requireEntity(context, uid);
4358
5532
  const mirror = context.mirror;
4359
5533
  const withDocumentOverrides = (record) => {
4360
- const listed = documentOverrides && record.instance !== void 0 ? mirror.overridesOf(record.uid) : null;
4361
- if (listed === null || record.instance === void 0) return record;
4362
- const { scene, hash } = record.instance;
4363
- const instance = {
5534
+ if (record.instance === void 0) return record;
5535
+ const { scene, hash, overrides: serialized } = record.instance;
5536
+ const listed = mirror.overridesOf(record.uid) ?? serialized ?? [];
5537
+ return withOverrideList(record, {
4364
5538
  scene,
4365
- ...hash === void 0 ? {} : { hash },
5539
+ ...hash === void 0 || !keepHashes ? {} : { hash },
4366
5540
  ...listed.length === 0 ? {} : { overrides: listed }
4367
- };
4368
- return {
4369
- ...record,
4370
- instance
4371
- };
5541
+ }, mirror.rootPathOf(record.uid));
4372
5542
  };
4373
5543
  const found = index.records.get(uid);
4374
5544
  const record = found === void 0 ? void 0 : withDocumentOverrides(found);
4375
5545
  const instance = record?.instance;
4376
5546
  if (record === void 0 || instance === void 0) throw new OpFailure(ApplyOpFailureCode.notAnInstance, `${root.name} (${uid}) has no instance entry.`);
4377
5547
  const overrides = edit(instance.overrides ?? []);
4378
- const top = {
4379
- ...record,
4380
- instance: {
4381
- scene: instance.scene,
4382
- ...instance.hash === void 0 ? {} : { hash: instance.hash },
4383
- ...overrides.length === 0 ? {} : { overrides }
4384
- }
4385
- };
5548
+ const top = withOverrideList(record, {
5549
+ scene: instance.scene,
5550
+ ...instance.hash === void 0 ? {} : { hash: instance.hash },
5551
+ ...overrides.length === 0 ? {} : { overrides }
5552
+ }, mirror.rootPathOf(uid));
4386
5553
  const inside = /* @__PURE__ */ new Set([uid]);
4387
5554
  const records = [top];
4388
5555
  for (const candidate of index.file.entities) if (candidate.parent !== null && inside.has(candidate.parent)) {
4389
5556
  inside.add(candidate.uid);
4390
5557
  records.push(withDocumentOverrides(candidate));
4391
5558
  }
4392
- const insideComponents = new Set(records.flatMap((entry_) => (entry_.components ?? []).map((component) => component.uid)));
5559
+ const insideComponents = /* @__PURE__ */ new Set([...records.flatMap((entry_) => (entry_.components ?? []).map((component) => component.uid)), ...[...instance.overrides ?? [], ...records.flatMap((entry_) => entry_.instance?.overrides ?? [])].flatMap((override) => addedUid(override) ?? [])]);
5560
+ const held = heldByMembers(context.app, context.mirror, index, root, inside, insideComponents);
4393
5561
  const parent = root.parent;
4394
5562
  const at = documentSiblings(context, parent, null).indexOf(root);
4395
5563
  root.destroyImmediate();
@@ -4398,13 +5566,33 @@ async function rebuildInstance(context, uid, edit, documentOverrides = false) {
4398
5566
  mirror.recordInstances(records);
4399
5567
  const references = context.mirror.decoder();
4400
5568
  const rebuilt = indexOf(context);
5569
+ const issues = [];
5570
+ const repoint = (live, props, decoder = references) => {
5571
+ const fields = new Set(Object.entries(props ?? {}).filter(([, value]) => pointsInto(value, inside, insideComponents)).map(([name]) => name));
5572
+ if (live === void 0 || live.isDestroyed || props === void 0 || fields.size === 0) return;
5573
+ const reported = new Set(propIssues(live, props, {
5574
+ entity: (target) => decoder.entity(target),
5575
+ component: (target) => insideComponents.has(target) ? target : decoder.component(target),
5576
+ asset: (address, type) => decoder.asset(address, type)
5577
+ }, fields).map((issue) => issue.message));
5578
+ issues.push(...assignProps(live, props, decoder, fields).filter((issue) => !reported.has(issue.message)));
5579
+ };
4401
5580
  for (const outside of index.file.entities) {
4402
5581
  if (inside.has(outside.uid)) continue;
4403
- for (const component of outside.components ?? []) {
4404
- const live = rebuilt.components.get(component.uid);
4405
- if (live !== void 0 && pointsInto(component.props, inside, insideComponents)) assignProps(live, component.props ?? {}, references);
5582
+ for (const component of outside.components ?? []) repoint(rebuilt.components.get(component.uid), component.props);
5583
+ for (const override of mirror.overridesOf(outside.uid) ?? []) {
5584
+ const added = addedUid(override);
5585
+ const props = asJsonObject(asJsonObject(override.value)?.["props"]);
5586
+ if (added !== null && props !== null) repoint(rebuilt.added.get(added), props);
4406
5587
  }
4407
5588
  }
5589
+ const keep = {
5590
+ entity: (target) => (inside.has(target) ? null : held.entities.get(target)) ?? references.entity(target),
5591
+ component: (target) => (insideComponents.has(target) ? null : held.components.get(target)) ?? references.component(target),
5592
+ asset: (address, type) => references.asset(address, type)
5593
+ };
5594
+ for (const [component, props] of held.fields) repoint(component, props, keep);
5595
+ reportBuildIssues(context, issues);
4408
5596
  }
4409
5597
  /**
4410
5598
  * Rebuilds one instance root from its scene asset's current value, keeping its uid, its record
@@ -4415,38 +5603,19 @@ async function rebuildInstance(context, uid, edit, documentOverrides = false) {
4415
5603
  * @param app - The scene view's app.
4416
5604
  * @param mirror - The open document.
4417
5605
  * @param uid - The instance root.
4418
- * @param documentOverrides - Whether to rebuild with the override lists the document holds rather
4419
- * than the ones the live members read as; `true` after a hot reload changed a default.
4420
5606
  * @throws OpFailure when the uid names no document entity or one without an instance entry.
4421
5607
  */
4422
- async function reloadInstance(app, mirror, uid, documentOverrides = false) {
5608
+ async function reloadInstance(app, mirror, uid) {
4423
5609
  try {
4424
5610
  await rebuildInstance({
4425
5611
  app,
4426
5612
  mirror
4427
- }, uid, (overrides) => overrides, documentOverrides);
5613
+ }, uid, (overrides) => overrides, false);
4428
5614
  } finally {
4429
5615
  mirror.invalidate();
4430
5616
  }
4431
5617
  }
4432
5618
  /**
4433
- * Tells whether JSON references an entity or component of a set.
4434
- *
4435
- * @param value - The JSON.
4436
- * @param entities - The entity uids.
4437
- * @param components - The component uids.
4438
- * @returns True when a `$entity` or `$component` names one of them.
4439
- */
4440
- function pointsInto(value, entities, components) {
4441
- const array = asJsonArray(value);
4442
- if (array !== null) return array.some((item) => pointsInto(item, entities, components));
4443
- const object = asJsonObject(value);
4444
- if (object === null) return false;
4445
- const entity = object["$entity"];
4446
- const component = object["$component"];
4447
- return typeof entity === "string" && entities.has(entity) || typeof component === "string" && components.has(component) || Object.values(object).some((item) => pointsInto(item, entities, components));
4448
- }
4449
- /**
4450
5619
  * Applies `setOverride`: replaces the override with the same identity, or inserts it.
4451
5620
  *
4452
5621
  * @param context - The app and the document.
@@ -4484,6 +5653,45 @@ async function removeOverride(context, op) {
4484
5653
  });
4485
5654
  }
4486
5655
  //#endregion
5656
+ //#region src/scene/sample-animation.ts
5657
+ /**
5658
+ * `sampleAnimation`: the scene view poses an entity's `Animator` at one point of one state, through
5659
+ * the engine's `Animator.sample` (ADR-0028, amendment 2026-10-20). The host depends on core only, so
5660
+ * it finds the `Animator` by its type id and calls `sample` by shape.
5661
+ */
5662
+ /** The type id `@ignifx/3d` registers its `Animator` under. */
5663
+ const ANIMATOR_TYPE_ID = "ignifx/Animator";
5664
+ /**
5665
+ * Answers `sampleAnimation` on the open document.
5666
+ *
5667
+ * @param app - The scene view's app.
5668
+ * @param mirror - The open document.
5669
+ * @param params - The received `params`.
5670
+ * @returns Whether the pose was written.
5671
+ * @throws InvalidParamsError for malformed params, an entity the document lacks or one without an
5672
+ * `Animator`, and any `IgnifxError` the engine throws, whose code it carries as `data.code`.
5673
+ */
5674
+ function sampleAnimation(app, mirror, params) {
5675
+ if (!isSampleAnimationParams(params)) throw new InvalidParamsError(`sampleAnimation takes { entity: uid, state: string, normalizedTime: number, parameters?: { [name]: number | boolean } }, with names of at most ${String(256)} characters and at most ${String(64)} parameters.`);
5676
+ const entity = mirror.index()?.entities.get(params.entity);
5677
+ if (entity === void 0) throw new InvalidParamsError(`sampleAnimation names ${params.entity}, which is not an entity of the open scene.`);
5678
+ const type = componentTypeOf(app, ANIMATOR_TYPE_ID);
5679
+ const animator = type === null ? null : entity.getComponent(type);
5680
+ const sample = animator === null ? void 0 : Reflect.get(animator, "sample");
5681
+ if (animator === null || typeof sample !== "function") throw new InvalidParamsError(`The entity ${params.entity} has no Animator to sample.`);
5682
+ const options = params.parameters === void 0 ? [] : [{ parameters: params.parameters }];
5683
+ try {
5684
+ return { posed: Reflect.apply(sample, animator, [
5685
+ params.state,
5686
+ params.normalizedTime,
5687
+ ...options
5688
+ ]) === true };
5689
+ } catch (error) {
5690
+ if (isIgnifxError(error)) throw new InvalidParamsError(error.message, { code: error.code });
5691
+ throw error;
5692
+ }
5693
+ }
5694
+ //#endregion
4487
5695
  //#region src/scene/schemas.ts
4488
5696
  /**
4489
5697
  * `getSchemas` and `schemasChanged`: every registered component's schema, as the inspector reads
@@ -4503,7 +5711,8 @@ const COMPONENTS_FORMAT = "components";
4503
5711
  * keeps core's title and summary; any other is titled from its type id. The host's own classes are left out: they are not the
4504
5712
  * document's. `ignifx/Transform` is described with core's `transformSchema()` and carries
4505
5713
  * `builtIn`: its fields are each entity's `transform` block, edited with `setTransform`, and it is
4506
- * never added or removed.
5714
+ * never added or removed. Each component also carries `extends` (engine ask E44): the registered
5715
+ * components its class derives from, which count as present for a `requires` entry.
4507
5716
  *
4508
5717
  * The set is read from the live registry each time, so a hot reload that adds a field or a script
4509
5718
  * shows in the next `schemasChanged`.
@@ -4523,409 +5732,149 @@ function schemaSet(app, hidden) {
4523
5732
  const schema = type === Transform ? transformSchema() : registry.describe(type).schema ?? {};
4524
5733
  schemas[typeId] = {
4525
5734
  ...description,
5735
+ extends: registeredAncestors(registry, type),
4526
5736
  propsSchema: toJsonSchema(schema)
4527
5737
  };
4528
5738
  }
4529
5739
  for (const [id, description] of Object.entries(core)) if (description.format !== COMPONENTS_FORMAT) schemas[id] = description;
4530
5740
  return { schemas };
4531
5741
  }
4532
- //#endregion
4533
- //#region src/scene/screenshot.ts
4534
- /** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */
4535
- const BASE64_CHUNK = 32768;
4536
- /**
4537
- * Encodes bytes as base64.
4538
- *
4539
- * @param bytes - The bytes.
4540
- * @returns The base64 text.
4541
- */
4542
- function toBase64(bytes) {
4543
- let binary = "";
4544
- for (let start = 0; start < bytes.length; start += BASE64_CHUNK) binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));
4545
- return btoa(binary);
4546
- }
4547
- /**
4548
- * Scales a captured frame to a size and encodes it as a data URL.
4549
- *
4550
- * @param capture - The frame, RGBA8 with the top row first.
4551
- * @param size - The image size.
4552
- * @param format - `"png"` or `"jpeg"`.
4553
- * @param quality - The JPEG quality, from 0 to 1; ignored for PNG.
4554
- * @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.
4555
- * @throws Error when the browser has no 2D canvas context.
4556
- */
4557
- async function encodeCapture(capture, size, format, quality) {
4558
- const source = new OffscreenCanvas(capture.width, capture.height);
4559
- const sourceContext = source.getContext("2d");
4560
- const target = new OffscreenCanvas(size.width, size.height);
4561
- const targetContext = target.getContext("2d");
4562
- if (sourceContext === null || targetContext === null) throw new Error("This browser has no 2D canvas to encode the screenshot with.");
4563
- sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);
4564
- targetContext.imageSmoothingQuality = "high";
4565
- targetContext.drawImage(source, 0, 0, size.width, size.height);
4566
- const type = format === "png" ? "image/png" : "image/jpeg";
4567
- const blob = await target.convertToBlob(format === "png" ? { type } : {
4568
- type,
4569
- quality
4570
- });
4571
- return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;
4572
- }
4573
- //#endregion
4574
- //#region src/scene/settings.ts
4575
- /**
4576
- * `describeSettings`: the project's settings sections, as the editor's settings panel reads them,
4577
- * and the values the app resolved for them.
4578
- */
4579
- /**
4580
- * Copies a value made of JSON data, leaving out what JSON cannot carry.
4581
- *
4582
- * @param value - The value.
4583
- * @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a
4584
- * non-finite number.
4585
- */
4586
- function jsonCopy(value) {
4587
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4588
- if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
4589
- if (Array.isArray(value)) return value.map((item) => jsonCopy(item) ?? null);
4590
- if (typeof value === "object") return jsonObjectCopy(value);
4591
- }
4592
- /**
4593
- * Copies an object's own enumerable members with {@link jsonCopy}.
4594
- *
4595
- * @param value - The object.
4596
- * @returns The copy.
4597
- */
4598
- function jsonObjectCopy(value) {
4599
- const copy = {};
4600
- for (const [key, member] of Object.entries(value)) {
4601
- const converted = jsonCopy(member);
4602
- if (converted !== void 0) copy[key] = converted;
4603
- }
4604
- return copy;
4605
- }
4606
- /**
4607
- * Tells whether a JSON value is an object.
4608
- *
4609
- * @param value - The value.
4610
- * @returns True for an object that is not an array.
4611
- */
4612
- function isObject(value) {
4613
- return typeof value === "object" && value !== null && !Array.isArray(value);
4614
- }
4615
- /**
4616
- * Describes every settings section the app registered with core's `describeSettings`, each with
4617
- * its JSON Schema from `settingsJsonSchema` as `propsSchema`, and copies the value the app resolved
4618
- * for each section.
4619
- *
4620
- * @remarks
4621
- * Settings are held in the settings form (`{ x, y, z }` for a vector), which is plain data, so a
4622
- * section's value is copied member by member; a member JSON cannot carry is left out. The answer is
4623
- * read from the app each time and sent only on request.
4624
- *
4625
- * @param app - The scene view's app.
4626
- * @returns The sections and their values, keyed by section name in registration order.
4627
- */
4628
- function settingsSet(app) {
4629
- const described = describeSettings(app);
4630
- const properties = settingsJsonSchema(app)["properties"];
4631
- const sections = {};
4632
- const values = {};
4633
- for (const [name, description] of Object.entries(described)) {
4634
- const propsSchema = isObject(properties) ? properties[name] : void 0;
4635
- sections[name] = isObject(propsSchema) ? {
4636
- ...description,
4637
- propsSchema
4638
- } : description;
4639
- const value = app.settings.section(name);
4640
- values[name] = typeof value === "object" && value !== null ? jsonObjectCopy(value) : {};
4641
- }
4642
- return {
4643
- sections,
4644
- values
4645
- };
4646
- }
4647
- //#endregion
4648
- //#region src/scene/view-math.ts
4649
- /**
4650
- * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and
4651
- * plane point a `pick` answers with, the `screenshot` size rule, the transform the drag
4652
- * notifications carry, and gizmo snapping. Each is a pure function, so the headless tests check it
4653
- * directly.
4654
- */
4655
- /**
4656
- * Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its
4657
- * backing pixels.
4658
- *
4659
- * @param surface - The canvas.
4660
- * @returns The sizes.
4661
- */
4662
- function viewSurfaceOf(surface) {
4663
- const clientWidth = Reflect.get(surface, "clientWidth");
4664
- const clientHeight = Reflect.get(surface, "clientHeight");
4665
- return {
4666
- width: surface.width,
4667
- height: surface.height,
4668
- clientWidth: typeof clientWidth === "number" && clientWidth > 0 ? clientWidth : surface.width,
4669
- clientHeight: typeof clientHeight === "number" && clientHeight > 0 ? clientHeight : surface.height
4670
- };
4671
- }
4672
- /**
4673
- * Converts a `pick` point to the backing-store pixels `app.renderer.pickAsync` takes (protocol 0.3,
4674
- * "The pick unit rule"; engine ask E3). This is the host's one conversion: the renderer converts
4675
- * on to the CSS pixels Lite's picker wants.
4676
- *
4677
- * @param params - The point and its unit.
4678
- * @param surface - The canvas's sizes.
4679
- * @returns The point in backing-store pixels, or `null` when it is outside the canvas (a miss).
4680
- */
4681
- function toBackingPixels(params, surface) {
4682
- const x = params.unit === PickUnit.backing ? params.x : params.x * surface.width / surface.clientWidth;
4683
- const y = params.unit === PickUnit.backing ? params.y : params.y * surface.height / surface.clientHeight;
4684
- if (x < 0 || y < 0 || x >= surface.width || y >= surface.height) return null;
4685
- return {
4686
- x,
4687
- y
4688
- };
4689
- }
4690
- /**
4691
- * Turns a camera ray into a `pick` answer's `ray` and `plane` members (protocol 0.3, additive): the
4692
- * ray as it is, and the point where it meets the 2D world plane `z = 0`. The plane point is
4693
- * computed before rounding, and its `z` is exactly `0`.
4694
- *
4695
- * @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.
4696
- * @returns The members, every number rounded with `canonicalizeNumber`.
4697
- */
4698
- function pickRayMembers(ray) {
4699
- const c = canonicalizeNumber;
4700
- const { origin, direction } = ray;
4701
- const members = { ray: {
4702
- origin: [
4703
- c(origin.x),
4704
- c(origin.y),
4705
- c(origin.z)
4706
- ],
4707
- direction: [
4708
- c(direction.x),
4709
- c(direction.y),
4710
- c(direction.z)
4711
- ]
4712
- } };
4713
- const t = direction.z === 0 ? NaN : -origin.z / direction.z;
4714
- if (!Number.isFinite(t) || t < 0) return members;
4715
- return {
4716
- ...members,
4717
- plane: [
4718
- c(origin.x + direction.x * t),
4719
- c(origin.y + direction.y * t),
4720
- 0
4721
- ]
4722
- };
4723
- }
4724
- /**
4725
- * Rounds an image side and keeps it from 1 to {@link SCREENSHOT_MAX_SIZE}.
4726
- *
4727
- * @param side - The side, in pixels.
4728
- * @returns The whole side in range.
4729
- */
4730
- function clampSide(side) {
4731
- return Math.min(SCREENSHOT_MAX_SIZE, Math.max(1, Math.round(side)));
4732
- }
4733
- /**
4734
- * The size of a `screenshot`: the request's, or the view's backing size scaled down, keeping its
4735
- * aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.
4736
- *
4737
- * @param params - The request; its sizes are already checked to be 1 to 2048.
4738
- * @param view - The captured frame's size.
4739
- * @returns The image size, each side at least 1 and at most 2048.
4740
- */
4741
- function screenshotSize(params, view) {
4742
- const aspect = view.height > 0 ? view.width / view.height : 1;
4743
- const { width, height } = params;
4744
- if (width !== void 0 && height !== void 0) return {
4745
- width,
4746
- height
4747
- };
4748
- if (width !== void 0) return {
4749
- width,
4750
- height: clampSide(width / aspect)
4751
- };
4752
- if (height !== void 0) return {
4753
- width: clampSide(height * aspect),
4754
- height
4755
- };
4756
- const fit = Math.min(1, SCREENSHOT_MAX_SIZE / Math.max(view.width, view.height, 1));
4757
- return {
4758
- width: clampSide(view.width * fit),
4759
- height: clampSide(view.height * fit)
4760
- };
4761
- }
4762
- /**
4763
- * Reads an entity's local transform as the scene file writes it, numbers canonicalized.
4764
- *
4765
- * @param entity - The entity.
4766
- * @returns The transform.
4767
- */
4768
- function readLocalTransform(entity) {
4769
- const { localPosition: p, localRotation: r, localScale: s } = entity.transform;
4770
- const c = canonicalizeNumber;
4771
- return {
4772
- position: [
4773
- c(p.x),
4774
- c(p.y),
4775
- c(p.z)
4776
- ],
4777
- rotation: [
4778
- c(r.x),
4779
- c(r.y),
4780
- c(r.z),
4781
- c(r.w)
4782
- ],
4783
- scale: [
4784
- c(s.x),
4785
- c(s.y),
4786
- c(s.z)
4787
- ]
4788
- };
5742
+ /**
5743
+ * The type ids of the registered component classes a class derives from, nearest first.
5744
+ *
5745
+ * @remarks
5746
+ * `Entity.getComponent`, and so `addComponent`'s `requires` check, matches a class against the
5747
+ * attached component's ancestor chain, by class identity. An ancestor is listed when it is
5748
+ * registered under its own `static typeId`, the id `requires` names it by; an intermediate class
5749
+ * that only inherits a registered parent's `typeId` is not that registration and is left out.
5750
+ *
5751
+ * @param registry - The app's component registry.
5752
+ * @param type - The described class.
5753
+ * @returns The ancestors' type ids, the class itself excluded; empty when none is registered.
5754
+ */
5755
+ function registeredAncestors(registry, type) {
5756
+ const ids = [];
5757
+ const ancestors = registry.describe(type).ancestors;
5758
+ for (let index = 1; index < ancestors.length; index += 1) {
5759
+ const ancestor = ancestors[index];
5760
+ if (ancestor !== void 0 && registry.isRegistered(ancestor)) ids.push(registry.requireTypeId(ancestor));
5761
+ }
5762
+ return ids;
4789
5763
  }
5764
+ //#endregion
5765
+ //#region src/scene/screenshot.ts
5766
+ /** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */
5767
+ const BASE64_CHUNK = 32768;
4790
5768
  /**
4791
- * Tells whether two transforms are equal number for number.
5769
+ * Encodes bytes as base64.
4792
5770
  *
4793
- * @param a - One transform.
4794
- * @param b - The other.
4795
- * @returns True when every channel matches.
5771
+ * @param bytes - The bytes.
5772
+ * @returns The base64 text.
4796
5773
  */
4797
- function sameTransform(a, b) {
4798
- return JSON.stringify(a) === JSON.stringify(b);
5774
+ function toBase64(bytes) {
5775
+ let binary = "";
5776
+ for (let start = 0; start < bytes.length; start += BASE64_CHUNK) binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));
5777
+ return btoa(binary);
4799
5778
  }
4800
5779
  /**
4801
- * Rounds a value to a step; a step of 0 leaves it alone.
5780
+ * Scales a captured frame to a size and encodes it as a data URL.
5781
+ *
5782
+ * @param capture - The frame, RGBA8 with the top row first.
5783
+ * @param size - The image size.
5784
+ * @param format - `"png"` or `"jpeg"`.
5785
+ * @param quality - The JPEG quality, from 0 to 1; ignored for PNG.
5786
+ * @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.
5787
+ * @throws Error when the browser has no 2D canvas context.
5788
+ */
5789
+ async function encodeCapture(capture, size, format, quality) {
5790
+ const source = new OffscreenCanvas(capture.width, capture.height);
5791
+ const sourceContext = source.getContext("2d");
5792
+ const target = new OffscreenCanvas(size.width, size.height);
5793
+ const targetContext = target.getContext("2d");
5794
+ if (sourceContext === null || targetContext === null) throw new Error("This browser has no 2D canvas to encode the screenshot with.");
5795
+ sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);
5796
+ targetContext.imageSmoothingQuality = "high";
5797
+ targetContext.drawImage(source, 0, 0, size.width, size.height);
5798
+ const type = format === "png" ? "image/png" : "image/jpeg";
5799
+ const blob = await target.convertToBlob(format === "png" ? { type } : {
5800
+ type,
5801
+ quality
5802
+ });
5803
+ return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;
5804
+ }
5805
+ //#endregion
5806
+ //#region src/scene/settings.ts
5807
+ /**
5808
+ * `describeSettings`: the project's settings sections, as the editor's settings panel reads them,
5809
+ * and the values the app resolved for them.
5810
+ */
5811
+ /**
5812
+ * Copies a value made of JSON data, leaving out what JSON cannot carry.
4802
5813
  *
4803
5814
  * @param value - The value.
4804
- * @param step - The step.
4805
- * @returns The snapped value.
5815
+ * @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a
5816
+ * non-finite number.
4806
5817
  */
4807
- function snapTo(value, step) {
4808
- return step > 0 ? Math.round(value / step) * step : value;
5818
+ function jsonCopy(value) {
5819
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
5820
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
5821
+ if (Array.isArray(value)) return value.map((item) => jsonCopy(item) ?? null);
5822
+ if (typeof value === "object") return jsonObjectCopy(value);
4809
5823
  }
4810
5824
  /**
4811
- * Snaps a gizmo drag after Lite has applied each move (S0.2 §3.4, post-correction). The raw, unsnapped
4812
- * value is kept apart from the node, so the snapped steps do not accumulate rounding.
5825
+ * Copies an object's own enumerable members with {@link jsonCopy}.
5826
+ *
5827
+ * @param value - The object.
5828
+ * @returns The copy.
4813
5829
  */
4814
- var DragSnapper = class {
4815
- #mode;
4816
- #snap;
4817
- #start;
4818
- #raw;
4819
- #written;
4820
- /**
4821
- * Starts snapping one drag.
4822
- *
4823
- * @param mode - The drag's mode.
4824
- * @param snap - The snapping steps.
4825
- * @param entity - The dragged entity, at drag start.
4826
- */
4827
- constructor(mode, snap, entity) {
4828
- this.#mode = mode;
4829
- this.#snap = snap;
4830
- this.#start = this.#read(entity);
4831
- this.#raw = [...this.#start];
4832
- this.#written = [...this.#start];
4833
- }
4834
- /**
4835
- * Folds the move Lite just wrote into the raw value and writes the snapped value back.
4836
- *
4837
- * @param entity - The dragged entity.
4838
- */
4839
- apply(entity) {
4840
- const now = this.#read(entity);
4841
- if (this.#mode === "rotate") {
4842
- this.#applyRotation(entity, now);
4843
- return;
4844
- }
4845
- const step = this.#mode === "translate" ? this.#snap.translate : this.#snap.scale;
4846
- if (step <= 0) return;
4847
- this.#raw = this.#raw.map((value, index) => value + (now[index] ?? 0) - (this.#written[index] ?? 0));
4848
- const snapped = this.#raw.map((value, index) => (this.#start[index] ?? 0) + snapTo(value - (this.#start[index] ?? 0), step));
4849
- (this.#mode === "translate" ? entity.transform.localPosition : entity.transform.localScale).set(snapped[0] ?? 0, snapped[1] ?? 0, snapped[2] ?? 0);
4850
- this.#written = snapped;
4851
- }
4852
- /**
4853
- * Snaps a rotation drag: a ring turns about one axis, so the turn since drag start is one angle,
4854
- * which is rounded to the step.
4855
- *
4856
- * @param entity - The dragged entity.
4857
- * @param now - Its rotation now, as Lite wrote it.
4858
- */
4859
- #applyRotation(entity, now) {
4860
- const step = this.#snap.rotate;
4861
- if (step <= 0) return;
4862
- this.#raw = multiply(multiply(now, conjugate(this.#written)), this.#raw);
4863
- const turn = multiply(this.#raw, conjugate(this.#start));
4864
- const sine = Math.hypot(turn[0] ?? 0, turn[1] ?? 0, turn[2] ?? 0);
4865
- if (sine < 1e-9) return;
4866
- const half = snapTo(2 * Math.atan2(sine, turn[3] ?? 1) * 180 / Math.PI, step) * Math.PI / 180 / 2;
4867
- const scale = Math.sin(half) / sine;
4868
- const result = multiply([
4869
- (turn[0] ?? 0) * scale,
4870
- (turn[1] ?? 0) * scale,
4871
- (turn[2] ?? 0) * scale,
4872
- Math.cos(half)
4873
- ], this.#start);
4874
- entity.transform.localRotation.set(result[0] ?? 0, result[1] ?? 0, result[2] ?? 0, result[3] ?? 1);
4875
- this.#written = result;
4876
- }
4877
- /**
4878
- * Reads the channels this drag moves.
4879
- *
4880
- * @param entity - The entity.
4881
- * @returns Position, scale, or the rotation quaternion.
4882
- */
4883
- #read(entity) {
4884
- const t = entity.transform;
4885
- if (this.#mode === "rotate") return [
4886
- t.localRotation.x,
4887
- t.localRotation.y,
4888
- t.localRotation.z,
4889
- t.localRotation.w
4890
- ];
4891
- const v = this.#mode === "translate" ? t.localPosition : t.localScale;
4892
- return [
4893
- v.x,
4894
- v.y,
4895
- v.z
4896
- ];
5830
+ function jsonObjectCopy(value) {
5831
+ const entries = [];
5832
+ for (const [key, member] of Object.entries(value)) {
5833
+ const converted = jsonCopy(member);
5834
+ if (converted !== void 0) entries.push([key, converted]);
4897
5835
  }
4898
- };
5836
+ return Object.fromEntries(entries);
5837
+ }
4899
5838
  /**
4900
- * Multiplies two quaternions, `a · b`.
5839
+ * Tells whether a JSON value is an object.
4901
5840
  *
4902
- * @param a - The left operand, `[x, y, z, w]`.
4903
- * @param b - The right operand.
4904
- * @returns The product.
5841
+ * @param value - The value.
5842
+ * @returns True for an object that is not an array.
4905
5843
  */
4906
- function multiply(a, b) {
4907
- const [ax = 0, ay = 0, az = 0, aw = 1] = a;
4908
- const [bx = 0, by = 0, bz = 0, bw = 1] = b;
4909
- return [
4910
- aw * bx + ax * bw + ay * bz - az * by,
4911
- aw * by - ax * bz + ay * bw + az * bx,
4912
- aw * bz + ax * by - ay * bx + az * bw,
4913
- aw * bw - ax * bx - ay * by - az * bz
4914
- ];
5844
+ function isObject(value) {
5845
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4915
5846
  }
4916
5847
  /**
4917
- * A unit quaternion's inverse.
5848
+ * Describes every settings section the app registered with core's `describeSettings`, each with
5849
+ * its JSON Schema from `settingsJsonSchema` as `propsSchema`, and copies the value the app resolved
5850
+ * for each section.
4918
5851
  *
4919
- * @param q - The quaternion.
4920
- * @returns Its conjugate.
5852
+ * @remarks
5853
+ * Settings are held in the settings form (`{ x, y, z }` for a vector), which is plain data, so a
5854
+ * section's value is copied member by member; a member JSON cannot carry is left out. The answer is
5855
+ * read from the app each time and sent only on request.
5856
+ *
5857
+ * @param app - The scene view's app.
5858
+ * @returns The sections and their values, keyed by section name in registration order.
4921
5859
  */
4922
- function conjugate(q) {
4923
- return [
4924
- -(q[0] ?? 0),
4925
- -(q[1] ?? 0),
4926
- -(q[2] ?? 0),
4927
- q[3] ?? 1
4928
- ];
5860
+ function settingsSet(app) {
5861
+ const described = describeSettings(app);
5862
+ const properties = settingsJsonSchema(app)["properties"];
5863
+ const sections = {};
5864
+ const values = {};
5865
+ for (const [name, description] of Object.entries(described)) {
5866
+ const propsSchema = isObject(properties) ? properties[name] : void 0;
5867
+ sections[name] = isObject(propsSchema) ? {
5868
+ ...description,
5869
+ propsSchema
5870
+ } : description;
5871
+ const value = app.settings.section(name);
5872
+ values[name] = typeof value === "object" && value !== null ? jsonObjectCopy(value) : {};
5873
+ }
5874
+ return {
5875
+ sections,
5876
+ values
5877
+ };
4929
5878
  }
4930
5879
  //#endregion
4931
5880
  //#region src/scene/scene-host.ts
@@ -4969,7 +5918,7 @@ var SceneHost = class {
4969
5918
  space: GizmoSpace.world,
4970
5919
  snap: null
4971
5920
  };
4972
- #drag = null;
5921
+ #drag;
4973
5922
  #started = false;
4974
5923
  /** The field defaults seen at start and after each hot reload, from {@link SceneHost.start} on. */
4975
5924
  #defaults = null;
@@ -4985,6 +5934,7 @@ var SceneHost = class {
4985
5934
  */
4986
5935
  constructor(options) {
4987
5936
  this.#notify = options.notify;
5937
+ this.#drag = new GizmoDragRelay(options.notify);
4988
5938
  const has = (capability) => options.capabilities.includes(capability);
4989
5939
  this.#hasViewMode2D = has(HostCapability.viewMode2d);
4990
5940
  const methods = /* @__PURE__ */ new Map([
@@ -4997,7 +5947,10 @@ var SceneHost = class {
4997
5947
  [SceneMethod.pick, async (params) => this.#pick(params)],
4998
5948
  [SceneMethod.getSchemas, () => this.#getSchemas()],
4999
5949
  [SceneMethod.describeSettings, () => this.#describeSettings()],
5000
- [SceneMethod.setViewMode, (params) => this.#setViewMode(params)]
5950
+ [SceneMethod.setViewMode, (params) => this.#setViewMode(params)],
5951
+ [SceneMethod.setAnimateMaterials, (params) => this.#setAnimateMaterials(params)],
5952
+ [SceneMethod.getColliderOutlines, (params) => this.#getColliderOutlines(params)],
5953
+ [SceneMethod.sampleAnimation, (params) => this.#sampleAnimation(params)]
5001
5954
  ]);
5002
5955
  if (has(HostCapability.gizmos)) methods.set(SceneMethod.setGizmo, (params) => this.#setGizmo(params));
5003
5956
  if (has(HostCapability.screenshot)) methods.set(SceneMethod.screenshot, async (params) => this.#screenshot(params));
@@ -5074,7 +6027,17 @@ var SceneHost = class {
5074
6027
  this.#view = view;
5075
6028
  this.#applyGizmo();
5076
6029
  const onClick = (click) => {
5077
- this.#onClick(click);
6030
+ this.#onClick(click).catch((error) => {
6031
+ const params = {
6032
+ code: isIgnifxError(error) ? error.code : null,
6033
+ message: clipHostText(`Selecting what a click in the view hit: ${messageOf(error)}`),
6034
+ data: {
6035
+ x: click.x,
6036
+ y: click.y
6037
+ }
6038
+ };
6039
+ this.#notify(SceneNotification.hostError, params);
6040
+ });
5078
6041
  };
5079
6042
  for (const camera of [this.#camera, this.#camera2D]) if (camera !== null) {
5080
6043
  camera.claims = view;
@@ -5117,7 +6080,7 @@ var SceneHost = class {
5117
6080
  return this.#serial(async () => {
5118
6081
  const index = handle.type === "scene" ? mirror.index() : null;
5119
6082
  const roots = index === null ? [] : instancesOf(app, index, address);
5120
- const entities = await this.#rebuildInstances(app, mirror, roots, address, { address }, false);
6083
+ const entities = await this.#rebuildInstances(app, mirror, roots, address, { address });
5121
6084
  this.#setSelection(this.#selection);
5122
6085
  const params = {
5123
6086
  address,
@@ -5137,18 +6100,17 @@ var SceneHost = class {
5137
6100
  * @param roots - The roots' uids, none inside another.
5138
6101
  * @param cause - What the rebuild follows, for the error's message.
5139
6102
  * @param data - What the error's `data` carries besides the root's uid.
5140
- * @param documentOverrides - Whether to rebuild with the document's override lists.
5141
6103
  * @returns The roots rebuilt.
5142
6104
  */
5143
- async #rebuildInstances(app, mirror, roots, cause, data, documentOverrides) {
6105
+ async #rebuildInstances(app, mirror, roots, cause, data) {
5144
6106
  const rebuilt = [];
5145
6107
  for (const uid of roots) try {
5146
- await reloadInstance(app, mirror, uid, documentOverrides);
6108
+ await reloadInstance(app, mirror, uid);
5147
6109
  rebuilt.push(uid);
5148
6110
  } catch (error) {
5149
6111
  const params = {
5150
6112
  code: isIgnifxError(error) ? error.code : null,
5151
- message: `Rebuilding ${uid} from ${cause}: ${messageOf(error)}`,
6113
+ message: clipHostText(`Rebuilding ${uid} from ${cause}: ${messageOf(error)}`),
5152
6114
  data: {
5153
6115
  ...data,
5154
6116
  entity: uid
@@ -5161,7 +6123,8 @@ var SceneHost = class {
5161
6123
  /**
5162
6124
  * Gives the open document the defaults a hot reload changed, where it leaves them out (engine ask
5163
6125
  * E25): each document component's omitted fields take the new default, then each prefab instance
5164
- * whose members hold a changed type is rebuilt from its prefab with its overrides.
6126
+ * whose members hold a changed type is rebuilt from its prefab with its overrides. A component
6127
+ * that throws while taking a default is a `hostError`, and the rest still runs.
5165
6128
  *
5166
6129
  * @param changed - The changed fields, by type id.
5167
6130
  */
@@ -5170,14 +6133,25 @@ var SceneHost = class {
5170
6133
  const mirror = this.#mirror;
5171
6134
  const index = mirror?.index() ?? null;
5172
6135
  if (app === null || mirror === null || index === null) return;
5173
- applyDefaults(app, mirror, index, changed);
6136
+ applyDefaults(app, mirror, index, changed, (component, typeId, error) => {
6137
+ const params = {
6138
+ code: isIgnifxError(error) ? error.code : null,
6139
+ message: clipHostText(`Applying the new defaults of ${typeId} to ${component.uid}: ${messageOf(error)}`),
6140
+ data: {
6141
+ typeIds: [typeId],
6142
+ entity: component.entity.uid,
6143
+ component: typeId
6144
+ }
6145
+ };
6146
+ this.#notify(SceneNotification.hostError, params);
6147
+ });
5174
6148
  mirror.invalidate();
5175
6149
  const rebuilt = mirror.index();
5176
- const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, rebuilt, changed));
6150
+ const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, mirror, rebuilt, changed));
5177
6151
  if (roots.length > 0) {
5178
6152
  const typeIds = [...changed.keys()];
5179
6153
  const cause = `the new defaults of ${typeIds.join(", ")}`;
5180
- await this.#rebuildInstances(app, mirror, roots, cause, { typeIds }, true);
6154
+ await this.#rebuildInstances(app, mirror, roots, cause, { typeIds });
5181
6155
  this.#setSelection(this.#selection);
5182
6156
  }
5183
6157
  }
@@ -5237,7 +6211,7 @@ var SceneHost = class {
5237
6211
  * `applyOps`: one command's ops, in order.
5238
6212
  *
5239
6213
  * @param params - `{ ops, commandName, commandId }`.
5240
- * @returns How many applied, and the failures.
6214
+ * @returns How many applied, the failures, and the build problems.
5241
6215
  */
5242
6216
  async #applyOps(params) {
5243
6217
  const mirror = this.#requireMirror(SceneMethod.applyOps);
@@ -5383,6 +6357,44 @@ var SceneHost = class {
5383
6357
  return settingsSet(this.#requireApp());
5384
6358
  }
5385
6359
  /**
6360
+ * `setAnimateMaterials`: the editor's "animate materials" toggle, which runs or holds the shader
6361
+ * clock of the scene view (`app.renderer.animateMaterialsInEditMode`).
6362
+ *
6363
+ * @param params - `{ enabled }`.
6364
+ * @returns `null`.
6365
+ */
6366
+ #setAnimateMaterials(params) {
6367
+ this.#requireMirror(SceneMethod.setAnimateMaterials);
6368
+ if (!isSetAnimateMaterialsParams(params)) throw new InvalidParamsError("setAnimateMaterials takes { enabled: boolean }.");
6369
+ this.#requireApp().renderer.animateMaterialsInEditMode = params.enabled;
6370
+ return null;
6371
+ }
6372
+ /**
6373
+ * `getColliderOutlines`: the world-space outlines of the requested entities' colliders, from the
6374
+ * project's physics extensions, for the editor's collider gizmos. Changes nothing.
6375
+ *
6376
+ * @param params - `{ entities }`.
6377
+ * @returns The outlines, within the protocol's caps; uids the open scene does not have are skipped.
6378
+ */
6379
+ #getColliderOutlines(params) {
6380
+ const mirror = this.#requireMirror(SceneMethod.getColliderOutlines);
6381
+ if (!isEntitySelection(params)) throw new InvalidParamsError("getColliderOutlines takes { entities: uid[] }.");
6382
+ this.#requireOpen(SceneMethod.getColliderOutlines);
6383
+ const index = mirror.index();
6384
+ return colliderOutlinesOf(this.#requireApp(), params.entities, (uid) => index?.entities.get(uid));
6385
+ }
6386
+ /**
6387
+ * `sampleAnimation`: poses an entity's `Animator` at one point of one state.
6388
+ *
6389
+ * @param params - `{ entity, state, normalizedTime, parameters? }`.
6390
+ * @returns `{ posed }`.
6391
+ */
6392
+ #sampleAnimation(params) {
6393
+ const mirror = this.#requireMirror(SceneMethod.sampleAnimation);
6394
+ this.#requireOpen(SceneMethod.sampleAnimation);
6395
+ return sampleAnimation(this.#requireApp(), mirror, params);
6396
+ }
6397
+ /**
5386
6398
  * `setViewMode`: switches the view between the 3D editor camera and the 2D one. The first switch
5387
6399
  * to 2D on a document starts where the level's own `Camera2D` looks, or frames the document.
5388
6400
  *
@@ -5612,7 +6624,7 @@ var SceneHost = class {
5612
6624
  this.#notify(SceneNotification.selectionChanged, { entities: this.#selection });
5613
6625
  }
5614
6626
  /**
5615
- * Turns a gizmo drag into `transformDragging` (at most every 50 ms) and `transformDragged`.
6627
+ * Hands a gizmo drag of the selection's last entity to {@link GizmoDragRelay}.
5616
6628
  *
5617
6629
  * @param phase - Which part of the gesture.
5618
6630
  * @param drag - The handle.
@@ -5621,43 +6633,10 @@ var SceneHost = class {
5621
6633
  if (phase === "start") {
5622
6634
  const uid = this.#selection.at(-1);
5623
6635
  const entity = uid === void 0 ? void 0 : this.#mirror?.index()?.entities.get(uid);
5624
- if (entity === void 0) {
5625
- this.#drag = null;
5626
- return;
5627
- }
5628
- const snap = this.#gizmo.snap;
5629
- this.#drag = {
5630
- entity,
5631
- mode: drag.mode,
5632
- before: readLocalTransform(entity),
5633
- snapper: snap === null ? null : new DragSnapper(drag.mode, snap, entity),
5634
- lastSentMs: Number.NEGATIVE_INFINITY
5635
- };
5636
- return;
5637
- }
5638
- const state = this.#drag;
5639
- if (state === null) return;
5640
- if (phase === "move") {
5641
- state.snapper?.apply(state.entity);
5642
- const now = performance.now();
5643
- if (now - state.lastSentMs >= 50) {
5644
- state.lastSentMs = now;
5645
- this.#notify(SceneNotification.transformDragging, {
5646
- entity: state.entity.uid,
5647
- mode: state.mode,
5648
- after: readLocalTransform(state.entity)
5649
- });
5650
- }
5651
- return;
5652
- }
5653
- this.#drag = null;
5654
- const after = readLocalTransform(state.entity);
5655
- if (!sameTransform(state.before, after)) this.#notify(SceneNotification.transformDragged, {
5656
- entity: state.entity.uid,
5657
- mode: state.mode,
5658
- before: state.before,
5659
- after
5660
- });
6636
+ if (entity === void 0) this.#drag.clear();
6637
+ else this.#drag.start(entity, drag.mode, this.#gizmo.snap);
6638
+ } else if (phase === "move") this.#drag.move();
6639
+ else this.#drag.end();
5661
6640
  }
5662
6641
  /**
5663
6642
  * The world bounds of entities: their meshes' when the view can measure them, else their
@@ -5707,7 +6686,14 @@ var SceneHost = class {
5707
6686
  #hotReloaded(report) {
5708
6687
  this.#mirror?.invalidate();
5709
6688
  const changed = this.#defaults?.changed(report.typeIds) ?? /* @__PURE__ */ new Map();
5710
- if (changed.size > 0) this.#serial(async () => this.#followDefaults(changed));
6689
+ if (changed.size > 0) this.#serial(async () => this.#followDefaults(changed)).catch((error) => {
6690
+ const params = {
6691
+ code: isIgnifxError(error) ? error.code : null,
6692
+ message: clipHostText(`Following the new defaults of ${[...changed.keys()].join(", ")}: ${messageOf(error)}`),
6693
+ data: { typeIds: [...changed.keys()] }
6694
+ };
6695
+ this.#notify(SceneNotification.hostError, params);
6696
+ });
5711
6697
  const params = hotReloadedParamsOf(report);
5712
6698
  this.#notify(SceneNotification.hotReloaded, params);
5713
6699
  this.sendSchemas();
@@ -5817,7 +6803,7 @@ function resolveEngineVersion(fallback, coreVersion = VERSION) {
5817
6803
  * ```ts
5818
6804
  * import { startEditorHost } from "@ignifx/editor-host";
5819
6805
  *
5820
- * const host = await startEditorHost({ editorOrigin: "ignifx://app", canvas, extensions: [], scripts });
6806
+ * const host = await startEditorHost({ editorOrigin: "ignifx-editor://app", canvas, extensions: [], scripts });
5821
6807
  * ```
5822
6808
  *
5823
6809
  * @beta
@@ -6149,7 +7135,7 @@ function openPlayControls(app, options, target, heartbeatIntervalMs, port) {
6149
7135
  *
6150
7136
  * @example
6151
7137
  * ```ts
6152
- * const controls = startEditorPlayControls(app, { editorOrigin: "ignifx://app" });
7138
+ * const controls = startEditorPlayControls(app, { editorOrigin: "ignifx-editor://app" });
6153
7139
  * controls.dispose();
6154
7140
  * ```
6155
7141
  *
@@ -6178,7 +7164,7 @@ function startEditorPlayControls(app, options) {
6178
7164
  *
6179
7165
  * @example
6180
7166
  * ```ts
6181
- * const connector = listenForEditorPlayControls({ editorOrigin: "ignifx://app" });
7167
+ * const connector = listenForEditorPlayControls({ editorOrigin: "ignifx-editor://app" });
6182
7168
  * const app = await createApp({ headless: true });
6183
7169
  * const controls = connector.attach(app);
6184
7170
  * connector.dispose();
@@ -6231,6 +7217,6 @@ function listenForEditorPlayControls(options) {
6231
7217
  };
6232
7218
  }
6233
7219
  //#endregion
6234
- export { ApplyOpFailureCode, DEFAULT_HEARTBEAT_INTERVAL_MS, EDITOR_CONNECT_MESSAGE_TYPE, EditorHostErrorCode, GizmoMode, GizmoSpace, HandshakeMethod, HostCapability, HostKind, HostNotification, JSON_RPC_VERSION, PROTOCOL_VERSION, PickUnit, PlayMethod, PlayNotification, PlayPhase, RpcErrorCode, SCREENSHOT_MAX_SIZE, SceneMethod, SceneNotification, SceneOpKind, ScreenshotFormat, TRANSFORM_DRAGGING_INTERVAL_MS, ViewMode, isAppErrorData, isApplyOpsParams, isApplyOpsResult, isAssetReloadedParams, isEditorConnectMessage, isEditorOrigin, isEntitySelection, isFrameParams, isHostErrorParams, isHotReloadedParams, isIncompatibleProtocolData, isInvalidSceneFileData, isJsonObject, isJsonValue, isLogParams, isOpenSceneParams, isOpenSceneResult, isPickParams, isPickResult, isPlayState, isPlayStateReport, isPlayStats, isProtocolVersion, isReadBackParams, isReadBackResult, isReadyResult, isRpcMessage, isSceneFile, isSceneFileAssetRef, isSceneFileComponent, isSceneFileEntity, isSceneFileInstance, isSceneFileOverride, isSceneFileTransform, isSceneIssue, isSceneOp, isSceneOpenedParams, isSchemaSet, isScreenshotParams, isScreenshotResult, isSetGizmoParams, isSetViewModeParams, isSettingsSet, isTransformDraggedParams, isTransformDraggingParams, listenForEditorPlayControls, protocolVersionIsCompatible, startEditorHost, startEditorPlayControls };
7220
+ export { ApplyOpFailureCode, COLLIDER_OUTLINES_MAX_ENTITIES, COLLIDER_OUTLINES_MAX_NUMBERS, DEFAULT_HEARTBEAT_INTERVAL_MS, EDITOR_CONNECT_MESSAGE_TYPE, EditorHostErrorCode, GizmoMode, GizmoSpace, HOST_LIST_MAX_LENGTH, HOST_TEXT_MAX_LENGTH, HandshakeMethod, HostCapability, HostKind, HostNotification, JSON_RPC_VERSION, PROTOCOL_VERSION, PickUnit, PlayMethod, PlayNotification, PlayPhase, RpcErrorCode, SAMPLE_ANIMATION_MAX_NAME_LENGTH, SAMPLE_ANIMATION_MAX_PARAMETERS, SCREENSHOT_MAX_SIZE, SceneMethod, SceneNotification, SceneOpKind, ScreenshotFormat, TRANSFORM_DRAGGING_INTERVAL_MS, ViewMode, isAppErrorData, isApplyOpsParams, isApplyOpsResult, isAssetReloadedParams, isColliderOutlineRecord, isColliderOutlineSet, isEditorConnectMessage, isEditorOrigin, isEntitySelection, isFrameParams, isHostErrorParams, isHotReloadedParams, isIncompatibleProtocolData, isInvalidSceneFileData, isJsonObject, isJsonValue, isLogParams, isOpenSceneParams, isOpenSceneResult, isPickParams, isPickResult, isPlayState, isPlayStateReport, isPlayStats, isProtocolVersion, isReadBackParams, isReadBackResult, isReadyResult, isRpcMessage, isSampleAnimationParams, isSampleAnimationResult, isSceneFile, isSceneFileAssetRef, isSceneFileComponent, isSceneFileEntity, isSceneFileInstance, isSceneFileOverride, isSceneFileTransform, isSceneIssue, isSceneOp, isSceneOpenedParams, isSchemaSet, isScreenshotParams, isScreenshotResult, isSetAnimateMaterialsParams, isSetGizmoParams, isSetViewModeParams, isSettingsSet, isTransformDraggedParams, isTransformDraggingParams, listenForEditorPlayControls, protocolVersionIsCompatible, startEditorHost, startEditorPlayControls };
6235
7221
 
6236
7222
  //# sourceMappingURL=index.js.map