@ignifx/editor-host 0.11.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, Component, 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`.
@@ -1135,12 +1189,13 @@ function isApplyOpFailure(value) {
1135
1189
  * Checks the result of `applyOps`.
1136
1190
  *
1137
1191
  * @param value - The received `result`.
1138
- * @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.
1139
1194
  *
1140
1195
  * @public
1141
1196
  */
1142
1197
  function isApplyOpsResult(value) {
1143
- 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));
1144
1199
  }
1145
1200
  /**
1146
1201
  * Checks the parameters of `readBack`.
@@ -1281,10 +1336,10 @@ function isSchemaFieldDescription(value) {
1281
1336
  *
1282
1337
  * @param value - The value to test.
1283
1338
  * @returns True for `{ title, format, description?, fields, allowMultiple?, package?, builtIn?,
1284
- * propsSchema? }`, ignoring members it does not declare.
1339
+ * requires?, extends?, propsSchema? }`, ignoring members it does not declare.
1285
1340
  */
1286
1341
  function isSchemaDescription(value) {
1287
- 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);
1288
1343
  }
1289
1344
  /**
1290
1345
  * Checks the result of `getSchemas` and the parameters of `schemasChanged`.
@@ -1432,13 +1487,14 @@ const HOT_RELOAD_KINDS = {
1432
1487
  * Checks the parameters of `hotReloaded`.
1433
1488
  *
1434
1489
  * @param value - The received `params`.
1435
- * @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`.
1436
1492
  *
1437
1493
  * @public
1438
1494
  */
1439
1495
  function isHotReloadedParams(value) {
1440
1496
  const report = isRecord(value) ? value["report"] : void 0;
1441
- 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));
1442
1498
  }
1443
1499
  /**
1444
1500
  * Checks the parameters of `assetReloaded`.
@@ -1483,24 +1539,26 @@ function isTransformDraggedParams(value) {
1483
1539
  * Checks the parameters of `hostError`.
1484
1540
  *
1485
1541
  * @param value - The received `params`.
1486
- * @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`.
1487
1544
  *
1488
1545
  * @public
1489
1546
  */
1490
1547
  function isHostErrorParams(value) {
1491
- 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));
1492
1549
  }
1493
1550
  /**
1494
1551
  * Checks the `data` of a `hostError` for an error the app reported.
1495
1552
  *
1496
1553
  * @param value - The received `data`.
1497
1554
  * @returns True for a boundary name, a phase or `null`, an entity uid or `null`, and, when present,
1498
- * 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`.
1499
1557
  *
1500
1558
  * @public
1501
1559
  */
1502
1560
  function isAppErrorData(value) {
1503
- 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);
1504
1562
  }
1505
1563
  /** The severities of a log line. */
