@combeenation/3d-viewer 9.0.1 → 9.0.2-alpha2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +111 -111
  2. package/dist/lib-cjs/api/classes/animationInterface.d.ts +8 -8
  3. package/dist/lib-cjs/api/classes/animationInterface.js +2 -2
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +166 -166
  6. package/dist/lib-cjs/api/classes/element.d.ts +153 -153
  7. package/dist/lib-cjs/api/classes/element.js +667 -667
  8. package/dist/lib-cjs/api/classes/event.d.ts +401 -401
  9. package/dist/lib-cjs/api/classes/event.js +424 -424
  10. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  11. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -49
  12. package/dist/lib-cjs/api/classes/fuzzyMap.d.ts +7 -7
  13. package/dist/lib-cjs/api/classes/fuzzyMap.js +21 -21
  14. package/dist/lib-cjs/api/classes/parameter.d.ts +410 -410
  15. package/dist/lib-cjs/api/classes/parameter.js +642 -642
  16. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  17. package/dist/lib-cjs/api/classes/parameterObservable.js +72 -72
  18. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  19. package/dist/lib-cjs/api/classes/parameterizable.js +102 -102
  20. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +45 -45
  21. package/dist/lib-cjs/api/classes/placementAnimation.js +176 -176
  22. package/dist/lib-cjs/api/classes/variant.d.ts +261 -261
  23. package/dist/lib-cjs/api/classes/variant.js +870 -870
  24. package/dist/lib-cjs/api/classes/variantInstance.d.ts +53 -53
  25. package/dist/lib-cjs/api/classes/variantInstance.js +125 -125
  26. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  27. package/dist/lib-cjs/api/classes/variantParameterizable.js +86 -86
  28. package/dist/lib-cjs/api/classes/viewer.d.ts +213 -213
  29. package/dist/lib-cjs/api/classes/viewer.js +717 -717
  30. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  31. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  32. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  33. package/dist/lib-cjs/api/classes/viewerLight.js +348 -348
  34. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  35. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  36. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  37. package/dist/lib-cjs/api/internal/sceneSetup.js +226 -226
  38. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  39. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  40. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +103 -103
  41. package/dist/lib-cjs/api/manager/gltfExportManager.js +331 -325
  42. package/dist/lib-cjs/api/manager/gltfExportManager.js.map +1 -1
  43. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  44. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  45. package/dist/lib-cjs/api/manager/tagManager.d.ts +118 -118
  46. package/dist/lib-cjs/api/manager/tagManager.js +535 -522
  47. package/dist/lib-cjs/api/manager/tagManager.js.map +1 -1
  48. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  49. package/dist/lib-cjs/api/manager/textureLoadManager.js +97 -97
  50. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  51. package/dist/lib-cjs/api/manager/variantInstanceManager.js +290 -290
  52. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  53. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  54. package/dist/lib-cjs/api/util/babylonHelper.d.ts +237 -237
  55. package/dist/lib-cjs/api/util/babylonHelper.js +825 -825
  56. package/dist/lib-cjs/api/util/globalTypes.d.ts +479 -479
  57. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  58. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  59. package/dist/lib-cjs/api/util/resourceHelper.js +214 -211
  60. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  61. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  62. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  63. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  64. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  65. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  66. package/dist/lib-cjs/api/util/structureHelper.js +60 -60
  67. package/dist/lib-cjs/buildinfo.json +3 -3
  68. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  69. package/dist/lib-cjs/index.d.ts +54 -54
  70. package/dist/lib-cjs/index.js +117 -117
  71. package/package.json +82 -82
  72. package/src/api/classes/animationInterface.ts +10 -10
  73. package/src/api/classes/dottedPath.ts +181 -181
  74. package/src/api/classes/element.ts +723 -723
  75. package/src/api/classes/event.ts +457 -457
  76. package/src/api/classes/eventBroadcaster.ts +52 -52
  77. package/src/api/classes/fuzzyMap.ts +21 -21
  78. package/src/api/classes/parameter.ts +686 -686
  79. package/src/api/classes/parameterObservable.ts +73 -73
  80. package/src/api/classes/parameterizable.ts +87 -87
  81. package/src/api/classes/placementAnimation.ts +162 -162
  82. package/src/api/classes/variant.ts +963 -963
  83. package/src/api/classes/variantInstance.ts +123 -123
  84. package/src/api/classes/variantParameterizable.ts +83 -83
  85. package/src/api/classes/viewer.ts +770 -770
  86. package/src/api/classes/viewerError.ts +63 -63
  87. package/src/api/classes/viewerLight.ts +339 -339
  88. package/src/api/internal/debugViewer.ts +90 -90
  89. package/src/api/internal/lensRendering.ts +9 -9
  90. package/src/api/internal/sceneSetup.ts +205 -205
  91. package/src/api/manager/animationManager.ts +143 -143
  92. package/src/api/manager/gltfExportManager.ts +310 -302
  93. package/src/api/manager/sceneManager.ts +134 -134
  94. package/src/api/manager/tagManager.ts +576 -564
  95. package/src/api/manager/textureLoadManager.ts +95 -95
  96. package/src/api/manager/variantInstanceManager.ts +306 -306
  97. package/src/api/store/specStorage.ts +68 -68
  98. package/src/api/util/babylonHelper.ts +913 -913
  99. package/src/api/util/globalTypes.ts +555 -555
  100. package/src/api/util/resourceHelper.ts +201 -198
  101. package/src/api/util/sceneLoaderHelper.ts +170 -170
  102. package/src/api/util/stringHelper.ts +30 -30
  103. package/src/api/util/structureHelper.ts +60 -60
  104. package/src/buildinfo.json +3 -3
  105. package/src/dev.ts +62 -62
  106. package/src/index.ts +103 -103
  107. package/src/types.d.ts +38 -38
