@ignifx/editor-host 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as isEditorOrigin, t as EditorHostErrorCode } from "./error-codes.js";
2
- import { Camera, Component, 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";
2
+ import { Camera, Component, CoreErrorCode, IgnifxError, Light, 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
  /**
@@ -186,9 +186,9 @@ const HostKind = {
186
186
  * @remarks
187
187
  * The play controls send `"heartbeat"`, `"playControls"`, `"logRelay"` and `"queryRuntime"`, plus
188
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.
189
+ * host sends `"heartbeat"` and whichever of `"gizmos"`, `"screenshot"`, `"viewMode2d"`,
190
+ * `"pick2d"`, `"gameView"`, `"thumbnails"` and `"grid"` it supports; every `SceneMethod` not tied
191
+ * to one of them is required of a 0.3 scene host.
192
192
  *
193
193
  * @public
194
194
  */
@@ -242,7 +242,26 @@ const HostCapability = {
242
242
  * when the game has `app.input`. From engine ask E49 (additive in 0.3); without it, the play view
243
243
  * answers `sendInput` with `RpcErrorCode.methodNotFound`.
244
244
  */
245
- sendInput: "sendInput"
245
+ sendInput: "sendInput",
246
+ /**
247
+ * The scene host answers `setGameView` and `gameViewFrame`: the open scene through its own main
248
+ * camera, rendered beside the editor camera (`RenderViewMethod`). From engine ask E8 (additive in
249
+ * 0.3); without it, the host answers both with `RpcErrorCode.methodNotFound`.
250
+ */
251
+ gameView: "gameView",
252
+ /**
253
+ * The scene host answers `renderThumbnail`: a model or prefab asset rendered on its own
254
+ * (`RenderViewMethod`). From engine ask E8 (additive in 0.3); without it, the host answers it with
255
+ * `RpcErrorCode.methodNotFound`.
256
+ */
257
+ thumbnails: "thumbnails",
258
+ /**
259
+ * The scene host draws a grid in the view and answers `setGrid`: a ground grid at `y = 0` in 3D
260
+ * view mode and a unit grid (a pixel grid when zoomed in) over the 2D view. From engine ask E31
261
+ * (additive in 0.3); without it, the scene host answers `setGrid` with
262
+ * `RpcErrorCode.methodNotFound`.
263
+ */
264
+ grid: "grid"
246
265
  };
247
266
  /**
248
267
  * The longest string, in UTF-16 code units, the editor accepts from a host in `ready` (the engine
@@ -1086,7 +1105,12 @@ const SceneMethod = {
1086
1105
  * amendment 2026-10-20). Answers {@link SampleAnimationResult}. A host from before it answers
1087
1106
  * `RpcErrorCode.methodNotFound`. Additive in 0.3.
1088
1107
  */
1089
- sampleAnimation: "sampleAnimation"
1108
+ sampleAnimation: "sampleAnimation",
1109
+ /**
1110
+ * Shows or hides the view's grid and sets its spacing (engine ask E31). Needs
1111
+ * `HostCapability.grid`. Answers `null`. Additive in 0.3.
1112
+ */
1113
+ setGrid: "setGrid"
1090
1114
  };
1091
1115
  /**
1092
1116
  * Scene host → editor: the notifications of protocol 0.3. None has an answer.
@@ -1263,6 +1287,18 @@ const ViewMode = {
1263
1287
  twoD: "2d"
1264
1288
  };
1265
1289
  /**
1290
+ * The smallest grid spacing `setGrid` accepts, in metres.
1291
+ *
1292
+ * @public
1293
+ */
1294
+ const GRID_MIN_SIZE = .001;
1295
+ /**
1296
+ * The largest grid spacing `setGrid` accepts, in metres.
1297
+ *
1298
+ * @public
1299
+ */
1300
+ const GRID_MAX_SIZE = 1e3;
1301
+ /**
1266
1302
  * Tells whether a value is one of an `as const` object's values.
1267
1303
  *
1268
1304
  * @param names - The object.
@@ -1578,6 +1614,20 @@ function isSetAnimateMaterialsParams(value) {
1578
1614
  return isRecord(value) && isBoolean(value["enabled"]);
1579
1615
  }
1580
1616
  /**
1617
+ * Checks the parameters of `setGrid`.
1618
+ *
1619
+ * @param value - The received `params`.
1620
+ * @returns True for an object whose `visible`, if present, is a boolean and whose `size`, if
1621
+ * present, is a number from {@link GRID_MIN_SIZE} to {@link GRID_MAX_SIZE}.
1622
+ *
1623
+ * @public
1624
+ */
1625
+ function isSetGridParams(value) {
1626
+ if (!isRecord(value)) return false;
1627
+ const size = value["size"];
1628
+ return optionalField(value, "visible", isBoolean) && (size === void 0 || isFiniteNumber(size) && size >= .001 && size <= 1e3);
1629
+ }
1630
+ /**
1581
1631
  * Checks one record of `getColliderOutlines`.
1582
1632
  *
1583
1633
  * @param value - The value to test.
@@ -1768,6 +1818,163 @@ function isLogParams(value) {
1768
1818
  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"]));
1769
1819
  }
1770
1820
  //#endregion
1821
+ //#region src/protocol/render-views.ts
1822
+ /**
1823
+ * Protocol 0.3, additive (engine ask E8): the scene host's second views, rendered through the
1824
+ * engine's render textures. The Game panel's view is the document's own camera rendered beside the
1825
+ * editor camera (`setGameView`, `gameViewFrame`); a thumbnail is an asset rendered on its own
1826
+ * (`renderThumbnail`). Both answer images in the shape of `screenshot`'s.
1827
+ */
1828
+ /**
1829
+ * Editor → scene host: the render-view methods, answered after `ready` like every `SceneMethod`.
1830
+ *
1831
+ * @remarks
1832
+ * A host lists `HostCapability.gameView` when it answers the first two and
1833
+ * `HostCapability.thumbnails` when it answers the third; one that does not answers
1834
+ * `RpcErrorCode.methodNotFound`. Additive in 0.3.
1835
+ *
1836
+ * @public
1837
+ */
1838
+ const RenderViewMethod = {
1839
+ /** Turns the Game panel's view on, off, or to a new size. Answers {@link GameViewState}. */
1840
+ setGameView: "setGameView",
1841
+ /**
1842
+ * Renders the open scene through its own main camera, the one the game would use, and answers
1843
+ * the image: {@link GameViewFrameResult}. Fails with `RpcErrorCode.noScene` while no scene is
1844
+ * open and `RpcErrorCode.invalidRequest` while the game view is off.
1845
+ */
1846
+ gameViewFrame: "gameViewFrame",
1847
+ /** Renders one model or prefab asset on its own and answers the image: {@link ThumbnailResult}. */
1848
+ renderThumbnail: "renderThumbnail"
1849
+ };
1850
+ /**
1851
+ * The largest width and height, in pixels, of the game view.
1852
+ *
1853
+ * @public
1854
+ */
1855
+ const GAME_VIEW_MAX_SIZE = 2048;
1856
+ /**
1857
+ * The game view's size until `setGameView` gives one: 640 by 360.
1858
+ *
1859
+ * @public
1860
+ */
1861
+ const GAME_VIEW_DEFAULT_SIZE = {
1862
+ width: 640,
1863
+ height: 360
1864
+ };
1865
+ /**
1866
+ * The largest side, in pixels, of a thumbnail.
1867
+ *
1868
+ * @public
1869
+ */
1870
+ const THUMBNAIL_MAX_SIZE = 1024;
1871
+ /**
1872
+ * A thumbnail's side when the request gives none.
1873
+ *
1874
+ * @public
1875
+ */
1876
+ const THUMBNAIL_DEFAULT_SIZE = 128;
1877
+ /**
1878
+ * Tells whether a value is a whole number from 1 to a maximum.
1879
+ *
1880
+ * @param value - The value to test.
1881
+ * @param max - The largest value allowed.
1882
+ * @returns True for an integer in range.
1883
+ */
1884
+ function isSide(value, max) {
1885
+ return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= max;
1886
+ }
1887
+ /**
1888
+ * Tells whether a value is an image format and, when present, a quality from 0 to 1.
1889
+ *
1890
+ * @param value - The record to test.
1891
+ * @returns True for a known format and a quality in range when given.
1892
+ */
1893
+ function hasImageFormat(value) {
1894
+ const format = value["format"];
1895
+ return (format === ScreenshotFormat.png || format === ScreenshotFormat.jpeg) && optionalField(value, "quality", (quality) => isFiniteNumber(quality) && quality >= 0 && quality <= 1);
1896
+ }
1897
+ /**
1898
+ * Tells whether a value is a PNG or JPEG data URL.
1899
+ *
1900
+ * @param value - The value to test.
1901
+ * @returns True for a `data:image/png;base64,…` or `data:image/jpeg;base64,…` string.
1902
+ */
1903
+ function isImageDataUrl(value) {
1904
+ return isString(value) && /^data:image\/(?:png|jpeg);base64,/u.test(value);
1905
+ }
1906
+ /**
1907
+ * Checks the parameters of `setGameView`.
1908
+ *
1909
+ * @param value - The received `params`.
1910
+ * @returns True for a boolean `enabled` and sizes in range when given.
1911
+ *
1912
+ * @public
1913
+ */
1914
+ function isSetGameViewParams(value) {
1915
+ return isRecord(value) && typeof value["enabled"] === "boolean" && optionalField(value, "width", (width) => isSide(width, 2048)) && optionalField(value, "height", (height) => isSide(height, 2048));
1916
+ }
1917
+ /**
1918
+ * Checks the result of `setGameView`.
1919
+ *
1920
+ * @param value - The received `result`.
1921
+ * @returns True for a boolean `enabled` and sizes in range.
1922
+ *
1923
+ * @public
1924
+ */
1925
+ function isGameViewState(value) {
1926
+ return isRecord(value) && typeof value["enabled"] === "boolean" && isSide(value["width"], 2048) && isSide(value["height"], 2048);
1927
+ }
1928
+ /**
1929
+ * Checks the parameters of `gameViewFrame`.
1930
+ *
1931
+ * @param value - The received `params`.
1932
+ * @returns True for a known format and a quality from 0 to 1 when given.
1933
+ *
1934
+ * @public
1935
+ */
1936
+ function isGameViewFrameParams(value) {
1937
+ return isRecord(value) && hasImageFormat(value);
1938
+ }
1939
+ /**
1940
+ * Checks the result of `gameViewFrame`.
1941
+ *
1942
+ * @param value - The received `result`.
1943
+ * @returns True for an image and a camera uid, or `null` for both, and sizes in range.
1944
+ *
1945
+ * @public
1946
+ */
1947
+ function isGameViewFrameResult(value) {
1948
+ if (!isRecord(value) || !isSide(value["width"], 2048) || !isSide(value["height"], 2048)) return false;
1949
+ const dataUrl = value["dataUrl"];
1950
+ const camera = value["camera"];
1951
+ return dataUrl === null ? camera === null : isImageDataUrl(dataUrl) && isUidString(camera);
1952
+ }
1953
+ /**
1954
+ * Checks the parameters of `renderThumbnail`.
1955
+ *
1956
+ * @param value - The received `params`.
1957
+ * @returns True for an address or asset reference, a size in range when given, and a known format.
1958
+ *
1959
+ * @public
1960
+ */
1961
+ function isRenderThumbnailParams(value) {
1962
+ if (!isRecord(value) || !hasImageFormat(value)) return false;
1963
+ const asset = value["asset"];
1964
+ return (isString(asset) && asset.length > 0 || isSceneFileAssetRef(asset)) && optionalField(value, "size", (size) => isSide(size, 1024));
1965
+ }
1966
+ /**
1967
+ * Checks the result of `renderThumbnail`.
1968
+ *
1969
+ * @param value - The received `result`.
1970
+ * @returns True for an image and sizes in range.
1971
+ *
1972
+ * @public
1973
+ */
1974
+ function isThumbnailResult(value) {
1975
+ return isRecord(value) && isImageDataUrl(value["dataUrl"]) && isSide(value["width"], 1024) && isSide(value["height"], 1024);
1976
+ }
1977
+ //#endregion
1771
1978
  //#region src/protocol/version.ts
1772
1979
  /**
1773
1980
  * The protocol version this package describes. The editor sends it in `hello` and the host in
@@ -2550,6 +2757,16 @@ function createEditorView(handles, overlay, canvas) {
2550
2757
  };
2551
2758
  }
2552
2759
  /**
2760
+ * The world bounds of every visible mesh an entity draws, without a view: for a thumbnail stage.
2761
+ *
2762
+ * @param handles - The app's Lite engine and render scene (`app.lite`).
2763
+ * @param entity - The entity.
2764
+ * @returns The box, or `null` when nothing under the entity is drawn yet.
2765
+ */
2766
+ function entityWorldBounds(handles, entity) {
2767
+ return computeWorldBounds(entity.transform.lite, handles.scene);
2768
+ }
2769
+ /**
2553
2770
  * A node's parent. Lite types it as a bare world-matrix provider, so it is followed by identity only.
2554
2771
  *
2555
2772
  * @param node - The node.
@@ -4521,6 +4738,37 @@ var EditorCamera2D = class extends Script {
4521
4738
  }
4522
4739
  };
4523
4740
  //#endregion
4741
+ //#region src/scene/editor-grid.ts
4742
+ /**
4743
+ * The scene view's grid (engine ask E31): a script on the `Scene Grid` entity of the host's
4744
+ * persistent `editor` scene, which moves the grid with the editor camera every frame.
4745
+ */
4746
+ /**
4747
+ * Places the view's grid every frame, where {@link EditorGrid.placement} says.
4748
+ *
4749
+ * @remarks
4750
+ * The host sets both fields: `view` once a canvas has the grid's meshes (never headless), and
4751
+ * `placement` to read the editor cameras and the `setGrid` settings.
4752
+ */
4753
+ var EditorGrid = class extends Script {
4754
+ /** The type id; the host leaves it out of the schemas it reports. */
4755
+ static typeId = "ignifx-editor/EditorGrid";
4756
+ /** The scene view runs in edit mode, where only these scripts get callbacks. */
4757
+ static runInEditMode = true;
4758
+ /** The grid's meshes, or `null` while there is nothing to draw on. */
4759
+ view = null;
4760
+ /**
4761
+ * Reads this frame's grid.
4762
+ *
4763
+ * @returns The placement, or `null` to hide the grid.
4764
+ */
4765
+ placement = () => null;
4766
+ /** Moves the grid after the cameras have moved. */
4767
+ lateUpdate() {
4768
+ this.view?.place(this.placement());
4769
+ }
4770
+ };
4771
+ //#endregion
4524
4772
  //#region src/scene/view-math.ts
4525
4773
  /**
4526
4774
  * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and
@@ -4794,6 +5042,181 @@ function conjugate(q) {
4794
5042
  ];
4795
5043
  }
4796
5044
  //#endregion
5045
+ //#region src/scene/screenshot.ts
5046
+ /**
5047
+ * `screenshot`, shared by the scene view and the play view: the parameter check, and a captured
5048
+ * frame scaled to the requested size and written as a PNG or JPEG data URL. Encoding needs a
5049
+ * browser's `OffscreenCanvas`, as the capture needs a GPU.
5050
+ */
5051
+ /** The JPEG quality when the request gives none. */
5052
+ const DEFAULT_JPEG_QUALITY$2 = .9;
5053
+ /** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */
5054
+ const BASE64_CHUNK = 32768;
5055
+ /**
5056
+ * Encodes bytes as base64.
5057
+ *
5058
+ * @param bytes - The bytes.
5059
+ * @returns The base64 text.
5060
+ */
5061
+ function toBase64(bytes) {
5062
+ let binary = "";
5063
+ for (let start = 0; start < bytes.length; start += BASE64_CHUNK) binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));
5064
+ return btoa(binary);
5065
+ }
5066
+ /**
5067
+ * Scales a captured frame to a size and encodes it as a data URL.
5068
+ *
5069
+ * @param capture - The frame, RGBA8 with the top row first.
5070
+ * @param size - The image size.
5071
+ * @param format - `"png"` or `"jpeg"`.
5072
+ * @param quality - The JPEG quality, from 0 to 1; ignored for PNG.
5073
+ * @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.
5074
+ * @throws Error when the browser has no 2D canvas context.
5075
+ */
5076
+ async function encodeCapture(capture, size, format, quality) {
5077
+ const source = new OffscreenCanvas(capture.width, capture.height);
5078
+ const sourceContext = source.getContext("2d");
5079
+ const target = new OffscreenCanvas(size.width, size.height);
5080
+ const targetContext = target.getContext("2d");
5081
+ if (sourceContext === null || targetContext === null) throw new Error("This browser has no 2D canvas to encode the screenshot with.");
5082
+ sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);
5083
+ targetContext.imageSmoothingQuality = "high";
5084
+ targetContext.drawImage(source, 0, 0, size.width, size.height);
5085
+ const type = format === "png" ? "image/png" : "image/jpeg";
5086
+ const blob = await target.convertToBlob(format === "png" ? { type } : {
5087
+ type,
5088
+ quality
5089
+ });
5090
+ return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;
5091
+ }
5092
+ /**
5093
+ * Checks `screenshot`'s parameters.
5094
+ *
5095
+ * @param params - The received `params`.
5096
+ * @returns The parameters.
5097
+ * @throws InvalidParamsError for a side outside 1 to {@link SCREENSHOT_MAX_SIZE}, an unknown format, or
5098
+ * a quality outside 0 to 1.
5099
+ */
5100
+ function checkScreenshotParams(params) {
5101
+ if (typeof params === "object" && params !== null) for (const side of ["width", "height"]) {
5102
+ const value = Reflect.get(params, side);
5103
+ 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.`);
5104
+ }
5105
+ if (!isScreenshotParams(params)) throw new InvalidParamsError("screenshot takes { width?, height?, format: \"png\" | \"jpeg\", quality? }.");
5106
+ return params;
5107
+ }
5108
+ /**
5109
+ * Captures the app's next presented frame and encodes it as `screenshot` answers.
5110
+ *
5111
+ * @param app - The app whose canvas is captured.
5112
+ * @param params - Checked parameters.
5113
+ * @returns The data URL and its size.
5114
+ * @throws IgnifxError `IGX-0707` when the app's render loop does not run.
5115
+ */
5116
+ async function takeScreenshot(app, params) {
5117
+ const capture = await app.renderer.captureScreenshot();
5118
+ const size = screenshotSize(params, capture);
5119
+ return {
5120
+ dataUrl: await encodeCapture(capture, size, params.format, params.quality ?? DEFAULT_JPEG_QUALITY$2),
5121
+ width: size.width,
5122
+ height: size.height
5123
+ };
5124
+ }
5125
+ //#endregion
5126
+ //#region src/scene/game-view.ts
5127
+ /**
5128
+ * The Game panel's view (engine ask E8): the open scene through its own main camera, rendered into
5129
+ * a render texture beside the editor camera's frame (`setGameView`, `gameViewFrame`).
5130
+ */
5131
+ /** The JPEG quality when the request gives none, as for `screenshot`. */
5132
+ const DEFAULT_JPEG_QUALITY$1 = .9;
5133
+ /**
5134
+ * The camera the game would render the open scene through: the enabled document camera with the
5135
+ * highest priority, the first one on a tie, as the engine picks its main camera.
5136
+ *
5137
+ * @param app - The scene view's app.
5138
+ * @param mirror - The open document.
5139
+ * @returns The camera, or `null` when the document has no enabled one.
5140
+ */
5141
+ function documentCamera(app, mirror) {
5142
+ const scene = mirror.scene;
5143
+ let best = null;
5144
+ for (const camera of app.world.components(Camera)) {
5145
+ if (camera.entity.scene !== scene || !camera.isEnabledInHierarchy) continue;
5146
+ if (best === null || camera.priority > best.priority) best = camera;
5147
+ }
5148
+ return best;
5149
+ }
5150
+ /** The game view's state and texture. */
5151
+ var GameView = class {
5152
+ #enabled = false;
5153
+ #width = GAME_VIEW_DEFAULT_SIZE.width;
5154
+ #height = GAME_VIEW_DEFAULT_SIZE.height;
5155
+ #texture = null;
5156
+ /**
5157
+ * `setGameView`: turns the view on or off, or resizes it. Off frees the texture.
5158
+ *
5159
+ * @param app - The scene view's app.
5160
+ * @param params - `{ enabled, width?, height? }`.
5161
+ * @returns The view as it now is.
5162
+ */
5163
+ set(app, params) {
5164
+ if (!isSetGameViewParams(params)) throw new InvalidParamsError("setGameView takes { enabled: boolean, width?, height? } with sides from 1 to 2048.");
5165
+ const width = params.width ?? this.#width;
5166
+ const height = params.height ?? this.#height;
5167
+ if (!params.enabled || width !== this.#width || height !== this.#height) {
5168
+ this.#texture?.dispose();
5169
+ this.#texture = null;
5170
+ }
5171
+ this.#enabled = params.enabled;
5172
+ this.#width = width;
5173
+ this.#height = height;
5174
+ if (this.#enabled) this.#texture ??= app.renderer.createRenderTexture(width, height);
5175
+ return {
5176
+ enabled: this.#enabled,
5177
+ width,
5178
+ height
5179
+ };
5180
+ }
5181
+ /**
5182
+ * `gameViewFrame`: renders the document camera into the texture on the next frame and answers it
5183
+ * as an image.
5184
+ *
5185
+ * @param app - The scene view's app.
5186
+ * @param mirror - The open document.
5187
+ * @param params - `{ format, quality? }`.
5188
+ * @returns The image and the camera's document uid, or no image when the document has no camera.
5189
+ */
5190
+ async frame(app, mirror, params) {
5191
+ if (!isGameViewFrameParams(params)) throw new InvalidParamsError("gameViewFrame takes { format: \"png\" | \"jpeg\", quality? }.");
5192
+ const texture = this.#texture;
5193
+ if (!this.#enabled || texture === null) throw new RpcFailure(RpcErrorCode.invalidRequest, "The game view is off; send \"setGameView\" with enabled: true first.");
5194
+ const size = {
5195
+ width: this.#width,
5196
+ height: this.#height
5197
+ };
5198
+ const camera = documentCamera(app, mirror);
5199
+ if (camera === null) return {
5200
+ dataUrl: null,
5201
+ ...size,
5202
+ camera: null
5203
+ };
5204
+ const uid = (mirror.documentEntityOf(camera.entity) ?? camera.entity).uid;
5205
+ await app.renderer.renderToTexture(camera, texture);
5206
+ return {
5207
+ dataUrl: await encodeCapture(await texture.readPixels(), size, params.format, params.quality ?? DEFAULT_JPEG_QUALITY$1),
5208
+ ...size,
5209
+ camera: uid
5210
+ };
5211
+ }
5212
+ /** Frees the texture. */
5213
+ dispose() {
5214
+ this.#texture?.dispose();
5215
+ this.#texture = null;
5216
+ this.#enabled = false;
5217
+ }
5218
+ };
5219
+ //#endregion
4797
5220
  //#region src/scene/gizmo-drag.ts
4798
5221
  /**
4799
5222
  * Turns one gizmo drag into the scene view's drag notifications. It needs no GPU: the view calls
@@ -4876,6 +5299,74 @@ var GizmoDragRelay = class {
4876
5299
  }
4877
5300
  };
4878
5301
  //#endregion
5302
+ //#region src/scene/grid.ts
5303
+ /** Every how many minor lines a major line falls. */
5304
+ const MAJOR_EVERY = 10;
5305
+ /** The 3D grid's spacing grows tenfold for each tenfold of eye height above this many minor lines. */
5306
+ const GROUND_LINES_PER_HEIGHT = 25;
5307
+ /** The 3D grid reaches this many eye heights from the eye before it has faded out. */
5308
+ const GROUND_REACH_PER_HEIGHT = 40;
5309
+ /** The 3D grid reaches at least this many lines from the eye. */
5310
+ const GROUND_MIN_REACH_LINES = 100;
5311
+ /** The 2D grid's lines are never closer than this, in screen pixels; denser ones step up tenfold. */
5312
+ const MIN_LINE_GAP_PX = 8;
5313
+ /**
5314
+ * The 3D view's ground grid: centred under the eye, coarser the higher the eye is, and large enough
5315
+ * that it fades out before its edge is in view.
5316
+ *
5317
+ * @param eye - The editor camera's position, in metres.
5318
+ * @param size - The spacing `setGrid` asked for, in metres.
5319
+ * @param far - The camera's far plane, in metres; the grid stays inside it.
5320
+ * @returns The placement.
5321
+ */
5322
+ function groundGridPlacement(eye, size, far) {
5323
+ const height = Math.max(Math.abs(eye.y), size);
5324
+ const step = size * 10 ** Math.max(0, Math.floor(Math.log10(height / (size * GROUND_LINES_PER_HEIGHT))));
5325
+ const reach = Math.min(Math.max(height * GROUND_REACH_PER_HEIGHT, step * GROUND_MIN_REACH_LINES), far * .9);
5326
+ return {
5327
+ plane: "ground",
5328
+ centerX: eye.x,
5329
+ centerY: eye.z,
5330
+ extent: reach * 2,
5331
+ step,
5332
+ majorEvery: MAJOR_EVERY
5333
+ };
5334
+ }
5335
+ /**
5336
+ * The 2D view's grid: lines `size` apart (tenfold coarser while they would be closer than a few
5337
+ * screen pixels), or one line per layer pixel from {@link PIXEL_GRID_ZOOM} on, with a major line
5338
+ * every `size`. It covers the whole view.
5339
+ *
5340
+ * @param view - What the 2D editor camera shows.
5341
+ * @param size - The spacing `setGrid` asked for, in metres.
5342
+ * @returns The placement.
5343
+ */
5344
+ function screenGridPlacement(view, size) {
5345
+ const pixelsPerMetre = Math.max(view.zoom * view.pixelsPerUnit, Number.MIN_VALUE);
5346
+ const extent = 2 * Math.max(view.widthPx, view.heightPx) / pixelsPerMetre;
5347
+ const base = {
5348
+ plane: "screen",
5349
+ centerX: view.centerX,
5350
+ centerY: view.centerY,
5351
+ extent
5352
+ };
5353
+ if (view.zoom >= 8 && view.pixelsPerUnit > 0) {
5354
+ const step = 1 / view.pixelsPerUnit;
5355
+ return {
5356
+ ...base,
5357
+ step,
5358
+ majorEvery: Math.max(1, Math.round(size / step))
5359
+ };
5360
+ }
5361
+ let step = size;
5362
+ while (step * pixelsPerMetre < MIN_LINE_GAP_PX) step *= MAJOR_EVERY;
5363
+ return {
5364
+ ...base,
5365
+ step,
5366
+ majorEvery: MAJOR_EVERY
5367
+ };
5368
+ }
5369
+ //#endregion
4879
5370
  //#region src/scene/json.ts
4880
5371
  /**
4881
5372
  * The uid of a referenced entity or component.
@@ -5953,87 +6444,6 @@ function registeredAncestors(registry, type) {
5953
6444
  return ids;
5954
6445
  }
5955
6446
  //#endregion
5956
- //#region src/scene/screenshot.ts
5957
- /**
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.
5968
- *
5969
- * @param bytes - The bytes.
5970
- * @returns The base64 text.
5971
- */
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);
5976
- }
5977
- /**
5978
- * Scales a captured frame to a size and encodes it as a data URL.
5979
- *
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.
5986
- */
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()))}`;
6002
- }
6003
- /**
6004
- * Checks `screenshot`'s parameters.
6005
- *
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.
6010
- */
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;
6018
- }
6019
- /**
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.
6026
- */
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
6447
  //#region src/scene/settings.ts