1506
1564
  const LOG_LEVELS = {
@@ -1513,12 +1571,13 @@ const LOG_LEVELS = {
1513
1571
  * Checks the parameters of `log`.
1514
1572
  *
1515
1573
  * @param value - The received `params`.
1516
- * @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`.
1517
1576
  *
1518
1577
  * @public
1519
1578
  */
1520
1579
  function isLogParams(value) {
1521
- 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"]));
1522
1581
  }
1523
1582
  //#endregion
1524
1583
  //#region src/protocol/version.ts
@@ -1686,7 +1745,7 @@ function send(port, message) {
1686
1745
  * period that is not a positive finite number.
1687
1746
  */
1688
1747
  function checkChannelOptions(editorOrigin, heartbeatIntervalMs) {
1689
- 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\"." });
1690
1749
  const interval = heartbeatIntervalMs ?? 1e3;
1691
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" } });
1692
1751
  return interval;
@@ -1887,6 +1946,41 @@ function openChannel(options) {
1887
1946
  * The app's reports as the editor's Console reads them: log lines, `app.onError` reports and hot
1888
1947
  * reloads, made JSON. The scene view and the play view relay the same shapes.
1889
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
+ }
1890
1984
  /**
1891
1985
  * Names one of the engine's phases.
1892
1986
  *
@@ -1897,59 +1991,60 @@ function phaseName(phase) {
1897
1991
  return Object.entries(Phase).find(([, value]) => value === phase)?.[0] ?? null;
1898
1992
  }
1899
1993
  /**
1900
- * Reads a thrown value's message.
1994
+ * Reads a thrown value's message, clipped by {@link clipHostText}.
1901
1995
  *
1902
1996
  * @param error - Whatever was thrown.
1903
1997
  * @returns Its message, or the value as a string when it is not an `Error`.
1904
1998
  */
1905
1999
  function messageOf(error) {
1906
- return error instanceof Error ? error.message : String(error);
2000
+ return clipHostText(error instanceof Error ? error.message : String(error));
1907
2001
  }
1908
2002
  /**
1909
- * Reads a thrown value's stack.
2003
+ * Reads a thrown value's stack, clipped by {@link clipHostText}.
1910
2004
  *
1911
2005
  * @param error - Whatever was thrown.
1912
2006
  * @returns Its `stack` when it is an `Error` with one, else `null`.
1913
2007
  */
1914
2008
  function stackOf(error) {
1915
- 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;
1916
2010
  }
1917
2011
  /**
1918
- * Reads a thrown value's `IGX-` code.
2012
+ * Reads a thrown value's `IGX-` code, clipped by {@link clipHostText}.
1919
2013
  *
1920
2014
  * @param error - Whatever was thrown.
1921
2015
  * @returns The code of an `IgnifxError`, else `null`.
1922
2016
  */
1923
2017
  function codeOf(error) {
1924
- return isIgnifxError(error) ? error.code : null;
2018
+ return isIgnifxError(error) ? clipHostText(error.code) : null;
1925
2019
  }
1926
2020
  /**
1927
2021
  * Names a component for the editor: its `typeId`, else its class name.
1928
2022
  *
1929
2023
  * @param component - The component.
1930
- * @returns The name.
2024
+ * @returns The name, clipped by {@link clipHostText}.
1931
2025
  */
1932
2026
  function componentName(component) {
1933
2027
  const typeId = Reflect.get(component.constructor, "typeId");
1934
- return typeof typeId === "string" && typeId !== "" ? typeId : component.constructor.name;
2028
+ return clipHostText(typeof typeId === "string" && typeId !== "" ? typeId : component.constructor.name);
1935
2029
  }
1936
2030
  /**
1937
2031
  * Builds the parameters of `log` from one record.
1938
2032
  *
1939
2033
  * @param record - The record the app's logger wrote.
1940
- * @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}.
1941
2036
  */
1942
2037
  function logParamsOf(record) {
1943
2038
  const params = {
1944
2039
  level: record.level,
1945
- scope: record.scope,
1946
- message: record.message,
2040
+ scope: clipHostTextOrNull(record.scope),
2041
+ message: clipHostText(record.message),
1947
2042
  timeMs: record.timeMs
1948
2043
  };
1949
2044
  const error = record.data.find((value) => value instanceof Error);
1950
2045
  if (error === void 0) return params;
1951
2046
  const logged = {
1952
- message: error.message,
2047
+ message: messageOf(error),
1953
2048
  code: codeOf(error),
1954
2049
  stack: stackOf(error)
1955
2050
  };
@@ -1962,15 +2057,16 @@ function logParamsOf(record) {
1962
2057
  * Builds the parameters of `hostError` from one `app.onError` report.
1963
2058
  *
1964
2059
  * @param report - The report.
1965
- * @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}.
1966
2062
  */
1967
2063
  function hostErrorParamsOf(report) {
1968
2064
  const data = {
1969
- source: report.source,
2065
+ source: clipHostText(report.source),
1970
2066
  phase: report.phase,
1971
2067
  phaseName: report.phase === null ? null : phaseName(report.phase),
1972
2068
  entity: report.entity?.uid ?? null,
1973
- entityName: report.entity?.name ?? null,
2069
+ entityName: clipHostTextOrNull(report.entity?.name ?? null),
1974
2070
  component: report.component === null ? null : componentName(report.component),
1975
2071
  stack: stackOf(report.error)
1976
2072
  };
@@ -1984,15 +2080,16 @@ function hostErrorParamsOf(report) {
1984
2080
  * Builds the parameters of `hotReloaded` from one report.
1985
2081
  *
1986
2082
  * @param report - What `app.hotReload` did.
1987
- * @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.
1988
2085
  */
1989
2086
  function hotReloadedParamsOf(report) {
1990
2087
  return { report: {
1991
2088
  kind: report.kind,
1992
- typeIds: report.typeIds,
2089
+ typeIds: clipHostList(report.typeIds).map((typeId) => clipHostText(typeId)),
1993
2090
  instances: report.instances,
1994
2091
  durationMs: report.durationMs,
1995
- errors: report.errors.map((error) => ({
2092
+ errors: clipHostList(report.errors).map((error) => ({
1996
2093
  message: messageOf(error),
1997
2094
  code: codeOf(error),
1998
2095
  stack: stackOf(error)
@@ -2619,18 +2716,52 @@ function copyJson(value) {
2619
2716
  * @param component - The component.
2620
2717
  * @param props - The `props` object.
2621
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.
2622
2734
  * @returns The decoding problems, as `{ code, message }`.
2623
2735
  */
2624
- 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) {
2625
2749
  const schema = component.world.registry.describe(component.constructor).schema;
2626
- if (schema === null) return [];
2750
+ if (schema === null) return {
2751
+ values: /* @__PURE__ */ new Map(),
2752
+ issues: []
2753
+ };
2627
2754
  const decoded = decodeProps(schema, props, references);
2628
- const values = new Map(Object.entries(decoded.value));
2629
- for (const name of Object.keys(schema)) Reflect.set(component, name, values.get(name));
2630
- return decoded.issues.map((issue) => ({
2631
- code: issue.code,
2632
- message: `${component.uid}.${issue.path}: ${issue.message}`
2633
- }));
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
+ };
2634
2765
  }
2635
2766
  /**
2636
2767
  * Tells a component that the host changed some of its fields, through its `onValidate` hook
@@ -2643,6 +2774,54 @@ function validateFields(component, fields) {
2643
2774
  const hook = Reflect.get(component, "onValidate");
2644
2775
  if (fields.length > 0 && typeof hook === "function") Reflect.apply(hook, component, [fields]);
2645
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
+ }
2646
2825
  /** The live mirror of the editor's open scene document. */
2647
2826
  var DocumentMirror = class {
2648
2827
  #app;
@@ -2662,6 +2841,19 @@ var DocumentMirror = class {
2662
2841
  * that changed a default reads every stale member value as an override.
2663
2842
  */
2664
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();
2665
2857
  /** Assets loaded for ops, held until the document closes. */
2666
2858
  #handles = [];
2667
2859
  /**
@@ -2720,27 +2912,59 @@ var DocumentMirror = class {
2720
2912
  */
2721
2913
  async open(file, address) {
2722
2914
  await this.close();
2915
+ const where = address ?? "memory:scene/unsaved";
2723
2916
  const warnings = [];
2724
- const scene = await this.#app.world.loadSceneFile(file, {
2725
- address: address ?? "memory:scene/unsaved",
2726
- onIssue: (issue) => {
2727
- warnings.push({
2728
- code: issue.code,
2729
- message: issue.message
2730
- });
2731
- }
2732
- });
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
+ }
2733
2937
  this.#scene = scene;
2734
2938
  this.#address = address;
2735
2939
  this.#name = file.name;
2736
2940
  this.#settings = file.settings === void 0 ? null : copyJson(file.settings);
2737
- this.recordComponents(file.entities.flatMap((record) => record.components ?? []));
2738
- this.recordInstances(file.entities);
2941
+ this.recordComponents(entities.flatMap((record) => record.components ?? []));
2942
+ this.recordInstances(entities);
2943
+ this.invalidate();
2739
2944
  return {
2740
2945
  entityCount: countEntities(scene),
2741
2946
  warnings
2742
2947
  };
2743
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
+ }
2744
2968
  /** Unloads the open document, if any, and releases the assets its ops loaded. */
2745
2969
  async close() {
2746
2970
  const scene = this.#scene;
@@ -2751,6 +2975,8 @@ var DocumentMirror = class {
2751
2975
  this.#index = null;
2752
2976
  this.#explicit.clear();
2753
2977
  this.#overrides.clear();
2978
+ this.#builtAs.clear();
2979
+ this.#rootPaths.clear();
2754
2980
  if (scene !== null) await this.#app.world.unloadScene(scene);
2755
2981
  for (const handle of this.#handles.splice(0)) handle.release();
2756
2982
  }
@@ -2805,21 +3031,47 @@ var DocumentMirror = class {
2805
3031
  return this.#explicit.get(uid) ?? null;
2806
3032
  }
2807
3033
  /**
2808
- * 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.
2809
3037
  *
2810
3038
  * @param records - The records, as a file or an op carries them.
2811
3039
  */
2812
3040
  recordInstances(records) {
2813
- 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
+ }
2814
3054
  }
2815
3055
  /**
2816
- * 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.
2817
3059
  *
2818
3060
  * @param uid - The root's uid.
2819
3061
  * @param overrides - The list.
2820
3062
  */
2821
3063
  recordOverrides(uid, overrides) {
2822
- 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;
2823
3075
  }
2824
3076
  /**
2825
3077
  * An instance root's override list as the document holds it.
@@ -2835,7 +3087,10 @@ var DocumentMirror = class {
2835
3087
  this.#index = null;
2836
3088
  }
2837
3089
  /**
2838
- * 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.
2839
3094
  *
2840
3095
  * @returns The index, or `null` while no document is open.
2841
3096
  */
@@ -2848,16 +3103,27 @@ var DocumentMirror = class {
2848
3103
  /**
2849
3104
  * Serializes the requested entities as the live world has them (protocol `readBack`).
2850
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
+ *
2851
3116
  * @param params - The uids to read, or none for all.
2852
3117
  * @returns The records in file order, the uids not found, the settings, and the serializer's issues.
2853
3118
  */
2854
3119
  readBack(params) {
3120
+ this.invalidate();
2855
3121
  const index = this.index();
2856
3122
  if (index === null) return null;
2857
3123
  const requested = params.entities;
2858
3124
  const wanted = requested === void 0 ? null : new Set(requested);
2859
3125
  return {
2860
- 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)),
2861
3127
  missing: requested === void 0 ? [] : [...new Set(requested)].filter((uid) => !index.records.has(uid)),
2862
3128
  settings: index.file.settings ?? null,
2863
3129
  issues: index.issues
@@ -2878,6 +3144,7 @@ var DocumentMirror = class {
2878
3144
  }
2879
3145
  /**
2880
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;
2881
3148
  * and assets already loaded in the app's cache.
2882
3149
  *
2883
3150
  * @param built - The uid table of a subtree an op just built, if any.
@@ -2888,7 +3155,7 @@ var DocumentMirror = class {
2888
3155
  const assets = this.#app.assets;
2889
3156
  return {
2890
3157
  entity: (uid) => index?.entities.get(uid) ?? built?.entity(uid) ?? null,
2891
- 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,
2892
3159
  asset: (address, type) => {
2893
3160
  const handle = assets.get(address);
2894
3161
  return handle !== null && handle.state === "loaded" && (type === null || handle.type === type) ? handle : null;
@@ -2896,6 +3163,24 @@ var DocumentMirror = class {
2896
3163
  };
2897
3164
  }
2898
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
+ /**
2899
3184
  * Serializes the document and indexes its entities and components.
2900
3185
  *
2901
3186
  * @param scene - The document's scene instance.
@@ -2917,6 +3202,7 @@ var DocumentMirror = class {
2917
3202
  const entities = /* @__PURE__ */ new Map();
2918
3203
  const records = /* @__PURE__ */ new Map();
2919
3204
  const components = /* @__PURE__ */ new Map();
3205
+ const added = /* @__PURE__ */ new Map();
2920
3206
  for (const record of file.entities) {
2921
3207
  const entity = world.getEntity(record.uid);
2922
3208
  if (entity === null) continue;
@@ -2924,16 +3210,122 @@ var DocumentMirror = class {
2924
3210
  records.set(record.uid, record);
2925
3211
  const uids = new Set((record.components ?? []).map((component) => component.uid));
2926
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);
2927
3215
  }
2928
3216
  return {
2929
3217
  file,
2930
3218
  issues,
2931
3219
  entities,
2932
3220
  records,
2933
- components
3221
+ components,
3222
+ added
2934
3223
  };
2935
3224
  }
2936
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
+ }
2937
3329
  //#endregion
2938
3330
  //#region src/scene/defaults.ts
2939
3331
  /**
@@ -3010,47 +3402,59 @@ function typeIdOf(app, component) {
3010
3402
  }
3011
3403
  /**
3012
3404
  * Gives every document component the new default of each changed field its record leaves out. A
3013
- * component the mirror has no record of is left alone.
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.
3014
3407
  *
3015
3408
  * @param app - The scene view's app.
3016
3409
  * @param mirror - The open document.
3017
3410
  * @param index - Its index.
3018
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.
3019
3413
  */
3020
- function applyDefaults(app, mirror, index, changed) {
3414
+ function applyDefaults(app, mirror, index, changed, failed) {
3021
3415
  for (const [uid, component] of index.components) {
3022
- const fields = changed.get(typeIdOf(app, component) ?? "");
3416
+ const typeId = typeIdOf(app, component) ?? "";
3417
+ const fields = changed.get(typeId);
3023
3418
  const set = mirror.propsSetBy(uid);
3024
3419
  const schema = app.world.registry.describe(component.constructor).schema;
3025
3420
  if (fields === void 0 || set === null || schema === null) continue;
3026
3421
  const assigned = [];
3027
- for (const name of fields) {
3028
- const field = Object.hasOwn(schema, name) ? schema[name] : void 0;
3029
- if (field !== void 0 && !set.has(name)) {
3030
- Reflect.set(component, name, field.createDefault());
3031
- assigned.push(name);
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
+ }
3032
3429
  }
3430
+ validateFields(component, assigned);
3431
+ } catch (error) {
3432
+ failed(component, typeId, error);
3033
3433
  }
3034
- validateFields(component, assigned);
3035
3434
  }
3036
3435
  }
3037
3436
  /**
3038
3437
  * The document's instance roots whose members (not the document's own components) include a
3039
- * component of a changed type, in document order.
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.
3040
3442
  *
3041
3443
  * @param app - The scene view's app.
3042
- * @param index - The open document's index.
3444
+ * @param mirror - The open document.
3445
+ * @param index - Its index.
3043
3446
  * @param changed - The changed fields, by type id.
3044
3447
  * @returns The roots' uids.
3045
3448
  */
3046
- function instancesHolding(app, index, changed) {
3449
+ function instancesHolding(app, mirror, index, changed) {
3450
+ const isMember = (component) => !index.components.has(component.uid) || mirror.propsSetBy(component.uid) === null;
3047
3451
  const roots = /* @__PURE__ */ new Set();
3048
3452
  for (const record of index.file.entities) {
3049
3453
  const root = index.entities.get(record.uid);
3050
3454
  if (record.instance === void 0 || root === void 0) continue;
3051
3455
  const pending = [root];
3052
3456
  for (let entity = pending.pop(); entity !== void 0; entity = pending.pop()) {
3053
- if (entity.components.some((component) => !index.components.has(component.uid) && changed.has(typeIdOf(app, component) ?? ""))) {
3457
+ if (entity.components.some((component) => isMember(component) && changed.has(typeIdOf(app, component) ?? ""))) {
3054
3458
  roots.add(record.uid);
3055
3459
  break;
3056
3460
  }
@@ -3929,97 +4333,593 @@ var EditorCamera2D = class extends Script {
3929
4333
  }
3930
4334
  };
3931
4335
  //#endregion
3932
- //#region src/scene/ops.ts
4336
+ //#region src/scene/view-math.ts
3933
4337
  /**
3934
- * `applyOps`: the thirteen scene ops of protocol 0.3, applied to the open document's live world.
3935
- *
3936
- * Each op changes the world the way the editor's `applyOp` changes the document, so that a mirror
3937
- * that started exact stays exact: `readBack` then returns the document's own records. An op that
3938
- * the world disagrees with fails with one of editor-core's codes; the host does not roll back,
3939
- * 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.
3940
4342
  */
3941
- /** The address the subtrees ops build are named by, in the engine's diagnostics. */
3942
- const SUBTREE_ADDRESS = "memory:scene/editor-op";
3943
- /** Why one op failed, as `applyOps` reports it. */
3944
- var OpFailure = class extends Error {
3945
- /** The failure code. */
3946
- code;
3947
- /** The engine's diagnostic code, when there is one. */
3948
- diagnostic;
3949
- /**
3950
- * Creates the failure.
3951
- *
3952
- * @param code - The failure code.
3953
- * @param message - An actionable sentence.
3954
- * @param diagnostic - The engine's `IGX-` code, if any.
3955
- */
3956
- constructor(code, message, diagnostic = null) {
3957
- super(message);
3958
- this.name = "OpFailure";
3959
- this.code = code;
3960
- this.diagnostic = diagnostic;
3961
- }
3962
- };
3963
4343
  /**
3964
- * Applies one command's ops in order, never stopping at a failure.
4344
+ * Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its
4345
+ * backing pixels.
3965
4346
  *
3966
- * @param app - The scene view's app.
3967
- * @param mirror - The open document.
3968
- * @param params - The ops and the command they belong to.
3969
- * @returns How many applied, and the failures in order.
4347
+ * @param surface - The canvas.
4348
+ * @returns The sizes.
3970
4349
  */
3971
- async function applyOps(app, mirror, params) {
3972
- const context = {
3973
- app,
3974
- mirror
3975
- };
3976
- const failures = [];
3977
- let applied = 0;
3978
- for (const [index, op] of params.ops.entries()) try {
3979
- await applyOp(context, op);
3980
- applied += 1;
3981
- } catch (error) {
3982
- const failure = toFailure(index, error);
3983
- failures.push(failure);
3984
- app.log.warn(`applyOps ${params.commandId} (${params.commandName}): op ${String(index)} (${op.op}) failed: ${failure.code}: ${failure.message}`);
3985
- } finally {
3986
- mirror.invalidate();
3987
- }
4350
+ function viewSurfaceOf(surface) {
4351
+ const clientWidth = Reflect.get(surface, "clientWidth");
4352
+ const clientHeight = Reflect.get(surface, "clientHeight");
3988
4353
  return {
3989
- applied,
3990
- failures
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
3991
4358
  };
3992
4359
  }
3993
4360
  /**
3994
- * Turns whatever an op threw into its failure record.
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.
3995
4364
  *
3996
- * @param index - The op's index.
3997
- * @param error - What it threw.
3998
- * @returns The failure.
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).
3999
4368
  */
4000
- function toFailure(index, error) {
4001
- if (error instanceof OpFailure) return {
4002
- index,
4003
- code: error.code,
4004
- message: error.message,
4005
- ...error.diagnostic === null ? {} : { diagnostic: error.diagnostic }
4006
- };
4007
- const message = error instanceof Error ? error.message : String(error);
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;
4008
4373
  return {
4009
- index,
4010
- code: ApplyOpFailureCode.engineError,
4011
- message,
4012
- ...isIgnifxError(error) ? { diagnostic: error.code } : {}
4374
+ x,
4375
+ y
4013
4376
  };
4014
4377
  }
4015
4378
  /**
4016
- * Applies one op.
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`.
4017
4382
  *
4018
- * @param context - The app and the document.
4019
- * @param op - The op.
4383
+ * @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.
4384
+ * @returns The members, every number rounded with `canonicalizeNumber`.
4020
4385
  */
4021
- async function applyOp(context, op) {
4022
- switch (op.op) {
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
+ *
4863
+ * @param app - The scene view's app.
4864
+ * @param mirror - The open document.
4865
+ * @param params - The ops and the command they belong to.
4866
+ * @returns How many applied, the failures in order, and the build problems the ops met, in order.
4867
+ */
4868
+ async function applyOps(app, mirror, params) {
4869
+ const warnings = [];
4870
+ const context = {
4871
+ app,
4872
+ mirror,
4873
+ warnings
4874
+ };
4875
+ const failures = [];
4876
+ let applied = 0;
4877
+ for (const [index, op] of params.ops.entries()) try {
4878
+ await applyOp(context, op);
4879
+ applied += 1;
4880
+ } catch (error) {
4881
+ const failure = toFailure(index, error);
4882
+ failures.push(failure);
4883
+ app.log.warn(`applyOps ${params.commandId} (${params.commandName}): op ${String(index)} (${op.op}) failed: ${failure.code}: ${failure.message}`);
4884
+ } finally {
4885
+ mirror.invalidate();
4886
+ }
4887
+ return {
4888
+ applied,
4889
+ failures,
4890
+ warnings
4891
+ };
4892
+ }
4893
+ /**
4894
+ * Turns whatever an op threw into its failure record.
4895
+ *
4896
+ * @param index - The op's index.
4897
+ * @param error - What it threw.
4898
+ * @returns The failure.
4899
+ */
4900
+ function toFailure(index, error) {
4901
+ if (error instanceof OpFailure) return {
4902
+ index,
4903
+ code: error.code,
4904
+ message: error.message,
4905
+ ...error.diagnostic === null ? {} : { diagnostic: error.diagnostic }
4906
+ };
4907
+ const message = error instanceof Error ? error.message : String(error);
4908
+ return {
4909
+ index,
4910
+ code: ApplyOpFailureCode.engineError,
4911
+ message,
4912
+ ...isIgnifxError(error) ? { diagnostic: error.code } : {}
4913
+ };
4914
+ }
4915
+ /**
4916
+ * Applies one op.
4917
+ *
4918
+ * @param context - The app and the document.
4919
+ * @param op - The op.
4920
+ */
4921
+ async function applyOp(context, op) {
4922
+ switch (op.op) {
4023
4923
  case "createEntity":
4024
4924
  await createEntity(context, op);
4025
4925
  return;
@@ -4181,21 +5081,28 @@ function requireFreeUids(context, records) {
4181
5081
  }
4182
5082
  }
4183
5083
  /**
4184
- * 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.
4185
5088
  *
4186
- * @param value - The JSON.
4187
- * @returns True when a `$entity` or `$component` object is in it.
5089
+ * @param records - The new entity records, parents first.
4188
5090
  */
4189
- function hasReferences(value) {
4190
- const array = asJsonArray(value);
4191
- if (array !== null) return array.some((item) => hasReferences(item));
4192
- const object = asJsonObject(value);
4193
- 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");
4194
5099
  }
4195
5100
  /**
4196
5101
  * Builds a subtree from entity records under a live parent, with the records' uids, loading the
4197
- * assets they reference first; then resolves references to the rest of the document, which a
4198
- * 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}).
4199
5106
  *
4200
5107
  * @param context - The app and the document.
4201
5108
  * @param records - The subtree's records, parents first; the first is its root.
@@ -4218,23 +5125,49 @@ async function buildSubtree(context, records, parent, index) {
4218
5125
  };
4219
5126
  const dependencies = await loadSceneDependencies(context.app.assets, file);
4220
5127
  context.mirror.retain(dependencies);
4221
- const asset = await createSceneAsset(SUBTREE_ADDRESS, file, dependencies);
5128
+ const asset = await createSceneAsset(documentAddress(context), file, dependencies);
5129
+ const outsideReferences = context.mirror.decoder();
4222
5130
  const built = instantiateScene(context.app.world, asset, {
4223
5131
  scene,
5132
+ outsideReferences,
4224
5133
  ...parent === null ? {} : { parent }
4225
5134
  });
4226
5135
  context.mirror.invalidate();
4227
- const references = context.mirror.decoder(built.remap);
4228
- for (const record of file.entities) for (const component of record.components ?? []) {
4229
- const live = built.remap.component(component.uid);
4230
- if (live !== null && hasReferences(component.props)) assignProps(live, component.props ?? {}, references);
4231
- }
5136
+ reportBuildIssues(context, built.issues);
4232
5137
  const root = built.roots[0] ?? built.remap.entity(top.uid);
4233
5138
  if (root === null) throw new OpFailure(ApplyOpFailureCode.engineError, `The engine built no entity for ${top.uid}.`);
4234
5139
  placeAmongSiblings(context, root, index);
4235
5140
  return root;
4236
5141
  }
4237
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
+ /**
4238
5171
  * Applies `createEntity`: the entity and its descendants, with their uids and components.
4239
5172
  *
4240
5173
  * @param context - The app and the document.
@@ -4245,6 +5178,7 @@ async function createEntity(context, op) {
4245
5178
  const parent = requireParent(context, op.entity.parent);
4246
5179
  checkIndex(op.index, documentSiblings(context, parent, null).length);
4247
5180
  requireFreeUids(context, records);
5181
+ requireValidRecords(records);
4248
5182
  const inside = /* @__PURE__ */ new Set([op.entity.uid]);
4249
5183
  for (const record of op.descendants ?? []) {
4250
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.`);
@@ -4404,51 +5338,22 @@ async function instantiate(context, op) {
4404
5338
  instance: op.instance
4405
5339
  };
4406
5340
  requireFreeUids(context, [record]);
5341
+ requireValidRecords([record]);
4407
5342
  await buildSubtree(context, [record], parent, op.index);
4408
5343
  context.mirror.recordInstances([record]);
4409
5344
  }
4410
5345
  /**
4411
- * The uid of a referenced entity or component.
4412
- *
4413
- * @param target - The field's value.
4414
- * @returns Its uid, or `null` for anything without one.
4415
- */
4416
- function uidOf(target) {
4417
- const uid = typeof target === "object" && target !== null ? Reflect.get(target, "uid") : null;
4418
- return typeof uid === "string" ? uid : null;
4419
- }
4420
- /**
4421
5346
  * Reads a schema field's current value as JSON, references written as the uids they point at.
4422
5347
  *
4423
- * @param field - The field.
4424
- * @param value - The live value.
4425
- * @returns The JSON.
4426
- */
4427
- function encodeLive(field, value) {
4428
- return encodeValue(field, value, {
4429
- entityUid: uidOf,
4430
- componentUid: uidOf
4431
- });
4432
- }
4433
- /**
4434
- * Narrows JSON to an object. `Array.isArray` does not remove a readonly array from the union, so the
4435
- * discrimination lives here once.
4436
- *
4437
- * @param value - The JSON.
4438
- * @returns The object, or `null` for anything else.
4439
- */
4440
- function asJsonObject(value) {
4441
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
4442
- return value;
4443
- }
4444
- /**
4445
- * Narrows JSON to an array.
4446
- *
4447
- * @param value - The JSON.
4448
- * @returns The array, or `null`.
5348
+ * @param field - The field.
5349
+ * @param value - The live value.
5350
+ * @returns The JSON.
4449
5351
  */
4450
- function asJsonArray(value) {
4451
- return Array.isArray(value) ? value : null;
5352
+ function encodeLive(field, value) {
5353
+ return encodeValue(field, value, {
5354
+ entityUid: uidOf,
5355
+ componentUid: uidOf
5356
+ });
4452
5357
  }
4453
5358
  /**
4454
5359
  * Returns JSON with the value at a path set, or removed, leaving the input unchanged.
@@ -4474,7 +5379,7 @@ function withValueAt(container, path, value) {
4474
5379
  const object = asJsonObject(container);
4475
5380
  if (object !== null && typeof step === "string") {
4476
5381
  if (rest.length > 0) {
4477
- const next = object[step];
5382
+ const next = Object.hasOwn(object, step) ? object[step] : void 0;
4478
5383
  if (next === void 0) throw invalidPath(path);
4479
5384
  return {
4480
5385
  ...object,
@@ -4607,53 +5512,52 @@ function findOverride(overrides, path, op, added) {
4607
5512
  * Rebuilds an instance root's subtree with an edited override list: the live world has no way to
4608
5513
  * re-apply one override, so the root and its document children are serialized, destroyed and built
4609
5514
  * again from the instanced scene with the new list. References from the rest of the document into
4610
- * 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.
4611
5522
  *
4612
5523
  * @param context - The app and the document.
4613
5524
  * @param uid - The instance root.
4614
- * @param edit - Returns the new override list from the current one.
4615
- * @param documentOverrides - Whether the root and the instance roots under it are rebuilt with the
4616
- * override lists the document holds rather than the ones the serializer recomputes from the live
4617
- * 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.
4618
5528
  */
4619
- async function rebuildInstance(context, uid, edit, documentOverrides = false) {
5529
+ async function rebuildInstance(context, uid, edit, keepHashes = true) {
4620
5530
  const index = indexOf(context);
4621
5531
  const root = requireEntity(context, uid);
4622
5532
  const mirror = context.mirror;
4623
5533
  const withDocumentOverrides = (record) => {
4624
- const listed = documentOverrides && record.instance !== void 0 ? mirror.overridesOf(record.uid) : null;
4625
- if (listed === null || record.instance === void 0) return record;
4626
- const { scene, hash } = record.instance;
4627
- 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, {
4628
5538
  scene,
4629
- ...hash === void 0 ? {} : { hash },
5539
+ ...hash === void 0 || !keepHashes ? {} : { hash },
4630
5540
  ...listed.length === 0 ? {} : { overrides: listed }
4631
- };
4632
- return {
4633
- ...record,
4634
- instance
4635
- };
5541
+ }, mirror.rootPathOf(record.uid));
4636
5542
  };
4637
5543
  const found = index.records.get(uid);
4638
5544
  const record = found === void 0 ? void 0 : withDocumentOverrides(found);
4639
5545
  const instance = record?.instance;
4640
5546
  if (record === void 0 || instance === void 0) throw new OpFailure(ApplyOpFailureCode.notAnInstance, `${root.name} (${uid}) has no instance entry.`);
4641
5547
  const overrides = edit(instance.overrides ?? []);
4642
- const top = {
4643
- ...record,
4644
- instance: {
4645
- scene: instance.scene,
4646
- ...instance.hash === void 0 ? {} : { hash: instance.hash },
4647
- ...overrides.length === 0 ? {} : { overrides }
4648
- }
4649
- };
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));
4650
5553
  const inside = /* @__PURE__ */ new Set([uid]);
4651
5554
  const records = [top];
4652
5555
  for (const candidate of index.file.entities) if (candidate.parent !== null && inside.has(candidate.parent)) {
4653
5556
  inside.add(candidate.uid);
4654
5557
  records.push(withDocumentOverrides(candidate));
4655
5558
  }
4656
- 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);
4657
5561
  const parent = root.parent;
4658
5562
  const at = documentSiblings(context, parent, null).indexOf(root);
4659
5563
  root.destroyImmediate();
@@ -4662,13 +5566,33 @@ async function rebuildInstance(context, uid, edit, documentOverrides = false) {
4662
5566
  mirror.recordInstances(records);
4663
5567
  const references = context.mirror.decoder();
4664
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
+ };
4665
5580
  for (const outside of index.file.entities) {
4666
5581
  if (inside.has(outside.uid)) continue;
4667
- for (const component of outside.components ?? []) {
4668
- const live = rebuilt.components.get(component.uid);
4669
- 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);
4670
5587
  }
4671
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);
4672
5596
  }
4673
5597
  /**
4674
5598
  * Rebuilds one instance root from its scene asset's current value, keeping its uid, its record
@@ -4679,38 +5603,19 @@ async function rebuildInstance(context, uid, edit, documentOverrides = false) {
4679
5603
  * @param app - The scene view's app.
4680
5604
  * @param mirror - The open document.
4681
5605
  * @param uid - The instance root.
4682
- * @param documentOverrides - Whether to rebuild with the override lists the document holds rather
4683
- * than the ones the live members read as; `true` after a hot reload changed a default.
4684
5606
  * @throws OpFailure when the uid names no document entity or one without an instance entry.
4685
5607
  */
4686
- async function reloadInstance(app, mirror, uid, documentOverrides = false) {
5608
+ async function reloadInstance(app, mirror, uid) {
4687
5609
  try {
4688
5610
  await rebuildInstance({
4689
5611
  app,
4690
5612
  mirror
4691
- }, uid, (overrides) => overrides, documentOverrides);
5613
+ }, uid, (overrides) => overrides, false);
4692
5614
  } finally {
4693
5615
  mirror.invalidate();
4694
5616
  }
4695
5617
  }
4696
5618
  /**
4697
- * Tells whether JSON references an entity or component of a set.
4698
- *
4699
- * @param value - The JSON.
4700
- * @param entities - The entity uids.
4701
- * @param components - The component uids.
4702
- * @returns True when a `$entity` or `$component` names one of them.
4703
- */
4704
- function pointsInto(value, entities, components) {
4705
- const array = asJsonArray(value);
4706
- if (array !== null) return array.some((item) => pointsInto(item, entities, components));
4707
- const object = asJsonObject(value);
4708
- if (object === null) return false;
4709
- const entity = object["$entity"];
4710
- const component = object["$component"];
4711
- return typeof entity === "string" && entities.has(entity) || typeof component === "string" && components.has(component) || Object.values(object).some((item) => pointsInto(item, entities, components));
4712
- }
4713
- /**
4714
5619
  * Applies `setOverride`: replaces the override with the same identity, or inserts it.
4715
5620
  *
4716
5621
  * @param context - The app and the document.
@@ -4806,7 +5711,8 @@ const COMPONENTS_FORMAT = "components";
4806
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
4807
5712
  * document's. `ignifx/Transform` is described with core's `transformSchema()` and carries
4808
5713
  * `builtIn`: its fields are each entity's `transform` block, edited with `setTransform`, and it is
4809
- * 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.
4810
5716
  *
4811
5717
  * The set is read from the live registry each time, so a hot reload that adds a field or a script
4812
5718
  * shows in the next `schemasChanged`.
@@ -4826,409 +5732,149 @@ function schemaSet(app, hidden) {
4826
5732
  const schema = type === Transform ? transformSchema() : registry.describe(type).schema ?? {};
4827
5733
  schemas[typeId] = {
4828
5734
  ...description,
5735
+ extends: registeredAncestors(registry, type),
4829
5736
  propsSchema: toJsonSchema(schema)
4830
5737
  };
4831
5738
  }
4832
5739
  for (const [id, description] of Object.entries(core)) if (description.format !== COMPONENTS_FORMAT) schemas[id] = description;
4833
5740
  return { schemas };
4834
5741
  }
4835
- //#endregion
4836
- //#region src/scene/screenshot.ts
4837
- /** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */
4838
- const BASE64_CHUNK = 32768;
4839
- /**
4840
- * Encodes bytes as base64.
4841
- *
4842
- * @param bytes - The bytes.
4843
- * @returns The base64 text.
4844
- */
4845
- function toBase64(bytes) {
4846
- let binary = "";
4847
- for (let start = 0; start < bytes.length; start += BASE64_CHUNK) binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));
4848
- return btoa(binary);
4849
- }
4850
- /**
4851
- * Scales a captured frame to a size and encodes it as a data URL.
4852
- *
4853
- * @param capture - The frame, RGBA8 with the top row first.
4854
- * @param size - The image size.
4855
- * @param format - `"png"` or `"jpeg"`.
4856
- * @param quality - The JPEG quality, from 0 to 1; ignored for PNG.
4857
- * @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.
4858
- * @throws Error when the browser has no 2D canvas context.
4859
- */
4860
- async function encodeCapture(capture, size, format, quality) {
4861
- const source = new OffscreenCanvas(capture.width, capture.height);
4862
- const sourceContext = source.getContext("2d");
4863
- const target = new OffscreenCanvas(size.width, size.height);
4864
- const targetContext = target.getContext("2d");
4865
- if (sourceContext === null || targetContext === null) throw new Error("This browser has no 2D canvas to encode the screenshot with.");
4866
- sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);
4867
- targetContext.imageSmoothingQuality = "high";
4868
- targetContext.drawImage(source, 0, 0, size.width, size.height);
4869
- const type = format === "png" ? "image/png" : "image/jpeg";
4870
- const blob = await target.convertToBlob(format === "png" ? { type } : {
4871
- type,
4872
- quality
4873
- });
4874
- return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;
4875
- }
4876
- //#endregion
4877
- //#region src/scene/settings.ts
4878
- /**
4879
- * `describeSettings`: the project's settings sections, as the editor's settings panel reads them,
4880
- * and the values the app resolved for them.
4881
- */
4882
- /**
4883
- * Copies a value made of JSON data, leaving out what JSON cannot carry.
4884
- *
4885
- * @param value - The value.
4886
- * @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a
4887
- * non-finite number.
4888
- */
4889
- function jsonCopy(value) {
4890
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4891
- if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
4892
- if (Array.isArray(value)) return value.map((item) => jsonCopy(item) ?? null);
4893
- if (typeof value === "object") return jsonObjectCopy(value);
4894
- }
4895
5742
  /**
4896
- * Copies an object's own enumerable members with {@link jsonCopy}.
4897
- *
4898
- * @param value - The object.
4899
- * @returns The copy.
4900
- */
4901
- function jsonObjectCopy(value) {
4902
- const copy = {};
4903
- for (const [key, member] of Object.entries(value)) {
4904
- const converted = jsonCopy(member);
4905
- if (converted !== void 0) copy[key] = converted;
4906
- }
4907
- return copy;
4908
- }
4909
- /**
4910
- * Tells whether a JSON value is an object.
4911
- *
4912
- * @param value - The value.
4913
- * @returns True for an object that is not an array.
4914
- */
4915
- function isObject(value) {
4916
- return typeof value === "object" && value !== null && !Array.isArray(value);
4917
- }
4918
- /**
4919
- * Describes every settings section the app registered with core's `describeSettings`, each with
4920
- * its JSON Schema from `settingsJsonSchema` as `propsSchema`, and copies the value the app resolved
4921
- * for each section.
5743
+ * The type ids of the registered component classes a class derives from, nearest first.
4922
5744
  *
4923
5745
  * @remarks
4924
- * Settings are held in the settings form (`{ x, y, z }` for a vector), which is plain data, so a
4925
- * section's value is copied member by member; a member JSON cannot carry is left out. The answer is
4926
- * read from the app each time and sent only on request.
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.
4927
5750
  *
4928
- * @param app - The scene view's app.
4929
- * @returns The sections and their values, keyed by section name in registration order.
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.
4930
5754
  */
4931
- function settingsSet(app) {
4932
- const described = describeSettings(app);
4933
- const properties = settingsJsonSchema(app)["properties"];
4934
- const sections = {};
4935
- const values = {};
4936
- for (const [name, description] of Object.entries(described)) {
4937
- const propsSchema = isObject(properties) ? properties[name] : void 0;
4938
- sections[name] = isObject(propsSchema) ? {
4939
- ...description,
4940
- propsSchema
4941
- } : description;
4942
- const value = app.settings.section(name);
4943
- values[name] = typeof value === "object" && value !== null ? jsonObjectCopy(value) : {};
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));
4944
5761
  }
4945
- return {
4946
- sections,
4947
- values
4948
- };
4949
- }
4950
- //#endregion
4951
- //#region src/scene/view-math.ts
4952
- /**
4953
- * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and
4954
- * plane point a `pick` answers with, the `screenshot` size rule, the transform the drag
4955
- * notifications carry, and gizmo snapping. Each is a pure function, so the headless tests check it
4956
- * directly.
4957
- */
4958
- /**
4959
- * Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its
4960
- * backing pixels.
4961
- *
4962
- * @param surface - The canvas.
4963
- * @returns The sizes.
4964
- */
4965
- function viewSurfaceOf(surface) {
4966
- const clientWidth = Reflect.get(surface, "clientWidth");
4967
- const clientHeight = Reflect.get(surface, "clientHeight");
4968
- return {
4969
- width: surface.width,
4970
- height: surface.height,
4971
- clientWidth: typeof clientWidth === "number" && clientWidth > 0 ? clientWidth : surface.width,
4972
- clientHeight: typeof clientHeight === "number" && clientHeight > 0 ? clientHeight : surface.height
4973
- };
4974
- }
4975
- /**
4976
- * Converts a `pick` point to the backing-store pixels `app.renderer.pickAsync` takes (protocol 0.3,
4977
- * "The pick unit rule"; engine ask E3). This is the host's one conversion: the renderer converts
4978
- * on to the CSS pixels Lite's picker wants.
4979
- *
4980
- * @param params - The point and its unit.
4981
- * @param surface - The canvas's sizes.
4982
- * @returns The point in backing-store pixels, or `null` when it is outside the canvas (a miss).
4983
- */
4984
- function toBackingPixels(params, surface) {
4985
- const x = params.unit === PickUnit.backing ? params.x : params.x * surface.width / surface.clientWidth;
4986
- const y = params.unit === PickUnit.backing ? params.y : params.y * surface.height / surface.clientHeight;
4987
- if (x < 0 || y < 0 || x >= surface.width || y >= surface.height) return null;
4988
- return {
4989
- x,
4990
- y
4991
- };
4992
- }
4993
- /**
4994
- * Turns a camera ray into a `pick` answer's `ray` and `plane` members (protocol 0.3, additive): the
4995
- * ray as it is, and the point where it meets the 2D world plane `z = 0`. The plane point is
4996
- * computed before rounding, and its `z` is exactly `0`.
4997
- *
4998
- * @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.
4999
- * @returns The members, every number rounded with `canonicalizeNumber`.
5000
- */
5001
- function pickRayMembers(ray) {
5002
- const c = canonicalizeNumber;
5003
- const { origin, direction } = ray;
5004
- const members = { ray: {
5005
- origin: [
5006
- c(origin.x),
5007
- c(origin.y),
5008
- c(origin.z)
5009
- ],
5010
- direction: [
5011
- c(direction.x),
5012
- c(direction.y),
5013
- c(direction.z)
5014
- ]
5015
- } };
5016
- const t = direction.z === 0 ? NaN : -origin.z / direction.z;
5017
- if (!Number.isFinite(t) || t < 0) return members;
5018
- return {
5019
- ...members,
5020
- plane: [
5021
- c(origin.x + direction.x * t),
5022
- c(origin.y + direction.y * t),
5023
- 0
5024
- ]
5025
- };
5026
- }
5027
- /**
5028
- * Rounds an image side and keeps it from 1 to {@link SCREENSHOT_MAX_SIZE}.
5029
- *
5030
- * @param side - The side, in pixels.
5031
- * @returns The whole side in range.
5032
- */
5033
- function clampSide(side) {
5034
- return Math.min(SCREENSHOT_MAX_SIZE, Math.max(1, Math.round(side)));
5035
- }
5036
- /**
5037
- * The size of a `screenshot`: the request's, or the view's backing size scaled down, keeping its
5038
- * aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.
5039
- *
5040
- * @param params - The request; its sizes are already checked to be 1 to 2048.
5041
- * @param view - The captured frame's size.
5042
- * @returns The image size, each side at least 1 and at most 2048.
5043
- */
5044
- function screenshotSize(params, view) {
5045
- const aspect = view.height > 0 ? view.width / view.height : 1;
5046
- const { width, height } = params;
5047
- if (width !== void 0 && height !== void 0) return {
5048
- width,
5049
- height
5050
- };
5051
- if (width !== void 0) return {
5052
- width,
5053
- height: clampSide(width / aspect)
5054
- };
5055
- if (height !== void 0) return {
5056
- width: clampSide(height * aspect),
5057
- height
5058
- };
5059
- const fit = Math.min(1, SCREENSHOT_MAX_SIZE / Math.max(view.width, view.height, 1));
5060
- return {
5061
- width: clampSide(view.width * fit),
5062
- height: clampSide(view.height * fit)
5063
- };
5762
+ return ids;
5064
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;
5065
5768
  /**
5066
- * Reads an entity's local transform as the scene file writes it, numbers canonicalized.
5769
+ * Encodes bytes as base64.
5067
5770
  *
5068
- * @param entity - The entity.
5069
- * @returns The transform.
5771
+ * @param bytes - The bytes.
5772
+ * @returns The base64 text.
5070
5773
  */
5071
- function readLocalTransform(entity) {
5072
- const { localPosition: p, localRotation: r, localScale: s } = entity.transform;
5073
- const c = canonicalizeNumber;
5074
- return {
5075
- position: [
5076
- c(p.x),
5077
- c(p.y),
5078
- c(p.z)
5079
- ],
5080
- rotation: [
5081
- c(r.x),
5082
- c(r.y),
5083
- c(r.z),
5084
- c(r.w)
5085
- ],
5086
- scale: [
5087
- c(s.x),
5088
- c(s.y),
5089
- c(s.z)
5090
- ]
5091
- };
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);
5092
5778
  }
5093
5779
  /**
5094
- * Tells whether two transforms are equal number for number.
5780
+ * Scales a captured frame to a size and encodes it as a data URL.
5095
5781
  *
5096
- * @param a - One transform.
5097
- * @param b - The other.
5098
- * @returns True when every channel matches.
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.
5099
5788
  */
5100
- function sameTransform(a, b) {
5101
- return JSON.stringify(a) === JSON.stringify(b);
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()))}`;
5102
5804
  }
5805
+ //#endregion
5806
+ //#region src/scene/settings.ts
5103
5807
  /**
5104
- * Rounds a value to a step; a step of 0 leaves it alone.
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.
5105
5813
  *
5106
5814
  * @param value - The value.
5107
- * @param step - The step.
5108
- * @returns The snapped value.
5815
+ * @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a
5816
+ * non-finite number.
5109
5817
  */
5110
- function snapTo(value, step) {
5111
- 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);
5112
5823
  }
5113
5824
  /**
5114
- * Snaps a gizmo drag after Lite has applied each move (S0.2 §3.4, post-correction). The raw, unsnapped
5115
- * 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.
5116
5829
  */
5117
- var DragSnapper = class {
5118
- #mode;
5119
- #snap;
5120
- #start;
5121
- #raw;
5122
- #written;
5123
- /**
5124
- * Starts snapping one drag.
5125
- *
5126
- * @param mode - The drag's mode.
5127
- * @param snap - The snapping steps.
5128
- * @param entity - The dragged entity, at drag start.
5129
- */
5130
- constructor(mode, snap, entity) {
5131
- this.#mode = mode;
5132
- this.#snap = snap;
5133
- this.#start = this.#read(entity);
5134
- this.#raw = [...this.#start];
5135
- this.#written = [...this.#start];
5136
- }
5137
- /**
5138
- * Folds the move Lite just wrote into the raw value and writes the snapped value back.
5139
- *
5140
- * @param entity - The dragged entity.
5141
- */
5142
- apply(entity) {
5143
- const now = this.#read(entity);
5144
- if (this.#mode === "rotate") {
5145
- this.#applyRotation(entity, now);
5146
- return;
5147
- }
5148
- const step = this.#mode === "translate" ? this.#snap.translate : this.#snap.scale;
5149
- if (step <= 0) return;
5150
- this.#raw = this.#raw.map((value, index) => value + (now[index] ?? 0) - (this.#written[index] ?? 0));
5151
- const snapped = this.#raw.map((value, index) => (this.#start[index] ?? 0) + snapTo(value - (this.#start[index] ?? 0), step));
5152
- (this.#mode === "translate" ? entity.transform.localPosition : entity.transform.localScale).set(snapped[0] ?? 0, snapped[1] ?? 0, snapped[2] ?? 0);
5153
- this.#written = snapped;
5154
- }
5155
- /**
5156
- * Snaps a rotation drag: a ring turns about one axis, so the turn since drag start is one angle,
5157
- * which is rounded to the step.
5158
- *
5159
- * @param entity - The dragged entity.
5160
- * @param now - Its rotation now, as Lite wrote it.
5161
- */
5162
- #applyRotation(entity, now) {
5163
- const step = this.#snap.rotate;
5164
- if (step <= 0) return;
5165
- this.#raw = multiply(multiply(now, conjugate(this.#written)), this.#raw);
5166
- const turn = multiply(this.#raw, conjugate(this.#start));
5167
- const sine = Math.hypot(turn[0] ?? 0, turn[1] ?? 0, turn[2] ?? 0);
5168
- if (sine < 1e-9) return;
5169
- const half = snapTo(2 * Math.atan2(sine, turn[3] ?? 1) * 180 / Math.PI, step) * Math.PI / 180 / 2;
5170
- const scale = Math.sin(half) / sine;
5171
- const result = multiply([
5172
- (turn[0] ?? 0) * scale,
5173
- (turn[1] ?? 0) * scale,
5174
- (turn[2] ?? 0) * scale,
5175
- Math.cos(half)
5176
- ], this.#start);
5177
- entity.transform.localRotation.set(result[0] ?? 0, result[1] ?? 0, result[2] ?? 0, result[3] ?? 1);
5178
- this.#written = result;
5179
- }
5180
- /**
5181
- * Reads the channels this drag moves.
5182
- *
5183
- * @param entity - The entity.
5184
- * @returns Position, scale, or the rotation quaternion.
5185
- */
5186
- #read(entity) {
5187
- const t = entity.transform;
5188
- if (this.#mode === "rotate") return [
5189
- t.localRotation.x,
5190
- t.localRotation.y,
5191
- t.localRotation.z,
5192
- t.localRotation.w
5193
- ];
5194
- const v = this.#mode === "translate" ? t.localPosition : t.localScale;
5195
- return [
5196
- v.x,
5197
- v.y,
5198
- v.z
5199
- ];
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]);
5200
5835
  }
5201
- };
5836
+ return Object.fromEntries(entries);
5837
+ }
5202
5838
  /**
5203
- * Multiplies two quaternions, `a · b`.
5839
+ * Tells whether a JSON value is an object.
5204
5840
  *
5205
- * @param a - The left operand, `[x, y, z, w]`.
5206
- * @param b - The right operand.
5207
- * @returns The product.
5841
+ * @param value - The value.
5842
+ * @returns True for an object that is not an array.
5208
5843
  */
5209
- function multiply(a, b) {
5210
- const [ax = 0, ay = 0, az = 0, aw = 1] = a;
5211
- const [bx = 0, by = 0, bz = 0, bw = 1] = b;
5212
- return [
5213
- aw * bx + ax * bw + ay * bz - az * by,
5214
- aw * by - ax * bz + ay * bw + az * bx,
5215
- aw * bz + ax * by - ay * bx + az * bw,
5216
- aw * bw - ax * bx - ay * by - az * bz
5217
- ];
5844
+ function isObject(value) {
5845
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5218
5846
  }
5219
5847
  /**
5220
- * 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.
5221
5851
  *
5222
- * @param q - The quaternion.
5223
- * @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.
5224
5859
  */
5225
- function conjugate(q) {
5226
- return [
5227
- -(q[0] ?? 0),
5228
- -(q[1] ?? 0),
5229
- -(q[2] ?? 0),
5230
- q[3] ?? 1
5231
- ];
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
+ };
5232
5878
  }
5233
5879
  //#endregion
5234
5880
  //#region src/scene/scene-host.ts
@@ -5272,7 +5918,7 @@ var SceneHost = class {
5272
5918
  space: GizmoSpace.world,
5273
5919
  snap: null
5274
5920
  };
5275
- #drag = null;
5921
+ #drag;
5276
5922
  #started = false;
5277
5923
  /** The field defaults seen at start and after each hot reload, from {@link SceneHost.start} on. */
5278
5924
  #defaults = null;
@@ -5288,6 +5934,7 @@ var SceneHost = class {
5288
5934
  */
5289
5935
  constructor(options) {
5290
5936
  this.#notify = options.notify;
5937
+ this.#drag = new GizmoDragRelay(options.notify);
5291
5938
  const has = (capability) => options.capabilities.includes(capability);
5292
5939
  this.#hasViewMode2D = has(HostCapability.viewMode2d);
5293
5940
  const methods = /* @__PURE__ */ new Map([
@@ -5380,7 +6027,17 @@ var SceneHost = class {
5380
6027
  this.#view = view;
5381
6028
  this.#applyGizmo();
5382
6029
  const onClick = (click) => {
5383
- 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
+ });
5384
6041
  };
5385
6042
  for (const camera of [this.#camera, this.#camera2D]) if (camera !== null) {
5386
6043
  camera.claims = view;
@@ -5423,7 +6080,7 @@ var SceneHost = class {
5423
6080
  return this.#serial(async () => {
5424
6081
  const index = handle.type === "scene" ? mirror.index() : null;
5425
6082
  const roots = index === null ? [] : instancesOf(app, index, address);
5426
- const entities = await this.#rebuildInstances(app, mirror, roots, address, { address }, false);
6083
+ const entities = await this.#rebuildInstances(app, mirror, roots, address, { address });
5427
6084
  this.#setSelection(this.#selection);
5428
6085
  const params = {
5429
6086
  address,
@@ -5443,18 +6100,17 @@ var SceneHost = class {
5443
6100
  * @param roots - The roots' uids, none inside another.
5444
6101
  * @param cause - What the rebuild follows, for the error's message.
5445
6102
  * @param data - What the error's `data` carries besides the root's uid.
5446
- * @param documentOverrides - Whether to rebuild with the document's override lists.
5447
6103
  * @returns The roots rebuilt.
5448
6104
  */
5449
- async #rebuildInstances(app, mirror, roots, cause, data, documentOverrides) {
6105
+ async #rebuildInstances(app, mirror, roots, cause, data) {
5450
6106
  const rebuilt = [];
5451
6107
  for (const uid of roots) try {
5452
- await reloadInstance(app, mirror, uid, documentOverrides);
6108
+ await reloadInstance(app, mirror, uid);
5453
6109
  rebuilt.push(uid);
5454
6110
  } catch (error) {
5455
6111
  const params = {
5456
6112
  code: isIgnifxError(error) ? error.code : null,
5457
- message: `Rebuilding ${uid} from ${cause}: ${messageOf(error)}`,
6113
+ message: clipHostText(`Rebuilding ${uid} from ${cause}: ${messageOf(error)}`),
5458
6114
  data: {
5459
6115
  ...data,
5460
6116
  entity: uid
@@ -5467,7 +6123,8 @@ var SceneHost = class {
5467
6123
  /**
5468
6124
  * Gives the open document the defaults a hot reload changed, where it leaves them out (engine ask
5469
6125
  * E25): each document component's omitted fields take the new default, then each prefab instance
5470
- * 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.
5471
6128
  *
5472
6129
  * @param changed - The changed fields, by type id.
5473
6130
  */
@@ -5476,14 +6133,25 @@ var SceneHost = class {
5476
6133
  const mirror = this.#mirror;
5477
6134
  const index = mirror?.index() ?? null;
5478
6135
  if (app === null || mirror === null || index === null) return;
5479
- 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
+ });
5480
6148
  mirror.invalidate();
5481
6149
  const rebuilt = mirror.index();
5482
- const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, rebuilt, changed));
6150
+ const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, mirror, rebuilt, changed));
5483
6151
  if (roots.length > 0) {
5484
6152
  const typeIds = [...changed.keys()];
5485
6153
  const cause = `the new defaults of ${typeIds.join(", ")}`;
5486
- await this.#rebuildInstances(app, mirror, roots, cause, { typeIds }, true);
6154
+ await this.#rebuildInstances(app, mirror, roots, cause, { typeIds });
5487
6155
  this.#setSelection(this.#selection);
5488
6156
  }
5489
6157
  }
@@ -5543,7 +6211,7 @@ var SceneHost = class {
5543
6211
  * `applyOps`: one command's ops, in order.
5544
6212
  *
5545
6213
  * @param params - `{ ops, commandName, commandId }`.
5546
- * @returns How many applied, and the failures.
6214
+ * @returns How many applied, the failures, and the build problems.
5547
6215
  */
5548
6216
  async #applyOps(params) {
5549
6217
  const mirror = this.#requireMirror(SceneMethod.applyOps);
@@ -5956,7 +6624,7 @@ var SceneHost = class {
5956
6624
  this.#notify(SceneNotification.selectionChanged, { entities: this.#selection });
5957
6625
  }
5958
6626
  /**
5959
- * 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}.
5960
6628
  *
5961
6629
  * @param phase - Which part of the gesture.
5962
6630
  * @param drag - The handle.
@@ -5965,43 +6633,10 @@ var SceneHost = class {
5965
6633
  if (phase === "start") {
5966
6634
  const uid = this.#selection.at(-1);
5967
6635
  const entity = uid === void 0 ? void 0 : this.#mirror?.index()?.entities.get(uid);
5968
- if (entity === void 0) {
5969
- this.#drag = null;
5970
- return;
5971
- }
5972
- const snap = this.#gizmo.snap;
5973
- this.#drag = {
5974
- entity,
5975
- mode: drag.mode,
5976
- before: readLocalTransform(entity),
5977
- snapper: snap === null ? null : new DragSnapper(drag.mode, snap, entity),
5978
- lastSentMs: Number.NEGATIVE_INFINITY
5979
- };
5980
- return;
5981
- }
5982
- const state = this.#drag;
5983
- if (state === null) return;
5984
- if (phase === "move") {
5985
- state.snapper?.apply(state.entity);
5986
- const now = performance.now();
5987
- if (now - state.lastSentMs >= 50) {
5988
- state.lastSentMs = now;
5989
- this.#notify(SceneNotification.transformDragging, {
5990
- entity: state.entity.uid,
5991
- mode: state.mode,
5992
- after: readLocalTransform(state.entity)
5993
- });
5994
- }
5995
- return;
5996
- }
5997
- this.#drag = null;
5998
- const after = readLocalTransform(state.entity);
5999
- if (!sameTransform(state.before, after)) this.#notify(SceneNotification.transformDragged, {
6000
- entity: state.entity.uid,
6001
- mode: state.mode,
6002
- before: state.before,
6003
- after
6004
- });
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();
6005
6640
  }
6006
6641
  /**
6007
6642
  * The world bounds of entities: their meshes' when the view can measure them, else their
@@ -6051,7 +6686,14 @@ var SceneHost = class {
6051
6686
  #hotReloaded(report) {
6052
6687
  this.#mirror?.invalidate();
6053
6688
  const changed = this.#defaults?.changed(report.typeIds) ?? /* @__PURE__ */ new Map();
6054
- 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
+ });
6055
6697
  const params = hotReloadedParamsOf(report);
6056
6698
  this.#notify(SceneNotification.hotReloaded, params);
6057
6699
  this.sendSchemas();
@@ -6161,7 +6803,7 @@ function resolveEngineVersion(fallback, coreVersion = VERSION) {
6161
6803
  * ```ts
6162
6804
  * import { startEditorHost } from "@ignifx/editor-host";
6163
6805
  *
6164
- * const host = await startEditorHost({ editorOrigin: "ignifx://app", canvas, extensions: [], scripts });
6806
+ * const host = await startEditorHost({ editorOrigin: "ignifx-editor://app", canvas, extensions: [], scripts });
6165
6807
  * ```
6166
6808
  *
6167
6809
  * @beta
@@ -6493,7 +7135,7 @@ function openPlayControls(app, options, target, heartbeatIntervalMs, port) {
6493
7135
  *
6494
7136
  * @example
6495
7137
  * ```ts
6496
- * const controls = startEditorPlayControls(app, { editorOrigin: "ignifx://app" });
7138
+ * const controls = startEditorPlayControls(app, { editorOrigin: "ignifx-editor://app" });
6497
7139
  * controls.dispose();
6498
7140
  * ```
6499
7141
  *
@@ -6522,7 +7164,7 @@ function startEditorPlayControls(app, options) {
6522
7164
  *
6523
7165
  * @example
6524
7166
  * ```ts
6525
- * const connector = listenForEditorPlayControls({ editorOrigin: "ignifx://app" });
7167
+ * const connector = listenForEditorPlayControls({ editorOrigin: "ignifx-editor://app" });
6526
7168
  * const app = await createApp({ headless: true });
6527
7169
  * const controls = connector.attach(app);
6528
7170
  * connector.dispose();
@@ -6575,6 +7217,6 @@ function listenForEditorPlayControls(options) {
6575
7217
  };
6576
7218
  }
6577
7219
  //#endregion
6578
- export { ApplyOpFailureCode, COLLIDER_OUTLINES_MAX_ENTITIES, COLLIDER_OUTLINES_MAX_NUMBERS, 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, 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 };
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 };
6579
7221
 
6580
7222
  //# sourceMappingURL=index.js.map