@@ -1,770 +1,770 @@
1
- import buildInfo from '../../buildinfo.json';
2
- import { sceneSetup } from '../internal/sceneSetup';
3
- import { AnimationManager } from '../manager/animationManager';
4
- import { GltfExportManager } from '../manager/gltfExportManager';
5
- import { SceneManager } from '../manager/sceneManager';
6
- import { TagManager } from '../manager/tagManager';
7
- import { VariantInstanceManager } from '../manager/variantInstanceManager';
8
- import { SpecStorage } from '../store/specStorage';
9
- import { backgroundDomeName, envHelperMetadataName } from '../util/babylonHelper';
10
- import { debounce, loadJavascript, loadJson } from '../util/resourceHelper';
11
- import { getCustomCbnBabylonLoaderPlugin } from '../util/sceneLoaderHelper';
12
- import { replaceDots } from '../util/stringHelper';
13
- import { isNodeIncludedInExclusionList } from '../util/structureHelper';
14
- import * as Index from './../../index';
15
- import { AnimationInterface } from './animationInterface';
16
- import { Event } from './event';
17
- import { EventBroadcaster } from './eventBroadcaster';
18
- import { Parameter } from './parameter';
19
- import { VariantInstance } from './variantInstance';
20
- import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
21
- import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
22
- import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
23
- import { DebugLayer } from '@babylonjs/core/Debug/debugLayer';
24
- import { Engine } from '@babylonjs/core/Engines/engine';
25
- import { IPointerEvent } from '@babylonjs/core/Events/deviceInputEvents';
26
- import { EnvironmentHelper } from '@babylonjs/core/Helpers/environmentHelper';
27
- import { PhotoDome } from '@babylonjs/core/Helpers/photoDome';
28
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
29
- import { ISceneLoaderPlugin, SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
30
- import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
31
- import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
32
- import { Color3 } from '@babylonjs/core/Maths/math.color';
33
- import { Vector3 } from '@babylonjs/core/Maths/math.vector';
34
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
35
- import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
36
- import { WebXRSessionManager } from '@babylonjs/core/XR/webXRSessionManager';
37
- import { Scene } from '@babylonjs/core/scene';
38
- import { isString } from 'lodash-es';
39
-
40
- /**
41
- * The main exposed object. This is the entry point into the application
42
- *
43
- * ```js
44
- * const canvas = document.getElementById( 'babylon-canvas' );
45
- * const viewer = Viewer( canvas, '/path/to/index.json' );
46
- * ```
47
- * The class does nothing on its own and needs to {@link bootstrap}
48
- */
49
- export class Viewer extends EventBroadcaster {
50
- public static readonly BOUNDING_BOX_NAME = '__bounding_box__';
51
-
52
- protected _scene: Scene | null = null;
53
-
54
- protected _animationManager: AnimationManager | null = null;
55
-
56
- protected _sceneManager: SceneManager | null = null;
57
-
58
- protected _tagManager: TagManager | null = null;
59
-
60
- protected _gltfExportManager: GltfExportManager | null = null;
61
-
62
- protected _variantInstances: VariantInstanceManager | null = null;
63
-
64
- // defaults to `false` as material cloning should be the edge case
65
- protected _cloneMaterialsOnMutation: boolean = false;
66
-
67
- protected _isRenderLoopPaused: boolean = false;
68
-
69
- protected _inspectorLoaded: boolean = false;
70
-
71
- protected _nodeNamingStrategyHandler: NodeNamingStrategyHandler | null = null;
72
-
73
- static version = buildInfo.version;
74
-
75
- // these are constants for calculating the camera settings, depending on the bounding box size of the meshes to zoom
76
- // the algorithms and constant values are directly taken from the Babylon.js repository
77
- private static readonly _autofocusConstants = {
78
- minZ: 100,
79
- wheelPrecision: 100,
80
- panningSensibility: 5000,
81
- pinchPrecision: 200,
82
- };
83
-
84
- /**
85
- * Help function for automatically creating a valid Spec from a list of variant names and dedicated GLB/babylon URLs.
86
- * This data is most likely coming from babylon assets from the Combeenation system but other sources are also valid.
87
- */
88
- public static generateSpec(genData: SpecGenerationData[]): AutoSpecStructureJson {
89
- // dots in the variant name indicate inheritance, but this should not be the case for an auto-generated spec
90
- // therefore dots are exchanged with slashes
91
- const safeGenData: SpecGenerationData[] = genData.map(data => ({ ...data, name: replaceDots(data.name) }));
92
-
93
- const spec: AutoSpecStructureJson = {
94
- // common scene settings as suggested in the viewer docs
95
- scene: {
96
- engine: {
97
- antialiasing: true,
98
- options: {
99
- preserveDrawingBuffer: true,
100
- stencil: true,
101
- xrCompatible: false,
102
- },
103
- },
104
- scene: {
105
- globals: {},
106
- },
107
- },
108
- setup: {
109
- // create one instance for each input entry
110
- // name and variant are named accordingly from the input, instance will be hidden by default and lazy loading
111
- // is activated
112
- instances: safeGenData.map(instanceData => ({
113
- name: instanceData.name,
114
- variant: instanceData.name,
115
- lazy: true,
116
- parameters: {
117
- [Parameter.VISIBLE]: false,
118
- },
119
- })),
120
- },
121
- // variants definition is also mapped to the input array, using the name as key and url as glTF source
122
- // no elements are created here, since this should be done automatically from the system
123
- // => create one element which contains all root nodes of the imported 3d file (GLB or babylon)
124
- variants: safeGenData.reduce((accVariants, curVariant) => {
125
- accVariants[curVariant.name] = {
126
- glTF: curVariant.url,
127
- };
128
-
129
- return accVariants;
130
- }, {} as { [id: string]: StructureJson }),
131
- };
132
-
133
- return spec;
134
- }
135
-
136
- /**
137
- * Returns all modules which are exported by the viewers index file.
138
- *
139
- * Needed by the [Combeenation viewer control](https://docs.combeenation.com/docs/3d-viewer-control) in situations where the viewer is injected from external code.
140
- *
141
- * See [Combeenation docs](https://docs.combeenation.com/docs/3d-viewer-control-with-custom-js) for more details.
142
- */
143
- public static getAllViewerModules() {
144
- return Index;
145
- }
146
-
147
- /**
148
- * Constructor
149
- */
150
- public constructor(public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson) {
151
- super();
152
- this._tagManager = new TagManager(this);
153
- this._nodeNamingStrategyHandler = (node, payload) => {
154
- const suffix: string[] = [];
155
- // (1) instance part
156
- const variantInstances = this.variantInstances.allWithVariantName(payload.variant.name);
157
- if (variantInstances.length > 0) {
158
- suffix.push(payload.variantInstance.name);
159
- }
160
- // (2) element part
161
- if (payload.variant.elements.length > 0) {
162
- const nodeElements = payload.variant.elements.filter(
163
- e => e.nodesFlat.filter(n => n.metadata?.cloneSource?.id === node.id).length > 0
164
- );
165
- if (nodeElements.length > 0) {
166
- suffix.push(payload.variantParameterizable.name);
167
- }
168
- }
169
- // (3) merge together
170
- const originalName = node.metadata?.originalName || node.name;
171
- return [originalName, ...suffix.filter(s => !!s)].join('.');
172
- };
173
- }
174
-
175
- /**
176
- * Gets the Babylon.js Scene that is attached to the instance.
177
- *
178
- * @throws Error if the `scene` has not been initialized.
179
- */
180
- get scene(): Scene {
181
- if (!this._scene) {
182
- throw new Error(`Scene has not been initialized.`);
183
- }
184
- return this._scene;
185
- }
186
-
187
- /**
188
- * Gets the {@link SceneManager} attached to the viewer.
189
- *
190
- * @throws Error if the {@link SceneManager} has not been initialized.
191
- */
192
- get sceneManager(): SceneManager {
193
- if (!this._sceneManager) {
194
- throw new Error(`SceneManager has not been initialized.`);
195
- }
196
- return this._sceneManager;
197
- }
198
-
199
- /**
200
- * Gets the {@link GltfExportManager} attached to the viewer.
201
- *
202
- * @throws Error if the {@link GltfExportManager} has not been initialized.
203
- */
204
- get gltfExportManager(): GltfExportManager {
205
- if (!this._gltfExportManager) {
206
- throw new Error(`GltfExportManager has not been initialized.`);
207
- }
208
- return this._gltfExportManager;
209
- }
210
-
211
- /**
212
- * Gets the Babylon.js Engine that is attached to the viewer.
213
- */
214
- get engine(): Engine {
215
- return this.scene.getEngine();
216
- }
217
-
218
- /**
219
- * Gets the {@link VariantInstanceManager} attached to the viewer.
220
- *
221
- * @throws Error if the {@link VariantInstanceManager} has not been initialized.
222
- */
223
- get variantInstances(): VariantInstanceManager {
224
- if (!this._variantInstances) {
225
- throw Error(`There is no variantInstanceManager.`);
226
- }
227
- return this._variantInstances;
228
- }
229
-
230
- /**
231
- * Gets the {@link AnimationManager} attached to the viewer.
232
- *
233
- * @throws Error if the {@link AnimationManager} has not been initialized.
234
- */
235
- get animationManager(): AnimationManager {
236
- if (!this._animationManager) {
237
- throw new Error(`There is no animationManager instance.`);
238
- }
239
- return this._animationManager;
240
- }
241
-
242
- get tagManager(): TagManager {
243
- if (!this._tagManager) {
244
- throw new Error(`There is no tagManager instance.`);
245
- }
246
- return this._tagManager;
247
- }
248
-
249
- /**
250
- * Gets the `cloneMaterialsOnMutation` flag, as defined in the spec
251
- */
252
- get cloneMaterialsOnMutation(): boolean {
253
- return this._cloneMaterialsOnMutation;
254
- }
255
-
256
- /**
257
- * Gets the strategy handler for naming cloned nodes.
258
- */
259
- get nodeNamingStrategyHandler(): NodeNamingStrategyHandler {
260
- if (!this._nodeNamingStrategyHandler) {
261
- throw new Error(`The NodeNamingStrategyHandler has not been registered yet.`);
262
- }
263
- return this._nodeNamingStrategyHandler;
264
- }
265
-
266
- /**
267
- * Sets the strategy handler for naming cloned nodes.\
268
- * Check the docs of the tag managers [renaming](https://3dviewer.docs.combeenation.com/pages/documentation/Tag-Manager.html#uniqueness-of-node-and-tag-names)
269
- * chapter for further details.
270
- */
271
- set nodeNamingStrategyHandler(value: NodeNamingStrategyHandler) {
272
- if (!value || typeof value !== 'function') {
273
- throw new Error(`The NodeNamingStrategyHandler is not a callable function.`);
274
- }
275
- this._nodeNamingStrategyHandler = value;
276
- }
277
-
278
- /**
279
- * Starts the application. This will
280
- * * load the given "index" JSON file
281
- * * setup the scene with the "scene" JSON file
282
- * * create an (optional) default setup with different variant settings
283
- * * sets up resizing by attaching a debounced version of {@link resize}
284
- *
285
- * @throws Error if any of the files is not found/valid
286
- *
287
- * @emits {@link Event.BOOTSTRAP_START}
288
- * @emits {@link Event.BOOTSTRAP_END}
289
- */
290
- public async bootstrap(tagManagerParameterValues?: TagManagerParameterValue[]): Promise<Viewer> {
291
- this.broadcastEvent(Event.BOOTSTRAP_START, this);
292
- let indexJson;
293
- if (isString(this.structureJson)) {
294
- indexJson = await loadJson<StructureJson>(this.structureJson);
295
- } else {
296
- indexJson = this.structureJson;
297
- }
298
- if (!indexJson.scene) {
299
- throw new Error(`No "scene" property found for bootstrapping.`);
300
- }
301
- // fill spec store
302
- SpecStorage.createFromSpec(indexJson);
303
- // init custom loader plugin
304
- this.initCbnBabylonLoaderPlugin();
305
- // load scene
306
- if (isString(indexJson.scene)) {
307
- const sceneJson = await loadJson<SceneJson>(indexJson.scene);
308
- indexJson.scene = sceneJson;
309
- }
310
- this._scene = await this.initScene();
311
- // set initial tag manager parameter values
312
- if (tagManagerParameterValues) {
313
- await this.tagManager.setParameterValues(tagManagerParameterValues);
314
- }
315
- // create instance manager
316
- this._variantInstances = await VariantInstanceManager.create(this);
317
- // create optional default instances
318
- if (indexJson.setup) {
319
- if (isString(indexJson.setup)) {
320
- const setupJson = await loadJson<SetupJson>(indexJson.setup);
321
- indexJson.setup = setupJson;
322
- }
323
- this.printInstanceDefinitions(indexJson.setup);
324
- await this.createVariantInstances();
325
- }
326
- this.broadcastEvent(Event.VARIANT_INSTANCES_READY, this);
327
- // create gltf export manager
328
- this._gltfExportManager = await GltfExportManager.create(this);
329
- // resize handler
330
- window.addEventListener('resize', debounce(this.resize.bind(this), 100));
331
- // wait until scene is completely ready
332
- await this.scene.whenReadyAsync();
333
- // event broadcasting
334
- this.broadcastEvent(Event.BOOTSTRAP_END, this);
335
- // render loop
336
- this.engine.runRenderLoop(() => {
337
- if (!this._isRenderLoopPaused) this.scene.render();
338
- });
339
- return this;
340
- }
341
-
342
- /**
343
- * Enables the Babylon.js [Inspector](https://doc.babylonjs.com/toolsAndResources/tools/inspector).\
344
- * Due to the additional size of the inspector, the CDN version is used instead of shipping the required code with
345
- * the viewer.\
346
- * This means that the code will be downloaded only when needed and calling `enableDebugLayer` can take a little while
347
- * depending on your internet connection etc.
348
- */
349
- public async enableDebugLayer(options?: IInspectorOptions) {
350
- if (!this._inspectorLoaded) {
351
- // CDN version of inspector requires the Babylon.js core to be available as CDN module as well
352
- await loadJavascript('https://cdn.jsdelivr.net/npm/babylonjs@5.6.0/babylon.min.js');
353
-
354
- DebugLayer.InspectorURL =
355
- 'https://cdn.jsdelivr.net/npm/babylonjs-inspector@5.6.0/babylon.inspector.bundle.max.min.js';
356
-
357
- this._inspectorLoaded = true;
358
- }
359
-
360
- await this.scene.debugLayer.show(options);
361
- }
362
-
363
- /**
364
- * Destroys all registered {@link VariantInstance}s that are registered
365
- */
366
- public destroyVariantInstances(): Viewer {
367
- this.variantInstances.all.forEach(variantInstance => {
368
- this.variantInstances.destroy(variantInstance.name);
369
- });
370
- return this;
371
- }
372
-
373
- /**
374
- * Trigger a resize event for the `Engine`
375
- */
376
- public resize(): Viewer {
377
- this.engine.resize();
378
- return this;
379
- }
380
-
381
- /**
382
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
383
- * {@link DottedPath}s.
384
- */
385
- public async getNode(
386
- variantInstanceName: string,
387
- elementDottedPath: DottedPathArgument,
388
- nodeDottedPath: DottedPathArgument
389
- ): Promise<TransformNode> {
390
- const variantInstance = await this.variantInstances.get(variantInstanceName);
391
- return variantInstance.getNode(elementDottedPath, nodeDottedPath);
392
- }
393
-
394
- /**
395
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
396
- * {@link DottedPath}s.
397
- */
398
- public async getMesh(
399
- variantInstanceName: string,
400
- elementDottedPath: DottedPathArgument,
401
- meshDottedPath: DottedPathArgument
402
- ): Promise<Mesh | null> {
403
- const variantInstance = await this.variantInstances.get(variantInstanceName);
404
- return variantInstance.getMesh(elementDottedPath, meshDottedPath);
405
- }
406
-
407
- /**
408
- * Switches the camera
409
- *
410
- * @emits {@link Event.CAMERA_SWITCHED}
411
- */
412
- public switchCamera(newCamera: string, reset: boolean = true): Viewer {
413
- const camera = this.scene.getCameraByName(newCamera);
414
- if (camera) {
415
- const activeCamera = this.scene.activeCamera;
416
- if (activeCamera) {
417
- activeCamera.detachControl(this.engine.getRenderingCanvas()!);
418
- }
419
- if (reset) {
420
- camera.restoreState();
421
- }
422
- this.scene.setActiveCameraByName(newCamera);
423
- camera.attachControl(this.engine.getRenderingCanvas()!);
424
- this.broadcastEvent(Event.CAMERA_SWITCHED, camera);
425
- } else {
426
- throw new Error(`Given camera "${newCamera}" not found.`);
427
- }
428
- // TODO: put traceable observers to new camera (@see element)
429
- return this;
430
- }
431
-
432
- /**
433
- * Moves or animates the active camera to given `placement`.
434
- */
435
- public async moveActiveCameraTo(
436
- placement: string | PlacementDefinition,
437
- animation?: string | AnimationDefinition
438
- ): Promise<AnimationInterface> {
439
- return this.animationManager.animateToPlacement(this.sceneManager.activeCamera, placement, animation);
440
- }
441
-
442
- /**
443
- * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
444
- */
445
- public screenshot(settings?: ScreenshotSettings): Promise<string> {
446
- return new Promise((resolve, reject) => {
447
- if (!this.engine) {
448
- return reject('Engine is null');
449
- }
450
- if (!this.scene) {
451
- return reject('Scene is null');
452
- }
453
- this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
454
- ScreenshotTools.CreateScreenshotUsingRenderTarget(
455
- this.engine,
456
- this.sceneManager.activeCamera,
457
- settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
458
- resolve,
459
- settings?.mimeType ?? 'image/png',
460
- settings?.samples ?? 1,
461
- settings?.antialiasing ?? false,
462
- settings?.fileName ?? 'screenshot.png',
463
- settings?.renderSprites ?? false
464
- );
465
- });
466
- }
467
-
468
- /**
469
- * Checks whether the browser is capable of handling XR.
470
- */
471
- public async isBrowserARCapable(): Promise<boolean> {
472
- return await WebXRSessionManager.IsSessionSupportedAsync('immersive-ar');
473
- }
474
-
475
- /**
476
- * Calculates the bounding box from all visible meshes on the scene.
477
- */
478
- public async calculateBoundingBox(excludeGeometry?: ExcludedGeometryList): Promise<Mesh> {
479
- if (this.scene.meshes.length === 0) {
480
- throw new Error('There are currently no meshes on the scene.');
481
- }
482
- this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
483
- const { max, min } = this.scene.meshes
484
- .filter(mesh => {
485
- const isEnabled = mesh.isEnabled();
486
- // ignore the existing bounding box mesh for calculating the current one
487
- const isNotBBoxMesh = Viewer.BOUNDING_BOX_NAME !== mesh.id;
488
- // ignore meshes with invalid bounding infos
489
- const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
490
- // ignore meshes with infinite distance, typically these are sky boxes
491
- const hasInfiniteDistance = mesh.infiniteDistance;
492
- // ignore excluded meshes
493
- const isExcluded = excludeGeometry ? isNodeIncludedInExclusionList(mesh, excludeGeometry) : false;
494
- return isEnabled && isNotBBoxMesh && hasValidBBoxInfo && !hasInfiniteDistance && !isExcluded;
495
- })
496
- .reduce(
497
- (accBBoxMinMax, curMesh, idx) => {
498
- const bBox = curMesh.getBoundingInfo().boundingBox;
499
- // use the first entry in the array as default value and get the resulting maximum/minimum values
500
- const max = idx === 0 ? bBox.maximumWorld : Vector3.Maximize(accBBoxMinMax.max, bBox.maximumWorld);
501
- const min = idx === 0 ? bBox.minimumWorld : Vector3.Minimize(accBBoxMinMax.min, bBox.minimumWorld);
502
- return { max, min };
503
- },
504
- { max: new Vector3(), min: new Vector3() }
505
- );
506
-
507
- let boundingBox = this.scene.getMeshByName(Viewer.BOUNDING_BOX_NAME) as Mesh;
508
- if (!boundingBox) {
509
- boundingBox = new Mesh(Viewer.BOUNDING_BOX_NAME, this.scene);
510
- }
511
- boundingBox.setBoundingInfo(new BoundingInfo(min, max));
512
- return boundingBox;
513
- }
514
-
515
- /**
516
- * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning
517
- */
518
- public async autofocusActiveCamera(settings?: AutofocusSettings) {
519
- // first check some preconditions
520
- const activeCamera = this.scene.activeCamera;
521
- if (!activeCamera) {
522
- throw new Error('No active camera found when using autofocus feature.');
523
- }
524
- if (!(activeCamera instanceof ArcRotateCamera)) {
525
- const cameraClsName = activeCamera.getClassName();
526
- throw new Error(`Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.`);
527
- }
528
-
529
- let exclude = settings?.exclude || [];
530
-
531
- // Exclude shown photo dome or environment helper from bounding box calculation
532
- const photoDome = this.scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
533
- const photoDomeMeshes = photoDome?.getChildMeshes();
534
- if (photoDomeMeshes?.length) {
535
- exclude = [...exclude, ...photoDomeMeshes];
536
- }
537
-
538
- const envHelper = this.scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
539
- if (envHelper?.rootMesh) {
540
- exclude = [...exclude, envHelper.rootMesh];
541
- }
542
-
543
- // get bounding box of all visible meshes, this is the base for the autofocus algorithm
544
- const boundingBox = await this.calculateBoundingBox(exclude);
545
-
546
- const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
547
- const center = boundingBox.getBoundingInfo().boundingSphere.center;
548
- const diameter = radius * 2;
549
-
550
- // set lower radius limit on edge of bounding sphere to make sure that we can't dive into the meshes
551
- activeCamera.lowerRadiusLimit = radius;
552
-
553
- // additional settings
554
- // constants for division are taken directly from Babylon.js repository
555
- activeCamera.minZ = Math.min(radius / Viewer._autofocusConstants.minZ, 1);
556
- if (settings?.adjustWheelPrecision !== false) {
557
- activeCamera.wheelPrecision = Viewer._autofocusConstants.wheelPrecision / radius;
558
- }
559
- if (settings?.adjustPanningSensibility !== false) {
560
- activeCamera.panningSensibility = Viewer._autofocusConstants.panningSensibility / diameter;
561
- }
562
- if (settings?.adjustPinchPrecision !== false) {
563
- activeCamera.pinchPrecision = Viewer._autofocusConstants.pinchPrecision / radius;
564
- }
565
-
566
- const radiusFactor = settings?.radiusFactor ?? 1.5;
567
- const alpha = (settings?.alpha ?? -90) * (Math.PI / 180);
568
- const beta = (settings?.beta ?? 90) * (Math.PI / 180);
569
-
570
- const newCameraPosition = {
571
- alpha: alpha,
572
- beta: beta,
573
- // this calculation is a bit "simplified", as it doesn't consider the viewport ratio or the frustum angle
574
- // but it's also done this way in the Babylon.js repository, so it should be fine for us
575
- radius: diameter * radiusFactor,
576
- target: center,
577
- };
578
-
579
- await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation);
580
- }
581
-
582
- /**
583
- * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
584
- * environment
585
- */
586
- public async reset(tagManagerParameterValues?: TagManagerParameterValue[]): Promise<Viewer> {
587
- await this.destroy();
588
- return this.bootstrap(tagManagerParameterValues);
589
- }
590
-
591
- /**
592
- * Destroys
593
- *
594
- * * all {@link VariantInstance}s using {@link destroyVariantInstances}
595
- * * calling `dispose` on the `Engine` and `Scene`
596
- */
597
- public destroy(): Viewer {
598
- this.destroyVariantInstances();
599
- this.engine.dispose();
600
- SpecStorage.destroy();
601
- return this;
602
- }
603
-
604
- /**
605
- * Show coordinate system with given dimension (for debugging purpose).
606
- */
607
- public showWorldCoordinates(dimension: number) {
608
- const scene = this.scene;
609
- const makeTextPlane = function (text: string, color: string, size: number) {
610
- const dynamicTexture = new DynamicTexture('DynamicTexture', 50, scene, true);
611
- dynamicTexture.hasAlpha = true;
612
- dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true);
613
- const plane = Mesh.CreatePlane('TextPlane', size, scene, true);
614
- plane.material = new StandardMaterial('TextPlaneMaterial', scene);
615
- plane.material.backFaceCulling = false;
616
- (plane.material as StandardMaterial).specularColor = new Color3(0, 0, 0);
617
- (plane.material as StandardMaterial).diffuseTexture = dynamicTexture;
618
- return plane;
619
- };
620
-
621
- const axisX = Mesh.CreateLines(
622
- 'axisX',
623
- [
624
- Vector3.Zero(),
625
- new Vector3(dimension, 0, 0),
626
- new Vector3(dimension * 0.95, 0.05 * dimension, 0),
627
- new Vector3(dimension, 0, 0),
628
- new Vector3(dimension * 0.95, -0.05 * dimension, 0),
629
- ],
630
- scene,
631
- false
632
- );
633
- axisX.color = new Color3(1, 0, 0);
634
- const xChar = makeTextPlane('X', 'red', dimension / 10);
635
- xChar.position = new Vector3(0.9 * dimension, -0.05 * dimension, 0);
636
- const axisY = Mesh.CreateLines(
637
- 'axisY',
638
- [
639
- Vector3.Zero(),
640
- new Vector3(0, dimension, 0),
641
- new Vector3(-0.05 * dimension, dimension * 0.95, 0),
642
- new Vector3(0, dimension, 0),
643
- new Vector3(0.05 * dimension, dimension * 0.95, 0),
644
- ],
645
- scene,
646
- false
647
- );
648
- axisY.color = new Color3(0, 1, 0);
649
- const yChar = makeTextPlane('Y', 'green', dimension / 10);
650
- yChar.position = new Vector3(0, 0.9 * dimension, -0.05 * dimension);
651
- const axisZ = Mesh.CreateLines(
652
- 'axisZ',
653
- [
654
- Vector3.Zero(),
655
- new Vector3(0, 0, dimension),
656
- new Vector3(0, -0.05 * dimension, dimension * 0.95),
657
- new Vector3(0, 0, dimension),
658
- new Vector3(0, 0.05 * dimension, dimension * 0.95),
659
- ],
660
- scene,
661
- false
662
- );
663
- axisZ.color = new Color3(0, 0, 1);
664
- const zChar = makeTextPlane('Z', 'blue', dimension / 10);
665
- zChar.position = new Vector3(0, 0.05 * dimension, 0.9 * dimension);
666
- }
667
-
668
- /**
669
- * Pause render loop.
670
- */
671
- public pauseRendering() {
672
- this._isRenderLoopPaused = true;
673
- }
674
-
675
- /**
676
- * Resume render loop when paused.
677
- */
678
- public resumeRendering() {
679
- this._isRenderLoopPaused = false;
680
- }
681
-
682
- /**
683
- * Prints defined instances from SetupJson to the console.
684
- */
685
- protected printInstanceDefinitions(setupJson: SetupJson) {
686
- console.info(
687
- 'The following variant instances have been read from the given spec: ',
688
- setupJson.instances.map(o => o.name)
689
- );
690
- }
691
-
692
- /**
693
- * @emits {@link Event.SCENE_PROCESSING_START}
694
- * @emits {@link Event.SCENE_PROCESSING_END}
695
- */
696
- protected async initScene(): Promise<Scene> {
697
- const sceneJson = SpecStorage.get<SceneJson>('scene');
698
- this.broadcastEvent(Event.SCENE_PROCESSING_START, sceneJson);
699
- const engine = new Engine(
700
- this.canvas as HTMLCanvasElement,
701
- sceneJson.engine?.antialiasing ?? false,
702
- sceneJson.engine?.options
703
- );
704
- const scene = await sceneSetup(engine, sceneJson);
705
- if (sceneJson.meshPicking) {
706
- new HighlightLayer('default', scene);
707
- scene.onPointerPick = (pointerEvent: IPointerEvent, pickInfo: PickingInfo) => {
708
- if (!pickInfo.hit) {
709
- return;
710
- }
711
- const mesh = pickInfo.pickedMesh;
712
- this.broadcastEvent(Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant);
713
- if (mesh?.metadata.element) {
714
- this.broadcastEvent(Event.ELEMENT_PICKED, mesh.metadata.element);
715
- }
716
- if (mesh?.metadata.variant) {
717
- if (mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
718
- mesh.metadata.variant.toggleHighlight();
719
- }
720
- this.broadcastEvent(Event.VARIANT_PICKED, mesh.metadata.variant);
721
- }
722
- };
723
- }
724
- this._sceneManager = await SceneManager.create(scene);
725
- this._animationManager = await AnimationManager.create(scene);
726
- if (sceneJson.cloneMaterialsOnMutation !== undefined) {
727
- this._cloneMaterialsOnMutation = sceneJson.cloneMaterialsOnMutation;
728
- }
729
- // register observers for tag manager
730
- this.tagManager.registerNewObjectObservers(scene);
731
- this.broadcastEvent(Event.SCENE_PROCESSING_END, scene);
732
- return scene;
733
- }
734
-
735
- /**
736
- * Register custom file loader for babylon files which adds "missing-material" metadata to meshes which reference
737
- * materials that are not present in the `materials` section of the given babylon file.
738
- *
739
- * Required for babylon files & materials loaded from "Combeenation configurator assets".
740
- */
741
- protected initCbnBabylonLoaderPlugin() {
742
- const previousLoaderPlugin = SceneLoader.GetPluginForExtension('babylon') as ISceneLoaderPlugin;
743
- const customLoaderPlugin = getCustomCbnBabylonLoaderPlugin(previousLoaderPlugin);
744
- SceneLoader.RegisterPlugin(customLoaderPlugin);
745
- }
746
-
747
- /**
748
- * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
749
- */
750
- protected async createVariantInstances(): Promise<VariantInstance[]> {
751
- const setupJson = SpecStorage.get<SetupJson>('setup');
752
- const instances: VariantInstance[] = [];
753
- for (const instanceDefinition of setupJson.instances) {
754
- // don't create the instance right away if `lazy` is set, register it for later creation (on first usage) instead
755
- // however if the variant should be `visible` by default, `lazy` loading doesn't make sense and should therefore
756
- // be overruled by the `visible` flag
757
- if (instanceDefinition.lazy && instanceDefinition.parameters?.visible !== true) {
758
- this.variantInstances.register(instanceDefinition);
759
- continue;
760
- }
761
- const instance = await this.variantInstances.create(
762
- instanceDefinition.variant,
763
- instanceDefinition.name,
764
- instanceDefinition.parameters
765
- );
766
- instances.push(instance);
767
- }
768
- return instances;
769
- }
770
- }
1
+ import buildInfo from '../../buildinfo.json';
2
+ import { sceneSetup } from '../internal/sceneSetup';
3
+ import { AnimationManager } from '../manager/animationManager';
4
+ import { GltfExportManager } from '../manager/gltfExportManager';
5
+ import { SceneManager } from '../manager/sceneManager';
6
+ import { TagManager } from '../manager/tagManager';
7
+ import { VariantInstanceManager } from '../manager/variantInstanceManager';
8
+ import { SpecStorage } from '../store/specStorage';
9
+ import { backgroundDomeName, envHelperMetadataName } from '../util/babylonHelper';
10
+ import { debounce, loadJavascript, loadJson } from '../util/resourceHelper';
11
+ import { getCustomCbnBabylonLoaderPlugin } from '../util/sceneLoaderHelper';
12
+ import { replaceDots } from '../util/stringHelper';
13
+ import { isNodeIncludedInExclusionList } from '../util/structureHelper';
14
+ import * as Index from './../../index';
15
+ import { AnimationInterface } from './animationInterface';
16
+ import { Event } from './event';
17
+ import { EventBroadcaster } from './eventBroadcaster';
18
+ import { Parameter } from './parameter';
19
+ import { VariantInstance } from './variantInstance';
20
+ import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
21
+ import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
22
+ import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
23
+ import { DebugLayer } from '@babylonjs/core/Debug/debugLayer';
24
+ import { Engine } from '@babylonjs/core/Engines/engine';
25
+ import { IPointerEvent } from '@babylonjs/core/Events/deviceInputEvents';
26
+ import { EnvironmentHelper } from '@babylonjs/core/Helpers/environmentHelper';
27
+ import { PhotoDome } from '@babylonjs/core/Helpers/photoDome';
28
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
29
+ import { ISceneLoaderPlugin, SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
30
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
31
+ import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
32
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
33
+ import { Vector3 } from '@babylonjs/core/Maths/math.vector';
34
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
35
+ import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
36
+ import { WebXRSessionManager } from '@babylonjs/core/XR/webXRSessionManager';
37
+ import { Scene } from '@babylonjs/core/scene';
38
+ import { isString } from 'lodash-es';
39
+
40
+ /**
41
+ * The main exposed object. This is the entry point into the application
42
+ *
43
+ * ```js
44
+ * const canvas = document.getElementById( 'babylon-canvas' );
45
+ * const viewer = Viewer( canvas, '/path/to/index.json' );
46
+ * ```
47
+ * The class does nothing on its own and needs to {@link bootstrap}
48
+ */
49
+ export class Viewer extends EventBroadcaster {
50
+ public static readonly BOUNDING_BOX_NAME = '__bounding_box__';
51
+
52
+ protected _scene: Scene | null = null;
53
+
54
+ protected _animationManager: AnimationManager | null = null;
55
+
56
+ protected _sceneManager: SceneManager | null = null;
57
+
58
+ protected _tagManager: TagManager | null = null;
59
+
60
+ protected _gltfExportManager: GltfExportManager | null = null;
61
+
62
+ protected _variantInstances: VariantInstanceManager | null = null;
63
+
64
+ // defaults to `false` as material cloning should be the edge case
65
+ protected _cloneMaterialsOnMutation: boolean = false;
66
+
67
+ protected _isRenderLoopPaused: boolean = false;
68
+
69
+ protected _inspectorLoaded: boolean = false;
70
+
71
+ protected _nodeNamingStrategyHandler: NodeNamingStrategyHandler | null = null;
72
+
73
+ static version = buildInfo.version;
74
+
75
+ // these are constants for calculating the camera settings, depending on the bounding box size of the meshes to zoom
76
+ // the algorithms and constant values are directly taken from the Babylon.js repository
77
+ private static readonly _autofocusConstants = {
78
+ minZ: 100,
79
+ wheelPrecision: 100,
80
+ panningSensibility: 5000,
81
+ pinchPrecision: 200,
82
+ };
83
+
84
+ /**
85
+ * Help function for automatically creating a valid Spec from a list of variant names and dedicated GLB/babylon URLs.
86
+ * This data is most likely coming from babylon assets from the Combeenation system but other sources are also valid.
87
+ */
88
+ public static generateSpec(genData: SpecGenerationData[]): AutoSpecStructureJson {
89
+ // dots in the variant name indicate inheritance, but this should not be the case for an auto-generated spec
90
+ // therefore dots are exchanged with slashes
91
+ const safeGenData: SpecGenerationData[] = genData.map(data => ({ ...data, name: replaceDots(data.name) }));
92
+
93
+ const spec: AutoSpecStructureJson = {
94
+ // common scene settings as suggested in the viewer docs
95
+ scene: {
96
+ engine: {
97
+ antialiasing: true,
98
+ options: {
99
+ preserveDrawingBuffer: true,
100
+ stencil: true,
101
+ xrCompatible: false,
102
+ },
103
+ },
104
+ scene: {
105
+ globals: {},
106
+ },
107
+ },
108
+ setup: {
109
+ // create one instance for each input entry
110
+ // name and variant are named accordingly from the input, instance will be hidden by default and lazy loading
111
+ // is activated
112
+ instances: safeGenData.map(instanceData => ({
113
+ name: instanceData.name,
114
+ variant: instanceData.name,
115
+ lazy: true,
116
+ parameters: {
117
+ [Parameter.VISIBLE]: false,
118
+ },
119
+ })),
120
+ },
121
+ // variants definition is also mapped to the input array, using the name as key and url as glTF source
122
+ // no elements are created here, since this should be done automatically from the system
123
+ // => create one element which contains all root nodes of the imported 3d file (GLB or babylon)
124
+ variants: safeGenData.reduce((accVariants, curVariant) => {
125
+ accVariants[curVariant.name] = {
126
+ glTF: curVariant.url,
127
+ };
128
+
129
+ return accVariants;
130
+ }, {} as { [id: string]: StructureJson }),
131
+ };
132
+
133
+ return spec;
134
+ }
135
+
136
+ /**
137
+ * Returns all modules which are exported by the viewers index file.
138
+ *
139
+ * Needed by the [Combeenation viewer control](https://docs.combeenation.com/docs/3d-viewer-control) in situations where the viewer is injected from external code.
140
+ *
141
+ * See [Combeenation docs](https://docs.combeenation.com/docs/3d-viewer-control-with-custom-js) for more details.
142
+ */
143
+ public static getAllViewerModules() {
144
+ return Index;
145
+ }
146
+
147
+ /**
148
+ * Constructor
149
+ */
150
+ public constructor(public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson) {
151
+ super();
152
+ this._tagManager = new TagManager(this);
153
+ this._nodeNamingStrategyHandler = (node, payload) => {
154
+ const suffix: string[] = [];
155
+ // (1) instance part
156
+ const variantInstances = this.variantInstances.allWithVariantName(payload.variant.name);
157
+ if (variantInstances.length > 0) {
158
+ suffix.push(payload.variantInstance.name);
159
+ }
160
+ // (2) element part
161
+ if (payload.variant.elements.length > 0) {
162
+ const nodeElements = payload.variant.elements.filter(
163
+ e => e.nodesFlat.filter(n => n.metadata?.cloneSource?.id === node.id).length > 0
164
+ );
165
+ if (nodeElements.length > 0) {
166
+ suffix.push(payload.variantParameterizable.name);
167
+ }
168
+ }
169
+ // (3) merge together
170
+ const originalName = node.metadata?.originalName || node.name;
171
+ return [originalName, ...suffix.filter(s => !!s)].join('.');
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Gets the Babylon.js Scene that is attached to the instance.
177
+ *
178
+ * @throws Error if the `scene` has not been initialized.
179
+ */
180
+ get scene(): Scene {
181
+ if (!this._scene) {
182
+ throw new Error(`Scene has not been initialized.`);
183
+ }
184
+ return this._scene;
185
+ }
186
+
187
+ /**
188
+ * Gets the {@link SceneManager} attached to the viewer.
189
+ *
190
+ * @throws Error if the {@link SceneManager} has not been initialized.
191
+ */
192
+ get sceneManager(): SceneManager {
193
+ if (!this._sceneManager) {
194
+ throw new Error(`SceneManager has not been initialized.`);
195
+ }
196
+ return this._sceneManager;
197
+ }
198
+
199
+ /**
200
+ * Gets the {@link GltfExportManager} attached to the viewer.
201
+ *
202
+ * @throws Error if the {@link GltfExportManager} has not been initialized.
203
+ */
204
+ get gltfExportManager(): GltfExportManager {
205
+ if (!this._gltfExportManager) {
206
+ throw new Error(`GltfExportManager has not been initialized.`);
207
+ }
208
+ return this._gltfExportManager;
209
+ }
210
+
211
+ /**
212
+ * Gets the Babylon.js Engine that is attached to the viewer.
213
+ */
214
+ get engine(): Engine {
215
+ return this.scene.getEngine();
216
+ }
217
+
218
+ /**
219
+ * Gets the {@link VariantInstanceManager} attached to the viewer.
220
+ *
221
+ * @throws Error if the {@link VariantInstanceManager} has not been initialized.
222
+ */
223
+ get variantInstances(): VariantInstanceManager {
224
+ if (!this._variantInstances) {
225
+ throw Error(`There is no variantInstanceManager.`);
226
+ }
227
+ return this._variantInstances;
228
+ }
229
+
230
+ /**
231
+ * Gets the {@link AnimationManager} attached to the viewer.
232
+ *
233
+ * @throws Error if the {@link AnimationManager} has not been initialized.
234
+ */
235
+ get animationManager(): AnimationManager {
236
+ if (!this._animationManager) {
237
+ throw new Error(`There is no animationManager instance.`);
238
+ }
239
+ return this._animationManager;
240
+ }
241
+
242
+ get tagManager(): TagManager {
243
+ if (!this._tagManager) {
244
+ throw new Error(`There is no tagManager instance.`);
245
+ }
246
+ return this._tagManager;
247
+ }
248
+
249
+ /**
250
+ * Gets the `cloneMaterialsOnMutation` flag, as defined in the spec
251
+ */
252
+ get cloneMaterialsOnMutation(): boolean {
253
+ return this._cloneMaterialsOnMutation;
254
+ }
255
+
256
+ /**
257
+ * Gets the strategy handler for naming cloned nodes.
258
+ */
259
+ get nodeNamingStrategyHandler(): NodeNamingStrategyHandler {
260
+ if (!this._nodeNamingStrategyHandler) {
261
+ throw new Error(`The NodeNamingStrategyHandler has not been registered yet.`);
262
+ }
263
+ return this._nodeNamingStrategyHandler;
264
+ }
265
+
266
+ /**
267
+ * Sets the strategy handler for naming cloned nodes.\
268
+ * Check the docs of the tag managers [renaming](https://3dviewer.docs.combeenation.com/pages/documentation/Tag-Manager.html#uniqueness-of-node-and-tag-names)
269
+ * chapter for further details.
270
+ */
271
+ set nodeNamingStrategyHandler(value: NodeNamingStrategyHandler) {
272
+ if (!value || typeof value !== 'function') {
273
+ throw new Error(`The NodeNamingStrategyHandler is not a callable function.`);
274
+ }
275
+ this._nodeNamingStrategyHandler = value;
276
+ }
277
+
278
+ /**
279
+ * Starts the application. This will
280
+ * * load the given "index" JSON file
281
+ * * setup the scene with the "scene" JSON file
282
+ * * create an (optional) default setup with different variant settings
283
+ * * sets up resizing by attaching a debounced version of {@link resize}
284
+ *
285
+ * @throws Error if any of the files is not found/valid
286
+ *
287
+ * @emits {@link Event.BOOTSTRAP_START}
288
+ * @emits {@link Event.BOOTSTRAP_END}
289
+ */
290
+ public async bootstrap(tagManagerParameterValues?: TagManagerParameterValue[]): Promise<Viewer> {
291
+ this.broadcastEvent(Event.BOOTSTRAP_START, this);
292
+ let indexJson;
293
+ if (isString(this.structureJson)) {
294
+ indexJson = await loadJson<StructureJson>(this.structureJson);
295
+ } else {
296
+ indexJson = this.structureJson;
297
+ }
298
+ if (!indexJson.scene) {
299
+ throw new Error(`No "scene" property found for bootstrapping.`);
300
+ }
301
+ // fill spec store
302
+ SpecStorage.createFromSpec(indexJson);
303
+ // init custom loader plugin
304
+ this.initCbnBabylonLoaderPlugin();
305
+ // load scene
306
+ if (isString(indexJson.scene)) {
307
+ const sceneJson = await loadJson<SceneJson>(indexJson.scene);
308
+ indexJson.scene = sceneJson;
309
+ }
310
+ this._scene = await this.initScene();
311
+ // set initial tag manager parameter values
312
+ if (tagManagerParameterValues) {
313
+ await this.tagManager.setParameterValues(tagManagerParameterValues);
314
+ }
315
+ // create instance manager
316
+ this._variantInstances = await VariantInstanceManager.create(this);
317
+ // create optional default instances
318
+ if (indexJson.setup) {
319
+ if (isString(indexJson.setup)) {
320
+ const setupJson = await loadJson<SetupJson>(indexJson.setup);
321
+ indexJson.setup = setupJson;
322
+ }
323
+ this.printInstanceDefinitions(indexJson.setup);
324
+ await this.createVariantInstances();
325
+ }
326
+ this.broadcastEvent(Event.VARIANT_INSTANCES_READY, this);
327
+ // create gltf export manager
328
+ this._gltfExportManager = await GltfExportManager.create(this);
329
+ // resize handler
330
+ window.addEventListener('resize', debounce(this.resize.bind(this), 100));
331
+ // wait until scene is completely ready
332
+ await this.scene.whenReadyAsync();
333
+ // event broadcasting
334
+ this.broadcastEvent(Event.BOOTSTRAP_END, this);
335
+ // render loop
336
+ this.engine.runRenderLoop(() => {
337
+ if (!this._isRenderLoopPaused) this.scene.render();
338
+ });
339
+ return this;
340
+ }
341
+
342
+ /**
343
+ * Enables the Babylon.js [Inspector](https://doc.babylonjs.com/toolsAndResources/tools/inspector).\
344
+ * Due to the additional size of the inspector, the CDN version is used instead of shipping the required code with
345
+ * the viewer.\
346
+ * This means that the code will be downloaded only when needed and calling `enableDebugLayer` can take a little while
347
+ * depending on your internet connection etc.
348
+ */
349
+ public async enableDebugLayer(options?: IInspectorOptions) {
350
+ if (!this._inspectorLoaded) {
351
+ // CDN version of inspector requires the Babylon.js core to be available as CDN module as well
352
+ await loadJavascript('https://cdn.jsdelivr.net/npm/babylonjs@5.6.0/babylon.min.js');
353
+
354
+ DebugLayer.InspectorURL =
355
+ 'https://cdn.jsdelivr.net/npm/babylonjs-inspector@5.6.0/babylon.inspector.bundle.max.min.js';
356
+
357
+ this._inspectorLoaded = true;
358
+ }
359
+
360
+ await this.scene.debugLayer.show(options);
361
+ }
362
+
363
+ /**
364
+ * Destroys all registered {@link VariantInstance}s that are registered
365
+ */
366
+ public destroyVariantInstances(): Viewer {
367
+ this.variantInstances.all.forEach(variantInstance => {
368
+ this.variantInstances.destroy(variantInstance.name);
369
+ });
370
+ return this;
371
+ }
372
+
373
+ /**
374
+ * Trigger a resize event for the `Engine`
375
+ */
376
+ public resize(): Viewer {
377
+ this.engine.resize();
378
+ return this;
379
+ }
380
+
381
+ /**
382
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
383
+ * {@link DottedPath}s.
384
+ */
385
+ public async getNode(
386
+ variantInstanceName: string,
387
+ elementDottedPath: DottedPathArgument,
388
+ nodeDottedPath: DottedPathArgument
389
+ ): Promise<TransformNode> {
390
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
391
+ return variantInstance.getNode(elementDottedPath, nodeDottedPath);
392
+ }
393
+
394
+ /**
395
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
396
+ * {@link DottedPath}s.
397
+ */
398
+ public async getMesh(
399
+ variantInstanceName: string,
400
+ elementDottedPath: DottedPathArgument,
401
+ meshDottedPath: DottedPathArgument
402
+ ): Promise<Mesh | null> {
403
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
404
+ return variantInstance.getMesh(elementDottedPath, meshDottedPath);
405
+ }
406
+
407
+ /**
408
+ * Switches the camera
409
+ *
410
+ * @emits {@link Event.CAMERA_SWITCHED}
411
+ */
412
+ public switchCamera(newCamera: string, reset: boolean = true): Viewer {
413
+ const camera = this.scene.getCameraByName(newCamera);
414
+ if (camera) {
415
+ const activeCamera = this.scene.activeCamera;
416
+ if (activeCamera) {
417
+ activeCamera.detachControl(this.engine.getRenderingCanvas()!);
418
+ }
419
+ if (reset) {
420
+ camera.restoreState();
421
+ }
422
+ this.scene.setActiveCameraByName(newCamera);
423
+ camera.attachControl(this.engine.getRenderingCanvas()!);
424
+ this.broadcastEvent(Event.CAMERA_SWITCHED, camera);
425
+ } else {
426
+ throw new Error(`Given camera "${newCamera}" not found.`);
427
+ }
428
+ // TODO: put traceable observers to new camera (@see element)
429
+ return this;
430
+ }
431
+
432
+ /**
433
+ * Moves or animates the active camera to given `placement`.
434
+ */
435
+ public async moveActiveCameraTo(
436
+ placement: string | PlacementDefinition,
437
+ animation?: string | AnimationDefinition
438
+ ): Promise<AnimationInterface> {
439
+ return this.animationManager.animateToPlacement(this.sceneManager.activeCamera, placement, animation);
440
+ }
441
+
442
+ /**
443
+ * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
444
+ */
445
+ public screenshot(settings?: ScreenshotSettings): Promise<string> {
446
+ return new Promise((resolve, reject) => {
447
+ if (!this.engine) {
448
+ return reject('Engine is null');
449
+ }
450
+ if (!this.scene) {
451
+ return reject('Scene is null');
452
+ }
453
+ this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
454
+ ScreenshotTools.CreateScreenshotUsingRenderTarget(
455
+ this.engine,
456
+ this.sceneManager.activeCamera,
457
+ settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
458
+ resolve,
459
+ settings?.mimeType ?? 'image/png',
460
+ settings?.samples ?? 1,
461
+ settings?.antialiasing ?? false,
462
+ settings?.fileName ?? 'screenshot.png',
463
+ settings?.renderSprites ?? false
464
+ );
465
+ });
466
+ }
467
+
468
+ /**
469
+ * Checks whether the browser is capable of handling XR.
470
+ */
471
+ public async isBrowserARCapable(): Promise<boolean> {
472
+ return await WebXRSessionManager.IsSessionSupportedAsync('immersive-ar');
473
+ }
474
+
475
+ /**
476
+ * Calculates the bounding box from all visible meshes on the scene.
477
+ */
478
+ public async calculateBoundingBox(excludeGeometry?: ExcludedGeometryList): Promise<Mesh> {
479
+ if (this.scene.meshes.length === 0) {
480
+ throw new Error('There are currently no meshes on the scene.');
481
+ }
482
+ this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
483
+ const { max, min } = this.scene.meshes
484
+ .filter(mesh => {
485
+ const isEnabled = mesh.isEnabled();
486
+ // ignore the existing bounding box mesh for calculating the current one
487
+ const isNotBBoxMesh = Viewer.BOUNDING_BOX_NAME !== mesh.id;
488
+ // ignore meshes with invalid bounding infos
489
+ const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
490
+ // ignore meshes with infinite distance, typically these are sky boxes
491
+ const hasInfiniteDistance = mesh.infiniteDistance;
492
+ // ignore excluded meshes
493
+ const isExcluded = excludeGeometry ? isNodeIncludedInExclusionList(mesh, excludeGeometry) : false;
494
+ return isEnabled && isNotBBoxMesh && hasValidBBoxInfo && !hasInfiniteDistance && !isExcluded;
495
+ })
496
+ .reduce(
497
+ (accBBoxMinMax, curMesh, idx) => {
498
+ const bBox = curMesh.getBoundingInfo().boundingBox;
499
+ // use the first entry in the array as default value and get the resulting maximum/minimum values
500
+ const max = idx === 0 ? bBox.maximumWorld : Vector3.Maximize(accBBoxMinMax.max, bBox.maximumWorld);
501
+ const min = idx === 0 ? bBox.minimumWorld : Vector3.Minimize(accBBoxMinMax.min, bBox.minimumWorld);
502
+ return { max, min };
503
+ },
504
+ { max: new Vector3(), min: new Vector3() }
505
+ );
506
+
507
+ let boundingBox = this.scene.getMeshByName(Viewer.BOUNDING_BOX_NAME) as Mesh;
508
+ if (!boundingBox) {
509
+ boundingBox = new Mesh(Viewer.BOUNDING_BOX_NAME, this.scene);
510
+ }
511
+ boundingBox.setBoundingInfo(new BoundingInfo(min, max));
512
+ return boundingBox;
513
+ }
514
+
515
+ /**
516
+ * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning
517
+ */
518
+ public async autofocusActiveCamera(settings?: AutofocusSettings) {
519
+ // first check some preconditions
520
+ const activeCamera = this.scene.activeCamera;
521
+ if (!activeCamera) {
522
+ throw new Error('No active camera found when using autofocus feature.');
523
+ }
524
+ if (!(activeCamera instanceof ArcRotateCamera)) {
525
+ const cameraClsName = activeCamera.getClassName();
526
+ throw new Error(`Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.`);
527
+ }
528
+
529
+ let exclude = settings?.exclude || [];
530
+
531
+ // Exclude shown photo dome or environment helper from bounding box calculation
532
+ const photoDome = this.scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
533
+ const photoDomeMeshes = photoDome?.getChildMeshes();
534
+ if (photoDomeMeshes?.length) {
535
+ exclude = [...exclude, ...photoDomeMeshes];
536
+ }
537
+
538
+ const envHelper = this.scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
539
+ if (envHelper?.rootMesh) {
540
+ exclude = [...exclude, envHelper.rootMesh];
541
+ }
542
+
543
+ // get bounding box of all visible meshes, this is the base for the autofocus algorithm
544
+ const boundingBox = await this.calculateBoundingBox(exclude);
545
+
546
+ const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
547
+ const center = boundingBox.getBoundingInfo().boundingSphere.center;
548
+ const diameter = radius * 2;
549
+
550
+ // set lower radius limit on edge of bounding sphere to make sure that we can't dive into the meshes
551
+ activeCamera.lowerRadiusLimit = radius;
552
+
553
+ // additional settings
554
+ // constants for division are taken directly from Babylon.js repository
555
+ activeCamera.minZ = Math.min(radius / Viewer._autofocusConstants.minZ, 1);
556
+ if (settings?.adjustWheelPrecision !== false) {
557
+ activeCamera.wheelPrecision = Viewer._autofocusConstants.wheelPrecision / radius;
558
+ }
559
+ if (settings?.adjustPanningSensibility !== false) {
560
+ activeCamera.panningSensibility = Viewer._autofocusConstants.panningSensibility / diameter;
561
+ }
562
+ if (settings?.adjustPinchPrecision !== false) {
563
+ activeCamera.pinchPrecision = Viewer._autofocusConstants.pinchPrecision / radius;
564
+ }
565
+
566
+ const radiusFactor = settings?.radiusFactor ?? 1.5;
567
+ const alpha = (settings?.alpha ?? -90) * (Math.PI / 180);
568
+ const beta = (settings?.beta ?? 90) * (Math.PI / 180);
569
+
570
+ const newCameraPosition = {
571
+ alpha: alpha,
572
+ beta: beta,
573
+ // this calculation is a bit "simplified", as it doesn't consider the viewport ratio or the frustum angle
574
+ // but it's also done this way in the Babylon.js repository, so it should be fine for us
575
+ radius: diameter * radiusFactor,
576
+ target: center,
577
+ };
578
+
579
+ await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation);
580
+ }
581
+
582
+ /**
583
+ * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
584
+ * environment
585
+ */
586
+ public async reset(tagManagerParameterValues?: TagManagerParameterValue[]): Promise<Viewer> {
587
+ await this.destroy();
588
+ return this.bootstrap(tagManagerParameterValues);
589
+ }
590
+
591
+ /**
592
+ * Destroys
593
+ *
594
+ * * all {@link VariantInstance}s using {@link destroyVariantInstances}
595
+ * * calling `dispose` on the `Engine` and `Scene`
596
+ */
597
+ public destroy(): Viewer {
598
+ this.destroyVariantInstances();
599
+ this.engine.dispose();
600
+ SpecStorage.destroy();
601
+ return this;
602
+ }
603
+
604
+ /**
605
+ * Show coordinate system with given dimension (for debugging purpose).
606
+ */
607
+ public showWorldCoordinates(dimension: number) {
608
+ const scene = this.scene;
609
+ const makeTextPlane = function (text: string, color: string, size: number) {
610
+ const dynamicTexture = new DynamicTexture('DynamicTexture', 50, scene, true);
611
+ dynamicTexture.hasAlpha = true;
612
+ dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true);
613
+ const plane = Mesh.CreatePlane('TextPlane', size, scene, true);
614
+ plane.material = new StandardMaterial('TextPlaneMaterial', scene);
615
+ plane.material.backFaceCulling = false;
616
+ (plane.material as StandardMaterial).specularColor = new Color3(0, 0, 0);
617
+ (plane.material as StandardMaterial).diffuseTexture = dynamicTexture;
618
+ return plane;
619
+ };
620
+
621
+ const axisX = Mesh.CreateLines(
622
+ 'axisX',
623
+ [
624
+ Vector3.Zero(),
625
+ new Vector3(dimension, 0, 0),
626
+ new Vector3(dimension * 0.95, 0.05 * dimension, 0),
627
+ new Vector3(dimension, 0, 0),
628
+ new Vector3(dimension * 0.95, -0.05 * dimension, 0),
629
+ ],
630
+ scene,
631
+ false
632
+ );
633
+ axisX.color = new Color3(1, 0, 0);
634
+ const xChar = makeTextPlane('X', 'red', dimension / 10);
635
+ xChar.position = new Vector3(0.9 * dimension, -0.05 * dimension, 0);
636
+ const axisY = Mesh.CreateLines(
637
+ 'axisY',
638
+ [
639
+ Vector3.Zero(),
640
+ new Vector3(0, dimension, 0),
641
+ new Vector3(-0.05 * dimension, dimension * 0.95, 0),
642
+ new Vector3(0, dimension, 0),
643
+ new Vector3(0.05 * dimension, dimension * 0.95, 0),
644
+ ],
645
+ scene,
646
+ false
647
+ );
648
+ axisY.color = new Color3(0, 1, 0);
649
+ const yChar = makeTextPlane('Y', 'green', dimension / 10);
650
+ yChar.position = new Vector3(0, 0.9 * dimension, -0.05 * dimension);
651
+ const axisZ = Mesh.CreateLines(
652
+ 'axisZ',
653
+ [
654
+ Vector3.Zero(),
655
+ new Vector3(0, 0, dimension),
656
+ new Vector3(0, -0.05 * dimension, dimension * 0.95),
657
+ new Vector3(0, 0, dimension),
658
+ new Vector3(0, 0.05 * dimension, dimension * 0.95),
659
+ ],
660
+ scene,
661
+ false
662
+ );
663
+ axisZ.color = new Color3(0, 0, 1);
664
+ const zChar = makeTextPlane('Z', 'blue', dimension / 10);
665
+ zChar.position = new Vector3(0, 0.05 * dimension, 0.9 * dimension);
666
+ }
667
+
668
+ /**
669
+ * Pause render loop.
670
+ */
671
+ public pauseRendering() {
672
+ this._isRenderLoopPaused = true;
673
+ }
674
+
675
+ /**
676
+ * Resume render loop when paused.
677
+ */
678
+ public resumeRendering() {
679
+ this._isRenderLoopPaused = false;
680
+ }
681
+
682
+ /**
683
+ * Prints defined instances from SetupJson to the console.
684
+ */
685
+ protected printInstanceDefinitions(setupJson: SetupJson) {
686
+ console.info(
687
+ 'The following variant instances have been read from the given spec: ',
688
+ setupJson.instances.map(o => o.name)
689
+ );
690
+ }
691
+
692
+ /**
693
+ * @emits {@link Event.SCENE_PROCESSING_START}
694
+ * @emits {@link Event.SCENE_PROCESSING_END}
695
+ */
696
+ protected async initScene(): Promise<Scene> {
697
+ const sceneJson = SpecStorage.get<SceneJson>('scene');
698
+ this.broadcastEvent(Event.SCENE_PROCESSING_START, sceneJson);
699
+ const engine = new Engine(
700
+ this.canvas as HTMLCanvasElement,
701
+ sceneJson.engine?.antialiasing ?? false,
702
+ sceneJson.engine?.options
703
+ );
704
+ const scene = await sceneSetup(engine, sceneJson);
705
+ if (sceneJson.meshPicking) {
706
+ new HighlightLayer('default', scene);
707
+ scene.onPointerPick = (pointerEvent: IPointerEvent, pickInfo: PickingInfo) => {
708
+ if (!pickInfo.hit) {
709
+ return;
710
+ }
711
+ const mesh = pickInfo.pickedMesh;
712
+ this.broadcastEvent(Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant);
713
+ if (mesh?.metadata.element) {
714
+ this.broadcastEvent(Event.ELEMENT_PICKED, mesh.metadata.element);
715
+ }
716
+ if (mesh?.metadata.variant) {
717
+ if (mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
718
+ mesh.metadata.variant.toggleHighlight();
719
+ }
720
+ this.broadcastEvent(Event.VARIANT_PICKED, mesh.metadata.variant);
721
+ }
722
+ };
723
+ }
724
+ this._sceneManager = await SceneManager.create(scene);
725
+ this._animationManager = await AnimationManager.create(scene);
726
+ if (sceneJson.cloneMaterialsOnMutation !== undefined) {
727
+ this._cloneMaterialsOnMutation = sceneJson.cloneMaterialsOnMutation;
728
+ }
729
+ // register observers for tag manager
730
+ this.tagManager.registerNewObjectObservers(scene);
731
+ this.broadcastEvent(Event.SCENE_PROCESSING_END, scene);
732
+ return scene;
733
+ }
734
+
735
+ /**
736
+ * Register custom file loader for babylon files which adds "missing-material" metadata to meshes which reference
737
+ * materials that are not present in the `materials` section of the given babylon file.
738
+ *
739
+ * Required for babylon files & materials loaded from "Combeenation configurator assets".
740
+ */
741
+ protected initCbnBabylonLoaderPlugin() {
742
+ const previousLoaderPlugin = SceneLoader.GetPluginForExtension('babylon') as ISceneLoaderPlugin;
743
+ const customLoaderPlugin = getCustomCbnBabylonLoaderPlugin(previousLoaderPlugin);
744
+ SceneLoader.RegisterPlugin(customLoaderPlugin);
745
+ }
746
+
747
+ /**
748
+ * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
749
+ */
750
+ protected async createVariantInstances(): Promise<VariantInstance[]> {
751
+ const setupJson = SpecStorage.get<SetupJson>('setup');
752
+ const instances: VariantInstance[] = [];
753
+ for (const instanceDefinition of setupJson.instances) {
754
+ // don't create the instance right away if `lazy` is set, register it for later creation (on first usage) instead
755
+ // however if the variant should be `visible` by default, `lazy` loading doesn't make sense and should therefore
756
+ // be overruled by the `visible` flag
757
+ if (instanceDefinition.lazy && instanceDefinition.parameters?.visible !== true) {
758
+ this.variantInstances.register(instanceDefinition);
759
+ continue;
760
+ }
761
+ const instance = await this.variantInstances.create(
762
+ instanceDefinition.variant,
763
+ instanceDefinition.name,
764
+ instanceDefinition.parameters
765
+ );
766
+ instances.push(instance);
767
+ }
768
+ return instances;
769
+ }
770
+ }