6038
6448
  /**
6039
6449
  * `describeSettings`: the project's settings sections, as the editor's settings panel reads them,
@@ -6108,6 +6518,311 @@ function settingsSet(app) {
6108
6518
  };
6109
6519
  }
6110
6520
  //#endregion
6521
+ //#region src/scene/thumbnails.ts
6522
+ /**
6523
+ * `renderThumbnail` (engine ask E8): a model or prefab rendered on its own, in a second app the
6524
+ * host keeps for the purpose, through `app.renderer.renderToTexture`.
6525
+ *
6526
+ * The stage is a separate app on a 1x1 `OffscreenCanvas`, built from the project's own options, so
6527
+ * a thumbnail never shows the open document, never lights it, and is never lit by it. It is
6528
+ * created on the first request and lives until the host is disposed.
6529
+ */
6530
+ /** The JPEG quality when the request gives none, as for `screenshot`. */
6531
+ const DEFAULT_JPEG_QUALITY = .9;
6532
+ /** The stage camera's vertical field of view, in degrees. */
6533
+ const STAGE_FOV = 35;
6534
+ /** The texture is this many times the image's side, and scaled down when encoded. */
6535
+ const SUPERSAMPLE = 2;
6536
+ /** How many frames a load is given to build its meshes before the thumbnail is taken anyway. */
6537
+ const MAX_SETTLE_FRAMES = 120;
6538
+ /** How many frames in a row the bounds must hold still before the thumbnail is taken. */
6539
+ const STILL_FRAMES = 2;
6540
+ /** The direction from the subject to the camera: in front, above and to the right. */
6541
+ const VIEW_DIRECTION = {
6542
+ x: .55,
6543
+ y: .45,
6544
+ z: -.7
6545
+ };
6546
+ /**
6547
+ * Types the requested asset.
6548
+ *
6549
+ * @param params - Checked parameters.
6550
+ * @returns The address and what it is.
6551
+ * @throws InvalidParamsError for an asset that is neither a model nor a prefab.
6552
+ */
6553
+ function thumbnailSubject(params) {
6554
+ const asset = params.asset;
6555
+ const address = typeof asset === "string" ? asset : asset.$asset;
6556
+ const type = typeof asset === "string" ? void 0 : asset.type;
6557
+ const lower = address.toLowerCase();
6558
+ if (type === "model" || type === void 0 && (lower.endsWith(".glb") || lower.endsWith(".gltf"))) return {
6559
+ address,
6560
+ kind: "model"
6561
+ };
6562
+ if (type === "scene" || type === "prefab" || type === void 0 && (lower.endsWith(".prefab.json") || lower.endsWith(".scene.json"))) return {
6563
+ address,
6564
+ kind: "prefab"
6565
+ };
6566
+ throw new InvalidParamsError(`renderThumbnail renders models (.glb, .gltf) and prefabs (.prefab.json); ${address} is neither.`);
6567
+ }
6568
+ /**
6569
+ * The one-entity scene file that shows a subject.
6570
+ *
6571
+ * @param address - The asset address.
6572
+ * @param kind - What it is.
6573
+ * @returns The file.
6574
+ */
6575
+ function thumbnailScene(address, kind) {
6576
+ const transform = {
6577
+ position: [
6578
+ 0,
6579
+ 0,
6580
+ 0
6581
+ ],
6582
+ rotation: [
6583
+ 0,
6584
+ 0,
6585
+ 0,
6586
+ 1
6587
+ ],
6588
+ scale: [
6589
+ 1,
6590
+ 1,
6591
+ 1
6592
+ ]
6593
+ };
6594
+ return {
6595
+ format: "ignifx.scene",
6596
+ formatVersion: 1,
6597
+ name: "thumbnail",
6598
+ entities: [kind === "model" ? {
6599
+ uid: "thumbnail-subject",
6600
+ name: "Thumbnail",
6601
+ parent: null,
6602
+ transform,
6603
+ components: [{
6604
+ uid: "thumbnail-model",
6605
+ type: "ignifx/Model",
6606
+ props: { model: {
6607
+ $asset: address,
6608
+ type: "model"
6609
+ } }
6610
+ }]
6611
+ } : {
6612
+ uid: "thumbnail-subject",
6613
+ name: "Thumbnail",
6614
+ parent: null,
6615
+ transform,
6616
+ instance: { scene: { $asset: address } }
6617
+ }]
6618
+ };
6619
+ }
6620
+ /** Renders thumbnails on a stage app of their own. */
6621
+ var ThumbnailRenderer = class {
6622
+ #createApp;
6623
+ #stage = null;
6624
+ #texture = null;
6625
+ #loads = 0;
6626
+ #isDisposed = false;
6627
+ /**
6628
+ * Keeps the factory; nothing is created until the first thumbnail.
6629
+ *
6630
+ * @param createApp - Creates the stage app from the project's options, unstarted.
6631
+ */
6632
+ constructor(createApp) {
6633
+ this.#createApp = createApp;
6634
+ }
6635
+ /**
6636
+ * `renderThumbnail`: loads the asset alone on the stage, frames it, renders it and encodes it.
6637
+ *
6638
+ * @param params - `{ asset, size?, format, quality? }`.
6639
+ * @returns The image.
6640
+ */
6641
+ async render(params) {
6642
+ if (!isRenderThumbnailParams(params)) throw new InvalidParamsError("renderThumbnail takes { asset: address | { $asset, type? }, size?: 1 to 1024, format: \"png\" | \"jpeg\", quality? }.");
6643
+ const { address, kind } = thumbnailSubject(params);
6644
+ const { app, camera } = await (this.#stage ??= this.#open());
6645
+ this.#loads += 1;
6646
+ const instance = await app.world.loadSceneFile(thumbnailScene(address, kind), {
6647
+ address: `__ignifx_thumbnail__/${String(this.#loads)}.scene.json`,
6648
+ mode: "single"
6649
+ });
6650
+ try {
6651
+ frameCamera(camera, await settledBounds(app, instance));
6652
+ await nextFrame();
6653
+ const size = params.size ?? 128;
6654
+ const texture = this.#textureOf(app, size * SUPERSAMPLE);
6655
+ await app.renderer.renderToTexture(camera, texture);
6656
+ return {
6657
+ dataUrl: await encodeCapture(await texture.readPixels(), {
6658
+ width: size,
6659
+ height: size
6660
+ }, params.format, params.quality ?? DEFAULT_JPEG_QUALITY),
6661
+ width: size,
6662
+ height: size
6663
+ };
6664
+ } finally {
6665
+ await app.world.unloadScene(instance);
6666
+ }
6667
+ }
6668
+ /** Disposes the stage app, now or once it has been created. */
6669
+ dispose() {
6670
+ this.#isDisposed = true;
6671
+ this.#texture = null;
6672
+ this.#stage?.then((stage) => {
6673
+ stage.app.dispose();
6674
+ }, () => null);
6675
+ }
6676
+ /**
6677
+ * Creates and starts the stage: a persistent scene with the camera and two lights.
6678
+ *
6679
+ * @returns The stage.
6680
+ */
6681
+ async #open() {
6682
+ const app = await this.#createApp();
6683
+ const scene = app.world.createScene("thumbnail-stage", { persistent: true });
6684
+ const camera = app.world.createEntity("Thumbnail Camera", { scene }).addComponent(Camera, {
6685
+ fov: STAGE_FOV,
6686
+ near: .01,
6687
+ far: 1e3
6688
+ });
6689
+ app.world.createEntity("Thumbnail Sky", { scene }).addComponent(Light, {
6690
+ type: "hemispheric",
6691
+ intensity: .8
6692
+ });
6693
+ const sun = app.world.createEntity("Thumbnail Sun", { scene });
6694
+ sun.transform.localPosition.set(4, 6, -5);
6695
+ sun.transform.lookAt({
6696
+ x: 0,
6697
+ y: 0,
6698
+ z: 0
6699
+ });
6700
+ sun.addComponent(Light, {
6701
+ type: "directional",
6702
+ intensity: 2
6703
+ });
6704
+ await app.start();
6705
+ if (this.#isDisposed) app.dispose();
6706
+ return {
6707
+ app,
6708
+ camera
6709
+ };
6710
+ }
6711
+ /**
6712
+ * The stage's texture at a side, created again when the side changes.
6713
+ *
6714
+ * @param app - The stage app.
6715
+ * @param side - The side in pixels.
6716
+ * @returns The texture.
6717
+ */
6718
+ #textureOf(app, side) {
6719
+ const current = this.#texture;
6720
+ if (current !== null && current.width === side && !current.isDisposed) return current;
6721
+ current?.dispose();
6722
+ const texture = app.renderer.createRenderTexture(side, side);
6723
+ this.#texture = texture;
6724
+ return texture;
6725
+ }
6726
+ };
6727
+ /**
6728
+ * Waits one animation frame.
6729
+ *
6730
+ * @returns A promise that settles in the next frame callback.
6731
+ */
6732
+ function nextFrame() {
6733
+ return new Promise((resolve) => {
6734
+ requestAnimationFrame(() => {
6735
+ resolve();
6736
+ });
6737
+ });
6738
+ }
6739
+ /**
6740
+ * Waits until a loaded subject's meshes exist and hold still, then measures them.
6741
+ *
6742
+ * @param app - The stage app.
6743
+ * @param instance - The loaded subject.
6744
+ * @returns Its world bounds; a unit box at the origin when nothing draws.
6745
+ */
6746
+ async function settledBounds(app, instance) {
6747
+ let last = null;
6748
+ let still = 0;
6749
+ for (let frame = 0; frame < MAX_SETTLE_FRAMES && still < STILL_FRAMES; frame += 1) {
6750
+ await nextFrame();
6751
+ const bounds = unionBounds(app, instance.roots);
6752
+ still = bounds !== null && last !== null && sameBounds(bounds, last) ? still + 1 : 0;
6753
+ last = bounds;
6754
+ }
6755
+ return last ?? {
6756
+ min: {
6757
+ x: -.5,
6758
+ y: -.5,
6759
+ z: -.5
6760
+ },
6761
+ max: {
6762
+ x: .5,
6763
+ y: .5,
6764
+ z: .5
6765
+ }
6766
+ };
6767
+ }
6768
+ /**
6769
+ * The union of entities' world bounds.
6770
+ *
6771
+ * @param app - The stage app.
6772
+ * @param entities - The entities.
6773
+ * @returns The box, or `null` when none draws.
6774
+ */
6775
+ function unionBounds(app, entities) {
6776
+ let result = null;
6777
+ for (const entity of entities) {
6778
+ const box = entityWorldBounds(app.lite, entity);
6779
+ if (box === null) continue;
6780
+ result = result === null ? box : {
6781
+ min: {
6782
+ x: Math.min(result.min.x, box.min.x),
6783
+ y: Math.min(result.min.y, box.min.y),
6784
+ z: Math.min(result.min.z, box.min.z)
6785
+ },
6786
+ max: {
6787
+ x: Math.max(result.max.x, box.max.x),
6788
+ y: Math.max(result.max.y, box.max.y),
6789
+ z: Math.max(result.max.z, box.max.z)
6790
+ }
6791
+ };
6792
+ }
6793
+ return result;
6794
+ }
6795
+ /**
6796
+ * Tells whether two boxes are equal.
6797
+ *
6798
+ * @param a - One box.
6799
+ * @param b - The other.
6800
+ * @returns True for the same corners.
6801
+ */
6802
+ function sameBounds(a, b) {
6803
+ return a.min.x === b.min.x && a.min.y === b.min.y && a.min.z === b.min.z && a.max.x === b.max.x && a.max.y === b.max.y && a.max.z === b.max.z;
6804
+ }
6805
+ /**
6806
+ * Places the stage camera so a box fills the view, with its clip planes around it.
6807
+ *
6808
+ * @param camera - The stage camera.
6809
+ * @param bounds - The subject's bounds.
6810
+ */
6811
+ function frameCamera(camera, bounds) {
6812
+ const center = {
6813
+ x: (bounds.min.x + bounds.max.x) / 2,
6814
+ y: (bounds.min.y + bounds.max.y) / 2,
6815
+ z: (bounds.min.z + bounds.max.z) / 2
6816
+ };
6817
+ const radius = Math.max(Math.hypot(bounds.max.x - center.x, bounds.max.y - center.y, bounds.max.z - center.z), .01);
6818
+ const distance = radius / Math.sin(STAGE_FOV / 2 * Math.PI / 180) * 1.05;
6819
+ const length = Math.hypot(VIEW_DIRECTION.x, VIEW_DIRECTION.y, VIEW_DIRECTION.z);
6820
+ camera.transform.localPosition.set(center.x + VIEW_DIRECTION.x / length * distance, center.y + VIEW_DIRECTION.y / length * distance, center.z + VIEW_DIRECTION.z / length * distance);
6821
+ camera.transform.lookAt(center);
6822
+ camera.near = Math.max(distance - radius * 1.5, distance / 1e3);
6823
+ camera.far = distance + radius * 1.5;
6824
+ }
6825
+ //#endregion
6111
6826
  //#region src/scene/scene-host.ts
