@ignifx/editor-host 0.11.0 → 0.13.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/error-codes.d.ts +3 -3
- package/dist/error-codes.js +3 -3
- package/dist/error-codes.js.map +1 -1
- package/dist/index.d.ts +559 -240
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2207 -938
- package/dist/index.js.map +1 -1
- package/dist/vite.d.ts +6 -4
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +86 -15
- package/dist/vite.js.map +1 -1
- package/package.json +10 -8
- package/skills/editor-host/SKILL.md +58 -17
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, serializeEntity, 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
|
/**
|
|
@@ -40,7 +40,20 @@ const RpcErrorCode = {
|
|
|
40
40
|
*/
|
|
41
41
|
notReady: -32001,
|
|
42
42
|
/** A scene method that needs an open scene was called while none is open (`SceneMethod`). */
|
|
43
|
-
noScene: -32002
|
|
43
|
+
noScene: -32002,
|
|
44
|
+
/**
|
|
45
|
+
* A play method that needs a running game was called while it does not run. `PlayMethod.screenshot`
|
|
46
|
+
* needs the frame loop: it fails before the game starts it, after `stop`, and after `step`.
|
|
47
|
+
* `PlayMethod.queryRuntime` and `PlayMethod.sendInput` need a game that plays or is paused (a
|
|
48
|
+
* stepped game is paused): they fail before the game starts and after `stop`. Additive in 0.3:
|
|
49
|
+
* only a host that answers one of those methods in the play view sends it.
|
|
50
|
+
*/
|
|
51
|
+
notPlaying: -32003,
|
|
52
|
+
/**
|
|
53
|
+
* A play method named an entity uid the game's world does not hold (`PlayMethod.queryRuntime`).
|
|
54
|
+
* Additive in 0.3: only a host that answers `queryRuntime` sends it.
|
|
55
|
+
*/
|
|
56
|
+
unknownEntity: -32004
|
|
44
57
|
};
|
|
45
58
|
/**
|
|
46
59
|
* Narrows to a plain object without an `as` assertion. Shared by this package's guards; not
|
|
@@ -171,9 +184,11 @@ const HostKind = {
|
|
|
171
184
|
* The optional features a host lists in its `ready` result.
|
|
172
185
|
*
|
|
173
186
|
* @remarks
|
|
174
|
-
* The play controls send `
|
|
175
|
-
*
|
|
176
|
-
* `
|
|
187
|
+
* The play controls send `"heartbeat"`, `"playControls"`, `"logRelay"` and `"queryRuntime"`, plus
|
|
188
|
+
* `"screenshot"` when the game has a canvas and `"sendInput"` when it has `app.input`. The scene
|
|
189
|
+
* host sends `"heartbeat"` and whichever of `"gizmos"`, `"screenshot"`, `"viewMode2d"` and
|
|
190
|
+
* `"pick2d"` it supports; every `SceneMethod` not tied to one of them is required of a 0.3 scene
|
|
191
|
+
* host.
|
|
177
192
|
*
|
|
178
193
|
* @public
|
|
179
194
|
*/
|
|
@@ -187,7 +202,11 @@ const HostCapability = {
|
|
|
187
202
|
* `transformDragging` and `transformDragged`.
|
|
188
203
|
*/
|
|
189
204
|
gizmos: "gizmos",
|
|
190
|
-
/**
|
|
205
|
+
/**
|
|
206
|
+
* The host answers `screenshot`: the scene host captures its view, the play controls the game's
|
|
207
|
+
* canvas. The play controls list it from engine ask E47 (additive in 0.3); without it, the play
|
|
208
|
+
* view answers `screenshot` with `RpcErrorCode.methodNotFound`.
|
|
209
|
+
*/
|
|
191
210
|
screenshot: "screenshot",
|
|
192
211
|
/** The scene host accepts `setViewMode` with `"2d"`: a 2D editor camera and planar gizmos. */
|
|
193
212
|
viewMode2d: "viewMode2d",
|
|
@@ -210,9 +229,75 @@ const HostCapability = {
|
|
|
210
229
|
* overrides). A value the document sets is kept. An editor need not reopen the scene for changed
|
|
211
230
|
* defaults. Additive in 0.3.
|
|
212
231
|
*/
|
|
213
|
-
hotReloadDefaults: "hotReloadDefaults"
|
|
232
|
+
hotReloadDefaults: "hotReloadDefaults",
|
|
233
|
+
/**
|
|
234
|
+
* The play controls answer `queryRuntime`: an entity's live state in the scene format. From engine
|
|
235
|
+
* ask E48 (additive in 0.3); without it, the play view answers `queryRuntime` with
|
|
236
|
+
* `RpcErrorCode.methodNotFound`.
|
|
237
|
+
*/
|
|
238
|
+
queryRuntime: "queryRuntime",
|
|
239
|
+
/**
|
|
240
|
+
* The play controls answer `sendInput`: synthetic key and pointer events queued into the game's
|
|
241
|
+
* own input system (`app.input` from `@ignifx/input`), never into the editor's window. Listed only
|
|
242
|
+
* when the game has `app.input`. From engine ask E49 (additive in 0.3); without it, the play view
|
|
243
|
+
* answers `sendInput` with `RpcErrorCode.methodNotFound`.
|
|
244
|
+
*/
|
|
245
|
+
sendInput: "sendInput"
|
|
214
246
|
};
|
|
215
247
|
/**
|
|
248
|
+
* The longest string, in UTF-16 code units, the editor accepts from a host in `ready` (the engine
|
|
249
|
+
* version, each capability name) and in the reports `log`, `hostError` (with `AppErrorData`) and
|
|
250
|
+
* `hotReloaded` (messages, codes, scopes, stacks, type ids). A message holding a longer one fails
|
|
251
|
+
* its guard and is dropped whole. It is far above what the Console keeps (which clips a message or
|
|
252
|
+
* a stack it shows), so it only stops a runaway report from crossing the editor's processes. The
|
|
253
|
+
* host does not clip to it.
|
|
254
|
+
*
|
|
255
|
+
* @public
|
|
256
|
+
*/
|
|
257
|
+
const HOST_TEXT_MAX_LENGTH = 1048576;
|
|
258
|
+
/**
|
|
259
|
+
* The longest list the editor accepts from a host in `ready` (the capabilities) and in a
|
|
260
|
+
* `hotReloaded` report (the type ids, the errors). A message holding a longer one fails its guard
|
|
261
|
+
* and is dropped whole.
|
|
262
|
+
*
|
|
263
|
+
* @public
|
|
264
|
+
*/
|
|
265
|
+
const HOST_LIST_MAX_LENGTH = 4096;
|
|
266
|
+
/**
|
|
267
|
+
* Tells whether a value is a string no longer than {@link HOST_TEXT_MAX_LENGTH}.
|
|
268
|
+
*
|
|
269
|
+
* @param value - The value to test.
|
|
270
|
+
* @returns True for such a string.
|
|
271
|
+
*
|
|
272
|
+
* @internal
|
|
273
|
+
*/
|
|
274
|
+
function isHostText(value) {
|
|
275
|
+
return typeof value === "string" && value.length <= 1048576;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Tells whether a value is `null` or a string no longer than {@link HOST_TEXT_MAX_LENGTH}.
|
|
279
|
+
*
|
|
280
|
+
* @param value - The value to test.
|
|
281
|
+
* @returns True for `null` or such a string.
|
|
282
|
+
*
|
|
283
|
+
* @internal
|
|
284
|
+
*/
|
|
285
|
+
function isHostTextOrNull(value) {
|
|
286
|
+
return value === null || isHostText(value);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Tells whether a value is a list of at most {@link HOST_LIST_MAX_LENGTH} passing items.
|
|
290
|
+
*
|
|
291
|
+
* @param value - The value to test.
|
|
292
|
+
* @param item - The test for one item.
|
|
293
|
+
* @returns True for such a list.
|
|
294
|
+
*
|
|
295
|
+
* @internal
|
|
296
|
+
*/
|
|
297
|
+
function isHostList(value, item) {
|
|
298
|
+
return Array.isArray(value) && value.length <= 4096 && value.every((entry) => item(entry));
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
216
301
|
* Tells whether a value is a protocol version: two non-negative integers.
|
|
217
302
|
*
|
|
218
303
|
* @param value - The value to test.
|
|
@@ -230,14 +315,15 @@ function isProtocolVersion(value) {
|
|
|
230
315
|
*
|
|
231
316
|
* @param value - The received `result`.
|
|
232
317
|
* @returns True when it has a string `engineVersion`, a protocol version, an array of capability
|
|
233
|
-
* strings, and a known `hostKind
|
|
318
|
+
* strings, and a known `hostKind`; the strings and the list within {@link HOST_TEXT_MAX_LENGTH}
|
|
319
|
+
* and {@link HOST_LIST_MAX_LENGTH}.
|
|
234
320
|
*
|
|
235
321
|
* @public
|
|
236
322
|
*/
|
|
237
323
|
function isReadyResult(value) {
|
|
238
324
|
if (!isRecord(value)) return false;
|
|
239
325
|
const { capabilities, hostKind } = value;
|
|
240
|
-
return
|
|
326
|
+
return isHostText(value["engineVersion"]) && isProtocolVersion(value["protocol"]) && isHostList(capabilities, isHostText) && Object.values(HostKind).some((kind) => kind === hostKind);
|
|
241
327
|
}
|
|
242
328
|
/**
|
|
243
329
|
* Checks the `data` of an `incompatibleProtocol` answer to `hello`.
|
|
@@ -277,140 +363,6 @@ heartbeat: "heartbeat" };
|
|
|
277
363
|
*/
|
|
278
364
|
const DEFAULT_HEARTBEAT_INTERVAL_MS = 1e3;
|
|
279
365
|
//#endregion
|
|
280
|
-
//#region src/protocol/play.ts
|
|
281
|
-
/**
|
|
282
|
-
* The play view's controls: the methods the editor calls on the project's own game page after the
|
|
283
|
-
* handshake, through `attachEditorPlayControls(app)` from `virtual:ignifx/editor`. Plan §3.6.
|
|
284
|
-
*/
|
|
285
|
-
/**
|
|
286
|
-
* The methods the play view answers after `ready`. `play`, `pause`, `step` and `stop` answer with a
|
|
287
|
-
* {@link PlayState}; `playState` answers with a {@link PlayStateReport}; `playStats` answers with
|
|
288
|
-
* {@link PlayStats}.
|
|
289
|
-
*
|
|
290
|
-
* @remarks
|
|
291
|
-
* A host that answers them lists `HostCapability.playControls` in `ready`. Sent before `ready`, they
|
|
292
|
-
* fail with `RpcErrorCode.notReady`; sent to a host without them, with `RpcErrorCode.methodNotFound`.
|
|
293
|
-
* `playState` and `playStats` are additive 0.3 methods: a host from before one answers it with
|
|
294
|
-
* `RpcErrorCode.methodNotFound`.
|
|
295
|
-
*
|
|
296
|
-
* @public
|
|
297
|
-
*/
|
|
298
|
-
const PlayMethod = {
|
|
299
|
-
/** Clears `app.time.paused` and starts the frame loop if it is stopped. */
|
|
300
|
-
play: "play",
|
|
301
|
-
/** Sets `app.time.paused`; scripts marked `updateWhenPaused` keep running. */
|
|
302
|
-
pause: "pause",
|
|
303
|
-
/** Stops the frame loop, then advances exactly one frame with `app.step()` and leaves the game paused. */
|
|
304
|
-
step: "step",
|
|
305
|
-
/** Stops the frame loop with `app.stop()`. The editor reloads the view to reset the game. */
|
|
306
|
-
stop: "stop",
|
|
307
|
-
/** Reads the game's state without changing it. Takes no parameters. */
|
|
308
|
-
playState: "playState",
|
|
309
|
-
/**
|
|
310
|
-
* Reads the game's frame rate, frame time, entity count and frame count without changing
|
|
311
|
-
* anything. Takes no parameters. The editor polls it; no notification carries it.
|
|
312
|
-
*/
|
|
313
|
-
playStats: "playStats"
|
|
314
|
-
};
|
|
315
|
-
/**
|
|
316
|
-
* The notifications the play view sends after `ready`.
|
|
317
|
-
*
|
|
318
|
-
* @remarks
|
|
319
|
-
* Additive in 0.3: a host from before them sends none, and answers `playState` with
|
|
320
|
-
* `RpcErrorCode.methodNotFound`. `log`, `hostError` and `hotReloaded` came later still: only a host
|
|
321
|
-
* that lists `HostCapability.logRelay` in `ready` sends them.
|
|
322
|
-
*
|
|
323
|
-
* @public
|
|
324
|
-
*/
|
|
325
|
-
const PlayNotification = {
|
|
326
|
-
/**
|
|
327
|
-
* After the game's {@link PlayStateReport.state} changed. A change a `PlayMethod` makes is sent
|
|
328
|
-
* right after that method's answer; one the game makes itself, such as setting
|
|
329
|
-
* `app.time.paused`, within one heartbeat interval.
|
|
330
|
-
*/
|
|
331
|
-
playStateChanged: "playStateChanged",
|
|
332
|
-
/**
|
|
333
|
-
* One line from the game's logger, with the same `LogParams` as the scene view's `log`. Sent by a
|
|
334
|
-
* host that lists `HostCapability.logRelay`; lines logged before the handshake are kept (the
|
|
335
|
-
* newest few hundred) and sent right after `ready`.
|
|
336
|
-
*/
|
|
337
|
-
log: "log",
|
|
338
|
-
/**
|
|
339
|
-
* An error the game's app reported through `app.onError`: the same `HostErrorParams` as the scene
|
|
340
|
-
* view's `hostError`, with `AppErrorData` as its `data`. Sent by a host that lists
|
|
341
|
-
* `HostCapability.logRelay`, kept before the handshake as `log` is.
|
|
342
|
-
*/
|
|
343
|
-
hostError: "hostError",
|
|
344
|
-
/**
|
|
345
|
-
* After every `app.hotReload` operation in the game: the same `HotReloadedParams` as the scene
|
|
346
|
-
* view's `hotReloaded`. Sent by a host that lists `HostCapability.logRelay`.
|
|
347
|
-
*/
|
|
348
|
-
hotReloaded: "hotReloaded"
|
|
349
|
-
};
|
|
350
|
-
/**
|
|
351
|
-
* Whether the game plays, is paused, or is stopped, as {@link PlayStateReport.state} reports it.
|
|
352
|
-
*
|
|
353
|
-
* @public
|
|
354
|
-
*/
|
|
355
|
-
const PlayPhase = {
|
|
356
|
-
/** The frame loop runs (`app.isRunning`) and game time is not paused. */
|
|
357
|
-
playing: "playing",
|
|
358
|
-
/**
|
|
359
|
-
* Game time is paused (`app.time.paused`): after `pause`, or after `step`, which leaves the frame
|
|
360
|
-
* loop stopped on the stepped frame.
|
|
361
|
-
*/
|
|
362
|
-
paused: "paused",
|
|
363
|
-
/** The frame loop does not run: before the game starts it, or after `stop`. */
|
|
364
|
-
stopped: "stopped"
|
|
365
|
-
};
|
|
366
|
-
/**
|
|
367
|
-
* Checks the `result` of a play method's response.
|
|
368
|
-
*
|
|
369
|
-
* @param value - The received `result`.
|
|
370
|
-
* @returns True when `value` has boolean `isRunning` and `isPaused` and a non-negative integer
|
|
371
|
-
* `frameCount`.
|
|
372
|
-
*
|
|
373
|
-
* @public
|
|
374
|
-
*/
|
|
375
|
-
function isPlayState(value) {
|
|
376
|
-
if (!isRecord(value)) return false;
|
|
377
|
-
const frameCount = value["frameCount"];
|
|
378
|
-
return typeof value["isRunning"] === "boolean" && typeof value["isPaused"] === "boolean" && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0;
|
|
379
|
-
}
|
|
380
|
-
/**
|
|
381
|
-
* Checks the `result` of `playState` and the `params` of `playStateChanged`.
|
|
382
|
-
*
|
|
383
|
-
* @param value - The received value.
|
|
384
|
-
* @returns True when `value` has a `state` that is a `PlayPhase`, a non-negative integer
|
|
385
|
-
* `frameCount`, and a non-negative finite `time`.
|
|
386
|
-
*
|
|
387
|
-
* @public
|
|
388
|
-
*/
|
|
389
|
-
function isPlayStateReport(value) {
|
|
390
|
-
if (!isRecord(value)) return false;
|
|
391
|
-
const state = value["state"];
|
|
392
|
-
const frameCount = value["frameCount"];
|
|
393
|
-
const time = value["time"];
|
|
394
|
-
return typeof state === "string" && Object.values(PlayPhase).includes(state) && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0 && typeof time === "number" && Number.isFinite(time) && time >= 0;
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
|
-
* Checks the `result` of `playStats`.
|
|
398
|
-
*
|
|
399
|
-
* @param value - The received `result`.
|
|
400
|
-
* @returns True when `value` has non-negative finite `fps` and `frameTimeMs` and non-negative
|
|
401
|
-
* integer `entityCount` and `frameCount`.
|
|
402
|
-
*
|
|
403
|
-
* @public
|
|
404
|
-
*/
|
|
405
|
-
function isPlayStats(value) {
|
|
406
|
-
if (!isRecord(value)) return false;
|
|
407
|
-
const fps = value["fps"];
|
|
408
|
-
const frameTimeMs = value["frameTimeMs"];
|
|
409
|
-
const entityCount = value["entityCount"];
|
|
410
|
-
const frameCount = value["frameCount"];
|
|
411
|
-
return typeof fps === "number" && Number.isFinite(fps) && fps >= 0 && typeof frameTimeMs === "number" && Number.isFinite(frameTimeMs) && frameTimeMs >= 0 && typeof entityCount === "number" && Number.isSafeInteger(entityCount) && entityCount >= 0 && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0;
|
|
412
|
-
}
|
|
413
|
-
//#endregion
|
|
414
366
|
//#region src/protocol/scene-file.ts
|
|
415
367
|
/**
|
|
416
368
|
* The engine's scene file format as it travels on the wire: the same object `@ignifx/core`'s
|
|
@@ -425,7 +377,7 @@ function isPlayStats(value) {
|
|
|
425
377
|
* file with the engine's `validateSceneFile`.
|
|
426
378
|
*/
|
|
427
379
|
/** How deep a JSON value may nest before {@link isJsonValue} refuses it, as a guard against cycles. */
|
|
428
|
-
const MAX_JSON_DEPTH = 256;
|
|
380
|
+
const MAX_JSON_DEPTH$1 = 256;
|
|
429
381
|
/**
|
|
430
382
|
* Tells whether a value is JSON: `null`, a boolean, a string, a finite number, or an array or
|
|
431
383
|
* plain object of JSON values, nested at most 256 levels deep.
|
|
@@ -446,7 +398,7 @@ function isJsonValue(value) {
|
|
|
446
398
|
* @returns True for a JSON value no deeper than the limit.
|
|
447
399
|
*/
|
|
448
400
|
function isJsonValueAt(value, depth) {
|
|
449
|
-
if (depth > MAX_JSON_DEPTH) return false;
|
|
401
|
+
if (depth > MAX_JSON_DEPTH$1) return false;
|
|
450
402
|
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
451
403
|
if (typeof value === "number") return Number.isFinite(value);
|
|
452
404
|
if (Array.isArray(value)) return value.every((item) => isJsonValueAt(item, depth + 1));
|
|
@@ -640,74 +592,364 @@ function isSceneFile(value) {
|
|
|
640
592
|
return isRecord(value) && isString(value["format"]) && Number.isSafeInteger(value["formatVersion"]) && optionalField(value, "engineVersion", isString) && isString(value["name"]) && optionalField(value, "settings", isJsonObject) && isArrayOf(value["entities"], isSceneFileEntity);
|
|
641
593
|
}
|
|
642
594
|
//#endregion
|
|
643
|
-
//#region src/protocol/
|
|
595
|
+
//#region src/protocol/play.ts
|
|
644
596
|
/**
|
|
645
|
-
* The
|
|
646
|
-
*
|
|
647
|
-
* applied to its document is sent to the host unchanged and MCP's `apply_ops` accepts the same JSON.
|
|
648
|
-
*
|
|
649
|
-
* @remarks
|
|
650
|
-
* The types are restated here because this package has no dependencies. Every op, field name and
|
|
651
|
-
* literal string is editor-core's; the package's tests check that editor-core's `SceneOp` and this
|
|
652
|
-
* one are assignable both ways. Whether an op makes sense for a document (does the entity exist, is
|
|
653
|
-
* the index in range) is not the wire's question: editor-core answers it before the op is sent, and
|
|
654
|
-
* the host answers it again when it applies the op to the live world.
|
|
597
|
+
* The play view's controls: the methods the editor calls on the project's own game page after the
|
|
598
|
+
* handshake, through `attachEditorPlayControls(app)` from `virtual:ignifx/editor`. Plan §3.6.
|
|
655
599
|
*/
|
|
656
600
|
/**
|
|
657
|
-
* The `
|
|
601
|
+
* The methods the play view answers after `ready`. `play`, `pause`, `step` and `stop` answer with a
|
|
602
|
+
* {@link PlayState}; `playState` answers with a {@link PlayStateReport}; `playStats` answers with
|
|
603
|
+
* {@link PlayStats}; `screenshot` answers with a `ScreenshotResult`; `queryRuntime` answers with a
|
|
604
|
+
* {@link QueryRuntimeResult}; `sendInput` answers with a {@link SendInputResult}.
|
|
658
605
|
*
|
|
659
606
|
* @remarks
|
|
660
|
-
*
|
|
607
|
+
* A host that answers them lists `HostCapability.playControls` in `ready`. Sent before `ready`, they
|
|
608
|
+
* fail with `RpcErrorCode.notReady`; sent to a host without them, with `RpcErrorCode.methodNotFound`.
|
|
609
|
+
* `playState`, `playStats`, `screenshot`, `queryRuntime` and `sendInput` are additive 0.3 methods:
|
|
610
|
+
* a host from before one answers it with `RpcErrorCode.methodNotFound`. `screenshot`, `queryRuntime`
|
|
611
|
+
* and `sendInput` also need the `HostCapability` of the same name in the play view's `ready`.
|
|
661
612
|
*
|
|
662
613
|
* @public
|
|
663
614
|
*/
|
|
664
|
-
const
|
|
665
|
-
/**
|
|
666
|
-
|
|
667
|
-
/**
|
|
668
|
-
|
|
669
|
-
/**
|
|
670
|
-
|
|
671
|
-
/**
|
|
672
|
-
|
|
673
|
-
/**
|
|
674
|
-
|
|
675
|
-
/**
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
615
|
+
const PlayMethod = {
|
|
616
|
+
/** Clears `app.time.paused` and starts the frame loop if it is stopped. */
|
|
617
|
+
play: "play",
|
|
618
|
+
/** Sets `app.time.paused`; scripts marked `updateWhenPaused` keep running. */
|
|
619
|
+
pause: "pause",
|
|
620
|
+
/** Stops the frame loop, then advances exactly one frame with `app.step()` and leaves the game paused. */
|
|
621
|
+
step: "step",
|
|
622
|
+
/** Stops the frame loop with `app.stop()`. The editor reloads the view to reset the game. */
|
|
623
|
+
stop: "stop",
|
|
624
|
+
/** Reads the game's state without changing it. Takes no parameters. */
|
|
625
|
+
playState: "playState",
|
|
626
|
+
/**
|
|
627
|
+
* Reads the game's frame rate, frame time, entity count and frame count without changing
|
|
628
|
+
* anything. Takes no parameters. The editor polls it; no notification carries it.
|
|
629
|
+
*/
|
|
630
|
+
playStats: "playStats",
|
|
631
|
+
/**
|
|
632
|
+
* Captures the game's canvas as an image, with the scene view's `screenshot` parameters, caps and
|
|
633
|
+
* answer (`ScreenshotParams`, `ScreenshotResult`). Changes nothing: a paused game is captured
|
|
634
|
+
* paused. Needs `HostCapability.screenshot`. Fails with `RpcErrorCode.notPlaying` while the frame
|
|
635
|
+
* loop does not run (before the game starts it, after `stop` or `step`), and with
|
|
636
|
+
* `RpcErrorCode.notReady` before the game's first frame.
|
|
637
|
+
*/
|
|
638
|
+
screenshot: "screenshot",
|
|
639
|
+
/**
|
|
640
|
+
* Reads one entity of the running game as the scene format writes it ({@link QueryRuntimeParams},
|
|
641
|
+
* {@link QueryRuntimeResult}): its live transform, flags and component props, never anything a
|
|
642
|
+
* component does not serialize, and no expressions. Each value is capped and the whole answer kept
|
|
643
|
+
* within {@link QUERY_RUNTIME_MAX_JSON_LENGTH}. Changes nothing. Needs
|
|
644
|
+
* `HostCapability.queryRuntime`. Fails with `RpcErrorCode.notPlaying` while the game is stopped
|
|
645
|
+
* (before it starts, after `stop`; a stepped game is paused and answers), and with
|
|
646
|
+
* `RpcErrorCode.unknownEntity` when no entity of the game has the uid.
|
|
647
|
+
*/
|
|
648
|
+
queryRuntime: "queryRuntime",
|
|
649
|
+
/**
|
|
650
|
+
* Queues synthetic key and pointer events into the game's own input system, as if the game's page
|
|
651
|
+
* had received them ({@link SendInputParams}, {@link SendInputResult}). Nothing reaches the
|
|
652
|
+
* editor's window or the operating system. Needs `HostCapability.sendInput`, which a game lists
|
|
653
|
+
* only when it has `app.input` (`@ignifx/input`). Fails with `RpcErrorCode.notPlaying` while the
|
|
654
|
+
* game is stopped; a paused or stepped game takes the events and resolves them on its next frame,
|
|
655
|
+
* which for a stepped game is the next `step`.
|
|
656
|
+
*/
|
|
657
|
+
sendInput: "sendInput"
|
|
691
658
|
};
|
|
692
659
|
/**
|
|
693
|
-
*
|
|
694
|
-
*
|
|
660
|
+
* The most components a `queryRuntime` answer holds, and the most type ids its `components` filter
|
|
661
|
+
* may name. Components past it are counted in {@link QueryRuntimeResult.omittedComponents}.
|
|
695
662
|
*
|
|
696
|
-
* @
|
|
697
|
-
* @returns True for a non-negative safe integer.
|
|
663
|
+
* @public
|
|
698
664
|
*/
|
|
699
|
-
|
|
700
|
-
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
701
|
-
}
|
|
665
|
+
const QUERY_RUNTIME_MAX_COMPONENTS = 64;
|
|
702
666
|
/**
|
|
703
|
-
*
|
|
667
|
+
* The longest a `queryRuntime` answer may be: its `result` as JSON text, in UTF-16 code units
|
|
668
|
+
* (`JSON.stringify(result).length`), 256 Ki. Components that would pass it are left out, in order,
|
|
669
|
+
* and counted in {@link QueryRuntimeResult.omittedComponents}.
|
|
704
670
|
*
|
|
705
|
-
* @
|
|
706
|
-
* @returns True for an array of strings and non-negative safe integers.
|
|
671
|
+
* @public
|
|
707
672
|
*/
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
673
|
+
const QUERY_RUNTIME_MAX_JSON_LENGTH = 262144;
|
|
674
|
+
/**
|
|
675
|
+
* In a `queryRuntime` answer, the most keys one object keeps and the longest a key may be; also the
|
|
676
|
+
* longest the entity's `name`, `layer`, each tag and each component `type` may be, and the most
|
|
677
|
+
* tags kept. Keys left out are counted in {@link QueryRuntimeResult.omittedEntries}.
|
|
678
|
+
*
|
|
679
|
+
* @public
|
|
680
|
+
*/
|
|
681
|
+
const QUERY_RUNTIME_MAX_KEYS = 256;
|
|
682
|
+
/**
|
|
683
|
+
* In a `queryRuntime` answer, the longest a prop string may be, `… [clipped]` included: 64 Ki, a
|
|
684
|
+
* quarter of {@link QUERY_RUNTIME_MAX_JSON_LENGTH}, so one long string does not cost its component
|
|
685
|
+
* its place.
|
|
686
|
+
*
|
|
687
|
+
* @public
|
|
688
|
+
*/
|
|
689
|
+
const QUERY_RUNTIME_MAX_STRING_LENGTH = 65536;
|
|
690
|
+
/**
|
|
691
|
+
* The most events one `sendInput` request may carry.
|
|
692
|
+
*
|
|
693
|
+
* @public
|
|
694
|
+
*/
|
|
695
|
+
const SEND_INPUT_MAX_EVENTS = 64;
|
|
696
|
+
/**
|
|
697
|
+
* The notifications the play view sends after `ready`.
|
|
698
|
+
*
|
|
699
|
+
* @remarks
|
|
700
|
+
* Additive in 0.3: a host from before them sends none, and answers `playState` with
|
|
701
|
+
* `RpcErrorCode.methodNotFound`. `log`, `hostError` and `hotReloaded` came later still: only a host
|
|
702
|
+
* that lists `HostCapability.logRelay` in `ready` sends them.
|
|
703
|
+
*
|
|
704
|
+
* @public
|
|
705
|
+
*/
|
|
706
|
+
const PlayNotification = {
|
|
707
|
+
/**
|
|
708
|
+
* After the game's {@link PlayStateReport.state} changed. A change a `PlayMethod` makes is sent
|
|
709
|
+
* right after that method's answer; one the game makes itself, such as setting
|
|
710
|
+
* `app.time.paused`, within one heartbeat interval.
|
|
711
|
+
*/
|
|
712
|
+
playStateChanged: "playStateChanged",
|
|
713
|
+
/**
|
|
714
|
+
* One line from the game's logger, with the same `LogParams` as the scene view's `log`. Sent by a
|
|
715
|
+
* host that lists `HostCapability.logRelay`; lines logged before the handshake are kept (the
|
|
716
|
+
* newest few hundred) and sent right after `ready`.
|
|
717
|
+
*/
|
|
718
|
+
log: "log",
|
|
719
|
+
/**
|
|
720
|
+
* An error the game's app reported through `app.onError`: the same `HostErrorParams` as the scene
|
|
721
|
+
* view's `hostError`, with `AppErrorData` as its `data`. Sent by a host that lists
|
|
722
|
+
* `HostCapability.logRelay`, kept before the handshake as `log` is.
|
|
723
|
+
*/
|
|
724
|
+
hostError: "hostError",
|
|
725
|
+
/**
|
|
726
|
+
* After every `app.hotReload` operation in the game: the same `HotReloadedParams` as the scene
|
|
727
|
+
* view's `hotReloaded`. Sent by a host that lists `HostCapability.logRelay`.
|
|
728
|
+
*/
|
|
729
|
+
hotReloaded: "hotReloaded"
|
|
730
|
+
};
|
|
731
|
+
/**
|
|
732
|
+
* Whether the game plays, is paused, or is stopped, as {@link PlayStateReport.state} reports it.
|
|
733
|
+
*
|
|
734
|
+
* @public
|
|
735
|
+
*/
|
|
736
|
+
const PlayPhase = {
|
|
737
|
+
/** The frame loop runs (`app.isRunning`) and game time is not paused. */
|
|
738
|
+
playing: "playing",
|
|
739
|
+
/**
|
|
740
|
+
* Game time is paused (`app.time.paused`): after `pause`, or after `step`, which leaves the frame
|
|
741
|
+
* loop stopped on the stepped frame.
|
|
742
|
+
*/
|
|
743
|
+
paused: "paused",
|
|
744
|
+
/** The frame loop does not run: before the game starts it, or after `stop`. */
|
|
745
|
+
stopped: "stopped"
|
|
746
|
+
};
|
|
747
|
+
/**
|
|
748
|
+
* Checks the `result` of a play method's response.
|
|
749
|
+
*
|
|
750
|
+
* @param value - The received `result`.
|
|
751
|
+
* @returns True when `value` has boolean `isRunning` and `isPaused` and a non-negative integer
|
|
752
|
+
* `frameCount`.
|
|
753
|
+
*
|
|
754
|
+
* @public
|
|
755
|
+
*/
|
|
756
|
+
function isPlayState(value) {
|
|
757
|
+
if (!isRecord(value)) return false;
|
|
758
|
+
const frameCount = value["frameCount"];
|
|
759
|
+
return typeof value["isRunning"] === "boolean" && typeof value["isPaused"] === "boolean" && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0;
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Checks the `result` of `playState` and the `params` of `playStateChanged`.
|
|
763
|
+
*
|
|
764
|
+
* @param value - The received value.
|
|
765
|
+
* @returns True when `value` has a `state` that is a `PlayPhase`, a non-negative integer
|
|
766
|
+
* `frameCount`, and a non-negative finite `time`.
|
|
767
|
+
*
|
|
768
|
+
* @public
|
|
769
|
+
*/
|
|
770
|
+
function isPlayStateReport(value) {
|
|
771
|
+
if (!isRecord(value)) return false;
|
|
772
|
+
const state = value["state"];
|
|
773
|
+
const frameCount = value["frameCount"];
|
|
774
|
+
const time = value["time"];
|
|
775
|
+
return typeof state === "string" && Object.values(PlayPhase).includes(state) && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0 && typeof time === "number" && Number.isFinite(time) && time >= 0;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Checks the `result` of `playStats`.
|
|
779
|
+
*
|
|
780
|
+
* @param value - The received `result`.
|
|
781
|
+
* @returns True when `value` has non-negative finite `fps` and `frameTimeMs` and non-negative
|
|
782
|
+
* integer `entityCount` and `frameCount`.
|
|
783
|
+
*
|
|
784
|
+
* @public
|
|
785
|
+
*/
|
|
786
|
+
function isPlayStats(value) {
|
|
787
|
+
if (!isRecord(value)) return false;
|
|
788
|
+
const fps = value["fps"];
|
|
789
|
+
const frameTimeMs = value["frameTimeMs"];
|
|
790
|
+
const entityCount = value["entityCount"];
|
|
791
|
+
const frameCount = value["frameCount"];
|
|
792
|
+
return typeof fps === "number" && Number.isFinite(fps) && fps >= 0 && typeof frameTimeMs === "number" && Number.isFinite(frameTimeMs) && frameTimeMs >= 0 && typeof entityCount === "number" && Number.isSafeInteger(entityCount) && entityCount >= 0 && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Checks the `params` of `queryRuntime`.
|
|
796
|
+
*
|
|
797
|
+
* @param value - The received `params`.
|
|
798
|
+
* @returns True for a non-empty `entity` uid and, when present, a `components` list of at most
|
|
799
|
+
* {@link QUERY_RUNTIME_MAX_COMPONENTS} non-empty strings.
|
|
800
|
+
*
|
|
801
|
+
* @public
|
|
802
|
+
*/
|
|
803
|
+
function isQueryRuntimeParams(value) {
|
|
804
|
+
if (!isRecord(value) || !isUidString(value["entity"])) return false;
|
|
805
|
+
const components = value["components"];
|
|
806
|
+
return components === void 0 || Array.isArray(components) && components.length <= 64 && components.every((typeId) => typeof typeId === "string" && typeId.length > 0);
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Checks the `result` of `queryRuntime`.
|
|
810
|
+
*
|
|
811
|
+
* @param value - The received `result`.
|
|
812
|
+
* @returns True for an entity record with at most {@link QUERY_RUNTIME_MAX_COMPONENTS} components,
|
|
813
|
+
* non-negative integer `omittedComponents`, `omittedEntries` and `frameCount`, and a non-negative
|
|
814
|
+
* finite `time`, no longer than {@link QUERY_RUNTIME_MAX_JSON_LENGTH} as JSON.
|
|
815
|
+
*
|
|
816
|
+
* @public
|
|
817
|
+
*/
|
|
818
|
+
function isQueryRuntimeResult(value) {
|
|
819
|
+
if (!isRecord(value)) return false;
|
|
820
|
+
const entity = value["entity"];
|
|
821
|
+
const omitted = value["omittedComponents"];
|
|
822
|
+
const omittedEntries = value["omittedEntries"];
|
|
823
|
+
const frameCount = value["frameCount"];
|
|
824
|
+
const time = value["time"];
|
|
825
|
+
return isSceneFileEntity(entity) && (entity.components ?? []).length <= 64 && typeof omitted === "number" && Number.isSafeInteger(omitted) && omitted >= 0 && typeof omittedEntries === "number" && Number.isSafeInteger(omittedEntries) && omittedEntries >= 0 && typeof frameCount === "number" && Number.isSafeInteger(frameCount) && frameCount >= 0 && typeof time === "number" && Number.isFinite(time) && time >= 0 && JSON.stringify(value).length <= 262144;
|
|
826
|
+
}
|
|
827
|
+
/** A `<Keyboard>` control name as `sendInput` accepts it. */
|
|
828
|
+
const KEY_CONTROL_PATTERN = /^[A-Za-z0-9]{1,64}$/u;
|
|
829
|
+
/**
|
|
830
|
+
* Tells whether a value is a fraction from 0 to 1.
|
|
831
|
+
*
|
|
832
|
+
* @param value - The value to test.
|
|
833
|
+
* @returns True for a finite number from 0 to 1.
|
|
834
|
+
*/
|
|
835
|
+
function isFraction(value) {
|
|
836
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Checks one event of a `sendInput` request.
|
|
840
|
+
*
|
|
841
|
+
* @param value - The value to test.
|
|
842
|
+
* @returns True for a key event with a well-formed `control`, or a pointer event with `x` and `y`
|
|
843
|
+
* from 0 to 1 and, when present, an integer `button` from 0 to 4.
|
|
844
|
+
*
|
|
845
|
+
* @public
|
|
846
|
+
*/
|
|
847
|
+
function isSendInputEvent(value) {
|
|
848
|
+
if (!isRecord(value)) return false;
|
|
849
|
+
const type = value["type"];
|
|
850
|
+
if (type === "keydown" || type === "keyup") {
|
|
851
|
+
const control = value["control"];
|
|
852
|
+
return typeof control === "string" && KEY_CONTROL_PATTERN.test(control);
|
|
853
|
+
}
|
|
854
|
+
if (type !== "pointermove" && type !== "pointerdown" && type !== "pointerup") return false;
|
|
855
|
+
const button = value["button"];
|
|
856
|
+
return isFraction(value["x"]) && isFraction(value["y"]) && (button === void 0 || typeof button === "number" && Number.isInteger(button) && button >= 0 && button <= 4);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Checks the `params` of `sendInput`.
|
|
860
|
+
*
|
|
861
|
+
* @param value - The received `params`.
|
|
862
|
+
* @returns True for an `events` list of 1 to {@link SEND_INPUT_MAX_EVENTS} well-formed events.
|
|
863
|
+
*
|
|
864
|
+
* @public
|
|
865
|
+
*/
|
|
866
|
+
function isSendInputParams(value) {
|
|
867
|
+
if (!isRecord(value)) return false;
|
|
868
|
+
const events = value["events"];
|
|
869
|
+
return Array.isArray(events) && events.length > 0 && events.length <= 64 && events.every((event) => isSendInputEvent(event));
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Checks the `result` of `sendInput`.
|
|
873
|
+
*
|
|
874
|
+
* @param value - The received `result`.
|
|
875
|
+
* @returns True for an integer `queued` from 0 to {@link SEND_INPUT_MAX_EVENTS}.
|
|
876
|
+
*
|
|
877
|
+
* @public
|
|
878
|
+
*/
|
|
879
|
+
function isSendInputResult(value) {
|
|
880
|
+
if (!isRecord(value)) return false;
|
|
881
|
+
const queued = value["queued"];
|
|
882
|
+
return typeof queued === "number" && Number.isSafeInteger(queued) && queued >= 0 && queued <= 64;
|
|
883
|
+
}
|
|
884
|
+
//#endregion
|
|
885
|
+
//#region src/protocol/scene-ops.ts
|
|
886
|
+
/**
|
|
887
|
+
* The scene op vocabulary on the wire: the thirteen ops of plan §3.4, exactly as
|
|
888
|
+
* `@ignifx/editor-core` defines them (`packages/editor-core/src/ops.ts`), so a command the editor
|
|
889
|
+
* applied to its document is sent to the host unchanged and MCP's `apply_ops` accepts the same JSON.
|
|
890
|
+
*
|
|
891
|
+
* @remarks
|
|
892
|
+
* The types are restated here because this package has no dependencies. Every op, field name and
|
|
893
|
+
* literal string is editor-core's; the package's tests check that editor-core's `SceneOp` and this
|
|
894
|
+
* one are assignable both ways. Whether an op makes sense for a document (does the entity exist, is
|
|
895
|
+
* the index in range) is not the wire's question: editor-core answers it before the op is sent, and
|
|
896
|
+
* the host answers it again when it applies the op to the live world.
|
|
897
|
+
*/
|
|
898
|
+
/**
|
|
899
|
+
* The `op` discriminant of every scene op.
|
|
900
|
+
*
|
|
901
|
+
* @remarks
|
|
902
|
+
* `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).
|
|
903
|
+
*
|
|
904
|
+
* @public
|
|
905
|
+
*/
|
|
906
|
+
const SceneOpKind = {
|
|
907
|
+
/** Creates an entity, optionally with a subtree. */
|
|
908
|
+
createEntity: "createEntity",
|
|
909
|
+
/** Destroys an entity and its subtree. */
|
|
910
|
+
destroyEntity: "destroyEntity",
|
|
911
|
+
/** Moves an entity under another parent, keeping its local transform. */
|
|
912
|
+
reparent: "reparent",
|
|
913
|
+
/** Moves an entity among its siblings. */
|
|
914
|
+
reorder: "reorder",
|
|
915
|
+
/** Sets `name`, `active`, `static`, `layer` or `tags`. */
|
|
916
|
+
setEntityField: "setEntityField",
|
|
917
|
+
/** Sets an entity's local transform. */
|
|
918
|
+
setTransform: "setTransform",
|
|
919
|
+
/** Adds a component. */
|
|
920
|
+
addComponent: "addComponent",
|
|
921
|
+
/** Removes a component. */
|
|
922
|
+
removeComponent: "removeComponent",
|
|
923
|
+
/** Sets or removes a value inside a component's `props`. */
|
|
924
|
+
setProp: "setProp",
|
|
925
|
+
/** Sets or removes a value inside the scene's `settings`. */
|
|
926
|
+
setSceneSetting: "setSceneSetting",
|
|
927
|
+
/** Creates an instance root (a prefab instance). */
|
|
928
|
+
instantiate: "instantiate",
|
|
929
|
+
/** Sets an override on an instance root. */
|
|
930
|
+
setOverride: "setOverride",
|
|
931
|
+
/** Removes an override from an instance root. */
|
|
932
|
+
removeOverride: "removeOverride"
|
|
933
|
+
};
|
|
934
|
+
/**
|
|
935
|
+
* Tells whether a value is an insertion index: a non-negative safe integer. Whether it is in range
|
|
936
|
+
* is the applier's question.
|
|
937
|
+
*
|
|
938
|
+
* @param value - The value to test.
|
|
939
|
+
* @returns True for a non-negative safe integer.
|
|
940
|
+
*/
|
|
941
|
+
function isIndex(value) {
|
|
942
|
+
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* Tells whether a value is a JSON path.
|
|
946
|
+
*
|
|
947
|
+
* @param value - The value to test.
|
|
948
|
+
* @returns True for an array of strings and non-negative safe integers.
|
|
949
|
+
*/
|
|
950
|
+
function isJsonPath(value) {
|
|
951
|
+
return isArrayOf(value, (step) => isString(step) || isIndex(step));
|
|
952
|
+
}
|
|
711
953
|
/**
|
|
712
954
|
* Tells whether a value is a parent: a uid or `null`.
|
|
713
955
|
*
|
|
@@ -1135,12 +1377,13 @@ function isApplyOpFailure(value) {
|
|
|
1135
1377
|
* Checks the result of `applyOps`.
|
|
1136
1378
|
*
|
|
1137
1379
|
* @param value - The received `result`.
|
|
1138
|
-
* @returns True for a count of applied ops
|
|
1380
|
+
* @returns True for a count of applied ops, a list of failures with known codes, and an optional
|
|
1381
|
+
* list of issues.
|
|
1139
1382
|
*
|
|
1140
1383
|
* @public
|
|
1141
1384
|
*/
|
|
1142
1385
|
function isApplyOpsResult(value) {
|
|
1143
|
-
return isRecord(value) && isCount(value["applied"]) && isArrayOf(value["failures"], isApplyOpFailure);
|
|
1386
|
+
return isRecord(value) && isCount(value["applied"]) && isArrayOf(value["failures"], isApplyOpFailure) && optionalField(value, "warnings", (warnings) => isArrayOf(warnings, isSceneIssue));
|
|
1144
1387
|
}
|
|
1145
1388
|
/**
|
|
1146
1389
|
* Checks the parameters of `readBack`.
|
|
@@ -1281,10 +1524,10 @@ function isSchemaFieldDescription(value) {
|
|
|
1281
1524
|
*
|
|
1282
1525
|
* @param value - The value to test.
|
|
1283
1526
|
* @returns True for `{ title, format, description?, fields, allowMultiple?, package?, builtIn?,
|
|
1284
|
-
* propsSchema? }`, ignoring members it does not declare.
|
|
1527
|
+
* requires?, extends?, propsSchema? }`, ignoring members it does not declare.
|
|
1285
1528
|
*/
|
|
1286
1529
|
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);
|
|
1530
|
+
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
1531
|
}
|
|
1289
1532
|
/**
|
|
1290
1533
|
* Checks the result of `getSchemas` and the parameters of `schemasChanged`.
|
|
@@ -1432,13 +1675,14 @@ const HOT_RELOAD_KINDS = {
|
|
|
1432
1675
|
* Checks the parameters of `hotReloaded`.
|
|
1433
1676
|
*
|
|
1434
1677
|
* @param value - The received `params`.
|
|
1435
|
-
* @returns True for `{ report }` with a known kind, type ids, counts and JSON errors
|
|
1678
|
+
* @returns True for `{ report }` with a known kind, type ids, counts and JSON errors, its strings and
|
|
1679
|
+
* lists within `HOST_TEXT_MAX_LENGTH` and `HOST_LIST_MAX_LENGTH`.
|
|
1436
1680
|
*
|
|
1437
1681
|
* @public
|
|
1438
1682
|
*/
|
|
1439
1683
|
function isHotReloadedParams(value) {
|
|
1440
1684
|
const report = isRecord(value) ? value["report"] : void 0;
|
|
1441
|
-
return isRecord(report) && isOneOf(HOT_RELOAD_KINDS, report["kind"]) &&
|
|
1685
|
+
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
1686
|
}
|
|
1443
1687
|
/**
|
|
1444
1688
|
* Checks the parameters of `assetReloaded`.
|
|
@@ -1483,24 +1727,26 @@ function isTransformDraggedParams(value) {
|
|
|
1483
1727
|
* Checks the parameters of `hostError`.
|
|
1484
1728
|
*
|
|
1485
1729
|
* @param value - The received `params`.
|
|
1486
|
-
* @returns True for a code or `null`, a message and optional JSON data
|
|
1730
|
+
* @returns True for a code or `null`, a message and optional JSON data, the strings within
|
|
1731
|
+
* `HOST_TEXT_MAX_LENGTH`.
|
|
1487
1732
|
*
|
|
1488
1733
|
* @public
|
|
1489
1734
|
*/
|
|
1490
1735
|
function isHostErrorParams(value) {
|
|
1491
|
-
return isRecord(value) &&
|
|
1736
|
+
return isRecord(value) && isHostTextOrNull(value["code"]) && isHostText(value["message"]) && optionalField(value, "data", (data) => isJsonValue(data));
|
|
1492
1737
|
}
|
|
1493
1738
|
/**
|
|
1494
1739
|
* Checks the `data` of a `hostError` for an error the app reported.
|
|
1495
1740
|
*
|
|
1496
1741
|
* @param value - The received `data`.
|
|
1497
1742
|
* @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
|
|
1743
|
+
* a phase name, an entity name, a component and a stack, each a string or `null`; the strings within
|
|
1744
|
+
* `HOST_TEXT_MAX_LENGTH`.
|
|
1499
1745
|
*
|
|
1500
1746
|
* @public
|
|
1501
1747
|
*/
|
|
1502
1748
|
function isAppErrorData(value) {
|
|
1503
|
-
return isRecord(value) &&
|
|
1749
|
+
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
1750
|
}
|
|
1505
1751
|
/** The severities of a log line. */
|
|
1506
1752
|
const LOG_LEVELS = {
|
|
@@ -1513,12 +1759,13 @@ const LOG_LEVELS = {
|
|
|
1513
1759
|
* Checks the parameters of `log`.
|
|
1514
1760
|
*
|
|
1515
1761
|
* @param value - The received `params`.
|
|
1516
|
-
* @returns True for a known level, a scope or `null`, a message and a finite time
|
|
1762
|
+
* @returns True for a known level, a scope or `null`, a message and a finite time, the strings
|
|
1763
|
+
* within `HOST_TEXT_MAX_LENGTH`.
|
|
1517
1764
|
*
|
|
1518
1765
|
* @public
|
|
1519
1766
|
*/
|
|
1520
1767
|
function isLogParams(value) {
|
|
1521
|
-
return isRecord(value) && isOneOf(LOG_LEVELS, value["level"]) &&
|
|
1768
|
+
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
1769
|
}
|
|
1523
1770
|
//#endregion
|
|
1524
1771
|
//#region src/protocol/version.ts
|
|
@@ -1686,7 +1933,7 @@ function send(port, message) {
|
|
|
1686
1933
|
* period that is not a positive finite number.
|
|
1687
1934
|
*/
|
|
1688
1935
|
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\"." });
|
|
1936
|
+
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
1937
|
const interval = heartbeatIntervalMs ?? 1e3;
|
|
1691
1938
|
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
1939
|
return interval;
|
|
@@ -1887,6 +2134,41 @@ function openChannel(options) {
|
|
|
1887
2134
|
* The app's reports as the editor's Console reads them: log lines, `app.onError` reports and hot
|
|
1888
2135
|
* reloads, made JSON. The scene view and the play view relay the same shapes.
|
|
1889
2136
|
*/
|
|
2137
|
+
/** What ends a string {@link clipHostText} cut. */
|
|
2138
|
+
const CLIPPED_MARKER = "… [clipped]";
|
|
2139
|
+
/**
|
|
2140
|
+
* Cuts a string to `HOST_TEXT_MAX_LENGTH`, the longest the editor accepts in a report: the editor
|
|
2141
|
+
* drops a whole report holding a longer one.
|
|
2142
|
+
*
|
|
2143
|
+
* @param text - The string.
|
|
2144
|
+
* @returns It unchanged when short enough, else its start and {@link CLIPPED_MARKER}, exactly
|
|
2145
|
+
* `HOST_TEXT_MAX_LENGTH` long or one shorter (a surrogate pair is never split).
|
|
2146
|
+
*/
|
|
2147
|
+
function clipHostText(text) {
|
|
2148
|
+
if (text.length <= 1048576) return text;
|
|
2149
|
+
let end = 1048565;
|
|
2150
|
+
const last = text.charCodeAt(end - 1);
|
|
2151
|
+
if (last >= 55296 && last <= 56319) end -= 1;
|
|
2152
|
+
return `${text.slice(0, end)}${CLIPPED_MARKER}`;
|
|
2153
|
+
}
|
|
2154
|
+
/**
|
|
2155
|
+
* Like {@link clipHostText}, passing `null` through.
|
|
2156
|
+
*
|
|
2157
|
+
* @param text - The string, or `null`.
|
|
2158
|
+
* @returns The clipped string, or `null`.
|
|
2159
|
+
*/
|
|
2160
|
+
function clipHostTextOrNull(text) {
|
|
2161
|
+
return text === null ? null : clipHostText(text);
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* Keeps the first `HOST_LIST_MAX_LENGTH` items of a list, the most the editor accepts in a report.
|
|
2165
|
+
*
|
|
2166
|
+
* @param items - The list.
|
|
2167
|
+
* @returns It, or its start when longer.
|
|
2168
|
+
*/
|
|
2169
|
+
function clipHostList(items) {
|
|
2170
|
+
return items.length <= 4096 ? items : items.slice(0, HOST_LIST_MAX_LENGTH);
|
|
2171
|
+
}
|
|
1890
2172
|
/**
|
|
1891
2173
|
* Names one of the engine's phases.
|
|
1892
2174
|
*
|
|
@@ -1897,59 +2179,60 @@ function phaseName(phase) {
|
|
|
1897
2179
|
return Object.entries(Phase).find(([, value]) => value === phase)?.[0] ?? null;
|
|
1898
2180
|
}
|
|
1899
2181
|
/**
|
|
1900
|
-
* Reads a thrown value's message.
|
|
2182
|
+
* Reads a thrown value's message, clipped by {@link clipHostText}.
|
|
1901
2183
|
*
|
|
1902
2184
|
* @param error - Whatever was thrown.
|
|
1903
2185
|
* @returns Its message, or the value as a string when it is not an `Error`.
|
|
1904
2186
|
*/
|
|
1905
2187
|
function messageOf(error) {
|
|
1906
|
-
return error instanceof Error ? error.message : String(error);
|
|
2188
|
+
return clipHostText(error instanceof Error ? error.message : String(error));
|
|
1907
2189
|
}
|
|
1908
2190
|
/**
|
|
1909
|
-
* Reads a thrown value's stack.
|
|
2191
|
+
* Reads a thrown value's stack, clipped by {@link clipHostText}.
|
|
1910
2192
|
*
|
|
1911
2193
|
* @param error - Whatever was thrown.
|
|
1912
2194
|
* @returns Its `stack` when it is an `Error` with one, else `null`.
|
|
1913
2195
|
*/
|
|
1914
2196
|
function stackOf(error) {
|
|
1915
|
-
return error instanceof Error && typeof error.stack === "string" && error.stack !== "" ? error.stack : null;
|
|
2197
|
+
return error instanceof Error && typeof error.stack === "string" && error.stack !== "" ? clipHostText(error.stack) : null;
|
|
1916
2198
|
}
|
|
1917
2199
|
/**
|
|
1918
|
-
* Reads a thrown value's `IGX-` code.
|
|
2200
|
+
* Reads a thrown value's `IGX-` code, clipped by {@link clipHostText}.
|
|
1919
2201
|
*
|
|
1920
2202
|
* @param error - Whatever was thrown.
|
|
1921
2203
|
* @returns The code of an `IgnifxError`, else `null`.
|
|
1922
2204
|
*/
|
|
1923
2205
|
function codeOf(error) {
|
|
1924
|
-
return isIgnifxError(error) ? error.code : null;
|
|
2206
|
+
return isIgnifxError(error) ? clipHostText(error.code) : null;
|
|
1925
2207
|
}
|
|
1926
2208
|
/**
|
|
1927
2209
|
* Names a component for the editor: its `typeId`, else its class name.
|
|
1928
2210
|
*
|
|
1929
2211
|
* @param component - The component.
|
|
1930
|
-
* @returns The name.
|
|
2212
|
+
* @returns The name, clipped by {@link clipHostText}.
|
|
1931
2213
|
*/
|
|
1932
2214
|
function componentName(component) {
|
|
1933
2215
|
const typeId = Reflect.get(component.constructor, "typeId");
|
|
1934
|
-
return typeof typeId === "string" && typeId !== "" ? typeId : component.constructor.name;
|
|
2216
|
+
return clipHostText(typeof typeId === "string" && typeId !== "" ? typeId : component.constructor.name);
|
|
1935
2217
|
}
|
|
1936
2218
|
/**
|
|
1937
2219
|
* Builds the parameters of `log` from one record.
|
|
1938
2220
|
*
|
|
1939
2221
|
* @param record - The record the app's logger wrote.
|
|
1940
|
-
* @returns The level, scope, message and time, and the first `Error` among the extras
|
|
2222
|
+
* @returns The level, scope, message and time, and the first `Error` among the extras; each string
|
|
2223
|
+
* clipped by {@link clipHostText}.
|
|
1941
2224
|
*/
|
|
1942
2225
|
function logParamsOf(record) {
|
|
1943
2226
|
const params = {
|
|
1944
2227
|
level: record.level,
|
|
1945
|
-
scope: record.scope,
|
|
1946
|
-
message: record.message,
|
|
2228
|
+
scope: clipHostTextOrNull(record.scope),
|
|
2229
|
+
message: clipHostText(record.message),
|
|
1947
2230
|
timeMs: record.timeMs
|
|
1948
2231
|
};
|
|
1949
2232
|
const error = record.data.find((value) => value instanceof Error);
|
|
1950
2233
|
if (error === void 0) return params;
|
|
1951
2234
|
const logged = {
|
|
1952
|
-
message: error
|
|
2235
|
+
message: messageOf(error),
|
|
1953
2236
|
code: codeOf(error),
|
|
1954
2237
|
stack: stackOf(error)
|
|
1955
2238
|
};
|
|
@@ -1962,15 +2245,16 @@ function logParamsOf(record) {
|
|
|
1962
2245
|
* Builds the parameters of `hostError` from one `app.onError` report.
|
|
1963
2246
|
*
|
|
1964
2247
|
* @param report - The report.
|
|
1965
|
-
* @returns The thrown error's code and message, and where it was caught
|
|
2248
|
+
* @returns The thrown error's code and message, and where it was caught; each string clipped by
|
|
2249
|
+
* {@link clipHostText}.
|
|
1966
2250
|
*/
|
|
1967
2251
|
function hostErrorParamsOf(report) {
|
|
1968
2252
|
const data = {
|
|
1969
|
-
source: report.source,
|
|
2253
|
+
source: clipHostText(report.source),
|
|
1970
2254
|
phase: report.phase,
|
|
1971
2255
|
phaseName: report.phase === null ? null : phaseName(report.phase),
|
|
1972
2256
|
entity: report.entity?.uid ?? null,
|
|
1973
|
-
entityName: report.entity?.name ?? null,
|
|
2257
|
+
entityName: clipHostTextOrNull(report.entity?.name ?? null),
|
|
1974
2258
|
component: report.component === null ? null : componentName(report.component),
|
|
1975
2259
|
stack: stackOf(report.error)
|
|
1976
2260
|
};
|
|
@@ -1984,15 +2268,16 @@ function hostErrorParamsOf(report) {
|
|
|
1984
2268
|
* Builds the parameters of `hotReloaded` from one report.
|
|
1985
2269
|
*
|
|
1986
2270
|
* @param report - What `app.hotReload` did.
|
|
1987
|
-
* @returns The report, with its errors made JSON
|
|
2271
|
+
* @returns The report, with its errors made JSON; each string clipped by {@link clipHostText} and
|
|
2272
|
+
* each list cut to `HOST_LIST_MAX_LENGTH` items.
|
|
1988
2273
|
*/
|
|
1989
2274
|
function hotReloadedParamsOf(report) {
|
|
1990
2275
|
return { report: {
|
|
1991
2276
|
kind: report.kind,
|
|
1992
|
-
typeIds: report.typeIds,
|
|
2277
|
+
typeIds: clipHostList(report.typeIds).map((typeId) => clipHostText(typeId)),
|
|
1993
2278
|
instances: report.instances,
|
|
1994
2279
|
durationMs: report.durationMs,
|
|
1995
|
-
errors: report.errors.map((error) => ({
|
|
2280
|
+
errors: clipHostList(report.errors).map((error) => ({
|
|
1996
2281
|
message: messageOf(error),
|
|
1997
2282
|
code: codeOf(error),
|
|
1998
2283
|
stack: stackOf(error)
|
|
@@ -2619,34 +2904,116 @@ function copyJson(value) {
|
|
|
2619
2904
|
* @param component - The component.
|
|
2620
2905
|
* @param props - The `props` object.
|
|
2621
2906
|
* @param references - How references resolve.
|
|
2907
|
+
* @param only - The fields to assign, if not every one; only their problems are returned.
|
|
2622
2908
|
* @returns The decoding problems, as `{ code, message }`.
|
|
2623
2909
|
*/
|
|
2624
|
-
function assignProps(component, props, references) {
|
|
2625
|
-
const
|
|
2626
|
-
|
|
2627
|
-
|
|
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
|
-
}));
|
|
2910
|
+
function assignProps(component, props, references, only) {
|
|
2911
|
+
const decoded = decodeComponentProps(component, props, references, only);
|
|
2912
|
+
for (const [name, value] of decoded.values) Reflect.set(component, name, value);
|
|
2913
|
+
return decoded.issues;
|
|
2634
2914
|
}
|
|
2635
2915
|
/**
|
|
2636
|
-
*
|
|
2637
|
-
* (`ComponentHooks`), so one that builds something from them (a physics body) rebuilds it.
|
|
2916
|
+
* The problems {@link assignProps} would return, without assigning anything.
|
|
2638
2917
|
*
|
|
2639
2918
|
* @param component - The component.
|
|
2640
|
-
* @param
|
|
2919
|
+
* @param props - The `props` object.
|
|
2920
|
+
* @param references - How references resolve.
|
|
2921
|
+
* @param only - The fields to decode, if not every one.
|
|
2922
|
+
* @returns The decoding problems, as `{ code, message }`.
|
|
2641
2923
|
*/
|
|
2642
|
-
function
|
|
2643
|
-
|
|
2644
|
-
if (fields.length > 0 && typeof hook === "function") Reflect.apply(hook, component, [fields]);
|
|
2924
|
+
function propIssues(component, props, references, only) {
|
|
2925
|
+
return decodeComponentProps(component, props, references, only).issues;
|
|
2645
2926
|
}
|
|
2646
|
-
/**
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2927
|
+
/**
|
|
2928
|
+
* Decodes a component's props from JSON, every schema field the JSON leaves out taking its default.
|
|
2929
|
+
*
|
|
2930
|
+
* @param component - The component.
|
|
2931
|
+
* @param props - The `props` object.
|
|
2932
|
+
* @param references - How references resolve.
|
|
2933
|
+
* @param only - The fields to keep, if not every one.
|
|
2934
|
+
* @returns The kept fields' values, and their problems as `{ code, message }`.
|
|
2935
|
+
*/
|
|
2936
|
+
function decodeComponentProps(component, props, references, only) {
|
|
2937
|
+
const schema = component.world.registry.describe(component.constructor).schema;
|
|
2938
|
+
if (schema === null) return {
|
|
2939
|
+
values: /* @__PURE__ */ new Map(),
|
|
2940
|
+
issues: []
|
|
2941
|
+
};
|
|
2942
|
+
const decoded = decodeProps(schema, props, references);
|
|
2943
|
+
const all = new Map(Object.entries(decoded.value));
|
|
2944
|
+
const values = /* @__PURE__ */ new Map();
|
|
2945
|
+
for (const name of Object.keys(schema)) if (only === void 0 || only.has(name)) values.set(name, all.get(name));
|
|
2946
|
+
return {
|
|
2947
|
+
values,
|
|
2948
|
+
issues: decoded.issues.filter((issue) => only === void 0 || only.has(issue.path.split(/[.[]/u, 1)[0] ?? "")).map((issue) => ({
|
|
2949
|
+
code: issue.code,
|
|
2950
|
+
message: `${component.uid}.${issue.path}: ${issue.message}`
|
|
2951
|
+
}))
|
|
2952
|
+
};
|
|
2953
|
+
}
|
|
2954
|
+
/**
|
|
2955
|
+
* Tells a component that the host changed some of its fields, through its `onValidate` hook
|
|
2956
|
+
* (`ComponentHooks`), so one that builds something from them (a physics body) rebuilds it.
|
|
2957
|
+
*
|
|
2958
|
+
* @param component - The component.
|
|
2959
|
+
* @param fields - The fields that changed; nothing is called when the list is empty.
|
|
2960
|
+
*/
|
|
2961
|
+
function validateFields(component, fields) {
|
|
2962
|
+
const hook = Reflect.get(component, "onValidate");
|
|
2963
|
+
if (fields.length > 0 && typeof hook === "function") Reflect.apply(hook, component, [fields]);
|
|
2964
|
+
}
|
|
2965
|
+
/**
|
|
2966
|
+
* An override in the form the scene file writes it, which editor-core's document holds: an op
|
|
2967
|
+
* sent as `{ op: "replace" }` or a transform value with more than six decimals still reads back
|
|
2968
|
+
* as the document has it.
|
|
2969
|
+
*
|
|
2970
|
+
* @param override - The override as an op or a file carried it.
|
|
2971
|
+
* @returns The canonical override.
|
|
2972
|
+
*/
|
|
2973
|
+
function canonicalOverride(override) {
|
|
2974
|
+
const op = override.op ?? "replace";
|
|
2975
|
+
const value = op === "remove" ? void 0 : canonicalOverrideValue(override.path, override.value);
|
|
2976
|
+
return {
|
|
2977
|
+
...op === "replace" ? {} : { op },
|
|
2978
|
+
path: override.path,
|
|
2979
|
+
...value === void 0 ? {} : { value }
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
/**
|
|
2983
|
+
* A transform override's value with each number canonical; any other value as it is.
|
|
2984
|
+
*
|
|
2985
|
+
* @param path - The override's path.
|
|
2986
|
+
* @param value - Its value.
|
|
2987
|
+
* @returns The value to keep.
|
|
2988
|
+
*/
|
|
2989
|
+
function canonicalOverrideValue(path, value) {
|
|
2990
|
+
const list = value;
|
|
2991
|
+
if (!Array.isArray(list) || !isTransformPath(path)) return value;
|
|
2992
|
+
const items = list;
|
|
2993
|
+
const numbers = [];
|
|
2994
|
+
for (const item of items) {
|
|
2995
|
+
if (typeof item !== "number") return value;
|
|
2996
|
+
numbers.push(canonicalizeNumber(item));
|
|
2997
|
+
}
|
|
2998
|
+
return numbers;
|
|
2999
|
+
}
|
|
3000
|
+
/**
|
|
3001
|
+
* Whether an override path names a transform field.
|
|
3002
|
+
*
|
|
3003
|
+
* @param path - The path.
|
|
3004
|
+
* @returns `false` too for a path the engine's grammar refuses.
|
|
3005
|
+
*/
|
|
3006
|
+
function isTransformPath(path) {
|
|
3007
|
+
try {
|
|
3008
|
+
return parseOverridePath(path).kind === "transform";
|
|
3009
|
+
} catch {
|
|
3010
|
+
return false;
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
3013
|
+
/** The live mirror of the editor's open scene document. */
|
|
3014
|
+
var DocumentMirror = class {
|
|
3015
|
+
#app;
|
|
3016
|
+
#scene = null;
|
|
2650
3017
|
#address = null;
|
|
2651
3018
|
#name = "";
|
|
2652
3019
|
#settings = null;
|
|
@@ -2662,6 +3029,19 @@ var DocumentMirror = class {
|
|
|
2662
3029
|
* that changed a default reads every stale member value as an override.
|
|
2663
3030
|
*/
|
|
2664
3031
|
#overrides = /* @__PURE__ */ new Map();
|
|
3032
|
+
/**
|
|
3033
|
+
* Each instance root's overrides as the serializer read them right after the host built the root,
|
|
3034
|
+
* as JSON text, by root uid. While the serializer still reads the same, the members are as the
|
|
3035
|
+
* document's list built them, and `readBack` writes that list.
|
|
3036
|
+
*/
|
|
3037
|
+
#builtAs = /* @__PURE__ */ new Map();
|
|
3038
|
+
/**
|
|
3039
|
+
* Where an `add` puts a component on each instance root itself (`<root>/components` of a one-root
|
|
3040
|
+
* scene), or `null`, by root uid, read from the scene the root was last built from. A reload that
|
|
3041
|
+
* changes the scene's roots replaces the scene in the cache before the root is rebuilt, while the
|
|
3042
|
+
* serializer still writes the root as that build made it.
|
|
3043
|
+
*/
|
|
3044
|
+
#rootPaths = /* @__PURE__ */ new Map();
|
|
2665
3045
|
/** Assets loaded for ops, held until the document closes. */
|
|
2666
3046
|
#handles = [];
|
|
2667
3047
|
/**
|
|
@@ -2720,27 +3100,59 @@ var DocumentMirror = class {
|
|
|
2720
3100
|
*/
|
|
2721
3101
|
async open(file, address) {
|
|
2722
3102
|
await this.close();
|
|
3103
|
+
const where = address ?? "memory:scene/unsaved";
|
|
2723
3104
|
const warnings = [];
|
|
2724
|
-
const
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
3105
|
+
const held = await this.#loadDoubledScenes(file.entities);
|
|
3106
|
+
let scene;
|
|
3107
|
+
let entities;
|
|
3108
|
+
try {
|
|
3109
|
+
entities = withoutDoubleAdds(this.#app, file.entities, where, warnings);
|
|
3110
|
+
scene = await this.#app.world.loadSceneFile({
|
|
3111
|
+
...file,
|
|
3112
|
+
entities
|
|
3113
|
+
}, {
|
|
3114
|
+
address: where,
|
|
3115
|
+
onIssue: (issue) => {
|
|
3116
|
+
warnings.push({
|
|
3117
|
+
code: issue.code,
|
|
3118
|
+
message: issue.message
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
});
|
|
3122
|
+
} finally {
|
|
3123
|
+
for (const handle of held) handle.release();
|
|
3124
|
+
}
|
|
2733
3125
|
this.#scene = scene;
|
|
2734
3126
|
this.#address = address;
|
|
2735
3127
|
this.#name = file.name;
|
|
2736
3128
|
this.#settings = file.settings === void 0 ? null : copyJson(file.settings);
|
|
2737
|
-
this.recordComponents(
|
|
2738
|
-
this.recordInstances(
|
|
3129
|
+
this.recordComponents(entities.flatMap((record) => record.components ?? []));
|
|
3130
|
+
this.recordInstances(entities);
|
|
3131
|
+
this.invalidate();
|
|
2739
3132
|
return {
|
|
2740
3133
|
entityCount: countEntities(scene),
|
|
2741
3134
|
warnings
|
|
2742
3135
|
};
|
|
2743
3136
|
}
|
|
3137
|
+
/**
|
|
3138
|
+
* Loads the scenes of the instance roots whose records may hold the old double form of an added
|
|
3139
|
+
* component, so {@link withoutDoubleAdds} can tell where each scene's root is.
|
|
3140
|
+
*
|
|
3141
|
+
* @param records - The file's entity records.
|
|
3142
|
+
* @returns The handles, each with one holder the caller releases.
|
|
3143
|
+
*/
|
|
3144
|
+
async #loadDoubledScenes(records) {
|
|
3145
|
+
const handles = [];
|
|
3146
|
+
for (const record of records) {
|
|
3147
|
+
const instance = record.instance;
|
|
3148
|
+
const own = new Set((record.components ?? []).map((component) => component.uid));
|
|
3149
|
+
const adds = (instance?.overrides ?? []).flatMap((override) => addedUids(override));
|
|
3150
|
+
if (instance === void 0 || !adds.some((uid) => own.has(uid))) continue;
|
|
3151
|
+
handles.push(this.#app.assets.load(instance.scene.$asset, { type: instance.scene.type ?? SCENE_ASSET_TYPE }));
|
|
3152
|
+
}
|
|
3153
|
+
await Promise.allSettled(handles.map(async (handle) => handle.promise));
|
|
3154
|
+
return handles;
|
|
3155
|
+
}
|
|
2744
3156
|
/** Unloads the open document, if any, and releases the assets its ops loaded. */
|
|
2745
3157
|
async close() {
|
|
2746
3158
|
const scene = this.#scene;
|
|
@@ -2751,6 +3163,8 @@ var DocumentMirror = class {
|
|
|
2751
3163
|
this.#index = null;
|
|
2752
3164
|
this.#explicit.clear();
|
|
2753
3165
|
this.#overrides.clear();
|
|
3166
|
+
this.#builtAs.clear();
|
|
3167
|
+
this.#rootPaths.clear();
|
|
2754
3168
|
if (scene !== null) await this.#app.world.unloadScene(scene);
|
|
2755
3169
|
for (const handle of this.#handles.splice(0)) handle.release();
|
|
2756
3170
|
}
|
|
@@ -2805,21 +3219,47 @@ var DocumentMirror = class {
|
|
|
2805
3219
|
return this.#explicit.get(uid) ?? null;
|
|
2806
3220
|
}
|
|
2807
3221
|
/**
|
|
2808
|
-
* Records the override lists of the instance roots among some entity records
|
|
3222
|
+
* Records the override lists of the instance roots among some entity records the host has just
|
|
3223
|
+
* built, and what the serializer reads from those roots now, before anything else can change
|
|
3224
|
+
* their members.
|
|
2809
3225
|
*
|
|
2810
3226
|
* @param records - The records, as a file or an op carries them.
|
|
2811
3227
|
*/
|
|
2812
3228
|
recordInstances(records) {
|
|
2813
|
-
|
|
3229
|
+
const roots = records.filter((record) => record.instance !== void 0);
|
|
3230
|
+
for (const record of roots) {
|
|
3231
|
+
this.recordOverrides(record.uid, record.instance?.overrides ?? []);
|
|
3232
|
+
this.#rootPaths.set(record.uid, record.instance === void 0 ? null : rootComponentsPath(this.#app, record.instance));
|
|
3233
|
+
}
|
|
3234
|
+
if (roots.length === 0) return;
|
|
3235
|
+
this.#index = null;
|
|
3236
|
+
const index = this.index();
|
|
3237
|
+
for (const record of roots) {
|
|
3238
|
+
const read = index?.records.get(record.uid)?.instance;
|
|
3239
|
+
if (read === void 0) this.#builtAs.delete(record.uid);
|
|
3240
|
+
else this.#builtAs.set(record.uid, JSON.stringify(read.overrides ?? []));
|
|
3241
|
+
}
|
|
2814
3242
|
}
|
|
2815
3243
|
/**
|
|
2816
|
-
* Records an instance root's override list
|
|
3244
|
+
* Records an instance root's override list, each override in the form the scene file writes and
|
|
3245
|
+
* editor-core's document holds: no `op` for a `replace`, no value for a `remove`, and a
|
|
3246
|
+
* transform's numbers canonical.
|
|
2817
3247
|
*
|
|
2818
3248
|
* @param uid - The root's uid.
|
|
2819
3249
|
* @param overrides - The list.
|
|
2820
3250
|
*/
|
|
2821
3251
|
recordOverrides(uid, overrides) {
|
|
2822
|
-
this.#overrides.set(uid, structuredClone(overrides));
|
|
3252
|
+
this.#overrides.set(uid, structuredClone(overrides).map(canonicalOverride));
|
|
3253
|
+
}
|
|
3254
|
+
/**
|
|
3255
|
+
* Where an `add` override puts a component on an instance root itself, in the scene the root was
|
|
3256
|
+
* last built from.
|
|
3257
|
+
*
|
|
3258
|
+
* @param uid - The root's uid.
|
|
3259
|
+
* @returns `<scene root uid>/components` when that scene has one root, or `null`.
|
|
3260
|
+
*/
|
|
3261
|
+
rootPathOf(uid) {
|
|
3262
|
+
return this.#rootPaths.get(uid) ?? null;
|
|
2823
3263
|
}
|
|
2824
3264
|
/**
|
|
2825
3265
|
* An instance root's override list as the document holds it.
|
|
@@ -2835,7 +3275,10 @@ var DocumentMirror = class {
|
|
|
2835
3275
|
this.#index = null;
|
|
2836
3276
|
}
|
|
2837
3277
|
/**
|
|
2838
|
-
* The document as the live world holds it, serialized once and cached until
|
|
3278
|
+
* The document as the live world holds it, serialized once and cached until an op, `open` or
|
|
3279
|
+
* `readBack` drops it; the next call serializes the world again. Every lookup (selection, picks,
|
|
3280
|
+
* the ops' references) reads this cache, so a lookup after a `readBack` sees the world as that
|
|
3281
|
+
* `readBack` did.
|
|
2839
3282
|
*
|
|
2840
3283
|
* @returns The index, or `null` while no document is open.
|
|
2841
3284
|
*/
|
|
@@ -2848,16 +3291,27 @@ var DocumentMirror = class {
|
|
|
2848
3291
|
/**
|
|
2849
3292
|
* Serializes the requested entities as the live world has them (protocol `readBack`).
|
|
2850
3293
|
*
|
|
3294
|
+
* @remarks
|
|
3295
|
+
* The world is serialized again on every call, not read from the cache, because a `"run"`
|
|
3296
|
+
* system or a `runInEditMode` script can change it outside an op.
|
|
3297
|
+
*
|
|
3298
|
+
* An instance root's overrides are the list the document holds, in its order, while the
|
|
3299
|
+
* serializer still reads its members as they were built from that list. The serializer's own
|
|
3300
|
+
* list is a diff in file order that writes an added component whole and leaves out an override
|
|
3301
|
+
* equal to the instanced scene's value, so it never equals the document's; it is written instead
|
|
3302
|
+
* once the members read differently, so a change the document did not make still shows.
|
|
3303
|
+
*
|
|
2851
3304
|
* @param params - The uids to read, or none for all.
|
|
2852
3305
|
* @returns The records in file order, the uids not found, the settings, and the serializer's issues.
|
|
2853
3306
|
*/
|
|
2854
3307
|
readBack(params) {
|
|
3308
|
+
this.invalidate();
|
|
2855
3309
|
const index = this.index();
|
|
2856
3310
|
if (index === null) return null;
|
|
2857
3311
|
const requested = params.entities;
|
|
2858
3312
|
const wanted = requested === void 0 ? null : new Set(requested);
|
|
2859
3313
|
return {
|
|
2860
|
-
entities: index.file.entities.filter((record) => wanted === null || wanted.has(record.uid)),
|
|
3314
|
+
entities: index.file.entities.filter((record) => wanted === null || wanted.has(record.uid)).map((record) => this.#withDocumentOverrides(record)),
|
|
2861
3315
|
missing: requested === void 0 ? [] : [...new Set(requested)].filter((uid) => !index.records.has(uid)),
|
|
2862
3316
|
settings: index.file.settings ?? null,
|
|
2863
3317
|
issues: index.issues
|
|
@@ -2878,6 +3332,7 @@ var DocumentMirror = class {
|
|
|
2878
3332
|
}
|
|
2879
3333
|
/**
|
|
2880
3334
|
* How references in props resolve: document uids first, then the uids of a subtree just built,
|
|
3335
|
+
* then the components instances' `add` overrides gave their members, as a reopen resolves them;
|
|
2881
3336
|
* and assets already loaded in the app's cache.
|
|
2882
3337
|
*
|
|
2883
3338
|
* @param built - The uid table of a subtree an op just built, if any.
|
|
@@ -2888,7 +3343,7 @@ var DocumentMirror = class {
|
|
|
2888
3343
|
const assets = this.#app.assets;
|
|
2889
3344
|
return {
|
|
2890
3345
|
entity: (uid) => index?.entities.get(uid) ?? built?.entity(uid) ?? null,
|
|
2891
|
-
component: (uid) => index?.components.get(uid) ?? built?.component(uid) ?? null,
|
|
3346
|
+
component: (uid) => index?.components.get(uid) ?? built?.component(uid) ?? index?.added.get(uid) ?? null,
|
|
2892
3347
|
asset: (address, type) => {
|
|
2893
3348
|
const handle = assets.get(address);
|
|
2894
3349
|
return handle !== null && handle.state === "loaded" && (type === null || handle.type === type) ? handle : null;
|
|
@@ -2896,6 +3351,24 @@ var DocumentMirror = class {
|
|
|
2896
3351
|
};
|
|
2897
3352
|
}
|
|
2898
3353
|
/**
|
|
3354
|
+
* An entity's record with the document's override list, when it is an instance root whose
|
|
3355
|
+
* members still read as they were built from that list.
|
|
3356
|
+
*
|
|
3357
|
+
* @param record - The record as the serializer wrote it.
|
|
3358
|
+
* @returns The record to read back.
|
|
3359
|
+
*/
|
|
3360
|
+
#withDocumentOverrides(record) {
|
|
3361
|
+
const read = record.instance;
|
|
3362
|
+
const listed = this.#overrides.get(record.uid);
|
|
3363
|
+
const built = this.#builtAs.get(record.uid);
|
|
3364
|
+
if (read === void 0 || listed === void 0 || JSON.stringify(read.overrides ?? []) !== built) return record;
|
|
3365
|
+
return withOverrideList(record, {
|
|
3366
|
+
scene: read.scene,
|
|
3367
|
+
...read.hash === void 0 ? {} : { hash: read.hash },
|
|
3368
|
+
...listed.length === 0 ? {} : { overrides: structuredClone(listed) }
|
|
3369
|
+
}, this.rootPathOf(record.uid));
|
|
3370
|
+
}
|
|
3371
|
+
/**
|
|
2899
3372
|
* Serializes the document and indexes its entities and components.
|
|
2900
3373
|
*
|
|
2901
3374
|
* @param scene - The document's scene instance.
|
|
@@ -2917,6 +3390,7 @@ var DocumentMirror = class {
|
|
|
2917
3390
|
const entities = /* @__PURE__ */ new Map();
|
|
2918
3391
|
const records = /* @__PURE__ */ new Map();
|
|
2919
3392
|
const components = /* @__PURE__ */ new Map();
|
|
3393
|
+
const added = /* @__PURE__ */ new Map();
|
|
2920
3394
|
for (const record of file.entities) {
|
|
2921
3395
|
const entity = world.getEntity(record.uid);
|
|
2922
3396
|
if (entity === null) continue;
|
|
@@ -2924,16 +3398,122 @@ var DocumentMirror = class {
|
|
|
2924
3398
|
records.set(record.uid, record);
|
|
2925
3399
|
const uids = new Set((record.components ?? []).map((component) => component.uid));
|
|
2926
3400
|
for (const component of entity.components) if (uids.has(component.uid) && !component.isDestroyed) components.set(component.uid, component);
|
|
3401
|
+
const adds = new Set((record.instance?.overrides ?? []).flatMap((override) => addedUids(override)));
|
|
3402
|
+
if (adds.size > 0) collectComponents(entity, adds, added);
|
|
2927
3403
|
}
|
|
2928
3404
|
return {
|
|
2929
3405
|
file,
|
|
2930
3406
|
issues,
|
|
2931
3407
|
entities,
|
|
2932
3408
|
records,
|
|
2933
|
-
components
|
|
3409
|
+
components,
|
|
3410
|
+
added
|
|
2934
3411
|
};
|
|
2935
3412
|
}
|
|
2936
3413
|
};
|
|
3414
|
+
/**
|
|
3415
|
+
* A file's entity records without the old double form of an added component: before `readBack`
|
|
3416
|
+
* wrote each `add` override once, it also wrote one that adds to the root of a one-root scene as
|
|
3417
|
+
* the root's own component, with the same uid, so a reopen built it twice. Each is kept once, as the
|
|
3418
|
+
* override list adds it, so `readBack` reads the same from the first frame. Only an `add` to the
|
|
3419
|
+
* root's component list counts: one on another member that reuses a uid of the root's own
|
|
3420
|
+
* components is not the old form, so both are built, with a warning of its own.
|
|
3421
|
+
*
|
|
3422
|
+
* @param app - The scene view's app, whose cache holds the instanced scenes.
|
|
3423
|
+
* @param records - The file's entity records.
|
|
3424
|
+
* @param address - The document's address, for the warnings.
|
|
3425
|
+
* @param warnings - Gets one `IGX-0608` warning when a record had the double form, and one when a
|
|
3426
|
+
* record's list adds to a member with a uid of the root's own components.
|
|
3427
|
+
* @returns The records, each collapsed one replaced.
|
|
3428
|
+
*/
|
|
3429
|
+
function withoutDoubleAdds(app, records, address, warnings) {
|
|
3430
|
+
const doubled = [];
|
|
3431
|
+
const reused = [];
|
|
3432
|
+
const collapsed = records.map((record) => {
|
|
3433
|
+
const instance = record.instance;
|
|
3434
|
+
if (instance === void 0 || record.components === void 0) return record;
|
|
3435
|
+
const single = withOverrideList(record, instance, rootComponentsPath(app, instance));
|
|
3436
|
+
const kept = new Set((single.components ?? []).map((component) => component.uid));
|
|
3437
|
+
const adds = new Set((instance.overrides ?? []).flatMap((override) => addedUids(override)));
|
|
3438
|
+
for (const component of record.components) if (!kept.has(component.uid)) doubled.push(`${record.uid}/${component.uid}`);
|
|
3439
|
+
else if (adds.has(component.uid)) reused.push(`${record.uid}/${component.uid}`);
|
|
3440
|
+
return single;
|
|
3441
|
+
});
|
|
3442
|
+
if (reused.length > 0) warnings.push({
|
|
3443
|
+
code: CoreErrorCode.sceneFileInvalid,
|
|
3444
|
+
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.`
|
|
3445
|
+
});
|
|
3446
|
+
if (doubled.length > 0) warnings.push({
|
|
3447
|
+
code: CoreErrorCode.sceneFileInvalid,
|
|
3448
|
+
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.`
|
|
3449
|
+
});
|
|
3450
|
+
return collapsed;
|
|
3451
|
+
}
|
|
3452
|
+
/**
|
|
3453
|
+
* An instance root's record with an instance entry whose override list replaces the serializer's.
|
|
3454
|
+
* The serializer writes a component that an `add` override gives the root of a one-root scene as
|
|
3455
|
+
* the root's own, so the record leaves out each component the list adds there; a rebuild or a
|
|
3456
|
+
* reopen would otherwise add it twice.
|
|
3457
|
+
*
|
|
3458
|
+
* @param record - The record as the serializer wrote it.
|
|
3459
|
+
* @param instance - The instance entry, with the document's list.
|
|
3460
|
+
* @param path - `<scene root uid>/components` of the scene the record was written against, when
|
|
3461
|
+
* that scene has one root, or `null`.
|
|
3462
|
+
* @returns The record.
|
|
3463
|
+
*/
|
|
3464
|
+
function withOverrideList(record, instance, path) {
|
|
3465
|
+
const adds = new Set((instance.overrides ?? []).filter((override) => override.path === path).flatMap((override) => addedUids(override)));
|
|
3466
|
+
const own = record.components ?? [];
|
|
3467
|
+
const components = own.filter((component) => !adds.has(component.uid));
|
|
3468
|
+
if (components.length === own.length) return {
|
|
3469
|
+
...record,
|
|
3470
|
+
instance
|
|
3471
|
+
};
|
|
3472
|
+
const { components: _written, ...rest } = record;
|
|
3473
|
+
return {
|
|
3474
|
+
...rest,
|
|
3475
|
+
instance,
|
|
3476
|
+
...components.length === 0 ? {} : { components }
|
|
3477
|
+
};
|
|
3478
|
+
}
|
|
3479
|
+
/**
|
|
3480
|
+
* The override path of the component list of an instanced scene's root, when the scene has one
|
|
3481
|
+
* root: a component an `add` there gives is the instance root's own.
|
|
3482
|
+
*
|
|
3483
|
+
* @param app - The scene view's app.
|
|
3484
|
+
* @param instance - The instance entry.
|
|
3485
|
+
* @returns `<root uid>/components`, or `null` for a scene with several roots or none, or one the
|
|
3486
|
+
* cache does not hold loaded as a scene.
|
|
3487
|
+
*/
|
|
3488
|
+
function rootComponentsPath(app, instance) {
|
|
3489
|
+
const handle = app.assets.get(instance.scene.$asset);
|
|
3490
|
+
if (handle === null || handle.state !== "loaded" || handle.type !== SCENE_ASSET_TYPE) return null;
|
|
3491
|
+
const roots = handle.value.file.entities.filter((entity) => entity.parent === null);
|
|
3492
|
+
const root = roots.length === 1 ? roots[0] : void 0;
|
|
3493
|
+
return root === void 0 ? null : `${root.uid}/components`;
|
|
3494
|
+
}
|
|
3495
|
+
/**
|
|
3496
|
+
* The uid of the component an `add` override of a component list adds, as a list.
|
|
3497
|
+
*
|
|
3498
|
+
* @param override - The override.
|
|
3499
|
+
* @returns The uid, or nothing.
|
|
3500
|
+
*/
|
|
3501
|
+
function addedUids(override) {
|
|
3502
|
+
const value = override.value;
|
|
3503
|
+
const uid = override.op === "add" && typeof value === "object" && value !== null ? Reflect.get(value, "uid") : null;
|
|
3504
|
+
return typeof uid === "string" ? [uid] : [];
|
|
3505
|
+
}
|
|
3506
|
+
/**
|
|
3507
|
+
* Finds the live components with some uids in a subtree.
|
|
3508
|
+
*
|
|
3509
|
+
* @param entity - The subtree's root.
|
|
3510
|
+
* @param uids - The uids.
|
|
3511
|
+
* @param into - Filled with each one found, by uid.
|
|
3512
|
+
*/
|
|
3513
|
+
function collectComponents(entity, uids, into) {
|
|
3514
|
+
for (const component of entity.components) if (uids.has(component.uid) && !component.isDestroyed) into.set(component.uid, component);
|
|
3515
|
+
for (const child of entity.children) collectComponents(child, uids, into);
|
|
3516
|
+
}
|
|
2937
3517
|
//#endregion
|
|
2938
3518
|
//#region src/scene/defaults.ts
|
|
2939
3519
|
/**
|
|
@@ -3010,47 +3590,59 @@ function typeIdOf(app, component) {
|
|
|
3010
3590
|
}
|
|
3011
3591
|
/**
|
|
3012
3592
|
* 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.
|
|
3593
|
+
* component the mirror has no record of is left alone. A component whose setter or `onValidate`
|
|
3594
|
+
* throws is handed to `failed`, and the others still get their defaults.
|
|
3014
3595
|
*
|
|
3015
3596
|
* @param app - The scene view's app.
|
|
3016
3597
|
* @param mirror - The open document.
|
|
3017
3598
|
* @param index - Its index.
|
|
3018
3599
|
* @param changed - The changed fields, by type id.
|
|
3600
|
+
* @param failed - Called with each component that threw, its type id, and what it threw.
|
|
3019
3601
|
*/
|
|
3020
|
-
function applyDefaults(app, mirror, index, changed) {
|
|
3602
|
+
function applyDefaults(app, mirror, index, changed, failed) {
|
|
3021
3603
|
for (const [uid, component] of index.components) {
|
|
3022
|
-
const
|
|
3604
|
+
const typeId = typeIdOf(app, component) ?? "";
|
|
3605
|
+
const fields = changed.get(typeId);
|
|
3023
3606
|
const set = mirror.propsSetBy(uid);
|
|
3024
3607
|
const schema = app.world.registry.describe(component.constructor).schema;
|
|
3025
3608
|
if (fields === void 0 || set === null || schema === null) continue;
|
|
3026
3609
|
const assigned = [];
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3610
|
+
try {
|
|
3611
|
+
for (const name of fields) {
|
|
3612
|
+
const field = Object.hasOwn(schema, name) ? schema[name] : void 0;
|
|
3613
|
+
if (field !== void 0 && !set.has(name)) {
|
|
3614
|
+
Reflect.set(component, name, field.createDefault());
|
|
3615
|
+
assigned.push(name);
|
|
3616
|
+
}
|
|
3032
3617
|
}
|
|
3618
|
+
validateFields(component, assigned);
|
|
3619
|
+
} catch (error) {
|
|
3620
|
+
failed(component, typeId, error);
|
|
3033
3621
|
}
|
|
3034
|
-
validateFields(component, assigned);
|
|
3035
3622
|
}
|
|
3036
3623
|
}
|
|
3037
3624
|
/**
|
|
3038
3625
|
* The document's instance roots whose members (not the document's own components) include a
|
|
3039
|
-
* component of a changed type, in document order.
|
|
3626
|
+
* component of a changed type, in document order. A component the index lists but the mirror has
|
|
3627
|
+
* no record of is a member too: one an `add` override gives the root of a one-root prefab, which
|
|
3628
|
+
* the serializer writes as the root's own. So every component under a root either takes its new
|
|
3629
|
+
* defaults from {@link applyDefaults} or is rebuilt.
|
|
3040
3630
|
*
|
|
3041
3631
|
* @param app - The scene view's app.
|
|
3042
|
-
* @param
|
|
3632
|
+
* @param mirror - The open document.
|
|
3633
|
+
* @param index - Its index.
|
|
3043
3634
|
* @param changed - The changed fields, by type id.
|
|
3044
3635
|
* @returns The roots' uids.
|
|
3045
3636
|
*/
|
|
3046
|
-
function instancesHolding(app, index, changed) {
|
|
3637
|
+
function instancesHolding(app, mirror, index, changed) {
|
|
3638
|
+
const isMember = (component) => !index.components.has(component.uid) || mirror.propsSetBy(component.uid) === null;
|
|
3047
3639
|
const roots = /* @__PURE__ */ new Set();
|
|
3048
3640
|
for (const record of index.file.entities) {
|
|
3049
3641
|
const root = index.entities.get(record.uid);
|
|
3050
3642
|
if (record.instance === void 0 || root === void 0) continue;
|
|
3051
3643
|
const pending = [root];
|
|
3052
3644
|
for (let entity = pending.pop(); entity !== void 0; entity = pending.pop()) {
|
|
3053
|
-
if (entity.components.some((component) =>
|
|
3645
|
+
if (entity.components.some((component) => isMember(component) && changed.has(typeIdOf(app, component) ?? ""))) {
|
|
3054
3646
|
roots.add(record.uid);
|
|
3055
3647
|
break;
|
|
3056
3648
|
}
|
|
@@ -3929,104 +4521,600 @@ var EditorCamera2D = class extends Script {
|
|
|
3929
4521
|
}
|
|
3930
4522
|
};
|
|
3931
4523
|
//#endregion
|
|
3932
|
-
//#region src/scene/
|
|
4524
|
+
//#region src/scene/view-math.ts
|
|
3933
4525
|
/**
|
|
3934
|
-
*
|
|
3935
|
-
*
|
|
3936
|
-
*
|
|
3937
|
-
*
|
|
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.
|
|
4526
|
+
* The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and
|
|
4527
|
+
* plane point a `pick` answers with, the `screenshot` size rule, the transform the drag
|
|
4528
|
+
* notifications carry, and gizmo snapping. Each is a pure function, so the headless tests check it
|
|
4529
|
+
* directly.
|
|
3940
4530
|
*/
|
|
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
4531
|
/**
|
|
3964
|
-
*
|
|
4532
|
+
* Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its
|
|
4533
|
+
* backing pixels.
|
|
3965
4534
|
*
|
|
3966
|
-
* @param
|
|
3967
|
-
* @
|
|
3968
|
-
* @param params - The ops and the command they belong to.
|
|
3969
|
-
* @returns How many applied, and the failures in order.
|
|
4535
|
+
* @param surface - The canvas.
|
|
4536
|
+
* @returns The sizes.
|
|
3970
4537
|
*/
|
|
3971
|
-
|
|
3972
|
-
const
|
|
3973
|
-
|
|
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
|
-
}
|
|
4538
|
+
function viewSurfaceOf(surface) {
|
|
4539
|
+
const clientWidth = Reflect.get(surface, "clientWidth");
|
|
4540
|
+
const clientHeight = Reflect.get(surface, "clientHeight");
|
|
3988
4541
|
return {
|
|
3989
|
-
|
|
3990
|
-
|
|
4542
|
+
width: surface.width,
|
|
4543
|
+
height: surface.height,
|
|
4544
|
+
clientWidth: typeof clientWidth === "number" && clientWidth > 0 ? clientWidth : surface.width,
|
|
4545
|
+
clientHeight: typeof clientHeight === "number" && clientHeight > 0 ? clientHeight : surface.height
|
|
3991
4546
|
};
|
|
3992
4547
|
}
|
|
3993
4548
|
/**
|
|
3994
|
-
*
|
|
4549
|
+
* Converts a `pick` point to the backing-store pixels `app.renderer.pickAsync` takes (protocol 0.3,
|
|
4550
|
+
* "The pick unit rule"; engine ask E3). This is the host's one conversion: the renderer converts
|
|
4551
|
+
* on to the CSS pixels Lite's picker wants.
|
|
3995
4552
|
*
|
|
3996
|
-
* @param
|
|
3997
|
-
* @param
|
|
3998
|
-
* @returns The
|
|
4553
|
+
* @param params - The point and its unit.
|
|
4554
|
+
* @param surface - The canvas's sizes.
|
|
4555
|
+
* @returns The point in backing-store pixels, or `null` when it is outside the canvas (a miss).
|
|
3999
4556
|
*/
|
|
4000
|
-
function
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
|
|
4004
|
-
|
|
4005
|
-
|
|
4557
|
+
function toBackingPixels(params, surface) {
|
|
4558
|
+
const x = params.unit === PickUnit.backing ? params.x : params.x * surface.width / surface.clientWidth;
|
|
4559
|
+
const y = params.unit === PickUnit.backing ? params.y : params.y * surface.height / surface.clientHeight;
|
|
4560
|
+
if (x < 0 || y < 0 || x >= surface.width || y >= surface.height) return null;
|
|
4561
|
+
return {
|
|
4562
|
+
x,
|
|
4563
|
+
y
|
|
4006
4564
|
};
|
|
4007
|
-
|
|
4565
|
+
}
|
|
4566
|
+
/**
|
|
4567
|
+
* Turns a camera ray into a `pick` answer's `ray` and `plane` members (protocol 0.3, additive): the
|
|
4568
|
+
* ray as it is, and the point where it meets the 2D world plane `z = 0`. The plane point is
|
|
4569
|
+
* computed before rounding, and its `z` is exactly `0`.
|
|
4570
|
+
*
|
|
4571
|
+
* @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.
|
|
4572
|
+
* @returns The members, every number rounded with `canonicalizeNumber`.
|
|
4573
|
+
*/
|
|
4574
|
+
function pickRayMembers(ray) {
|
|
4575
|
+
const c = canonicalizeNumber;
|
|
4576
|
+
const { origin, direction } = ray;
|
|
4577
|
+
const members = { ray: {
|
|
4578
|
+
origin: [
|
|
4579
|
+
c(origin.x),
|
|
4580
|
+
c(origin.y),
|
|
4581
|
+
c(origin.z)
|
|
4582
|
+
],
|
|
4583
|
+
direction: [
|
|
4584
|
+
c(direction.x),
|
|
4585
|
+
c(direction.y),
|
|
4586
|
+
c(direction.z)
|
|
4587
|
+
]
|
|
4588
|
+
} };
|
|
4589
|
+
const t = direction.z === 0 ? NaN : -origin.z / direction.z;
|
|
4590
|
+
if (!Number.isFinite(t) || t < 0) return members;
|
|
4008
4591
|
return {
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4592
|
+
...members,
|
|
4593
|
+
plane: [
|
|
4594
|
+
c(origin.x + direction.x * t),
|
|
4595
|
+
c(origin.y + direction.y * t),
|
|
4596
|
+
0
|
|
4597
|
+
]
|
|
4013
4598
|
};
|
|
4014
4599
|
}
|
|
4015
4600
|
/**
|
|
4016
|
-
*
|
|
4601
|
+
* Rounds an image side and keeps it from 1 to {@link SCREENSHOT_MAX_SIZE}.
|
|
4017
4602
|
*
|
|
4018
|
-
* @param
|
|
4019
|
-
* @
|
|
4603
|
+
* @param side - The side, in pixels.
|
|
4604
|
+
* @returns The whole side in range.
|
|
4020
4605
|
*/
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4606
|
+
function clampSide(side) {
|
|
4607
|
+
return Math.min(SCREENSHOT_MAX_SIZE, Math.max(1, Math.round(side)));
|
|
4608
|
+
}
|
|
4609
|
+
/**
|
|
4610
|
+
* The size of a `screenshot`: the request's, or the view's backing size scaled down, keeping its
|
|
4611
|
+
* aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.
|
|
4612
|
+
*
|
|
4613
|
+
* @param params - The request; its sizes are already checked to be 1 to 2048.
|
|
4614
|
+
* @param view - The captured frame's size.
|
|
4615
|
+
* @returns The image size, each side at least 1 and at most 2048.
|
|
4616
|
+
*/
|
|
4617
|
+
function screenshotSize(params, view) {
|
|
4618
|
+
const aspect = view.height > 0 ? view.width / view.height : 1;
|
|
4619
|
+
const { width, height } = params;
|
|
4620
|
+
if (width !== void 0 && height !== void 0) return {
|
|
4621
|
+
width,
|
|
4622
|
+
height
|
|
4623
|
+
};
|
|
4624
|
+
if (width !== void 0) return {
|
|
4625
|
+
width,
|
|
4626
|
+
height: clampSide(width / aspect)
|
|
4627
|
+
};
|
|
4628
|
+
if (height !== void 0) return {
|
|
4629
|
+
width: clampSide(height * aspect),
|
|
4630
|
+
height
|
|
4631
|
+
};
|
|
4632
|
+
const fit = Math.min(1, SCREENSHOT_MAX_SIZE / Math.max(view.width, view.height, 1));
|
|
4633
|
+
return {
|
|
4634
|
+
width: clampSide(view.width * fit),
|
|
4635
|
+
height: clampSide(view.height * fit)
|
|
4636
|
+
};
|
|
4637
|
+
}
|
|
4638
|
+
/**
|
|
4639
|
+
* Reads an entity's local transform as the scene file writes it, numbers canonicalized.
|
|
4640
|
+
*
|
|
4641
|
+
* @param entity - The entity.
|
|
4642
|
+
* @returns The transform.
|
|
4643
|
+
*/
|
|
4644
|
+
function readLocalTransform(entity) {
|
|
4645
|
+
const { localPosition: p, localRotation: r, localScale: s } = entity.transform;
|
|
4646
|
+
const c = canonicalizeNumber;
|
|
4647
|
+
return {
|
|
4648
|
+
position: [
|
|
4649
|
+
c(p.x),
|
|
4650
|
+
c(p.y),
|
|
4651
|
+
c(p.z)
|
|
4652
|
+
],
|
|
4653
|
+
rotation: [
|
|
4654
|
+
c(r.x),
|
|
4655
|
+
c(r.y),
|
|
4656
|
+
c(r.z),
|
|
4657
|
+
c(r.w)
|
|
4658
|
+
],
|
|
4659
|
+
scale: [
|
|
4660
|
+
c(s.x),
|
|
4661
|
+
c(s.y),
|
|
4662
|
+
c(s.z)
|
|
4663
|
+
]
|
|
4664
|
+
};
|
|
4665
|
+
}
|
|
4666
|
+
/**
|
|
4667
|
+
* Rounds a value to a step; a step of 0 leaves it alone.
|
|
4668
|
+
*
|
|
4669
|
+
* @param value - The value.
|
|
4670
|
+
* @param step - The step.
|
|
4671
|
+
* @returns The snapped value.
|
|
4672
|
+
*/
|
|
4673
|
+
function snapTo(value, step) {
|
|
4674
|
+
return step > 0 ? Math.round(value / step) * step : value;
|
|
4675
|
+
}
|
|
4676
|
+
/**
|
|
4677
|
+
* Snaps a gizmo drag after Lite has applied each move (S0.2 §3.4, post-correction). The raw, unsnapped
|
|
4678
|
+
* value is kept apart from the node, so the snapped steps do not accumulate rounding.
|
|
4679
|
+
*/
|
|
4680
|
+
var DragSnapper = class {
|
|
4681
|
+
#mode;
|
|
4682
|
+
#snap;
|
|
4683
|
+
#start;
|
|
4684
|
+
#raw;
|
|
4685
|
+
#written;
|
|
4686
|
+
/**
|
|
4687
|
+
* Starts snapping one drag.
|
|
4688
|
+
*
|
|
4689
|
+
* @param mode - The drag's mode.
|
|
4690
|
+
* @param snap - The snapping steps.
|
|
4691
|
+
* @param entity - The dragged entity, at drag start.
|
|
4692
|
+
*/
|
|
4693
|
+
constructor(mode, snap, entity) {
|
|
4694
|
+
this.#mode = mode;
|
|
4695
|
+
this.#snap = snap;
|
|
4696
|
+
this.#start = this.#read(entity);
|
|
4697
|
+
this.#raw = [...this.#start];
|
|
4698
|
+
this.#written = [...this.#start];
|
|
4699
|
+
}
|
|
4700
|
+
/**
|
|
4701
|
+
* Folds the move Lite just wrote into the raw value and writes the snapped value back.
|
|
4702
|
+
*
|
|
4703
|
+
* @param entity - The dragged entity.
|
|
4704
|
+
*/
|
|
4705
|
+
apply(entity) {
|
|
4706
|
+
const now = this.#read(entity);
|
|
4707
|
+
if (this.#mode === "rotate") {
|
|
4708
|
+
this.#applyRotation(entity, now);
|
|
4709
|
+
return;
|
|
4710
|
+
}
|
|
4711
|
+
const step = this.#mode === "translate" ? this.#snap.translate : this.#snap.scale;
|
|
4712
|
+
if (step <= 0) return;
|
|
4713
|
+
this.#raw = this.#raw.map((value, index) => value + (now[index] ?? 0) - (this.#written[index] ?? 0));
|
|
4714
|
+
const snapped = this.#raw.map((value, index) => (this.#start[index] ?? 0) + snapTo(value - (this.#start[index] ?? 0), step));
|
|
4715
|
+
(this.#mode === "translate" ? entity.transform.localPosition : entity.transform.localScale).set(snapped[0] ?? 0, snapped[1] ?? 0, snapped[2] ?? 0);
|
|
4716
|
+
this.#written = snapped;
|
|
4717
|
+
}
|
|
4718
|
+
/**
|
|
4719
|
+
* Snaps a rotation drag: a ring turns about one axis, so the turn since drag start is one angle,
|
|
4720
|
+
* which is rounded to the step.
|
|
4721
|
+
*
|
|
4722
|
+
* @param entity - The dragged entity.
|
|
4723
|
+
* @param now - Its rotation now, as Lite wrote it.
|
|
4724
|
+
*/
|
|
4725
|
+
#applyRotation(entity, now) {
|
|
4726
|
+
const step = this.#snap.rotate;
|
|
4727
|
+
if (step <= 0) return;
|
|
4728
|
+
this.#raw = multiply(multiply(now, conjugate(this.#written)), this.#raw);
|
|
4729
|
+
const turn = multiply(this.#raw, conjugate(this.#start));
|
|
4730
|
+
const sine = Math.hypot(turn[0] ?? 0, turn[1] ?? 0, turn[2] ?? 0);
|
|
4731
|
+
if (sine < 1e-9) return;
|
|
4732
|
+
const half = snapTo(2 * Math.atan2(sine, turn[3] ?? 1) * 180 / Math.PI, step) * Math.PI / 180 / 2;
|
|
4733
|
+
const scale = Math.sin(half) / sine;
|
|
4734
|
+
const result = multiply([
|
|
4735
|
+
(turn[0] ?? 0) * scale,
|
|
4736
|
+
(turn[1] ?? 0) * scale,
|
|
4737
|
+
(turn[2] ?? 0) * scale,
|
|
4738
|
+
Math.cos(half)
|
|
4739
|
+
], this.#start);
|
|
4740
|
+
entity.transform.localRotation.set(result[0] ?? 0, result[1] ?? 0, result[2] ?? 0, result[3] ?? 1);
|
|
4741
|
+
this.#written = result;
|
|
4742
|
+
}
|
|
4743
|
+
/**
|
|
4744
|
+
* Reads the channels this drag moves.
|
|
4745
|
+
*
|
|
4746
|
+
* @param entity - The entity.
|
|
4747
|
+
* @returns Position, scale, or the rotation quaternion.
|
|
4748
|
+
*/
|
|
4749
|
+
#read(entity) {
|
|
4750
|
+
const t = entity.transform;
|
|
4751
|
+
if (this.#mode === "rotate") return [
|
|
4752
|
+
t.localRotation.x,
|
|
4753
|
+
t.localRotation.y,
|
|
4754
|
+
t.localRotation.z,
|
|
4755
|
+
t.localRotation.w
|
|
4756
|
+
];
|
|
4757
|
+
const v = this.#mode === "translate" ? t.localPosition : t.localScale;
|
|
4758
|
+
return [
|
|
4759
|
+
v.x,
|
|
4760
|
+
v.y,
|
|
4761
|
+
v.z
|
|
4762
|
+
];
|
|
4763
|
+
}
|
|
4764
|
+
};
|
|
4765
|
+
/**
|
|
4766
|
+
* Multiplies two quaternions, `a · b`.
|
|
4767
|
+
*
|
|
4768
|
+
* @param a - The left operand, `[x, y, z, w]`.
|
|
4769
|
+
* @param b - The right operand.
|
|
4770
|
+
* @returns The product.
|
|
4771
|
+
*/
|
|
4772
|
+
function multiply(a, b) {
|
|
4773
|
+
const [ax = 0, ay = 0, az = 0, aw = 1] = a;
|
|
4774
|
+
const [bx = 0, by = 0, bz = 0, bw = 1] = b;
|
|
4775
|
+
return [
|
|
4776
|
+
aw * bx + ax * bw + ay * bz - az * by,
|
|
4777
|
+
aw * by - ax * bz + ay * bw + az * bx,
|
|
4778
|
+
aw * bz + ax * by - ay * bx + az * bw,
|
|
4779
|
+
aw * bw - ax * bx - ay * by - az * bz
|
|
4780
|
+
];
|
|
4781
|
+
}
|
|
4782
|
+
/**
|
|
4783
|
+
* A unit quaternion's inverse.
|
|
4784
|
+
*
|
|
4785
|
+
* @param q - The quaternion.
|
|
4786
|
+
* @returns Its conjugate.
|
|
4787
|
+
*/
|
|
4788
|
+
function conjugate(q) {
|
|
4789
|
+
return [
|
|
4790
|
+
-(q[0] ?? 0),
|
|
4791
|
+
-(q[1] ?? 0),
|
|
4792
|
+
-(q[2] ?? 0),
|
|
4793
|
+
q[3] ?? 1
|
|
4794
|
+
];
|
|
4795
|
+
}
|
|
4796
|
+
//#endregion
|
|
4797
|
+
//#region src/scene/gizmo-drag.ts
|
|
4798
|
+
/**
|
|
4799
|
+
* Turns one gizmo drag into the scene view's drag notifications. It needs no GPU: the view calls
|
|
4800
|
+
* it with each part of the gesture, and the headless tests call it directly.
|
|
4801
|
+
*/
|
|
4802
|
+
/**
|
|
4803
|
+
* Sends `transformDragging` and `transformDragged` for gizmo drags, one drag at a time.
|
|
4804
|
+
*
|
|
4805
|
+
* @remarks
|
|
4806
|
+
* Every drag opens with a `transformDragging` and closes with a `transformDragged`, even one that
|
|
4807
|
+
* ends where it started, so the editor can hold its undo from pointer-down to pointer-up.
|
|
4808
|
+
*/
|
|
4809
|
+
var GizmoDragRelay = class {
|
|
4810
|
+
#notify;
|
|
4811
|
+
#now;
|
|
4812
|
+
#drag = null;
|
|
4813
|
+
/**
|
|
4814
|
+
* Makes a relay.
|
|
4815
|
+
*
|
|
4816
|
+
* @param notify - Sends one notification to the editor.
|
|
4817
|
+
* @param now - The clock, in milliseconds; `performance.now` by default.
|
|
4818
|
+
*/
|
|
4819
|
+
constructor(notify, now = () => performance.now()) {
|
|
4820
|
+
this.#notify = notify;
|
|
4821
|
+
this.#now = now;
|
|
4822
|
+
}
|
|
4823
|
+
/**
|
|
4824
|
+
* Starts a drag and sends its first `transformDragging`, the transform at drag start. A drag in
|
|
4825
|
+
* progress is dropped without a `transformDragged`.
|
|
4826
|
+
*
|
|
4827
|
+
* @param entity - The dragged entity.
|
|
4828
|
+
* @param mode - The drag's mode.
|
|
4829
|
+
* @param snap - The snapping steps, or `null`.
|
|
4830
|
+
*/
|
|
4831
|
+
start(entity, mode, snap) {
|
|
4832
|
+
const before = readLocalTransform(entity);
|
|
4833
|
+
this.#drag = {
|
|
4834
|
+
entity,
|
|
4835
|
+
mode,
|
|
4836
|
+
before,
|
|
4837
|
+
snapper: snap === null ? null : new DragSnapper(mode, snap, entity),
|
|
4838
|
+
lastSentMs: this.#now()
|
|
4839
|
+
};
|
|
4840
|
+
this.#notify(SceneNotification.transformDragging, {
|
|
4841
|
+
entity: entity.uid,
|
|
4842
|
+
mode,
|
|
4843
|
+
after: before
|
|
4844
|
+
});
|
|
4845
|
+
}
|
|
4846
|
+
/** Snaps the move the gizmo just made and sends `transformDragging`, at most every 50 ms. */
|
|
4847
|
+
move() {
|
|
4848
|
+
const state = this.#drag;
|
|
4849
|
+
if (state === null) return;
|
|
4850
|
+
state.snapper?.apply(state.entity);
|
|
4851
|
+
const now = this.#now();
|
|
4852
|
+
if (now - state.lastSentMs >= 50) {
|
|
4853
|
+
state.lastSentMs = now;
|
|
4854
|
+
this.#notify(SceneNotification.transformDragging, {
|
|
4855
|
+
entity: state.entity.uid,
|
|
4856
|
+
mode: state.mode,
|
|
4857
|
+
after: readLocalTransform(state.entity)
|
|
4858
|
+
});
|
|
4859
|
+
}
|
|
4860
|
+
}
|
|
4861
|
+
/** Ends the drag and sends `transformDragged`, whether or not the transform changed. */
|
|
4862
|
+
end() {
|
|
4863
|
+
const state = this.#drag;
|
|
4864
|
+
if (state === null) return;
|
|
4865
|
+
this.#drag = null;
|
|
4866
|
+
this.#notify(SceneNotification.transformDragged, {
|
|
4867
|
+
entity: state.entity.uid,
|
|
4868
|
+
mode: state.mode,
|
|
4869
|
+
before: state.before,
|
|
4870
|
+
after: readLocalTransform(state.entity)
|
|
4871
|
+
});
|
|
4872
|
+
}
|
|
4873
|
+
/** Forgets a drag that has no entity, so its moves and end send nothing. */
|
|
4874
|
+
clear() {
|
|
4875
|
+
this.#drag = null;
|
|
4876
|
+
}
|
|
4877
|
+
};
|
|
4878
|
+
//#endregion
|
|
4879
|
+
//#region src/scene/json.ts
|
|
4880
|
+
/**
|
|
4881
|
+
* The uid of a referenced entity or component.
|
|
4882
|
+
*
|
|
4883
|
+
* @param target - The field's value.
|
|
4884
|
+
* @returns Its uid, or `null` for anything without one.
|
|
4885
|
+
*/
|
|
4886
|
+
function uidOf(target) {
|
|
4887
|
+
const uid = typeof target === "object" && target !== null ? Reflect.get(target, "uid") : null;
|
|
4888
|
+
return typeof uid === "string" ? uid : null;
|
|
4889
|
+
}
|
|
4890
|
+
/**
|
|
4891
|
+
* Narrows JSON to an object. `Array.isArray` does not remove a readonly array from the union, so the
|
|
4892
|
+
* discrimination lives here once.
|
|
4893
|
+
*
|
|
4894
|
+
* @param value - The JSON.
|
|
4895
|
+
* @returns The object, or `null` for anything else.
|
|
4896
|
+
*/
|
|
4897
|
+
function asJsonObject(value) {
|
|
4898
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
4899
|
+
return value;
|
|
4900
|
+
}
|
|
4901
|
+
/**
|
|
4902
|
+
* Narrows JSON to an array.
|
|
4903
|
+
*
|
|
4904
|
+
* @param value - The JSON.
|
|
4905
|
+
* @returns The array, or `null`.
|
|
4906
|
+
*/
|
|
4907
|
+
function asJsonArray(value) {
|
|
4908
|
+
return Array.isArray(value) ? value : null;
|
|
4909
|
+
}
|
|
4910
|
+
/**
|
|
4911
|
+
* Tells whether JSON references an entity or component of a set.
|
|
4912
|
+
*
|
|
4913
|
+
* @param value - The JSON.
|
|
4914
|
+
* @param entities - The entity uids.
|
|
4915
|
+
* @param components - The component uids.
|
|
4916
|
+
* @returns True when a `$entity` or `$component` names one of them.
|
|
4917
|
+
*/
|
|
4918
|
+
function pointsInto(value, entities, components) {
|
|
4919
|
+
const array = asJsonArray(value);
|
|
4920
|
+
if (array !== null) return array.some((item) => pointsInto(item, entities, components));
|
|
4921
|
+
const object = asJsonObject(value);
|
|
4922
|
+
if (object === null) return false;
|
|
4923
|
+
const entity = object["$entity"];
|
|
4924
|
+
const component = object["$component"];
|
|
4925
|
+
return typeof entity === "string" && entities.has(entity) || typeof component === "string" && components.has(component) || Object.values(object).some((item) => pointsInto(item, entities, components));
|
|
4926
|
+
}
|
|
4927
|
+
//#endregion
|
|
4928
|
+
//#region src/scene/held-references.ts
|
|
4929
|
+
/**
|
|
4930
|
+
* What instance members outside a subtree that is about to be rebuilt hold in it: the reference
|
|
4931
|
+
* fields another instance's overrides aimed at the subtree, read from the live world before the
|
|
4932
|
+
* subtree is destroyed, so the rebuild can point them at the new objects.
|
|
4933
|
+
*/
|
|
4934
|
+
/**
|
|
4935
|
+
* The reference fields of instance members outside a subtree that point into it, read from the live
|
|
4936
|
+
* world as JSON: what another instance's overrides aimed at the subtree's document entities, or at
|
|
4937
|
+
* the components its `add` overrides give. A member is not in the document, so only its live
|
|
4938
|
+
* component knows the field; a document component and an added one are read from the document. Only
|
|
4939
|
+
* the instances whose override lists point into the subtree are read.
|
|
4940
|
+
*
|
|
4941
|
+
* @param app - The scene view's app.
|
|
4942
|
+
* @param mirror - The open document.
|
|
4943
|
+
* @param index - The document, read before the subtree is destroyed.
|
|
4944
|
+
* @param subtree - The subtree's root.
|
|
4945
|
+
* @param entities - The subtree's document entity uids.
|
|
4946
|
+
* @param components - The uids of its document components and the components its overrides add.
|
|
4947
|
+
* @returns The fields, and the objects they held.
|
|
4948
|
+
*/
|
|
4949
|
+
function heldByMembers(app, mirror, index, subtree, entities, components) {
|
|
4950
|
+
const fields = /* @__PURE__ */ new Map();
|
|
4951
|
+
const heldEntities = /* @__PURE__ */ new Map();
|
|
4952
|
+
const heldComponents = /* @__PURE__ */ new Map();
|
|
4953
|
+
const registry = app.world.registry;
|
|
4954
|
+
const visit = (entity) => {
|
|
4955
|
+
if (entity === subtree) return;
|
|
4956
|
+
for (const component of entity.components) {
|
|
4957
|
+
const uid = component.uid;
|
|
4958
|
+
if (index.components.get(uid) === component || index.added.get(uid) === component) continue;
|
|
4959
|
+
const props = {};
|
|
4960
|
+
for (const [name, field] of Object.entries(registry.describe(component.constructor).schema ?? {})) {
|
|
4961
|
+
if (!holdsReferences(field)) continue;
|
|
4962
|
+
const targets = [];
|
|
4963
|
+
const json = encodeValue(field, Reflect.get(component, name), {
|
|
4964
|
+
entityUid: (value) => remember(targets, heldEntities, value),
|
|
4965
|
+
componentUid: (value) => remember(targets, heldComponents, value)
|
|
4966
|
+
});
|
|
4967
|
+
if (pointsInto(json, entities, components)) {
|
|
4968
|
+
props[name] = json;
|
|
4969
|
+
for (const [into, target, value] of targets) into.set(target, value);
|
|
4970
|
+
}
|
|
4971
|
+
}
|
|
4972
|
+
if (Object.keys(props).length > 0) fields.set(component, props);
|
|
4973
|
+
}
|
|
4974
|
+
for (const child of entity.children) visit(child);
|
|
4975
|
+
};
|
|
4976
|
+
for (const record of index.file.entities) {
|
|
4977
|
+
const root = index.entities.get(record.uid);
|
|
4978
|
+
const aims = (mirror.overridesOf(record.uid) ?? []).some((override) => (override.op ?? "replace") === "replace" && pointsInto(override.value, entities, components));
|
|
4979
|
+
if (root !== void 0 && !entities.has(record.uid) && aims) visit(root);
|
|
4980
|
+
}
|
|
4981
|
+
return {
|
|
4982
|
+
fields,
|
|
4983
|
+
entities: heldEntities,
|
|
4984
|
+
components: heldComponents
|
|
4985
|
+
};
|
|
4986
|
+
}
|
|
4987
|
+
/**
|
|
4988
|
+
* Notes a referenced object by its uid, to keep if its field turns out to point into a subtree.
|
|
4989
|
+
*
|
|
4990
|
+
* @param targets - The field's notes.
|
|
4991
|
+
* @param into - Where the note goes if it is kept.
|
|
4992
|
+
* @param value - The referenced object.
|
|
4993
|
+
* @returns Its uid, or `null` for anything without one.
|
|
4994
|
+
*/
|
|
4995
|
+
function remember(targets, into, value) {
|
|
4996
|
+
const uid = uidOf(value);
|
|
4997
|
+
if (uid !== null) targets.push([
|
|
4998
|
+
into,
|
|
4999
|
+
uid,
|
|
5000
|
+
value
|
|
5001
|
+
]);
|
|
5002
|
+
return uid;
|
|
5003
|
+
}
|
|
5004
|
+
/**
|
|
5005
|
+
* Tells whether a field's value can hold an entity or component reference.
|
|
5006
|
+
*
|
|
5007
|
+
* @param field - The field.
|
|
5008
|
+
* @returns True for a reference, or a list, record, map or optional of one.
|
|
5009
|
+
*/
|
|
5010
|
+
function holdsReferences(field) {
|
|
5011
|
+
const spec = field.spec;
|
|
5012
|
+
if (spec.kind === "entityRef" || spec.kind === "componentRef") return true;
|
|
5013
|
+
if (spec.kind === "array") return holdsReferences(spec.item);
|
|
5014
|
+
if (spec.kind === "record") return Object.values(spec.fields).some((inner) => holdsReferences(inner));
|
|
5015
|
+
if (spec.kind === "map") return holdsReferences(spec.value);
|
|
5016
|
+
return spec.kind === "optional" && holdsReferences(spec.inner);
|
|
5017
|
+
}
|
|
5018
|
+
//#endregion
|
|
5019
|
+
//#region src/scene/ops.ts
|
|
5020
|
+
/**
|
|
5021
|
+
* `applyOps`: the thirteen scene ops of protocol 0.3, applied to the open document's live world.
|
|
5022
|
+
*
|
|
5023
|
+
* Each op changes the world the way the editor's `applyOp` changes the document, so that a mirror
|
|
5024
|
+
* that started exact stays exact: `readBack` then returns the document's own records. An op that
|
|
5025
|
+
* the world disagrees with fails with one of editor-core's codes; the host does not roll back,
|
|
5026
|
+
* because the editor reopens the scene after any failure.
|
|
5027
|
+
*/
|
|
5028
|
+
/** Why one op failed, as `applyOps` reports it. */
|
|
5029
|
+
var OpFailure = class extends Error {
|
|
5030
|
+
/** The failure code. */
|
|
5031
|
+
code;
|
|
5032
|
+
/** The engine's diagnostic code, when there is one. */
|
|
5033
|
+
diagnostic;
|
|
5034
|
+
/**
|
|
5035
|
+
* Creates the failure.
|
|
5036
|
+
*
|
|
5037
|
+
* @param code - The failure code.
|
|
5038
|
+
* @param message - An actionable sentence.
|
|
5039
|
+
* @param diagnostic - The engine's `IGX-` code, if any.
|
|
5040
|
+
*/
|
|
5041
|
+
constructor(code, message, diagnostic = null) {
|
|
5042
|
+
super(message);
|
|
5043
|
+
this.name = "OpFailure";
|
|
5044
|
+
this.code = code;
|
|
5045
|
+
this.diagnostic = diagnostic;
|
|
5046
|
+
}
|
|
5047
|
+
};
|
|
5048
|
+
/**
|
|
5049
|
+
* Applies one command's ops in order, never stopping at a failure.
|
|
5050
|
+
*
|
|
5051
|
+
* @param app - The scene view's app.
|
|
5052
|
+
* @param mirror - The open document.
|
|
5053
|
+
* @param params - The ops and the command they belong to.
|
|
5054
|
+
* @returns How many applied, the failures in order, and the build problems the ops met, in order.
|
|
5055
|
+
*/
|
|
5056
|
+
async function applyOps(app, mirror, params) {
|
|
5057
|
+
const warnings = [];
|
|
5058
|
+
const context = {
|
|
5059
|
+
app,
|
|
5060
|
+
mirror,
|
|
5061
|
+
warnings
|
|
5062
|
+
};
|
|
5063
|
+
const failures = [];
|
|
5064
|
+
let applied = 0;
|
|
5065
|
+
for (const [index, op] of params.ops.entries()) try {
|
|
5066
|
+
await applyOp(context, op);
|
|
5067
|
+
applied += 1;
|
|
5068
|
+
} catch (error) {
|
|
5069
|
+
const failure = toFailure(index, error);
|
|
5070
|
+
failures.push(failure);
|
|
5071
|
+
app.log.warn(`applyOps ${params.commandId} (${params.commandName}): op ${String(index)} (${op.op}) failed: ${failure.code}: ${failure.message}`);
|
|
5072
|
+
} finally {
|
|
5073
|
+
mirror.invalidate();
|
|
5074
|
+
}
|
|
5075
|
+
return {
|
|
5076
|
+
applied,
|
|
5077
|
+
failures,
|
|
5078
|
+
warnings
|
|
5079
|
+
};
|
|
5080
|
+
}
|
|
5081
|
+
/**
|
|
5082
|
+
* Turns whatever an op threw into its failure record.
|
|
5083
|
+
*
|
|
5084
|
+
* @param index - The op's index.
|
|
5085
|
+
* @param error - What it threw.
|
|
5086
|
+
* @returns The failure.
|
|
5087
|
+
*/
|
|
5088
|
+
function toFailure(index, error) {
|
|
5089
|
+
if (error instanceof OpFailure) return {
|
|
5090
|
+
index,
|
|
5091
|
+
code: error.code,
|
|
5092
|
+
message: error.message,
|
|
5093
|
+
...error.diagnostic === null ? {} : { diagnostic: error.diagnostic }
|
|
5094
|
+
};
|
|
5095
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
5096
|
+
return {
|
|
5097
|
+
index,
|
|
5098
|
+
code: ApplyOpFailureCode.engineError,
|
|
5099
|
+
message,
|
|
5100
|
+
...isIgnifxError(error) ? { diagnostic: error.code } : {}
|
|
5101
|
+
};
|
|
5102
|
+
}
|
|
5103
|
+
/**
|
|
5104
|
+
* Applies one op.
|
|
5105
|
+
*
|
|
5106
|
+
* @param context - The app and the document.
|
|
5107
|
+
* @param op - The op.
|
|
5108
|
+
*/
|
|
5109
|
+
async function applyOp(context, op) {
|
|
5110
|
+
switch (op.op) {
|
|
5111
|
+
case "createEntity":
|
|
5112
|
+
await createEntity(context, op);
|
|
5113
|
+
return;
|
|
5114
|
+
case "destroyEntity":
|
|
5115
|
+
requireEntity(context, op.entity).destroyImmediate();
|
|
5116
|
+
return;
|
|
5117
|
+
case "reparent":
|
|
4030
5118
|
reparent(context, op);
|
|
4031
5119
|
return;
|
|
4032
5120
|
case "reorder":
|
|
@@ -4181,21 +5269,28 @@ function requireFreeUids(context, records) {
|
|
|
4181
5269
|
}
|
|
4182
5270
|
}
|
|
4183
5271
|
/**
|
|
4184
|
-
*
|
|
5272
|
+
* Checks that new entity records form a scene file `validateSceneFile` accepts, before anything is
|
|
5273
|
+
* built: the protocol guard checks their shapes, and this adds the file's rules over them, among
|
|
5274
|
+
* them that no instance entry holds two overrides with one identity, which `setOverride` and
|
|
5275
|
+
* `removeOverride` could then reach only one of.
|
|
4185
5276
|
*
|
|
4186
|
-
* @param
|
|
4187
|
-
* @returns True when a `$entity` or `$component` object is in it.
|
|
5277
|
+
* @param records - The new entity records, parents first.
|
|
4188
5278
|
*/
|
|
4189
|
-
function
|
|
4190
|
-
const
|
|
4191
|
-
|
|
4192
|
-
|
|
4193
|
-
|
|
5279
|
+
function requireValidRecords(records) {
|
|
5280
|
+
const issue = validateSceneFile({
|
|
5281
|
+
format: SCENE_FILE_FORMAT,
|
|
5282
|
+
formatVersion: SCENE_FORMAT_VERSION,
|
|
5283
|
+
name: "",
|
|
5284
|
+
entities: records
|
|
5285
|
+
})[0];
|
|
5286
|
+
if (issue !== void 0) throw new OpFailure(ApplyOpFailureCode.invalidValue, `${issue.path}: ${issue.message}`, "IGX-0608");
|
|
4194
5287
|
}
|
|
4195
5288
|
/**
|
|
4196
5289
|
* Builds a subtree from entity records under a live parent, with the records' uids, loading the
|
|
4197
|
-
* assets they reference first
|
|
4198
|
-
*
|
|
5290
|
+
* assets they reference first. A reference to a uid the subtree does not declare resolves against
|
|
5291
|
+
* the rest of the document, as it would in the whole file: one a document component holds, and one
|
|
5292
|
+
* an instance's overrides hold (an added component's, or a member's overridden field). The build's
|
|
5293
|
+
* problems are logged as warnings ({@link reportBuildIssues}).
|
|
4199
5294
|
*
|
|
4200
5295
|
* @param context - The app and the document.
|
|
4201
5296
|
* @param records - The subtree's records, parents first; the first is its root.
|
|
@@ -4218,23 +5313,49 @@ async function buildSubtree(context, records, parent, index) {
|
|
|
4218
5313
|
};
|
|
4219
5314
|
const dependencies = await loadSceneDependencies(context.app.assets, file);
|
|
4220
5315
|
context.mirror.retain(dependencies);
|
|
4221
|
-
const asset = await createSceneAsset(
|
|
5316
|
+
const asset = await createSceneAsset(documentAddress(context), file, dependencies);
|
|
5317
|
+
const outsideReferences = context.mirror.decoder();
|
|
4222
5318
|
const built = instantiateScene(context.app.world, asset, {
|
|
4223
5319
|
scene,
|
|
5320
|
+
outsideReferences,
|
|
4224
5321
|
...parent === null ? {} : { parent }
|
|
4225
5322
|
});
|
|
4226
5323
|
context.mirror.invalidate();
|
|
4227
|
-
|
|
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
|
-
}
|
|
5324
|
+
reportBuildIssues(context, built.issues);
|
|
4232
5325
|
const root = built.roots[0] ?? built.remap.entity(top.uid);
|
|
4233
5326
|
if (root === null) throw new OpFailure(ApplyOpFailureCode.engineError, `The engine built no entity for ${top.uid}.`);
|
|
4234
5327
|
placeAmongSiblings(context, root, index);
|
|
4235
5328
|
return root;
|
|
4236
5329
|
}
|
|
4237
5330
|
/**
|
|
5331
|
+
* The open document's address, which names the subtrees ops build.
|
|
5332
|
+
*
|
|
5333
|
+
* @param context - The app and the document.
|
|
5334
|
+
* @returns Where the document is saved, or `memory:scene/unsaved`.
|
|
5335
|
+
*/
|
|
5336
|
+
function documentAddress(context) {
|
|
5337
|
+
return context.mirror.address ?? "memory:scene/unsaved";
|
|
5338
|
+
}
|
|
5339
|
+
/**
|
|
5340
|
+
* Writes a subtree build's recoverable problems to the app log, one warning each, the way
|
|
5341
|
+
* `world.loadSceneFile` writes a scene's (so a reopen of the document writes the same lines); the
|
|
5342
|
+
* host relays them to the editor as `log`. A stale override met while an instance is rebuilt is one.
|
|
5343
|
+
* Inside `applyOps` each also goes to the command's `warnings`, as `openScene` reports a build's.
|
|
5344
|
+
*
|
|
5345
|
+
* @param context - The app and the document.
|
|
5346
|
+
* @param issues - The problems, in the order found.
|
|
5347
|
+
*/
|
|
5348
|
+
function reportBuildIssues(context, issues) {
|
|
5349
|
+
const address = documentAddress(context);
|
|
5350
|
+
for (const issue of issues) {
|
|
5351
|
+
context.app.log.warn(`${issue.code}: ${address}: ${issue.message}`);
|
|
5352
|
+
context.warnings?.push({
|
|
5353
|
+
code: issue.code,
|
|
5354
|
+
message: issue.message
|
|
5355
|
+
});
|
|
5356
|
+
}
|
|
5357
|
+
}
|
|
5358
|
+
/**
|
|
4238
5359
|
* Applies `createEntity`: the entity and its descendants, with their uids and components.
|
|
4239
5360
|
*
|
|
4240
5361
|
* @param context - The app and the document.
|
|
@@ -4245,6 +5366,7 @@ async function createEntity(context, op) {
|
|
|
4245
5366
|
const parent = requireParent(context, op.entity.parent);
|
|
4246
5367
|
checkIndex(op.index, documentSiblings(context, parent, null).length);
|
|
4247
5368
|
requireFreeUids(context, records);
|
|
5369
|
+
requireValidRecords(records);
|
|
4248
5370
|
const inside = /* @__PURE__ */ new Set([op.entity.uid]);
|
|
4249
5371
|
for (const record of op.descendants ?? []) {
|
|
4250
5372
|
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,20 +5526,11 @@ async function instantiate(context, op) {
|
|
|
4404
5526
|
instance: op.instance
|
|
4405
5527
|
};
|
|
4406
5528
|
requireFreeUids(context, [record]);
|
|
5529
|
+
requireValidRecords([record]);
|
|
4407
5530
|
await buildSubtree(context, [record], parent, op.index);
|
|
4408
5531
|
context.mirror.recordInstances([record]);
|
|
4409
5532
|
}
|
|
4410
5533
|
/**
|
|
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
5534
|
* Reads a schema field's current value as JSON, references written as the uids they point at.
|
|
4422
5535
|
*
|
|
4423
5536
|
* @param field - The field.
|
|
@@ -4431,26 +5544,6 @@ function encodeLive(field, value) {
|
|
|
4431
5544
|
});
|
|
4432
5545
|
}
|
|
4433
5546
|
/**
|
|
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`.
|
|
4449
|
-
*/
|
|
4450
|
-
function asJsonArray(value) {
|
|
4451
|
-
return Array.isArray(value) ? value : null;
|
|
4452
|
-
}
|
|
4453
|
-
/**
|
|
4454
5547
|
* Returns JSON with the value at a path set, or removed, leaving the input unchanged.
|
|
4455
5548
|
*
|
|
4456
5549
|
* @param container - The JSON the path starts in.
|
|
@@ -4474,7 +5567,7 @@ function withValueAt(container, path, value) {
|
|
|
4474
5567
|
const object = asJsonObject(container);
|
|
4475
5568
|
if (object !== null && typeof step === "string") {
|
|
4476
5569
|
if (rest.length > 0) {
|
|
4477
|
-
const next = object[step];
|
|
5570
|
+
const next = Object.hasOwn(object, step) ? object[step] : void 0;
|
|
4478
5571
|
if (next === void 0) throw invalidPath(path);
|
|
4479
5572
|
return {
|
|
4480
5573
|
...object,
|
|
@@ -4607,53 +5700,52 @@ function findOverride(overrides, path, op, added) {
|
|
|
4607
5700
|
* Rebuilds an instance root's subtree with an edited override list: the live world has no way to
|
|
4608
5701
|
* re-apply one override, so the root and its document children are serialized, destroyed and built
|
|
4609
5702
|
* again from the instanced scene with the new list. References from the rest of the document into
|
|
4610
|
-
* the rebuilt subtree are resolved again.
|
|
5703
|
+
* the rebuilt subtree, the ones other instances' overrides hold included, are resolved again.
|
|
5704
|
+
*
|
|
5705
|
+
* The root and the instance roots under it are built with the override lists the document holds, and
|
|
5706
|
+
* the edit applies to the root's: the serializer recomputes a list by diffing the live members with
|
|
5707
|
+
* their scene, which writes an added component as its whole record and drops an override that
|
|
5708
|
+
* matches the scene, so a list read from it no longer follows a default or a prefab the document
|
|
5709
|
+
* leaves to them.
|
|
4611
5710
|
*
|
|
4612
5711
|
* @param context - The app and the document.
|
|
4613
5712
|
* @param uid - The instance root.
|
|
4614
|
-
* @param edit - Returns the new override list from the current one.
|
|
4615
|
-
* @param
|
|
4616
|
-
*
|
|
4617
|
-
* members, which a hot reload that changed a default has left stale.
|
|
5713
|
+
* @param edit - Returns the new override list from the document's current one.
|
|
5714
|
+
* @param keepHashes - Whether the instances keep the hashes they were built against; without them
|
|
5715
|
+
* they build from their scenes' current files without an `IGX-0604` mismatch, as after a reload.
|
|
4618
5716
|
*/
|
|
4619
|
-
async function rebuildInstance(context, uid, edit,
|
|
5717
|
+
async function rebuildInstance(context, uid, edit, keepHashes = true) {
|
|
4620
5718
|
const index = indexOf(context);
|
|
4621
5719
|
const root = requireEntity(context, uid);
|
|
4622
5720
|
const mirror = context.mirror;
|
|
4623
5721
|
const withDocumentOverrides = (record) => {
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
const
|
|
4627
|
-
|
|
5722
|
+
if (record.instance === void 0) return record;
|
|
5723
|
+
const { scene, hash, overrides: serialized } = record.instance;
|
|
5724
|
+
const listed = mirror.overridesOf(record.uid) ?? serialized ?? [];
|
|
5725
|
+
return withOverrideList(record, {
|
|
4628
5726
|
scene,
|
|
4629
|
-
...hash === void 0 ? {} : { hash },
|
|
5727
|
+
...hash === void 0 || !keepHashes ? {} : { hash },
|
|
4630
5728
|
...listed.length === 0 ? {} : { overrides: listed }
|
|
4631
|
-
};
|
|
4632
|
-
return {
|
|
4633
|
-
...record,
|
|
4634
|
-
instance
|
|
4635
|
-
};
|
|
5729
|
+
}, mirror.rootPathOf(record.uid));
|
|
4636
5730
|
};
|
|
4637
5731
|
const found = index.records.get(uid);
|
|
4638
5732
|
const record = found === void 0 ? void 0 : withDocumentOverrides(found);
|
|
4639
5733
|
const instance = record?.instance;
|
|
4640
5734
|
if (record === void 0 || instance === void 0) throw new OpFailure(ApplyOpFailureCode.notAnInstance, `${root.name} (${uid}) has no instance entry.`);
|
|
4641
5735
|
const overrides = edit(instance.overrides ?? []);
|
|
4642
|
-
const top = {
|
|
4643
|
-
|
|
4644
|
-
instance: {
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
...overrides.length === 0 ? {} : { overrides }
|
|
4648
|
-
}
|
|
4649
|
-
};
|
|
5736
|
+
const top = withOverrideList(record, {
|
|
5737
|
+
scene: instance.scene,
|
|
5738
|
+
...instance.hash === void 0 ? {} : { hash: instance.hash },
|
|
5739
|
+
...overrides.length === 0 ? {} : { overrides }
|
|
5740
|
+
}, mirror.rootPathOf(uid));
|
|
4650
5741
|
const inside = /* @__PURE__ */ new Set([uid]);
|
|
4651
5742
|
const records = [top];
|
|
4652
5743
|
for (const candidate of index.file.entities) if (candidate.parent !== null && inside.has(candidate.parent)) {
|
|
4653
5744
|
inside.add(candidate.uid);
|
|
4654
5745
|
records.push(withDocumentOverrides(candidate));
|
|
4655
5746
|
}
|
|
4656
|
-
const insideComponents = new Set(records.flatMap((entry_) => (entry_.components ?? []).map((component) => component.uid)));
|
|
5747
|
+
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) ?? [])]);
|
|
5748
|
+
const held = heldByMembers(context.app, context.mirror, index, root, inside, insideComponents);
|
|
4657
5749
|
const parent = root.parent;
|
|
4658
5750
|
const at = documentSiblings(context, parent, null).indexOf(root);
|
|
4659
5751
|
root.destroyImmediate();
|
|
@@ -4662,13 +5754,33 @@ async function rebuildInstance(context, uid, edit, documentOverrides = false) {
|
|
|
4662
5754
|
mirror.recordInstances(records);
|
|
4663
5755
|
const references = context.mirror.decoder();
|
|
4664
5756
|
const rebuilt = indexOf(context);
|
|
5757
|
+
const issues = [];
|
|
5758
|
+
const repoint = (live, props, decoder = references) => {
|
|
5759
|
+
const fields = new Set(Object.entries(props ?? {}).filter(([, value]) => pointsInto(value, inside, insideComponents)).map(([name]) => name));
|
|
5760
|
+
if (live === void 0 || live.isDestroyed || props === void 0 || fields.size === 0) return;
|
|
5761
|
+
const reported = new Set(propIssues(live, props, {
|
|
5762
|
+
entity: (target) => decoder.entity(target),
|
|
5763
|
+
component: (target) => insideComponents.has(target) ? target : decoder.component(target),
|
|
5764
|
+
asset: (address, type) => decoder.asset(address, type)
|
|
5765
|
+
}, fields).map((issue) => issue.message));
|
|
5766
|
+
issues.push(...assignProps(live, props, decoder, fields).filter((issue) => !reported.has(issue.message)));
|
|
5767
|
+
};
|
|
4665
5768
|
for (const outside of index.file.entities) {
|
|
4666
5769
|
if (inside.has(outside.uid)) continue;
|
|
4667
|
-
for (const component of outside.components ?? [])
|
|
4668
|
-
|
|
4669
|
-
|
|
5770
|
+
for (const component of outside.components ?? []) repoint(rebuilt.components.get(component.uid), component.props);
|
|
5771
|
+
for (const override of mirror.overridesOf(outside.uid) ?? []) {
|
|
5772
|
+
const added = addedUid(override);
|
|
5773
|
+
const props = asJsonObject(asJsonObject(override.value)?.["props"]);
|
|
5774
|
+
if (added !== null && props !== null) repoint(rebuilt.added.get(added), props);
|
|
4670
5775
|
}
|
|
4671
5776
|
}
|
|
5777
|
+
const keep = {
|
|
5778
|
+
entity: (target) => (inside.has(target) ? null : held.entities.get(target)) ?? references.entity(target),
|
|
5779
|
+
component: (target) => (insideComponents.has(target) ? null : held.components.get(target)) ?? references.component(target),
|
|
5780
|
+
asset: (address, type) => references.asset(address, type)
|
|
5781
|
+
};
|
|
5782
|
+
for (const [component, props] of held.fields) repoint(component, props, keep);
|
|
5783
|
+
reportBuildIssues(context, issues);
|
|
4672
5784
|
}
|
|
4673
5785
|
/**
|
|
4674
5786
|
* Rebuilds one instance root from its scene asset's current value, keeping its uid, its record
|
|
@@ -4679,38 +5791,19 @@ async function rebuildInstance(context, uid, edit, documentOverrides = false) {
|
|
|
4679
5791
|
* @param app - The scene view's app.
|
|
4680
5792
|
* @param mirror - The open document.
|
|
4681
5793
|
* @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
5794
|
* @throws OpFailure when the uid names no document entity or one without an instance entry.
|
|
4685
5795
|
*/
|
|
4686
|
-
async function reloadInstance(app, mirror, uid
|
|
5796
|
+
async function reloadInstance(app, mirror, uid) {
|
|
4687
5797
|
try {
|
|
4688
5798
|
await rebuildInstance({
|
|
4689
5799
|
app,
|
|
4690
5800
|
mirror
|
|
4691
|
-
}, uid, (overrides) => overrides,
|
|
5801
|
+
}, uid, (overrides) => overrides, false);
|
|
4692
5802
|
} finally {
|
|
4693
5803
|
mirror.invalidate();
|
|
4694
5804
|
}
|
|
4695
5805
|
}
|
|
4696
5806
|
/**
|
|
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
5807
|
* Applies `setOverride`: replaces the override with the same identity, or inserts it.
|
|
4715
5808
|
*
|
|
4716
5809
|
* @param context - The app and the document.
|
|
@@ -4787,448 +5880,232 @@ function sampleAnimation(app, mirror, params) {
|
|
|
4787
5880
|
}
|
|
4788
5881
|
}
|
|
4789
5882
|
//#endregion
|
|
4790
|
-
//#region src/scene/schemas.ts
|
|
4791
|
-
/**
|
|
4792
|
-
* `getSchemas` and `schemasChanged`: every registered component's schema, as the inspector reads
|
|
4793
|
-
* it, plus core's file-format entries.
|
|
4794
|
-
*/
|
|
4795
|
-
/** The `format` core's component entries carry; file formats carry their own name instead. */
|
|
4796
|
-
const COMPONENTS_FORMAT = "components";
|
|
4797
|
-
/**
|
|
4798
|
-
* Describes every component class the app's registry holds (engine, extensions and the project's
|
|
4799
|
-
* scripts) with core's `describeRegisteredSchemas`, plus the JSON Schema of its `props` and core's
|
|
4800
|
-
* file-format entries.
|
|
4801
|
-
*
|
|
4802
|
-
* @remarks
|
|
4803
|
-
* Each field carries its inspector options (`step`, `hidden`, `readonly`, `group`, an asset's
|
|
4804
|
-
* `assetType`, a `componentRef`'s `componentType`), and each component its `allowMultiple` and the
|
|
4805
|
-
* `package` that registered it, all optional members of protocol 0.3. A component core describes
|
|
4806
|
-
* 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
|
-
* document's. `ignifx/Transform` is described with core's `transformSchema()` and carries
|
|
4808
|
-
* `builtIn`: its fields are each entity's `transform` block, edited with `setTransform`, and it is
|
|
4809
|
-
* never added or removed.
|
|
4810
|
-
*
|
|
4811
|
-
* The set is read from the live registry each time, so a hot reload that adds a field or a script
|
|
4812
|
-
* shows in the next `schemasChanged`.
|
|
4813
|
-
*
|
|
4814
|
-
* @param app - The scene view's app.
|
|
4815
|
-
* @param hidden - Type ids to leave out.
|
|
4816
|
-
* @returns The set, keyed by type id.
|
|
4817
|
-
*/
|
|
4818
|
-
function schemaSet(app, hidden) {
|
|
4819
|
-
const core = describeSchemas();
|
|
4820
|
-
const registry = app.world.registry;
|
|
4821
|
-
const described = describeRegisteredSchemas(registry, core);
|
|
4822
|
-
const schemas = {};
|
|
4823
|
-
for (const [typeId, type] of registry.registrations()) {
|
|
4824
|
-
const description = described[typeId];
|
|
4825
|
-
if (hidden.has(typeId) || description === void 0) continue;
|
|
4826
|
-
const schema = type === Transform ? transformSchema() : registry.describe(type).schema ?? {};
|
|
4827
|
-
schemas[typeId] = {
|
|
4828
|
-
...description,
|
|
4829
|
-
propsSchema: toJsonSchema(schema)
|
|
4830
|
-
};
|
|
4831
|
-
}
|
|
4832
|
-
for (const [id, description] of Object.entries(core)) if (description.format !== COMPONENTS_FORMAT) schemas[id] = description;
|
|
4833
|
-
return { schemas };
|
|
4834
|
-
}
|
|
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
|
-
/**
|
|
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.
|
|
4922
|
-
*
|
|
4923
|
-
* @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.
|
|
4927
|
-
*
|
|
4928
|
-
* @param app - The scene view's app.
|
|
4929
|
-
* @returns The sections and their values, keyed by section name in registration order.
|
|
4930
|
-
*/
|
|
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) : {};
|
|
4944
|
-
}
|
|
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
|
-
}
|
|
5883
|
+
//#region src/scene/schemas.ts
|
|
4993
5884
|
/**
|
|
4994
|
-
*
|
|
4995
|
-
*
|
|
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`.
|
|
5885
|
+
* `getSchemas` and `schemasChanged`: every registered component's schema, as the inspector reads
|
|
5886
|
+
* it, plus core's file-format entries.
|
|
5000
5887
|
*/
|
|
5001
|
-
|
|
5002
|
-
|
|
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
|
-
}
|
|
5888
|
+
/** The `format` core's component entries carry; file formats carry their own name instead. */
|
|
5889
|
+
const COMPONENTS_FORMAT = "components";
|
|
5027
5890
|
/**
|
|
5028
|
-
*
|
|
5891
|
+
* Describes every component class the app's registry holds (engine, extensions and the project's
|
|
5892
|
+
* scripts) with core's `describeRegisteredSchemas`, plus the JSON Schema of its `props` and core's
|
|
5893
|
+
* file-format entries.
|
|
5029
5894
|
*
|
|
5030
|
-
* @
|
|
5031
|
-
*
|
|
5895
|
+
* @remarks
|
|
5896
|
+
* Each field carries its inspector options (`step`, `hidden`, `readonly`, `group`, an asset's
|
|
5897
|
+
* `assetType`, a `componentRef`'s `componentType`), and each component its `allowMultiple` and the
|
|
5898
|
+
* `package` that registered it, all optional members of protocol 0.3. Each component's title and
|
|
5899
|
+
* summary are its class's own `static title` and `static description`, which every package
|
|
5900
|
+
* declares on its components, so an extension's curated names arrive without the host importing
|
|
5901
|
+
* the extension; core's `describeSchemas()` still overrides core's entries, and a component with
|
|
5902
|
+
* neither is titled from its type id. The host's own classes are left out: they are not the
|
|
5903
|
+
* document's. `ignifx/Transform` is described with core's `transformSchema()` and carries
|
|
5904
|
+
* `builtIn`: its fields are each entity's `transform` block, edited with `setTransform`, and it is
|
|
5905
|
+
* never added or removed. Each component also carries `extends` (engine ask E44): the registered
|
|
5906
|
+
* components its class derives from, which count as present for a `requires` entry.
|
|
5907
|
+
*
|
|
5908
|
+
* The set is read from the live registry each time, so a hot reload that adds a field or a script
|
|
5909
|
+
* shows in the next `schemasChanged`.
|
|
5910
|
+
*
|
|
5911
|
+
* @param app - The scene view's app.
|
|
5912
|
+
* @param hidden - Type ids to leave out.
|
|
5913
|
+
* @returns The set, keyed by type id.
|
|
5032
5914
|
*/
|
|
5033
|
-
function
|
|
5034
|
-
|
|
5915
|
+
function schemaSet(app, hidden) {
|
|
5916
|
+
const core = describeSchemas();
|
|
5917
|
+
const registry = app.world.registry;
|
|
5918
|
+
const described = describeRegisteredSchemas(registry, core);
|
|
5919
|
+
const schemas = {};
|
|
5920
|
+
for (const [typeId, type] of registry.registrations()) {
|
|
5921
|
+
const description = described[typeId];
|
|
5922
|
+
if (hidden.has(typeId) || description === void 0) continue;
|
|
5923
|
+
const schema = type === Transform ? transformSchema() : registry.describe(type).schema ?? {};
|
|
5924
|
+
schemas[typeId] = {
|
|
5925
|
+
...description,
|
|
5926
|
+
extends: registeredAncestors(registry, type),
|
|
5927
|
+
propsSchema: toJsonSchema(schema)
|
|
5928
|
+
};
|
|
5929
|
+
}
|
|
5930
|
+
for (const [id, description] of Object.entries(core)) if (description.format !== COMPONENTS_FORMAT) schemas[id] = description;
|
|
5931
|
+
return { schemas };
|
|
5035
5932
|
}
|
|
5036
5933
|
/**
|
|
5037
|
-
* The
|
|
5038
|
-
* aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.
|
|
5934
|
+
* The type ids of the registered component classes a class derives from, nearest first.
|
|
5039
5935
|
*
|
|
5040
|
-
* @
|
|
5041
|
-
*
|
|
5042
|
-
*
|
|
5936
|
+
* @remarks
|
|
5937
|
+
* `Entity.getComponent`, and so `addComponent`'s `requires` check, matches a class against the
|
|
5938
|
+
* attached component's ancestor chain, by class identity. An ancestor is listed when it is
|
|
5939
|
+
* registered under its own `static typeId`, the id `requires` names it by; an intermediate class
|
|
5940
|
+
* that only inherits a registered parent's `typeId` is not that registration and is left out.
|
|
5941
|
+
*
|
|
5942
|
+
* @param registry - The app's component registry.
|
|
5943
|
+
* @param type - The described class.
|
|
5944
|
+
* @returns The ancestors' type ids, the class itself excluded; empty when none is registered.
|
|
5043
5945
|
*/
|
|
5044
|
-
function
|
|
5045
|
-
const
|
|
5046
|
-
const
|
|
5047
|
-
|
|
5048
|
-
|
|
5049
|
-
|
|
5050
|
-
}
|
|
5051
|
-
|
|
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
|
-
};
|
|
5946
|
+
function registeredAncestors(registry, type) {
|
|
5947
|
+
const ids = [];
|
|
5948
|
+
const ancestors = registry.describe(type).ancestors;
|
|
5949
|
+
for (let index = 1; index < ancestors.length; index += 1) {
|
|
5950
|
+
const ancestor = ancestors[index];
|
|
5951
|
+
if (ancestor !== void 0 && registry.isRegistered(ancestor)) ids.push(registry.requireTypeId(ancestor));
|
|
5952
|
+
}
|
|
5953
|
+
return ids;
|
|
5064
5954
|
}
|
|
5955
|
+
//#endregion
|
|
5956
|
+
//#region src/scene/screenshot.ts
|
|
5065
5957
|
/**
|
|
5066
|
-
*
|
|
5958
|
+
* `screenshot`, shared by the scene view and the play view: the parameter check, and a captured
|
|
5959
|
+
* frame scaled to the requested size and written as a PNG or JPEG data URL. Encoding needs a
|
|
5960
|
+
* browser's `OffscreenCanvas`, as the capture needs a GPU.
|
|
5961
|
+
*/
|
|
5962
|
+
/** The JPEG quality when the request gives none. */
|
|
5963
|
+
const DEFAULT_JPEG_QUALITY = .9;
|
|
5964
|
+
/** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */
|
|
5965
|
+
const BASE64_CHUNK = 32768;
|
|
5966
|
+
/**
|
|
5967
|
+
* Encodes bytes as base64.
|
|
5067
5968
|
*
|
|
5068
|
-
* @param
|
|
5069
|
-
* @returns The
|
|
5969
|
+
* @param bytes - The bytes.
|
|
5970
|
+
* @returns The base64 text.
|
|
5070
5971
|
*/
|
|
5071
|
-
function
|
|
5072
|
-
|
|
5073
|
-
|
|
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
|
-
};
|
|
5972
|
+
function toBase64(bytes) {
|
|
5973
|
+
let binary = "";
|
|
5974
|
+
for (let start = 0; start < bytes.length; start += BASE64_CHUNK) binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));
|
|
5975
|
+
return btoa(binary);
|
|
5092
5976
|
}
|
|
5093
5977
|
/**
|
|
5094
|
-
*
|
|
5978
|
+
* Scales a captured frame to a size and encodes it as a data URL.
|
|
5095
5979
|
*
|
|
5096
|
-
* @param
|
|
5097
|
-
* @param
|
|
5098
|
-
* @
|
|
5980
|
+
* @param capture - The frame, RGBA8 with the top row first.
|
|
5981
|
+
* @param size - The image size.
|
|
5982
|
+
* @param format - `"png"` or `"jpeg"`.
|
|
5983
|
+
* @param quality - The JPEG quality, from 0 to 1; ignored for PNG.
|
|
5984
|
+
* @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.
|
|
5985
|
+
* @throws Error when the browser has no 2D canvas context.
|
|
5099
5986
|
*/
|
|
5100
|
-
function
|
|
5101
|
-
|
|
5987
|
+
async function encodeCapture(capture, size, format, quality) {
|
|
5988
|
+
const source = new OffscreenCanvas(capture.width, capture.height);
|
|
5989
|
+
const sourceContext = source.getContext("2d");
|
|
5990
|
+
const target = new OffscreenCanvas(size.width, size.height);
|
|
5991
|
+
const targetContext = target.getContext("2d");
|
|
5992
|
+
if (sourceContext === null || targetContext === null) throw new Error("This browser has no 2D canvas to encode the screenshot with.");
|
|
5993
|
+
sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);
|
|
5994
|
+
targetContext.imageSmoothingQuality = "high";
|
|
5995
|
+
targetContext.drawImage(source, 0, 0, size.width, size.height);
|
|
5996
|
+
const type = format === "png" ? "image/png" : "image/jpeg";
|
|
5997
|
+
const blob = await target.convertToBlob(format === "png" ? { type } : {
|
|
5998
|
+
type,
|
|
5999
|
+
quality
|
|
6000
|
+
});
|
|
6001
|
+
return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;
|
|
5102
6002
|
}
|
|
5103
6003
|
/**
|
|
5104
|
-
*
|
|
6004
|
+
* Checks `screenshot`'s parameters.
|
|
5105
6005
|
*
|
|
5106
|
-
* @param
|
|
5107
|
-
* @
|
|
5108
|
-
* @
|
|
6006
|
+
* @param params - The received `params`.
|
|
6007
|
+
* @returns The parameters.
|
|
6008
|
+
* @throws InvalidParamsError for a side outside 1 to {@link SCREENSHOT_MAX_SIZE}, an unknown format, or
|
|
6009
|
+
* a quality outside 0 to 1.
|
|
5109
6010
|
*/
|
|
5110
|
-
function
|
|
5111
|
-
|
|
6011
|
+
function checkScreenshotParams(params) {
|
|
6012
|
+
if (typeof params === "object" && params !== null) for (const side of ["width", "height"]) {
|
|
6013
|
+
const value = Reflect.get(params, side);
|
|
6014
|
+
if (value !== void 0 && (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > 2048)) throw new InvalidParamsError(`screenshot takes a width and height from 1 to ${String(SCREENSHOT_MAX_SIZE)} pixels.`);
|
|
6015
|
+
}
|
|
6016
|
+
if (!isScreenshotParams(params)) throw new InvalidParamsError("screenshot takes { width?, height?, format: \"png\" | \"jpeg\", quality? }.");
|
|
6017
|
+
return params;
|
|
5112
6018
|
}
|
|
5113
6019
|
/**
|
|
5114
|
-
*
|
|
5115
|
-
*
|
|
6020
|
+
* Captures the app's next presented frame and encodes it as `screenshot` answers.
|
|
6021
|
+
*
|
|
6022
|
+
* @param app - The app whose canvas is captured.
|
|
6023
|
+
* @param params - Checked parameters.
|
|
6024
|
+
* @returns The data URL and its size.
|
|
6025
|
+
* @throws IgnifxError `IGX-0707` when the app's render loop does not run.
|
|
5116
6026
|
*/
|
|
5117
|
-
|
|
5118
|
-
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
|
|
5122
|
-
|
|
5123
|
-
|
|
5124
|
-
|
|
5125
|
-
|
|
5126
|
-
|
|
5127
|
-
|
|
5128
|
-
|
|
5129
|
-
|
|
5130
|
-
|
|
5131
|
-
|
|
5132
|
-
|
|
5133
|
-
|
|
5134
|
-
|
|
5135
|
-
|
|
5136
|
-
|
|
5137
|
-
|
|
5138
|
-
|
|
5139
|
-
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
|
|
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
|
-
];
|
|
6027
|
+
async function takeScreenshot(app, params) {
|
|
6028
|
+
const capture = await app.renderer.captureScreenshot();
|
|
6029
|
+
const size = screenshotSize(params, capture);
|
|
6030
|
+
return {
|
|
6031
|
+
dataUrl: await encodeCapture(capture, size, params.format, params.quality ?? DEFAULT_JPEG_QUALITY),
|
|
6032
|
+
width: size.width,
|
|
6033
|
+
height: size.height
|
|
6034
|
+
};
|
|
6035
|
+
}
|
|
6036
|
+
//#endregion
|
|
6037
|
+
//#region src/scene/settings.ts
|
|
6038
|
+
/**
|
|
6039
|
+
* `describeSettings`: the project's settings sections, as the editor's settings panel reads them,
|
|
6040
|
+
* and the values the app resolved for them.
|
|
6041
|
+
*/
|
|
6042
|
+
/**
|
|
6043
|
+
* Copies a value made of JSON data, leaving out what JSON cannot carry.
|
|
6044
|
+
*
|
|
6045
|
+
* @param value - The value.
|
|
6046
|
+
* @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a
|
|
6047
|
+
* non-finite number.
|
|
6048
|
+
*/
|
|
6049
|
+
function jsonCopy(value) {
|
|
6050
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
6051
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
6052
|
+
if (Array.isArray(value)) return value.map((item) => jsonCopy(item) ?? null);
|
|
6053
|
+
if (typeof value === "object") return jsonObjectCopy(value);
|
|
6054
|
+
}
|
|
6055
|
+
/**
|
|
6056
|
+
* Copies an object's own enumerable members with {@link jsonCopy}.
|
|
6057
|
+
*
|
|
6058
|
+
* @param value - The object.
|
|
6059
|
+
* @returns The copy.
|
|
6060
|
+
*/
|
|
6061
|
+
function jsonObjectCopy(value) {
|
|
6062
|
+
const entries = [];
|
|
6063
|
+
for (const [key, member] of Object.entries(value)) {
|
|
6064
|
+
const converted = jsonCopy(member);
|
|
6065
|
+
if (converted !== void 0) entries.push([key, converted]);
|
|
5200
6066
|
}
|
|
5201
|
-
|
|
6067
|
+
return Object.fromEntries(entries);
|
|
6068
|
+
}
|
|
5202
6069
|
/**
|
|
5203
|
-
*
|
|
6070
|
+
* Tells whether a JSON value is an object.
|
|
5204
6071
|
*
|
|
5205
|
-
* @param
|
|
5206
|
-
* @
|
|
5207
|
-
* @returns The product.
|
|
6072
|
+
* @param value - The value.
|
|
6073
|
+
* @returns True for an object that is not an array.
|
|
5208
6074
|
*/
|
|
5209
|
-
function
|
|
5210
|
-
|
|
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
|
-
];
|
|
6075
|
+
function isObject(value) {
|
|
6076
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5218
6077
|
}
|
|
5219
6078
|
/**
|
|
5220
|
-
*
|
|
6079
|
+
* Describes every settings section the app registered with core's `describeSettings`, each with
|
|
6080
|
+
* its JSON Schema from `settingsJsonSchema` as `propsSchema`, and copies the value the app resolved
|
|
6081
|
+
* for each section.
|
|
5221
6082
|
*
|
|
5222
|
-
* @
|
|
5223
|
-
*
|
|
6083
|
+
* @remarks
|
|
6084
|
+
* Settings are held in the settings form (`{ x, y, z }` for a vector), which is plain data, so a
|
|
6085
|
+
* section's value is copied member by member; a member JSON cannot carry is left out. The answer is
|
|
6086
|
+
* read from the app each time and sent only on request.
|
|
6087
|
+
*
|
|
6088
|
+
* @param app - The scene view's app.
|
|
6089
|
+
* @returns The sections and their values, keyed by section name in registration order.
|
|
5224
6090
|
*/
|
|
5225
|
-
function
|
|
5226
|
-
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
|
|
6091
|
+
function settingsSet(app) {
|
|
6092
|
+
const described = describeSettings(app);
|
|
6093
|
+
const properties = settingsJsonSchema(app)["properties"];
|
|
6094
|
+
const sections = {};
|
|
6095
|
+
const values = {};
|
|
6096
|
+
for (const [name, description] of Object.entries(described)) {
|
|
6097
|
+
const propsSchema = isObject(properties) ? properties[name] : void 0;
|
|
6098
|
+
sections[name] = isObject(propsSchema) ? {
|
|
6099
|
+
...description,
|
|
6100
|
+
propsSchema
|
|
6101
|
+
} : description;
|
|
6102
|
+
const value = app.settings.section(name);
|
|
6103
|
+
values[name] = typeof value === "object" && value !== null ? jsonObjectCopy(value) : {};
|
|
6104
|
+
}
|
|
6105
|
+
return {
|
|
6106
|
+
sections,
|
|
6107
|
+
values
|
|
6108
|
+
};
|
|
5232
6109
|
}
|
|
5233
6110
|
//#endregion
|
|
5234
6111
|
//#region src/scene/scene-host.ts
|
|
@@ -5272,7 +6149,7 @@ var SceneHost = class {
|
|
|
5272
6149
|
space: GizmoSpace.world,
|
|
5273
6150
|
snap: null
|
|
5274
6151
|
};
|
|
5275
|
-
#drag
|
|
6152
|
+
#drag;
|
|
5276
6153
|
#started = false;
|
|
5277
6154
|
/** The field defaults seen at start and after each hot reload, from {@link SceneHost.start} on. */
|
|
5278
6155
|
#defaults = null;
|
|
@@ -5288,6 +6165,7 @@ var SceneHost = class {
|
|
|
5288
6165
|
*/
|
|
5289
6166
|
constructor(options) {
|
|
5290
6167
|
this.#notify = options.notify;
|
|
6168
|
+
this.#drag = new GizmoDragRelay(options.notify);
|
|
5291
6169
|
const has = (capability) => options.capabilities.includes(capability);
|
|
5292
6170
|
this.#hasViewMode2D = has(HostCapability.viewMode2d);
|
|
5293
6171
|
const methods = /* @__PURE__ */ new Map([
|
|
@@ -5380,7 +6258,17 @@ var SceneHost = class {
|
|
|
5380
6258
|
this.#view = view;
|
|
5381
6259
|
this.#applyGizmo();
|
|
5382
6260
|
const onClick = (click) => {
|
|
5383
|
-
this.#onClick(click)
|
|
6261
|
+
this.#onClick(click).catch((error) => {
|
|
6262
|
+
const params = {
|
|
6263
|
+
code: isIgnifxError(error) ? error.code : null,
|
|
6264
|
+
message: clipHostText(`Selecting what a click in the view hit: ${messageOf(error)}`),
|
|
6265
|
+
data: {
|
|
6266
|
+
x: click.x,
|
|
6267
|
+
y: click.y
|
|
6268
|
+
}
|
|
6269
|
+
};
|
|
6270
|
+
this.#notify(SceneNotification.hostError, params);
|
|
6271
|
+
});
|
|
5384
6272
|
};
|
|
5385
6273
|
for (const camera of [this.#camera, this.#camera2D]) if (camera !== null) {
|
|
5386
6274
|
camera.claims = view;
|
|
@@ -5423,7 +6311,7 @@ var SceneHost = class {
|
|
|
5423
6311
|
return this.#serial(async () => {
|
|
5424
6312
|
const index = handle.type === "scene" ? mirror.index() : null;
|
|
5425
6313
|
const roots = index === null ? [] : instancesOf(app, index, address);
|
|
5426
|
-
const entities = await this.#rebuildInstances(app, mirror, roots, address, { address }
|
|
6314
|
+
const entities = await this.#rebuildInstances(app, mirror, roots, address, { address });
|
|
5427
6315
|
this.#setSelection(this.#selection);
|
|
5428
6316
|
const params = {
|
|
5429
6317
|
address,
|
|
@@ -5443,18 +6331,17 @@ var SceneHost = class {
|
|
|
5443
6331
|
* @param roots - The roots' uids, none inside another.
|
|
5444
6332
|
* @param cause - What the rebuild follows, for the error's message.
|
|
5445
6333
|
* @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
6334
|
* @returns The roots rebuilt.
|
|
5448
6335
|
*/
|
|
5449
|
-
async #rebuildInstances(app, mirror, roots, cause, data
|
|
6336
|
+
async #rebuildInstances(app, mirror, roots, cause, data) {
|
|
5450
6337
|
const rebuilt = [];
|
|
5451
6338
|
for (const uid of roots) try {
|
|
5452
|
-
await reloadInstance(app, mirror, uid
|
|
6339
|
+
await reloadInstance(app, mirror, uid);
|
|
5453
6340
|
rebuilt.push(uid);
|
|
5454
6341
|
} catch (error) {
|
|
5455
6342
|
const params = {
|
|
5456
6343
|
code: isIgnifxError(error) ? error.code : null,
|
|
5457
|
-
message: `Rebuilding ${uid} from ${cause}: ${messageOf(error)}
|
|
6344
|
+
message: clipHostText(`Rebuilding ${uid} from ${cause}: ${messageOf(error)}`),
|
|
5458
6345
|
data: {
|
|
5459
6346
|
...data,
|
|
5460
6347
|
entity: uid
|
|
@@ -5467,7 +6354,8 @@ var SceneHost = class {
|
|
|
5467
6354
|
/**
|
|
5468
6355
|
* Gives the open document the defaults a hot reload changed, where it leaves them out (engine ask
|
|
5469
6356
|
* 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.
|
|
6357
|
+
* whose members hold a changed type is rebuilt from its prefab with its overrides. A component
|
|
6358
|
+
* that throws while taking a default is a `hostError`, and the rest still runs.
|
|
5471
6359
|
*
|
|
5472
6360
|
* @param changed - The changed fields, by type id.
|
|
5473
6361
|
*/
|
|
@@ -5476,14 +6364,25 @@ var SceneHost = class {
|
|
|
5476
6364
|
const mirror = this.#mirror;
|
|
5477
6365
|
const index = mirror?.index() ?? null;
|
|
5478
6366
|
if (app === null || mirror === null || index === null) return;
|
|
5479
|
-
applyDefaults(app, mirror, index, changed)
|
|
6367
|
+
applyDefaults(app, mirror, index, changed, (component, typeId, error) => {
|
|
6368
|
+
const params = {
|
|
6369
|
+
code: isIgnifxError(error) ? error.code : null,
|
|
6370
|
+
message: clipHostText(`Applying the new defaults of ${typeId} to ${component.uid}: ${messageOf(error)}`),
|
|
6371
|
+
data: {
|
|
6372
|
+
typeIds: [typeId],
|
|
6373
|
+
entity: component.entity.uid,
|
|
6374
|
+
component: typeId
|
|
6375
|
+
}
|
|
6376
|
+
};
|
|
6377
|
+
this.#notify(SceneNotification.hostError, params);
|
|
6378
|
+
});
|
|
5480
6379
|
mirror.invalidate();
|
|
5481
6380
|
const rebuilt = mirror.index();
|
|
5482
|
-
const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, rebuilt, changed));
|
|
6381
|
+
const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, mirror, rebuilt, changed));
|
|
5483
6382
|
if (roots.length > 0) {
|
|
5484
6383
|
const typeIds = [...changed.keys()];
|
|
5485
6384
|
const cause = `the new defaults of ${typeIds.join(", ")}`;
|
|
5486
|
-
await this.#rebuildInstances(app, mirror, roots, cause, { typeIds }
|
|
6385
|
+
await this.#rebuildInstances(app, mirror, roots, cause, { typeIds });
|
|
5487
6386
|
this.#setSelection(this.#selection);
|
|
5488
6387
|
}
|
|
5489
6388
|
}
|
|
@@ -5543,7 +6442,7 @@ var SceneHost = class {
|
|
|
5543
6442
|
* `applyOps`: one command's ops, in order.
|
|
5544
6443
|
*
|
|
5545
6444
|
* @param params - `{ ops, commandName, commandId }`.
|
|
5546
|
-
* @returns How many applied, and the
|
|
6445
|
+
* @returns How many applied, the failures, and the build problems.
|
|
5547
6446
|
*/
|
|
5548
6447
|
async #applyOps(params) {
|
|
5549
6448
|
const mirror = this.#requireMirror(SceneMethod.applyOps);
|
|
@@ -5651,20 +6550,10 @@ var SceneHost = class {
|
|
|
5651
6550
|
async #screenshot(params) {
|
|
5652
6551
|
const app = this.#requireApp();
|
|
5653
6552
|
this.#requireMirror(SceneMethod.screenshot);
|
|
5654
|
-
|
|
5655
|
-
const value = Reflect.get(params, side);
|
|
5656
|
-
if (value !== void 0 && (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > 2048)) throw new InvalidParamsError(`screenshot takes a width and height from 1 to ${String(SCREENSHOT_MAX_SIZE)} pixels.`);
|
|
5657
|
-
}
|
|
5658
|
-
if (!isScreenshotParams(params)) throw new InvalidParamsError("screenshot takes { width?, height?, format: \"png\" | \"jpeg\", quality? }.");
|
|
6553
|
+
const checked = checkScreenshotParams(params);
|
|
5659
6554
|
this.#view?.setVisible(false);
|
|
5660
6555
|
try {
|
|
5661
|
-
|
|
5662
|
-
const size = screenshotSize(params, capture);
|
|
5663
|
-
return {
|
|
5664
|
-
dataUrl: await encodeCapture(capture, size, params.format, params.quality ?? .9),
|
|
5665
|
-
width: size.width,
|
|
5666
|
-
height: size.height
|
|
5667
|
-
};
|
|
6556
|
+
return await takeScreenshot(app, checked);
|
|
5668
6557
|
} finally {
|
|
5669
6558
|
this.#view?.setVisible(true);
|
|
5670
6559
|
}
|
|
@@ -5956,7 +6845,7 @@ var SceneHost = class {
|
|
|
5956
6845
|
this.#notify(SceneNotification.selectionChanged, { entities: this.#selection });
|
|
5957
6846
|
}
|
|
5958
6847
|
/**
|
|
5959
|
-
*
|
|
6848
|
+
* Hands a gizmo drag of the selection's last entity to {@link GizmoDragRelay}.
|
|
5960
6849
|
*
|
|
5961
6850
|
* @param phase - Which part of the gesture.
|
|
5962
6851
|
* @param drag - The handle.
|
|
@@ -5965,43 +6854,10 @@ var SceneHost = class {
|
|
|
5965
6854
|
if (phase === "start") {
|
|
5966
6855
|
const uid = this.#selection.at(-1);
|
|
5967
6856
|
const entity = uid === void 0 ? void 0 : this.#mirror?.index()?.entities.get(uid);
|
|
5968
|
-
if (entity === void 0)
|
|
5969
|
-
|
|
5970
|
-
|
|
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
|
-
});
|
|
6857
|
+
if (entity === void 0) this.#drag.clear();
|
|
6858
|
+
else this.#drag.start(entity, drag.mode, this.#gizmo.snap);
|
|
6859
|
+
} else if (phase === "move") this.#drag.move();
|
|
6860
|
+
else this.#drag.end();
|
|
6005
6861
|
}
|
|
6006
6862
|
/**
|
|
6007
6863
|
* The world bounds of entities: their meshes' when the view can measure them, else their
|
|
@@ -6051,7 +6907,14 @@ var SceneHost = class {
|
|
|
6051
6907
|
#hotReloaded(report) {
|
|
6052
6908
|
this.#mirror?.invalidate();
|
|
6053
6909
|
const changed = this.#defaults?.changed(report.typeIds) ?? /* @__PURE__ */ new Map();
|
|
6054
|
-
if (changed.size > 0) this.#serial(async () => this.#followDefaults(changed))
|
|
6910
|
+
if (changed.size > 0) this.#serial(async () => this.#followDefaults(changed)).catch((error) => {
|
|
6911
|
+
const params = {
|
|
6912
|
+
code: isIgnifxError(error) ? error.code : null,
|
|
6913
|
+
message: clipHostText(`Following the new defaults of ${[...changed.keys()].join(", ")}: ${messageOf(error)}`),
|
|
6914
|
+
data: { typeIds: [...changed.keys()] }
|
|
6915
|
+
};
|
|
6916
|
+
this.#notify(SceneNotification.hostError, params);
|
|
6917
|
+
});
|
|
6055
6918
|
const params = hotReloadedParamsOf(report);
|
|
6056
6919
|
this.#notify(SceneNotification.hotReloaded, params);
|
|
6057
6920
|
this.sendSchemas();
|
|
@@ -6161,7 +7024,7 @@ function resolveEngineVersion(fallback, coreVersion = VERSION) {
|
|
|
6161
7024
|
* ```ts
|
|
6162
7025
|
* import { startEditorHost } from "@ignifx/editor-host";
|
|
6163
7026
|
*
|
|
6164
|
-
* const host = await startEditorHost({ editorOrigin: "ignifx://app", canvas, extensions: [], scripts });
|
|
7027
|
+
* const host = await startEditorHost({ editorOrigin: "ignifx-editor://app", canvas, extensions: [], scripts });
|
|
6165
7028
|
* ```
|
|
6166
7029
|
*
|
|
6167
7030
|
* @beta
|
|
@@ -6266,6 +7129,348 @@ function appOptions(options) {
|
|
|
6266
7129
|
};
|
|
6267
7130
|
}
|
|
6268
7131
|
//#endregion
|
|
7132
|
+
//#region src/play-input.ts
|
|
7133
|
+
/**
|
|
7134
|
+
* The play view's `sendInput` (engine ask E49): synthetic key and pointer events queued into the
|
|
7135
|
+
* game's own `app.input`, the way headless tests drive the engine. The host does not depend on
|
|
7136
|
+
* `@ignifx/input`: it finds `app.input` by name and calls `simulateEvent` by shape, as it reaches
|
|
7137
|
+
* `app.twoD` (`./scene/view-2d.ts`). Nothing here dispatches a DOM event or touches the editor.
|
|
7138
|
+
*/
|
|
7139
|
+
/**
|
|
7140
|
+
* The game's input service, when the project registers `@ignifx/input`.
|
|
7141
|
+
*
|
|
7142
|
+
* @param app - The game's app.
|
|
7143
|
+
* @returns `app.input`, or `null` when it has no `simulateEvent`.
|
|
7144
|
+
*/
|
|
7145
|
+
function inputServiceOf(app) {
|
|
7146
|
+
const service = Reflect.get(app, "input");
|
|
7147
|
+
if (typeof service !== "object" || service === null) return null;
|
|
7148
|
+
const simulateEvent = Reflect.get(service, "simulateEvent");
|
|
7149
|
+
if (typeof simulateEvent !== "function") return null;
|
|
7150
|
+
const resolveControl = Reflect.get(service, "resolveControl");
|
|
7151
|
+
return {
|
|
7152
|
+
simulateEvent: (event) => {
|
|
7153
|
+
Reflect.apply(simulateEvent, service, [event]);
|
|
7154
|
+
},
|
|
7155
|
+
hasControl: (path) => {
|
|
7156
|
+
if (typeof resolveControl !== "function") return true;
|
|
7157
|
+
try {
|
|
7158
|
+
Reflect.apply(resolveControl, service, [path]);
|
|
7159
|
+
return true;
|
|
7160
|
+
} catch {
|
|
7161
|
+
return false;
|
|
7162
|
+
}
|
|
7163
|
+
}
|
|
7164
|
+
};
|
|
7165
|
+
}
|
|
7166
|
+
/**
|
|
7167
|
+
* Splits a `sendInput` event into a key event or a pointer one.
|
|
7168
|
+
*
|
|
7169
|
+
* @param event - The event.
|
|
7170
|
+
* @returns True for `keydown` and `keyup`.
|
|
7171
|
+
*/
|
|
7172
|
+
function isKeyEvent(event) {
|
|
7173
|
+
return event.type === "keydown" || event.type === "keyup";
|
|
7174
|
+
}
|
|
7175
|
+
/**
|
|
7176
|
+
* Measures the game's canvas.
|
|
7177
|
+
*
|
|
7178
|
+
* @param app - The game's app.
|
|
7179
|
+
* @returns Its size and pixel ratio.
|
|
7180
|
+
*/
|
|
7181
|
+
function canvasMetrics(app) {
|
|
7182
|
+
const surface = app.renderer.surface;
|
|
7183
|
+
const width = surface !== null && surface.width > 0 ? surface.width : 1;
|
|
7184
|
+
const height = surface !== null && surface.height > 0 ? surface.height : 1;
|
|
7185
|
+
const clientWidth = surface === null ? void 0 : Reflect.get(surface, "clientWidth");
|
|
7186
|
+
return {
|
|
7187
|
+
width,
|
|
7188
|
+
height,
|
|
7189
|
+
cssPerPixel: typeof clientWidth === "number" && clientWidth > 0 ? clientWidth / width : 1
|
|
7190
|
+
};
|
|
7191
|
+
}
|
|
7192
|
+
/**
|
|
7193
|
+
* Queues `sendInput`'s events into one game's input service. Keeps the last pointer position it
|
|
7194
|
+
* sent, so a move reports the motion since it, as a real pointer does.
|
|
7195
|
+
*/
|
|
7196
|
+
var PlayInput = class {
|
|
7197
|
+
#app;
|
|
7198
|
+
#input;
|
|
7199
|
+
#last = null;
|
|
7200
|
+
/**
|
|
7201
|
+
* Creates the queue for one game.
|
|
7202
|
+
*
|
|
7203
|
+
* @param app - The game's app.
|
|
7204
|
+
* @param input - Its input service.
|
|
7205
|
+
*/
|
|
7206
|
+
constructor(app, input) {
|
|
7207
|
+
this.#app = app;
|
|
7208
|
+
this.#input = input;
|
|
7209
|
+
}
|
|
7210
|
+
/**
|
|
7211
|
+
* `sendInput`: checks every event, then queues them all in order. The game resolves them on its
|
|
7212
|
+
* next frame, as it does events from the page.
|
|
7213
|
+
*
|
|
7214
|
+
* @param params - The received `params`.
|
|
7215
|
+
* @returns How many events were queued.
|
|
7216
|
+
* @throws InvalidParamsError for malformed parameters or a key the game's keyboard does not have;
|
|
7217
|
+
* nothing is queued then. If `simulateEvent` itself throws partway, the events before it stay
|
|
7218
|
+
* queued: the input service has no way to take them back.
|
|
7219
|
+
*/
|
|
7220
|
+
send(params) {
|
|
7221
|
+
if (!isSendInputParams(params)) throw new InvalidParamsError(`sendInput needs 1 to ${String(64)} events: { type: "keydown" | "keyup", control } or { type: "pointermove" | "pointerdown" | "pointerup", x, y (0 to 1), button? (0 to 4) }.`);
|
|
7222
|
+
for (const event of params.events) if (isKeyEvent(event) && !this.#input.hasControl(`<Keyboard>/${event.control}`)) throw new InvalidParamsError(`sendInput: the game's keyboard has no key "${event.control}". Use the <Keyboard> control name, such as w, space or arrowUp.`);
|
|
7223
|
+
const metrics = canvasMetrics(this.#app);
|
|
7224
|
+
for (const event of params.events) this.#input.simulateEvent(this.#simulated(event, metrics));
|
|
7225
|
+
return { queued: params.events.length };
|
|
7226
|
+
}
|
|
7227
|
+
/**
|
|
7228
|
+
* Builds the raw event for one request event.
|
|
7229
|
+
*
|
|
7230
|
+
* @param event - The request's event.
|
|
7231
|
+
* @param metrics - The canvas's size and pixel ratio.
|
|
7232
|
+
* @returns The event `simulateEvent` takes.
|
|
7233
|
+
*/
|
|
7234
|
+
#simulated(event, metrics) {
|
|
7235
|
+
if (isKeyEvent(event)) return {
|
|
7236
|
+
type: event.type,
|
|
7237
|
+
code: event.control
|
|
7238
|
+
};
|
|
7239
|
+
const x = event.x * metrics.width;
|
|
7240
|
+
const y = event.y * metrics.height;
|
|
7241
|
+
const last = this.#last;
|
|
7242
|
+
this.#last = {
|
|
7243
|
+
x,
|
|
7244
|
+
y
|
|
7245
|
+
};
|
|
7246
|
+
const moves = event.type !== "pointerdown" && last !== null;
|
|
7247
|
+
return {
|
|
7248
|
+
type: event.type,
|
|
7249
|
+
x,
|
|
7250
|
+
y,
|
|
7251
|
+
deltaX: moves ? (x - last.x) * metrics.cssPerPixel : 0,
|
|
7252
|
+
deltaY: moves ? (y - last.y) * metrics.cssPerPixel : 0,
|
|
7253
|
+
button: event.button ?? 0
|
|
7254
|
+
};
|
|
7255
|
+
}
|
|
7256
|
+
};
|
|
7257
|
+
//#endregion
|
|
7258
|
+
//#region src/play-query.ts
|
|
7259
|
+
/**
|
|
7260
|
+
* The play view's `queryRuntime` (engine ask E48): one entity of the running game, as the scene
|
|
7261
|
+
* format writes it, read through core's `serializeEntity`, each value capped and the whole answer
|
|
7262
|
+
* kept within `QUERY_RUNTIME_MAX_JSON_LENGTH`.
|
|
7263
|
+
*/
|
|
7264
|
+
/** How deep a capped JSON value may nest; deeper values become `null`, as `isJsonValue` allows 256. */
|
|
7265
|
+
const MAX_JSON_DEPTH = 256;
|
|
7266
|
+
/**
|
|
7267
|
+
* What `"components":[],` and the final counts can add to an answer's JSON beyond the skeleton the
|
|
7268
|
+
* budget measures first: the counts there are written with no more digits than they end with,
|
|
7269
|
+
* except `omittedEntries`, which may grow to a safe integer's 16.
|
|
7270
|
+
*/
|
|
7271
|
+
const COMPONENTS_OVERHEAD = 64;
|
|
7272
|
+
/** Thrown out of a copy once it is sure to pass its budget. */
|
|
7273
|
+
var OverBudget = class extends Error {};
|
|
7274
|
+
/**
|
|
7275
|
+
* Counts, while a component is copied, a lower bound of its JSON length, so a copy that cannot fit
|
|
7276
|
+
* stops early instead of building the whole oversized value.
|
|
7277
|
+
*/
|
|
7278
|
+
var Meter = class {
|
|
7279
|
+
/** How many object keys and list items the caps left out of the copy. */
|
|
7280
|
+
omitted = 0;
|
|
7281
|
+
#used = 0;
|
|
7282
|
+
#limit;
|
|
7283
|
+
/**
|
|
7284
|
+
* Creates the meter.
|
|
7285
|
+
*
|
|
7286
|
+
* @param limit - The JSON length the copy may take.
|
|
7287
|
+
*/
|
|
7288
|
+
constructor(limit) {
|
|
7289
|
+
this.#limit = limit;
|
|
7290
|
+
}
|
|
7291
|
+
/**
|
|
7292
|
+
* Counts part of the copy.
|
|
7293
|
+
*
|
|
7294
|
+
* @param length - At most as many UTF-16 code units as that part takes as JSON.
|
|
7295
|
+
* @throws OverBudget once the count passes the limit.
|
|
7296
|
+
*/
|
|
7297
|
+
charge(length) {
|
|
7298
|
+
this.#used += length;
|
|
7299
|
+
if (this.#used > this.#limit) throw new OverBudget();
|
|
7300
|
+
}
|
|
7301
|
+
};
|
|
7302
|
+
/**
|
|
7303
|
+
* Clips a string to a length, never splitting a surrogate pair.
|
|
7304
|
+
*
|
|
7305
|
+
* @param text - The string.
|
|
7306
|
+
* @param max - The longest it may be.
|
|
7307
|
+
* @returns It, or its start.
|
|
7308
|
+
*/
|
|
7309
|
+
function clipTo(text, max) {
|
|
7310
|
+
if (text.length <= max) return text;
|
|
7311
|
+
const last = text.charCodeAt(max - 1);
|
|
7312
|
+
return text.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
|
|
7313
|
+
}
|
|
7314
|
+
/**
|
|
7315
|
+
* Copies a value within the caps of `QueryRuntimeResult.entity`, counting it on the meter.
|
|
7316
|
+
*
|
|
7317
|
+
* @param value - The value, which a custom codec may have made something other than JSON.
|
|
7318
|
+
* @param depth - How deep it sits.
|
|
7319
|
+
* @param meter - The component's budget.
|
|
7320
|
+
* @returns The capped copy; `null` for anything that is not JSON or sits too deep.
|
|
7321
|
+
* @throws OverBudget when the copy cannot fit.
|
|
7322
|
+
*/
|
|
7323
|
+
function capJson(value, depth, meter) {
|
|
7324
|
+
if (typeof value === "string") {
|
|
7325
|
+
const clipped = clipWithMarker(value, QUERY_RUNTIME_MAX_STRING_LENGTH);
|
|
7326
|
+
meter.charge(clipped.length + 2);
|
|
7327
|
+
return clipped;
|
|
7328
|
+
}
|
|
7329
|
+
meter.charge(1);
|
|
7330
|
+
if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return value;
|
|
7331
|
+
if (typeof value !== "object" || value === null || depth >= MAX_JSON_DEPTH) return null;
|
|
7332
|
+
if (Array.isArray(value)) {
|
|
7333
|
+
meter.omitted += Math.max(0, value.length - HOST_LIST_MAX_LENGTH);
|
|
7334
|
+
return value.slice(0, HOST_LIST_MAX_LENGTH).map((item) => capJson(item, depth + 1, meter));
|
|
7335
|
+
}
|
|
7336
|
+
return capJsonObject(value, depth, meter);
|
|
7337
|
+
}
|
|
7338
|
+
/**
|
|
7339
|
+
* {@link capJson} for an object: its first `QUERY_RUNTIME_MAX_KEYS` keys, each clipped as long.
|
|
7340
|
+
* A key that clips to one already kept is left out, so the first keeps its value. Every key left
|
|
7341
|
+
* out is counted on the meter.
|
|
7342
|
+
*
|
|
7343
|
+
* @param value - The object.
|
|
7344
|
+
* @param depth - How deep it sits.
|
|
7345
|
+
* @param meter - The component's budget.
|
|
7346
|
+
* @returns The capped copy, keys in the same order.
|
|
7347
|
+
* @throws OverBudget when the copy cannot fit.
|
|
7348
|
+
*/
|
|
7349
|
+
function capJsonObject(value, depth, meter) {
|
|
7350
|
+
const out = {};
|
|
7351
|
+
const entries = Object.entries(value);
|
|
7352
|
+
let kept = 0;
|
|
7353
|
+
for (const [index, [key, item]] of entries.entries()) {
|
|
7354
|
+
if (kept === 256) {
|
|
7355
|
+
meter.omitted += entries.length - index;
|
|
7356
|
+
break;
|
|
7357
|
+
}
|
|
7358
|
+
const clipped = clipTo(key, 256);
|
|
7359
|
+
if (Object.hasOwn(out, clipped)) {
|
|
7360
|
+
meter.omitted += 1;
|
|
7361
|
+
continue;
|
|
7362
|
+
}
|
|
7363
|
+
meter.charge(clipped.length + 3);
|
|
7364
|
+
Object.defineProperty(out, clipped, {
|
|
7365
|
+
value: capJson(item, depth + 1, meter),
|
|
7366
|
+
enumerable: true,
|
|
7367
|
+
writable: true,
|
|
7368
|
+
configurable: true
|
|
7369
|
+
});
|
|
7370
|
+
kept += 1;
|
|
7371
|
+
}
|
|
7372
|
+
return out;
|
|
7373
|
+
}
|
|
7374
|
+
/**
|
|
7375
|
+
* Clips a string as the reports do, ending it with {@link CLIPPED_MARKER}.
|
|
7376
|
+
*
|
|
7377
|
+
* @param text - The string.
|
|
7378
|
+
* @param max - The longest it may be, marker included.
|
|
7379
|
+
* @returns It, or its start and the marker.
|
|
7380
|
+
*/
|
|
7381
|
+
function clipWithMarker(text, max) {
|
|
7382
|
+
return text.length <= max ? text : `${clipTo(text, max - 11)}${CLIPPED_MARKER}`;
|
|
7383
|
+
}
|
|
7384
|
+
/**
|
|
7385
|
+
* Copies one component record within the caps, if it fits.
|
|
7386
|
+
*
|
|
7387
|
+
* @param component - The record `serializeEntity` wrote.
|
|
7388
|
+
* @param room - The JSON length still free in the answer.
|
|
7389
|
+
* @returns The capped record and its JSON length, or `null` when it does not fit.
|
|
7390
|
+
*/
|
|
7391
|
+
function fitComponent(component, room) {
|
|
7392
|
+
try {
|
|
7393
|
+
const meter = new Meter(room);
|
|
7394
|
+
const record = {
|
|
7395
|
+
...component,
|
|
7396
|
+
type: clipTo(component.type, 256),
|
|
7397
|
+
...component.props === void 0 ? {} : { props: capJsonObject(component.props, 0, meter) }
|
|
7398
|
+
};
|
|
7399
|
+
const length = JSON.stringify(record).length + 1;
|
|
7400
|
+
return length <= room ? {
|
|
7401
|
+
record,
|
|
7402
|
+
length,
|
|
7403
|
+
omitted: meter.omitted
|
|
7404
|
+
} : null;
|
|
7405
|
+
} catch (error) {
|
|
7406
|
+
if (error instanceof OverBudget) return null;
|
|
7407
|
+
throw error;
|
|
7408
|
+
}
|
|
7409
|
+
}
|
|
7410
|
+
/**
|
|
7411
|
+
* Reads the type ids a `queryRuntime` keeps.
|
|
7412
|
+
*
|
|
7413
|
+
* @param params - The received `params`.
|
|
7414
|
+
* @returns The entity's uid and the type-id filter, or `null` for every component.
|
|
7415
|
+
* @throws InvalidParamsError when the parameters are not a uid and at most 64 type ids.
|
|
7416
|
+
*/
|
|
7417
|
+
function checkQueryRuntimeParams(params) {
|
|
7418
|
+
if (!isQueryRuntimeParams(params)) throw new InvalidParamsError(`queryRuntime needs { entity: uid, components?: typeId[] } with at most ${String(64)} type ids.`);
|
|
7419
|
+
return {
|
|
7420
|
+
uid: params.entity,
|
|
7421
|
+
filter: params.components === void 0 ? null : new Set(params.components)
|
|
7422
|
+
};
|
|
7423
|
+
}
|
|
7424
|
+
/**
|
|
7425
|
+
* `queryRuntime`: one entity of the game as `serializeEntity` writes it from the live world, capped.
|
|
7426
|
+
* Changes nothing.
|
|
7427
|
+
*
|
|
7428
|
+
* @param app - The game's app.
|
|
7429
|
+
* @param params - The received `params`.
|
|
7430
|
+
* @returns The entity record, how many components did not fit, and when it was read.
|
|
7431
|
+
* @throws InvalidParamsError for malformed parameters, and RpcFailure `unknownEntity` when no live
|
|
7432
|
+
* entity of the game has the uid.
|
|
7433
|
+
*/
|
|
7434
|
+
function queryRuntime(app, params) {
|
|
7435
|
+
const { uid, filter } = checkQueryRuntimeParams(params);
|
|
7436
|
+
const entity = app.world.getEntity(uid);
|
|
7437
|
+
if (entity === null || entity.isDestroyed) throw new RpcFailure(RpcErrorCode.unknownEntity, "No entity of the running game has that uid. Entities a script or a prefab spawns get new uids on every run.");
|
|
7438
|
+
const { components, ...fields } = serializeEntity(entity);
|
|
7439
|
+
const matching = (components ?? []).filter((component) => filter?.has(component.type) ?? true);
|
|
7440
|
+
const tagsOmitted = Math.max(0, (fields.tags?.length ?? 0) - 256);
|
|
7441
|
+
const answer = {
|
|
7442
|
+
entity: {
|
|
7443
|
+
...fields,
|
|
7444
|
+
name: clipTo(fields.name, 256),
|
|
7445
|
+
...fields.layer === void 0 ? {} : { layer: clipTo(fields.layer, 256) },
|
|
7446
|
+
...fields.tags === void 0 ? {} : { tags: fields.tags.slice(0, 256).map((tag) => clipTo(tag, 256)) }
|
|
7447
|
+
},
|
|
7448
|
+
omittedComponents: matching.length,
|
|
7449
|
+
omittedEntries: tagsOmitted,
|
|
7450
|
+
frameCount: app.time.frameCount,
|
|
7451
|
+
time: app.time.time
|
|
7452
|
+
};
|
|
7453
|
+
let room = QUERY_RUNTIME_MAX_JSON_LENGTH - JSON.stringify(answer).length - COMPONENTS_OVERHEAD;
|
|
7454
|
+
const kept = [];
|
|
7455
|
+
let omittedEntries = tagsOmitted;
|
|
7456
|
+
for (const component of matching.slice(0, 64)) {
|
|
7457
|
+
const fitted = fitComponent(component, room);
|
|
7458
|
+
if (fitted === null) break;
|
|
7459
|
+
kept.push(fitted.record);
|
|
7460
|
+
room -= fitted.length;
|
|
7461
|
+
omittedEntries += fitted.omitted;
|
|
7462
|
+
}
|
|
7463
|
+
return {
|
|
7464
|
+
...answer,
|
|
7465
|
+
entity: {
|
|
7466
|
+
...answer.entity,
|
|
7467
|
+
...kept.length === 0 ? {} : { components: kept }
|
|
7468
|
+
},
|
|
7469
|
+
omittedComponents: matching.length - kept.length,
|
|
7470
|
+
omittedEntries
|
|
7471
|
+
};
|
|
7472
|
+
}
|
|
7473
|
+
//#endregion
|
|
6269
7474
|
//#region src/play-controls.ts
|
|
6270
7475
|
/**
|
|
6271
7476
|
* The play view's controls: the project's own game page, reached by the editor through the app the
|
|
@@ -6355,6 +7560,53 @@ function stepDelta(app, params) {
|
|
|
6355
7560
|
if (typeof delta !== "number" || !Number.isFinite(delta) || delta <= 0) throw new InvalidParamsError("step needs deltaSeconds to be a positive number of seconds.");
|
|
6356
7561
|
return delta;
|
|
6357
7562
|
}
|
|
7563
|
+
/** How often a capture that waits for its frame checks that the game's loop still runs, in ms. */
|
|
7564
|
+
const CAPTURE_STOP_POLL_MS = 50;
|
|
7565
|
+
/**
|
|
7566
|
+
* The refusal of a `screenshot` while the game's frame loop does not run.
|
|
7567
|
+
*
|
|
7568
|
+
* @returns The failure, with code `notPlaying`.
|
|
7569
|
+
*/
|
|
7570
|
+
function notPlaying() {
|
|
7571
|
+
return new RpcFailure(RpcErrorCode.notPlaying, "The game is not running, so there is no frame to capture. Press Play first; after Step or Stop the game renders no frames.");
|
|
7572
|
+
}
|
|
7573
|
+
/**
|
|
7574
|
+
* Refuses a method that needs a game that plays or is paused, while the game is stopped.
|
|
7575
|
+
*
|
|
7576
|
+
* @param tracker - Reads the game's phase.
|
|
7577
|
+
* @param what - What the method would have done, for the message.
|
|
7578
|
+
* @throws RpcFailure `notPlaying` while the game is stopped: before it starts, or after `stop`.
|
|
7579
|
+
*/
|
|
7580
|
+
function requireStarted(tracker, what) {
|
|
7581
|
+
if (tracker.read().state === PlayPhase.stopped) throw new RpcFailure(RpcErrorCode.notPlaying, `The game is stopped, so there is no running game to ${what}. Press Play first; a paused or stepped game answers.`);
|
|
7582
|
+
}
|
|
7583
|
+
/**
|
|
7584
|
+
* `screenshot`: the game's canvas as an image, as the scene view's `screenshot` answers. Changes
|
|
7585
|
+
* nothing about the game.
|
|
7586
|
+
*
|
|
7587
|
+
* @param app - The game's app.
|
|
7588
|
+
* @param params - The received `params`.
|
|
7589
|
+
* @returns The data URL and its size.
|
|
7590
|
+
* @throws RpcFailure `notPlaying` while the frame loop does not run or when it stops before the
|
|
7591
|
+
* frame arrives, `notReady` before the first frame, and `invalidParams` for parameters the scene
|
|
7592
|
+
* view would refuse.
|
|
7593
|
+
*/
|
|
7594
|
+
async function playScreenshot(app, params) {
|
|
7595
|
+
if (!app.isRunning) throw notPlaying();
|
|
7596
|
+
if (app.time.frameCount === 0) throw new RpcFailure(RpcErrorCode.notReady, "The game has not rendered its first frame yet.");
|
|
7597
|
+
const checked = checkScreenshotParams(params);
|
|
7598
|
+
let poll;
|
|
7599
|
+
const stopped = new Promise((_resolve, reject) => {
|
|
7600
|
+
poll = setInterval(() => {
|
|
7601
|
+
if (!app.isRunning) reject(notPlaying());
|
|
7602
|
+
}, CAPTURE_STOP_POLL_MS);
|
|
7603
|
+
});
|
|
7604
|
+
try {
|
|
7605
|
+
return await Promise.race([takeScreenshot(app, checked), stopped]);
|
|
7606
|
+
} finally {
|
|
7607
|
+
clearInterval(poll);
|
|
7608
|
+
}
|
|
7609
|
+
}
|
|
6358
7610
|
/**
|
|
6359
7611
|
* Builds the play methods for one app.
|
|
6360
7612
|
*
|
|
@@ -6365,7 +7617,7 @@ function stepDelta(app, params) {
|
|
|
6365
7617
|
function playMethods(app, tracker) {
|
|
6366
7618
|
const answer = () => new Reply(playState(app), tracker.report);
|
|
6367
7619
|
const stats = new PlayStatsReader(app);
|
|
6368
|
-
|
|
7620
|
+
const methods = /* @__PURE__ */ new Map([
|
|
6369
7621
|
[PlayMethod.play, async () => {
|
|
6370
7622
|
tracker.isStopped = false;
|
|
6371
7623
|
app.time.paused = false;
|
|
@@ -6391,8 +7643,22 @@ function playMethods(app, tracker) {
|
|
|
6391
7643
|
return answer();
|
|
6392
7644
|
}],
|
|
6393
7645
|
[PlayMethod.playState, () => tracker.read()],
|
|
6394
|
-
[PlayMethod.playStats, () => stats.read()]
|
|
7646
|
+
[PlayMethod.playStats, () => stats.read()],
|
|
7647
|
+
[PlayMethod.queryRuntime, (params) => {
|
|
7648
|
+
requireStarted(tracker, "read");
|
|
7649
|
+
return queryRuntime(app, params);
|
|
7650
|
+
}]
|
|
6395
7651
|
]);
|
|
7652
|
+
if (!app.isHeadless) methods.set(PlayMethod.screenshot, async (params) => playScreenshot(app, params));
|
|
7653
|
+
const input = inputServiceOf(app);
|
|
7654
|
+
if (input !== null) {
|
|
7655
|
+
const queue = new PlayInput(app, input);
|
|
7656
|
+
methods.set(PlayMethod.sendInput, (params) => {
|
|
7657
|
+
requireStarted(tracker, "send input to");
|
|
7658
|
+
return queue.send(params);
|
|
7659
|
+
});
|
|
7660
|
+
}
|
|
7661
|
+
return methods;
|
|
6396
7662
|
}
|
|
6397
7663
|
/**
|
|
6398
7664
|
* The options every play view checks before it opens a channel.
|
|
@@ -6447,7 +7713,10 @@ function openPlayControls(app, options, target, heartbeatIntervalMs, port) {
|
|
|
6447
7713
|
capabilities: [
|
|
6448
7714
|
HostCapability.heartbeat,
|
|
6449
7715
|
HostCapability.playControls,
|
|
6450
|
-
HostCapability.logRelay
|
|
7716
|
+
HostCapability.logRelay,
|
|
7717
|
+
HostCapability.queryRuntime,
|
|
7718
|
+
...app.isHeadless ? [] : [HostCapability.screenshot],
|
|
7719
|
+
...inputServiceOf(app) === null ? [] : [HostCapability.sendInput]
|
|
6451
7720
|
],
|
|
6452
7721
|
hostKind: HostKind.play
|
|
6453
7722
|
},
|
|
@@ -6476,7 +7745,7 @@ function openPlayControls(app, options, target, heartbeatIntervalMs, port) {
|
|
|
6476
7745
|
}
|
|
6477
7746
|
/**
|
|
6478
7747
|
* Lets the editor drive a running game: answers the handshake with `hostKind: "play"`, then `play`,
|
|
6479
|
-
* `pause`, `step`, `stop`, `playState` and `
|
|
7748
|
+
* `pause`, `step`, `stop`, `playState`, `playStats`, `queryRuntime`, (with a canvas) `screenshot` and (with `app.input`) `sendInput`, and sends `playStateChanged` when the game's phase
|
|
6480
7749
|
* changes, and `log`, `hostError` and `hotReloaded` for the game's log lines, `app.onError` reports
|
|
6481
7750
|
* and hot reloads (the newest 256 from before the handshake right after it).
|
|
6482
7751
|
*
|
|
@@ -6493,7 +7762,7 @@ function openPlayControls(app, options, target, heartbeatIntervalMs, port) {
|
|
|
6493
7762
|
*
|
|
6494
7763
|
* @example
|
|
6495
7764
|
* ```ts
|
|
6496
|
-
* const controls = startEditorPlayControls(app, { editorOrigin: "ignifx://app" });
|
|
7765
|
+
* const controls = startEditorPlayControls(app, { editorOrigin: "ignifx-editor://app" });
|
|
6497
7766
|
* controls.dispose();
|
|
6498
7767
|
* ```
|
|
6499
7768
|
*
|
|
@@ -6522,7 +7791,7 @@ function startEditorPlayControls(app, options) {
|
|
|
6522
7791
|
*
|
|
6523
7792
|
* @example
|
|
6524
7793
|
* ```ts
|
|
6525
|
-
* const connector = listenForEditorPlayControls({ editorOrigin: "ignifx://app" });
|
|
7794
|
+
* const connector = listenForEditorPlayControls({ editorOrigin: "ignifx-editor://app" });
|
|
6526
7795
|
* const app = await createApp({ headless: true });
|
|
6527
7796
|
* const controls = connector.attach(app);
|
|
6528
7797
|
* connector.dispose();
|
|
@@ -6575,6 +7844,6 @@ function listenForEditorPlayControls(options) {
|
|
|
6575
7844
|
};
|
|
6576
7845
|
}
|
|
6577
7846
|
//#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 };
|
|
7847
|
+
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, QUERY_RUNTIME_MAX_COMPONENTS, QUERY_RUNTIME_MAX_JSON_LENGTH, QUERY_RUNTIME_MAX_KEYS, QUERY_RUNTIME_MAX_STRING_LENGTH, RpcErrorCode, SAMPLE_ANIMATION_MAX_NAME_LENGTH, SAMPLE_ANIMATION_MAX_PARAMETERS, SCREENSHOT_MAX_SIZE, SEND_INPUT_MAX_EVENTS, 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, isQueryRuntimeParams, isQueryRuntimeResult, isReadBackParams, isReadBackResult, isReadyResult, isRpcMessage, isSampleAnimationParams, isSampleAnimationResult, isSceneFile, isSceneFileAssetRef, isSceneFileComponent, isSceneFileEntity, isSceneFileInstance, isSceneFileOverride, isSceneFileTransform, isSceneIssue, isSceneOp, isSceneOpenedParams, isSchemaSet, isScreenshotParams, isScreenshotResult, isSendInputEvent, isSendInputParams, isSendInputResult, isSetAnimateMaterialsParams, isSetGizmoParams, isSetViewModeParams, isSettingsSet, isTransformDraggedParams, isTransformDraggingParams, listenForEditorPlayControls, protocolVersionIsCompatible, startEditorHost, startEditorPlayControls };
|
|
6579
7848
|
|
|
6580
7849
|
//# sourceMappingURL=index.js.map
|