6112
6827
  /**
6113
6828
  * The scene methods and notifications of protocol 0.3: what the scene view's host does with the
@@ -6149,7 +6864,15 @@ var SceneHost = class {
6149
6864
  space: GizmoSpace.world,
6150
6865
  snap: null
6151
6866
  };
6867
+ /** The script that moves the grid, on the `editor` scene's `Scene Grid` entity. */
6868
+ #grid = null;
6869
+ #gridSettings = {
6870
+ visible: true,
6871
+ size: 1
6872
+ };
6152
6873
  #drag;
6874
+ #gameView = new GameView();
6875
+ #thumbnails;
6153
6876
  #started = false;
6154
6877
  /** The field defaults seen at start and after each hot reload, from {@link SceneHost.start} on. */
6155
6878
  #defaults = null;
@@ -6185,6 +6908,25 @@ var SceneHost = class {
6185
6908
  ]);
6186
6909
  if (has(HostCapability.gizmos)) methods.set(SceneMethod.setGizmo, (params) => this.#setGizmo(params));
6187
6910
  if (has(HostCapability.screenshot)) methods.set(SceneMethod.screenshot, async (params) => this.#screenshot(params));
6911
+ if (has(HostCapability.gameView)) {
6912
+ methods.set(RenderViewMethod.setGameView, (params) => {
6913
+ this.#requireMirror(RenderViewMethod.setGameView);
6914
+ return this.#gameView.set(this.#requireApp(), params);
6915
+ });
6916
+ methods.set(RenderViewMethod.gameViewFrame, async (params) => {
6917
+ const mirror = this.#requireMirror(RenderViewMethod.gameViewFrame);
6918
+ this.#requireOpen(RenderViewMethod.gameViewFrame);
6919
+ return this.#gameView.frame(this.#requireApp(), mirror, params);
6920
+ });
6921
+ }
6922
+ const createThumbnailApp = options.createThumbnailApp;
6923
+ this.#thumbnails = has(HostCapability.thumbnails) && createThumbnailApp !== void 0 ? new ThumbnailRenderer(createThumbnailApp) : null;
6924
+ const thumbnails = this.#thumbnails;
6925
+ if (thumbnails !== null) methods.set(RenderViewMethod.renderThumbnail, async (params) => {
6926
+ this.#requireMirror(RenderViewMethod.renderThumbnail);
6927
+ return thumbnails.render(params);
6928
+ });
6929
+ if (has(HostCapability.grid)) methods.set(SceneMethod.setGrid, (params) => this.#setGrid(params));
6188
6930
  this.methods = new Map([...methods].map(([name, handler]) => [name, async (params) => this.#serial(() => handler(params))]));
6189
6931
  }
6190
6932
  /**
@@ -6196,7 +6938,7 @@ var SceneHost = class {
6196
6938
  return this.#editorScene;
6197
6939
  }
6198
6940
  /**
6199
- * Prepares the app before it starts: the persistent `editor` scene with the editor camera, and
6941
+ * Prepares the app before it starts: the persistent `editor` scene with the editor camera and grid, and
6200
6942
  * the log, error and hot-reload relays.
6201
6943
  *
6202
6944
  * @param app - The scene view's app, created and not yet started.
@@ -6206,7 +6948,11 @@ var SceneHost = class {
6206
6948
  this.#mirror = new DocumentMirror(app);
6207
6949
  const scene = app.world.createScene(EDITOR_SCENE_NAME, { persistent: true });
6208
6950
  this.#editorScene = scene;
6209
- app.registerComponents([EditorCamera, EditorCamera2D]);
6951
+ app.registerComponents([
6952
+ EditorCamera,
6953
+ EditorCamera2D,
6954
+ EditorGrid
6955
+ ]);
6210
6956
  const eye = app.world.createEntity("Editor Camera", { scene });
6211
6957
  this.#eye = eye.addComponent(Camera, {
6212
6958
  fov: 50,
@@ -6228,6 +6974,11 @@ var SceneHost = class {
6228
6974
  twoD.attach(this.#eye, isCamera2DLike(camera2D) ? camera2D : null);
6229
6975
  twoD.pixelsPerUnit = () => twoDServiceOf(app)?.pixelsPerUnit ?? 100;
6230
6976
  this.#camera2D = twoD;
6977
+ if (this.methods.has(SceneMethod.setGrid)) {
6978
+ const grid = app.world.createEntity("Scene Grid", { scene }).addComponent(EditorGrid);
6979
+ grid.placement = () => this.#gridPlacement();
6980
+ this.#grid = grid;
6981
+ }
6231
6982
  this.#cleanups.push(relayAppReports(app, {
6232
6983
  log: (params) => {
6233
6984
  this.#notify(SceneNotification.log, params);
@@ -6251,12 +7002,17 @@ var SceneHost = class {
6251
7002
  const app = this.#requireApp();
6252
7003
  this.#canvas = canvas;
6253
7004
  if (canvas !== null && !app.isHeadless && this.methods.has(SceneMethod.setGizmo) && isDomCanvas(canvas)) {
6254
- const view = createEditorView(app.lite, await app.renderer.openOverlay(), canvas);
7005
+ const overlay = await app.renderer.openOverlay();
7006
+ const view = createEditorView(app.lite, overlay, canvas);
6255
7007
  view.onDrag((phase, drag) => {
6256
7008
  this.#onDrag(phase, drag);
6257
7009
  });
6258
7010
  this.#view = view;
6259
7011
  this.#applyGizmo();
7012
+ if (this.methods.has(SceneMethod.setGrid) && this.#grid !== null) {
7013
+ const { createEditorGrid } = await import("./grid.js");
7014
+ this.#grid.view = createEditorGrid(app.lite, overlay);
7015
+ }
6260
7016
  const onClick = (click) => {
6261
7017
  this.#onClick(click).catch((error) => {
6262
7018
  const params = {
@@ -6390,8 +7146,14 @@ var SceneHost = class {
6390
7146
  dispose() {
6391
7147
  for (const pending of this.#reloads) pending.cancel();
6392
7148
  for (const cleanup of this.#cleanups.splice(0)) cleanup();
7149
+ if (this.#grid !== null) {
7150
+ this.#grid.view?.dispose();
7151
+ this.#grid.view = null;
7152
+ }
6393
7153
  this.#view?.dispose();
6394
7154
  this.#view = null;
7155
+ this.#gameView.dispose();
7156
+ this.#thumbnails?.dispose();
6395
7157
  }
6396
7158
  /**
6397
7159
  * `openScene`: replaces the open document with the editor's file.
@@ -6591,6 +7353,35 @@ var SceneHost = class {
6591
7353
  return null;
6592
7354
  }
6593
7355
  /**
7356
+ * `setGrid`: shows or hides the view's grid and sets its spacing. A field left out takes its
7357
+ * default.
7358
+ *
7359
+ * @param params - `{ visible?, size? }`.
7360
+ * @returns `null`.
7361
+ */
7362
+ #setGrid(params) {
7363
+ this.#requireMirror(SceneMethod.setGrid);
7364
+ if (!isSetGridParams(params)) throw new InvalidParamsError("setGrid takes { visible?: boolean, size?: number from 0.001 to 1000 }.");
7365
+ this.#gridSettings = {
7366
+ visible: params.visible ?? true,
7367
+ size: params.size ?? 1
7368
+ };
7369
+ return null;
7370
+ }
7371
+ /**
7372
+ * Where the grid draws this frame: on the ground under the 3D editor camera, or over the 2D view.
7373
+ *
7374
+ * @returns The placement, or `null` while the grid is hidden.
7375
+ */
7376
+ #gridPlacement() {
7377
+ const { visible, size } = this.#gridSettings;
7378
+ if (!visible) return null;
7379
+ const camera2D = this.#camera2D;
7380
+ if (this.#viewMode === ViewMode.twoD && camera2D !== null) return screenGridPlacement(camera2D.view(), size);
7381
+ const eye = this.#eye;
7382
+ return eye === null ? null : groundGridPlacement(eye.transform.position, size, eye.far);
7383
+ }
7384
+ /**
6594
7385
  * `getColliderOutlines`: the world-space outlines of the requested entities' colliders, from the
6595
7386
  * project's physics extensions, for the editor's collider gizmos. Changes nothing.
6596
7387
  *
@@ -6936,7 +7727,11 @@ var SceneHost = class {
6936
7727
  * @returns The set.
6937
7728
  */
6938
7729
  #schemas() {
6939
- return schemaSet(this.#requireApp(), /* @__PURE__ */ new Set([EditorCamera.typeId, EditorCamera2D.typeId]));
7730
+ return schemaSet(this.#requireApp(), /* @__PURE__ */ new Set([
7731
+ EditorCamera.typeId,
7732
+ EditorCamera2D.typeId,
7733
+ EditorGrid.typeId
7734
+ ]));
6940
7735
  }
6941
7736
  /**
6942
7737
  * The app, once {@link SceneHost.prepare} has run.
@@ -7039,7 +7834,10 @@ async function startEditorHost(options) {
7039
7834
  HostCapability.viewMode2d,
7040
7835
  HostCapability.pick2d,
7041
7836
  HostCapability.logRelay,
7042
- HostCapability.hotReloadDefaults
7837
+ HostCapability.hotReloadDefaults,
7838
+ HostCapability.gameView,
7839
+ ...canRenderThumbnails(options) ? [HostCapability.thumbnails] : [],
7840
+ HostCapability.grid
7043
7841
  ] : [
7044
7842
  HostCapability.heartbeat,
7045
7843
  HostCapability.logRelay,
@@ -7050,7 +7848,8 @@ async function startEditorHost(options) {
7050
7848
  capabilities,
7051
7849
  notify: (method, params) => {
7052
7850
  channel?.notify(method, params);
7053
- }
7851
+ },
7852
+ createThumbnailApp: async () => createThumbnailApp(options)
7054
7853
  });
7055
7854
  const opened = openChannel({
7056
7855
  target: resolveMessageTarget(options.messageTarget),
@@ -7113,6 +7912,34 @@ function hasGpuView(options) {
7113
7912
  return options.canvas !== void 0 && options.headless !== true;
7114
7913
  }
7115
7914
  /**
7915
+ * Tells whether the host can build the thumbnail stage app: it has `OffscreenCanvas`, and either
7916
+ * a way to build fresh extensions or no extensions to rebuild.
7917
+ *
7918
+ * @param options - The host options.
7919
+ * @returns True when `renderThumbnail` can be answered.
7920
+ */
7921
+ function canRenderThumbnails(options) {
7922
+ return typeof OffscreenCanvas !== "undefined" && (options.createExtensions !== void 0 || (options.extensions ?? []).length === 0);
7923
+ }
7924
+ /**
7925
+ * Creates the app thumbnails are rendered in: fresh instances of the project's extensions, its
7926
+ * settings, assets and scripts, on a 1x1 offscreen canvas of its own (the thumbnails draw into
7927
+ * render textures).
7928
+ *
7929
+ * @param options - The host options.
7930
+ * @returns The app, not started.
7931
+ */
7932
+ async function createThumbnailApp(options) {
7933
+ const app = await createApp({
7934
+ ...appOptions(options),
7935
+ extensions: options.createExtensions?.() ?? [],
7936
+ canvas: new OffscreenCanvas(1, 1),
7937
+ headless: false
7938
+ });
7939
+ app.registerComponents(options.scripts ?? []);
7940
+ return app;
7941
+ }
7942
+ /**
7116
7943
  * Picks the `createApp` options out of the host options, leaving out the ones that were not given.
7117
7944
  *
7118
7945
  * @param options - The host options.
@@ -7844,6 +8671,6 @@ function listenForEditorPlayControls(options) {
7844
8671
  };
7845
8672
  }
7846
8673
  //#endregion
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 };
8674
+ export { ApplyOpFailureCode, COLLIDER_OUTLINES_MAX_ENTITIES, COLLIDER_OUTLINES_MAX_NUMBERS, DEFAULT_HEARTBEAT_INTERVAL_MS, EDITOR_CONNECT_MESSAGE_TYPE, EditorHostErrorCode, GAME_VIEW_DEFAULT_SIZE, GAME_VIEW_MAX_SIZE, GRID_MAX_SIZE, GRID_MIN_SIZE, 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, RenderViewMethod, RpcErrorCode, SAMPLE_ANIMATION_MAX_NAME_LENGTH, SAMPLE_ANIMATION_MAX_PARAMETERS, SCREENSHOT_MAX_SIZE, SEND_INPUT_MAX_EVENTS, SceneMethod, SceneNotification, SceneOpKind, ScreenshotFormat, THUMBNAIL_DEFAULT_SIZE, THUMBNAIL_MAX_SIZE, TRANSFORM_DRAGGING_INTERVAL_MS, ViewMode, isAppErrorData, isApplyOpsParams, isApplyOpsResult, isAssetReloadedParams, isColliderOutlineRecord, isColliderOutlineSet, isEditorConnectMessage, isEditorOrigin, isEntitySelection, isFrameParams, isGameViewFrameParams, isGameViewFrameResult, isGameViewState, isHostErrorParams, isHotReloadedParams, isIncompatibleProtocolData, isInvalidSceneFileData, isJsonObject, isJsonValue, isLogParams, isOpenSceneParams, isOpenSceneResult, isPickParams, isPickResult, isPlayState, isPlayStateReport, isPlayStats, isProtocolVersion, isQueryRuntimeParams, isQueryRuntimeResult, isReadBackParams, isReadBackResult, isReadyResult, isRenderThumbnailParams, isRpcMessage, isSampleAnimationParams, isSampleAnimationResult, isSceneFile, isSceneFileAssetRef, isSceneFileComponent, isSceneFileEntity, isSceneFileInstance, isSceneFileOverride, isSceneFileTransform, isSceneIssue, isSceneOp, isSceneOpenedParams, isSchemaSet, isScreenshotParams, isScreenshotResult, isSendInputEvent, isSendInputParams, isSendInputResult, isSetAnimateMaterialsParams, isSetGameViewParams, isSetGizmoParams, isSetGridParams, isSetViewModeParams, isSettingsSet, isThumbnailResult, isTransformDraggedParams, isTransformDraggingParams, listenForEditorPlayControls, protocolVersionIsCompatible, startEditorHost, startEditorPlayControls };
7848
8675
 
7849
8676
  //# sourceMappingURL=index.js.map