@combeenation/3d-viewer 7.1.3 → 8.0.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.
Files changed (106) 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 +672 -672
  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 +351 -351
  15. package/dist/lib-cjs/api/classes/parameter.js +524 -524
  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 +253 -253
  23. package/dist/lib-cjs/api/classes/variant.js +858 -858
  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 +716 -716
  30. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  31. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  32. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  33. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  34. package/dist/lib-cjs/api/classes/viewerLight.js +348 -348
  35. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  36. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  37. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  38. package/dist/lib-cjs/api/internal/sceneSetup.js +226 -226
  39. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  40. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  41. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +102 -79
  42. package/dist/lib-cjs/api/manager/gltfExportManager.js +320 -242
  43. package/dist/lib-cjs/api/manager/gltfExportManager.js.map +1 -1
  44. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  45. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  46. package/dist/lib-cjs/api/manager/tagManager.d.ts +116 -116
  47. package/dist/lib-cjs/api/manager/tagManager.js +444 -444
  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 +292 -292
  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 +235 -235
  55. package/dist/lib-cjs/api/util/babylonHelper.js +753 -753
  56. package/dist/lib-cjs/api/util/globalTypes.d.ts +457 -455
  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 +203 -203
  60. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  61. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  62. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  63. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  64. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  65. package/dist/lib-cjs/api/util/structureHelper.js +57 -57
  66. package/dist/lib-cjs/buildinfo.json +3 -3
  67. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  68. package/dist/lib-cjs/index.d.ts +54 -54
  69. package/dist/lib-cjs/index.js +117 -117
  70. package/package.json +81 -81
  71. package/src/api/classes/animationInterface.ts +10 -10
  72. package/src/api/classes/dottedPath.ts +181 -181
  73. package/src/api/classes/element.ts +733 -733
  74. package/src/api/classes/event.ts +457 -457
  75. package/src/api/classes/eventBroadcaster.ts +52 -52
  76. package/src/api/classes/fuzzyMap.ts +21 -21
  77. package/src/api/classes/parameter.ts +561 -561
  78. package/src/api/classes/parameterObservable.ts +73 -73
  79. package/src/api/classes/parameterizable.ts +87 -87
  80. package/src/api/classes/placementAnimation.ts +162 -162
  81. package/src/api/classes/variant.ts +949 -949
  82. package/src/api/classes/variantInstance.ts +123 -123
  83. package/src/api/classes/variantParameterizable.ts +83 -83
  84. package/src/api/classes/viewer.ts +772 -772
  85. package/src/api/classes/viewerError.ts +63 -63
  86. package/src/api/classes/viewerLight.ts +339 -339
  87. package/src/api/internal/debugViewer.ts +90 -90
  88. package/src/api/internal/lensRendering.ts +9 -9
  89. package/src/api/internal/sceneSetup.ts +205 -205
  90. package/src/api/manager/animationManager.ts +143 -143
  91. package/src/api/manager/gltfExportManager.ts +297 -237
  92. package/src/api/manager/sceneManager.ts +134 -134
  93. package/src/api/manager/tagManager.ts +477 -477
  94. package/src/api/manager/textureLoadManager.ts +95 -95
  95. package/src/api/manager/variantInstanceManager.ts +309 -309
  96. package/src/api/store/specStorage.ts +68 -68
  97. package/src/api/util/babylonHelper.ts +823 -823
  98. package/src/api/util/globalTypes.ts +527 -525
  99. package/src/api/util/resourceHelper.ts +191 -191
  100. package/src/api/util/sceneLoaderHelper.ts +170 -170
  101. package/src/api/util/stringHelper.ts +30 -30
  102. package/src/api/util/structureHelper.ts +58 -58
  103. package/src/buildinfo.json +3 -3
  104. package/src/dev.ts +62 -62
  105. package/src/index.ts +103 -103
  106. package/src/types.d.ts +38 -38
@@ -1,772 +1,772 @@
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 { isMeshIncludedInExclusionList } 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 { isArray, 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
- // create instance manager
312
- this._variantInstances = await VariantInstanceManager.create(this);
313
- // create optional default instances
314
- if (indexJson.setup) {
315
- if (isString(indexJson.setup)) {
316
- const setupJson = await loadJson<SetupJson>(indexJson.setup);
317
- indexJson.setup = setupJson;
318
- }
319
- this.printInstanceDefinitions(indexJson.setup);
320
- await this.createVariantInstances(tagManagerParameterValues);
321
- }
322
- this.broadcastEvent(Event.VARIANT_INSTANCES_READY, this);
323
- // create gltf export manager
324
- this._gltfExportManager = await GltfExportManager.create(this);
325
- // resize handler
326
- window.addEventListener('resize', debounce(this.resize.bind(this), 100));
327
- // wait until scene is completely ready
328
- await this.scene.whenReadyAsync();
329
- // event broadcasting
330
- this.broadcastEvent(Event.BOOTSTRAP_END, this);
331
- // render loop
332
- this.engine.runRenderLoop(() => {
333
- if (!this._isRenderLoopPaused) this.scene.render();
334
- });
335
- return this;
336
- }
337
-
338
- /**
339
- * Enables the Babylon.js [Inspector](https://doc.babylonjs.com/toolsAndResources/tools/inspector).\
340
- * Due to the additional size of the inspector, the CDN version is used instead of shipping the required code with
341
- * the viewer.\
342
- * This means that the code will be downloaded only when needed and calling `enableDebugLayer` can take a little while
343
- * depending on your internet connection etc.
344
- */
345
- public async enableDebugLayer(options?: IInspectorOptions) {
346
- if (!this._inspectorLoaded) {
347
- // CDN version of inspector requires the Babylon.js core to be available as CDN module as well
348
- await loadJavascript('https://cdn.jsdelivr.net/npm/babylonjs@5.6.0/babylon.min.js');
349
-
350
- DebugLayer.InspectorURL =
351
- 'https://cdn.jsdelivr.net/npm/babylonjs-inspector@5.6.0/babylon.inspector.bundle.max.min.js';
352
-
353
- this._inspectorLoaded = true;
354
- }
355
-
356
- await this.scene.debugLayer.show(options);
357
- }
358
-
359
- /**
360
- * Destroys all registered {@link VariantInstance}s that are registered
361
- */
362
- public destroyVariantInstances(): Viewer {
363
- this.variantInstances.all.forEach(variantInstance => {
364
- this.variantInstances.destroy(variantInstance.name);
365
- });
366
- return this;
367
- }
368
-
369
- /**
370
- * Trigger a resize event for the `Engine`
371
- */
372
- public resize(): Viewer {
373
- this.engine.resize();
374
- return this;
375
- }
376
-
377
- /**
378
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
379
- * {@link DottedPath}s.
380
- */
381
- public async getNode(
382
- variantInstanceName: string,
383
- elementDottedPath: DottedPathArgument,
384
- nodeDottedPath: DottedPathArgument
385
- ): Promise<TransformNode> {
386
- const variantInstance = await this.variantInstances.get(variantInstanceName);
387
- return variantInstance.getNode(elementDottedPath, nodeDottedPath);
388
- }
389
-
390
- /**
391
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
392
- * {@link DottedPath}s.
393
- */
394
- public async getMesh(
395
- variantInstanceName: string,
396
- elementDottedPath: DottedPathArgument,
397
- meshDottedPath: DottedPathArgument
398
- ): Promise<Mesh | null> {
399
- const variantInstance = await this.variantInstances.get(variantInstanceName);
400
- return variantInstance.getMesh(elementDottedPath, meshDottedPath);
401
- }
402
-
403
- /**
404
- * Switches the camera
405
- *
406
- * @emits {@link Event.CAMERA_SWITCHED}
407
- */
408
- public switchCamera(newCamera: string, reset: boolean = true): Viewer {
409
- const camera = this.scene.getCameraByName(newCamera);
410
- if (camera) {
411
- const activeCamera = this.scene.activeCamera;
412
- if (activeCamera) {
413
- activeCamera.detachControl(this.engine.getRenderingCanvas()!);
414
- }
415
- if (reset) {
416
- camera.restoreState();
417
- }
418
- this.scene.setActiveCameraByName(newCamera);
419
- camera.attachControl(this.engine.getRenderingCanvas()!);
420
- this.broadcastEvent(Event.CAMERA_SWITCHED, camera);
421
- } else {
422
- throw new Error(`Given camera "${newCamera}" not found.`);
423
- }
424
- // TODO: put traceable observers to new camera (@see element)
425
- return this;
426
- }
427
-
428
- /**
429
- * Moves or animates the active camera to given `placement`.
430
- */
431
- public async moveActiveCameraTo(
432
- placement: string | PlacementDefinition,
433
- animation?: string | AnimationDefinition
434
- ): Promise<AnimationInterface> {
435
- return this.animationManager.animateToPlacement(this.sceneManager.activeCamera, placement, animation);
436
- }
437
-
438
- /**
439
- * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
440
- */
441
- public screenshot(settings?: ScreenshotSettings): Promise<string> {
442
- return new Promise((resolve, reject) => {
443
- if (!this.engine) {
444
- return reject('Engine is null');
445
- }
446
- if (!this.scene) {
447
- return reject('Scene is null');
448
- }
449
- this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
450
- ScreenshotTools.CreateScreenshotUsingRenderTarget(
451
- this.engine,
452
- this.sceneManager.activeCamera,
453
- settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
454
- resolve,
455
- settings?.mimeType ?? 'image/png',
456
- settings?.samples ?? 1,
457
- settings?.antialiasing ?? false,
458
- settings?.fileName ?? 'screenshot.png',
459
- settings?.renderSprites ?? false
460
- );
461
- });
462
- }
463
-
464
- /**
465
- * Checks whether the browser is capable of handling XR.
466
- */
467
- public async isBrowserARCapable(): Promise<boolean> {
468
- return await WebXRSessionManager.IsSessionSupportedAsync('immersive-ar');
469
- }
470
-
471
- /**
472
- * Calculates the bounding box from all visible meshes on the scene.
473
- */
474
- public async calculateBoundingBox(excludeGeometry?: ExcludedGeometryList): Promise<Mesh> {
475
- if (this.scene.meshes.length === 0) {
476
- throw new Error('There are currently no meshes on the scene.');
477
- }
478
- this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
479
- const { max, min } = this.scene.meshes
480
- .filter(mesh => {
481
- const isEnabled = mesh.isEnabled();
482
- // ignore the existing bounding box mesh for calculating the current one
483
- const isNotBBoxMesh = Viewer.BOUNDING_BOX_NAME !== mesh.id;
484
- // ignore meshes with invalid bounding infos
485
- const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
486
- // ignore meshes with infinite distance, typically these are sky boxes
487
- const hasInfiniteDistance = mesh.infiniteDistance;
488
- // ignore excluded meshes
489
- const isExcluded = excludeGeometry ? isMeshIncludedInExclusionList(mesh as Mesh, excludeGeometry) : false;
490
- return isEnabled && isNotBBoxMesh && hasValidBBoxInfo && !hasInfiniteDistance && !isExcluded;
491
- })
492
- .reduce(
493
- (accBBoxMinMax, curMesh, idx) => {
494
- const bBox = curMesh.getBoundingInfo().boundingBox;
495
- // use the first entry in the array as default value and get the resulting maximum/minimum values
496
- const max = idx === 0 ? bBox.maximumWorld : Vector3.Maximize(accBBoxMinMax.max, bBox.maximumWorld);
497
- const min = idx === 0 ? bBox.minimumWorld : Vector3.Minimize(accBBoxMinMax.min, bBox.minimumWorld);
498
- return { max, min };
499
- },
500
- { max: new Vector3(), min: new Vector3() }
501
- );
502
-
503
- let boundingBox = this.scene.getMeshByName(Viewer.BOUNDING_BOX_NAME) as Mesh;
504
- if (!boundingBox) {
505
- boundingBox = new Mesh(Viewer.BOUNDING_BOX_NAME, this.scene);
506
- }
507
- boundingBox.setBoundingInfo(new BoundingInfo(min, max));
508
- return boundingBox;
509
- }
510
-
511
- /**
512
- * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning
513
- */
514
- public async autofocusActiveCamera(settings?: AutofocusSettings) {
515
- // first check some preconditions
516
- const activeCamera = this.scene.activeCamera;
517
- if (!activeCamera) {
518
- throw new Error('No active camera found when using autofocus feature.');
519
- }
520
- if (!(activeCamera instanceof ArcRotateCamera)) {
521
- const cameraClsName = activeCamera.getClassName();
522
- throw new Error(`Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.`);
523
- }
524
-
525
- let exclude = settings?.exclude || [];
526
-
527
- // Exclude shown photo dome or environment helper from bounding box calculation
528
- const photoDome = this.scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
529
- const photoDomeMeshes = photoDome?.getChildMeshes();
530
- if (photoDomeMeshes?.length) {
531
- exclude = [...exclude, ...photoDomeMeshes];
532
- }
533
-
534
- const envHelper = this.scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
535
- if (envHelper?.rootMesh) {
536
- exclude = [...exclude, envHelper.rootMesh];
537
- }
538
-
539
- // get bounding box of all visible meshes, this is the base for the autofocus algorithm
540
- const boundingBox = await this.calculateBoundingBox(exclude);
541
-
542
- const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
543
- const center = boundingBox.getBoundingInfo().boundingSphere.center;
544
- const diameter = radius * 2;
545
-
546
- // set lower radius limit on edge of bounding sphere to make sure that we can't dive into the meshes
547
- activeCamera.lowerRadiusLimit = radius;
548
-
549
- // additional settings
550
- // constants for division are taken directly from Babylon.js repository
551
- activeCamera.minZ = Math.min(radius / Viewer._autofocusConstants.minZ, 1);
552
- if (settings?.adjustWheelPrecision !== false) {
553
- activeCamera.wheelPrecision = Viewer._autofocusConstants.wheelPrecision / radius;
554
- }
555
- if (settings?.adjustPanningSensibility !== false) {
556
- activeCamera.panningSensibility = Viewer._autofocusConstants.panningSensibility / diameter;
557
- }
558
- if (settings?.adjustPinchPrecision !== false) {
559
- activeCamera.pinchPrecision = Viewer._autofocusConstants.pinchPrecision / radius;
560
- }
561
-
562
- const radiusFactor = settings?.radiusFactor ?? 1.5;
563
- const alpha = (settings?.alpha ?? -90) * (Math.PI / 180);
564
- const beta = (settings?.beta ?? 90) * (Math.PI / 180);
565
-
566
- const newCameraPosition = {
567
- alpha: alpha,
568
- beta: beta,
569
- // this calculation is a bit "simplified", as it doesn't consider the viewport ratio or the frustum angle
570
- // but it's also done this way in the Babylon.js repository, so it should be fine for us
571
- radius: diameter * radiusFactor,
572
- target: center,
573
- };
574
-
575
- await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation);
576
- }
577
-
578
- /**
579
- * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
580
- * environment
581
- */
582
- public async reset(tagManagerParameterValues: TagManagerParameterValue[]): Promise<Viewer> {
583
- await this.destroy();
584
- return this.bootstrap(tagManagerParameterValues);
585
- }
586
-
587
- /**
588
- * Destroys
589
- *
590
- * * all {@link VariantInstance}s using {@link destroyVariantInstances}
591
- * * calling `dispose` on the `Engine` and `Scene`
592
- */
593
- public destroy(): Viewer {
594
- this.destroyVariantInstances();
595
- this.scene.dispose();
596
- SpecStorage.destroy();
597
- return this;
598
- }
599
-
600
- /**
601
- * Show coordinate system with given dimension (for debugging purpose).
602
- */
603
- public showWorldCoordinates(dimension: number) {
604
- const scene = this.scene;
605
- const makeTextPlane = function (text: string, color: string, size: number) {
606
- const dynamicTexture = new DynamicTexture('DynamicTexture', 50, scene, true);
607
- dynamicTexture.hasAlpha = true;
608
- dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true);
609
- const plane = Mesh.CreatePlane('TextPlane', size, scene, true);
610
- plane.material = new StandardMaterial('TextPlaneMaterial', scene);
611
- plane.material.backFaceCulling = false;
612
- (plane.material as StandardMaterial).specularColor = new Color3(0, 0, 0);
613
- (plane.material as StandardMaterial).diffuseTexture = dynamicTexture;
614
- return plane;
615
- };
616
-
617
- const axisX = Mesh.CreateLines(
618
- 'axisX',
619
- [
620
- Vector3.Zero(),
621
- new Vector3(dimension, 0, 0),
622
- new Vector3(dimension * 0.95, 0.05 * dimension, 0),
623
- new Vector3(dimension, 0, 0),
624
- new Vector3(dimension * 0.95, -0.05 * dimension, 0),
625
- ],
626
- scene,
627
- false
628
- );
629
- axisX.color = new Color3(1, 0, 0);
630
- const xChar = makeTextPlane('X', 'red', dimension / 10);
631
- xChar.position = new Vector3(0.9 * dimension, -0.05 * dimension, 0);
632
- const axisY = Mesh.CreateLines(
633
- 'axisY',
634
- [
635
- Vector3.Zero(),
636
- new Vector3(0, dimension, 0),
637
- new Vector3(-0.05 * dimension, dimension * 0.95, 0),
638
- new Vector3(0, dimension, 0),
639
- new Vector3(0.05 * dimension, dimension * 0.95, 0),
640
- ],
641
- scene,
642
- false
643
- );
644
- axisY.color = new Color3(0, 1, 0);
645
- const yChar = makeTextPlane('Y', 'green', dimension / 10);
646
- yChar.position = new Vector3(0, 0.9 * dimension, -0.05 * dimension);
647
- const axisZ = Mesh.CreateLines(
648
- 'axisZ',
649
- [
650
- Vector3.Zero(),
651
- new Vector3(0, 0, dimension),
652
- new Vector3(0, -0.05 * dimension, dimension * 0.95),
653
- new Vector3(0, 0, dimension),
654
- new Vector3(0, 0.05 * dimension, dimension * 0.95),
655
- ],
656
- scene,
657
- false
658
- );
659
- axisZ.color = new Color3(0, 0, 1);
660
- const zChar = makeTextPlane('Z', 'blue', dimension / 10);
661
- zChar.position = new Vector3(0, 0.05 * dimension, 0.9 * dimension);
662
- }
663
-
664
- /**
665
- * Pause render loop.
666
- */
667
- public pauseRendering() {
668
- this._isRenderLoopPaused = true;
669
- }
670
-
671
- /**
672
- * Resume render loop when paused.
673
- */
674
- public resumeRendering() {
675
- this._isRenderLoopPaused = false;
676
- }
677
-
678
- /**
679
- * Prints defined instances from SetupJson to the console.
680
- */
681
- protected printInstanceDefinitions(setupJson: SetupJson) {
682
- console.info(
683
- 'The following variant instances have been read from the given spec: ',
684
- setupJson.instances.map(o => o.name)
685
- );
686
- }
687
-
688
- /**
689
- * @emits {@link Event.SCENE_PROCESSING_START}
690
- * @emits {@link Event.SCENE_PROCESSING_END}
691
- */
692
- protected async initScene(): Promise<Scene> {
693
- const sceneJson = SpecStorage.get<SceneJson>('scene');
694
- this.broadcastEvent(Event.SCENE_PROCESSING_START, sceneJson);
695
- const engine = new Engine(
696
- this.canvas as HTMLCanvasElement,
697
- sceneJson.engine?.antialiasing ?? false,
698
- sceneJson.engine?.options
699
- );
700
- const scene = await sceneSetup(engine, sceneJson);
701
- if (sceneJson.meshPicking) {
702
- new HighlightLayer('default', scene);
703
- scene.onPointerPick = (pointerEvent: IPointerEvent, pickInfo: PickingInfo) => {
704
- if (!pickInfo.hit) {
705
- return;
706
- }
707
- const mesh = pickInfo.pickedMesh;
708
- this.broadcastEvent(Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant);
709
- if (mesh?.metadata.element) {
710
- this.broadcastEvent(Event.ELEMENT_PICKED, mesh.metadata.element);
711
- }
712
- if (mesh?.metadata.variant) {
713
- if (mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
714
- mesh.metadata.variant.toggleHighlight();
715
- }
716
- this.broadcastEvent(Event.VARIANT_PICKED, mesh.metadata.variant);
717
- }
718
- };
719
- }
720
- this._sceneManager = await SceneManager.create(scene);
721
- this._animationManager = await AnimationManager.create(scene);
722
- if (sceneJson.cloneMaterialsOnMutation !== undefined) {
723
- this._cloneMaterialsOnMutation = sceneJson.cloneMaterialsOnMutation;
724
- }
725
- // register observers for tag manager
726
- this.tagManager.registerNewTransformNodeObservers(scene);
727
- this.broadcastEvent(Event.SCENE_PROCESSING_END, scene);
728
- return scene;
729
- }
730
-
731
- /**
732
- * Register custom file loader for babylon files which adds "missing-material" metadata to meshes which reference
733
- * materials that are not present in the `materials` section of the given babylon file.
734
- *
735
- * Required for babylon files & materials loaded from "Combeenation configurator assets".
736
- */
737
- protected initCbnBabylonLoaderPlugin() {
738
- const previousLoaderPlugin = SceneLoader.GetPluginForExtension('babylon') as ISceneLoaderPlugin;
739
- const customLoaderPlugin = getCustomCbnBabylonLoaderPlugin(previousLoaderPlugin);
740
- SceneLoader.RegisterPlugin(customLoaderPlugin);
741
- }
742
-
743
- /**
744
- * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
745
- */
746
- protected async createVariantInstances(
747
- tagManagerParameterValues?: TagManagerParameterValue[]
748
- ): Promise<VariantInstance[]> {
749
- const setupJson = SpecStorage.get<SetupJson>('setup');
750
- const instances: VariantInstance[] = [];
751
- for (const instanceDefinition of setupJson.instances) {
752
- if (isArray(tagManagerParameterValues)) {
753
- instanceDefinition.tagManagerParameterValues = tagManagerParameterValues;
754
- }
755
- // don't create the instance right away if `lazy` is set, register it for later creation (on first usage) instead
756
- // however if the variant should be `visible` by default, `lazy` loading doesn't make sense and should therefore
757
- // be overruled by the `visible` flag
758
- if (instanceDefinition.lazy && instanceDefinition.parameters?.visible !== true) {
759
- this.variantInstances.register(instanceDefinition);
760
- continue;
761
- }
762
- const instance = await this.variantInstances.create(
763
- instanceDefinition.variant,
764
- instanceDefinition.name,
765
- instanceDefinition.parameters,
766
- instanceDefinition.tagManagerParameterValues
767
- );
768
- instances.push(instance);
769
- }
770
- return instances;
771
- }
772
- }
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 { isMeshIncludedInExclusionList } 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 { isArray, 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
+ // create instance manager
312
+ this._variantInstances = await VariantInstanceManager.create(this);
313
+ // create optional default instances
314
+ if (indexJson.setup) {
315
+ if (isString(indexJson.setup)) {
316
+ const setupJson = await loadJson<SetupJson>(indexJson.setup);
317
+ indexJson.setup = setupJson;
318
+ }
319
+ this.printInstanceDefinitions(indexJson.setup);
320
+ await this.createVariantInstances(tagManagerParameterValues);
321
+ }
322
+ this.broadcastEvent(Event.VARIANT_INSTANCES_READY, this);
323
+ // create gltf export manager
324
+ this._gltfExportManager = await GltfExportManager.create(this);
325
+ // resize handler
326
+ window.addEventListener('resize', debounce(this.resize.bind(this), 100));
327
+ // wait until scene is completely ready
328
+ await this.scene.whenReadyAsync();
329
+ // event broadcasting
330
+ this.broadcastEvent(Event.BOOTSTRAP_END, this);
331
+ // render loop
332
+ this.engine.runRenderLoop(() => {
333
+ if (!this._isRenderLoopPaused) this.scene.render();
334
+ });
335
+ return this;
336
+ }
337
+
338
+ /**
339
+ * Enables the Babylon.js [Inspector](https://doc.babylonjs.com/toolsAndResources/tools/inspector).\
340
+ * Due to the additional size of the inspector, the CDN version is used instead of shipping the required code with
341
+ * the viewer.\
342
+ * This means that the code will be downloaded only when needed and calling `enableDebugLayer` can take a little while
343
+ * depending on your internet connection etc.
344
+ */
345
+ public async enableDebugLayer(options?: IInspectorOptions) {
346
+ if (!this._inspectorLoaded) {
347
+ // CDN version of inspector requires the Babylon.js core to be available as CDN module as well
348
+ await loadJavascript('https://cdn.jsdelivr.net/npm/babylonjs@5.6.0/babylon.min.js');
349
+
350
+ DebugLayer.InspectorURL =
351
+ 'https://cdn.jsdelivr.net/npm/babylonjs-inspector@5.6.0/babylon.inspector.bundle.max.min.js';
352
+
353
+ this._inspectorLoaded = true;
354
+ }
355
+
356
+ await this.scene.debugLayer.show(options);
357
+ }
358
+
359
+ /**
360
+ * Destroys all registered {@link VariantInstance}s that are registered
361
+ */
362
+ public destroyVariantInstances(): Viewer {
363
+ this.variantInstances.all.forEach(variantInstance => {
364
+ this.variantInstances.destroy(variantInstance.name);
365
+ });
366
+ return this;
367
+ }
368
+
369
+ /**
370
+ * Trigger a resize event for the `Engine`
371
+ */
372
+ public resize(): Viewer {
373
+ this.engine.resize();
374
+ return this;
375
+ }
376
+
377
+ /**
378
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
379
+ * {@link DottedPath}s.
380
+ */
381
+ public async getNode(
382
+ variantInstanceName: string,
383
+ elementDottedPath: DottedPathArgument,
384
+ nodeDottedPath: DottedPathArgument
385
+ ): Promise<TransformNode> {
386
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
387
+ return variantInstance.getNode(elementDottedPath, nodeDottedPath);
388
+ }
389
+
390
+ /**
391
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
392
+ * {@link DottedPath}s.
393
+ */
394
+ public async getMesh(
395
+ variantInstanceName: string,
396
+ elementDottedPath: DottedPathArgument,
397
+ meshDottedPath: DottedPathArgument
398
+ ): Promise<Mesh | null> {
399
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
400
+ return variantInstance.getMesh(elementDottedPath, meshDottedPath);
401
+ }
402
+
403
+ /**
404
+ * Switches the camera
405
+ *
406
+ * @emits {@link Event.CAMERA_SWITCHED}
407
+ */
408
+ public switchCamera(newCamera: string, reset: boolean = true): Viewer {
409
+ const camera = this.scene.getCameraByName(newCamera);
410
+ if (camera) {
411
+ const activeCamera = this.scene.activeCamera;
412
+ if (activeCamera) {
413
+ activeCamera.detachControl(this.engine.getRenderingCanvas()!);
414
+ }
415
+ if (reset) {
416
+ camera.restoreState();
417
+ }
418
+ this.scene.setActiveCameraByName(newCamera);
419
+ camera.attachControl(this.engine.getRenderingCanvas()!);
420
+ this.broadcastEvent(Event.CAMERA_SWITCHED, camera);
421
+ } else {
422
+ throw new Error(`Given camera "${newCamera}" not found.`);
423
+ }
424
+ // TODO: put traceable observers to new camera (@see element)
425
+ return this;
426
+ }
427
+
428
+ /**
429
+ * Moves or animates the active camera to given `placement`.
430
+ */
431
+ public async moveActiveCameraTo(
432
+ placement: string | PlacementDefinition,
433
+ animation?: string | AnimationDefinition
434
+ ): Promise<AnimationInterface> {
435
+ return this.animationManager.animateToPlacement(this.sceneManager.activeCamera, placement, animation);
436
+ }
437
+
438
+ /**
439
+ * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
440
+ */
441
+ public screenshot(settings?: ScreenshotSettings): Promise<string> {
442
+ return new Promise((resolve, reject) => {
443
+ if (!this.engine) {
444
+ return reject('Engine is null');
445
+ }
446
+ if (!this.scene) {
447
+ return reject('Scene is null');
448
+ }
449
+ this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
450
+ ScreenshotTools.CreateScreenshotUsingRenderTarget(
451
+ this.engine,
452
+ this.sceneManager.activeCamera,
453
+ settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
454
+ resolve,
455
+ settings?.mimeType ?? 'image/png',
456
+ settings?.samples ?? 1,
457
+ settings?.antialiasing ?? false,
458
+ settings?.fileName ?? 'screenshot.png',
459
+ settings?.renderSprites ?? false
460
+ );
461
+ });
462
+ }
463
+
464
+ /**
465
+ * Checks whether the browser is capable of handling XR.
466
+ */
467
+ public async isBrowserARCapable(): Promise<boolean> {
468
+ return await WebXRSessionManager.IsSessionSupportedAsync('immersive-ar');
469
+ }
470
+
471
+ /**
472
+ * Calculates the bounding box from all visible meshes on the scene.
473
+ */
474
+ public async calculateBoundingBox(excludeGeometry?: ExcludedGeometryList): Promise<Mesh> {
475
+ if (this.scene.meshes.length === 0) {
476
+ throw new Error('There are currently no meshes on the scene.');
477
+ }
478
+ this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
479
+ const { max, min } = this.scene.meshes
480
+ .filter(mesh => {
481
+ const isEnabled = mesh.isEnabled();
482
+ // ignore the existing bounding box mesh for calculating the current one
483
+ const isNotBBoxMesh = Viewer.BOUNDING_BOX_NAME !== mesh.id;
484
+ // ignore meshes with invalid bounding infos
485
+ const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
486
+ // ignore meshes with infinite distance, typically these are sky boxes
487
+ const hasInfiniteDistance = mesh.infiniteDistance;
488
+ // ignore excluded meshes
489
+ const isExcluded = excludeGeometry ? isMeshIncludedInExclusionList(mesh as Mesh, excludeGeometry) : false;
490
+ return isEnabled && isNotBBoxMesh && hasValidBBoxInfo && !hasInfiniteDistance && !isExcluded;
491
+ })
492
+ .reduce(
493
+ (accBBoxMinMax, curMesh, idx) => {
494
+ const bBox = curMesh.getBoundingInfo().boundingBox;
495
+ // use the first entry in the array as default value and get the resulting maximum/minimum values
496
+ const max = idx === 0 ? bBox.maximumWorld : Vector3.Maximize(accBBoxMinMax.max, bBox.maximumWorld);
497
+ const min = idx === 0 ? bBox.minimumWorld : Vector3.Minimize(accBBoxMinMax.min, bBox.minimumWorld);
498
+ return { max, min };
499
+ },
500
+ { max: new Vector3(), min: new Vector3() }
501
+ );
502
+
503
+ let boundingBox = this.scene.getMeshByName(Viewer.BOUNDING_BOX_NAME) as Mesh;
504
+ if (!boundingBox) {
505
+ boundingBox = new Mesh(Viewer.BOUNDING_BOX_NAME, this.scene);
506
+ }
507
+ boundingBox.setBoundingInfo(new BoundingInfo(min, max));
508
+ return boundingBox;
509
+ }
510
+
511
+ /**
512
+ * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning
513
+ */
514
+ public async autofocusActiveCamera(settings?: AutofocusSettings) {
515
+ // first check some preconditions
516
+ const activeCamera = this.scene.activeCamera;
517
+ if (!activeCamera) {
518
+ throw new Error('No active camera found when using autofocus feature.');
519
+ }
520
+ if (!(activeCamera instanceof ArcRotateCamera)) {
521
+ const cameraClsName = activeCamera.getClassName();
522
+ throw new Error(`Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.`);
523
+ }
524
+
525
+ let exclude = settings?.exclude || [];
526
+
527
+ // Exclude shown photo dome or environment helper from bounding box calculation
528
+ const photoDome = this.scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
529
+ const photoDomeMeshes = photoDome?.getChildMeshes();
530
+ if (photoDomeMeshes?.length) {
531
+ exclude = [...exclude, ...photoDomeMeshes];
532
+ }
533
+
534
+ const envHelper = this.scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
535
+ if (envHelper?.rootMesh) {
536
+ exclude = [...exclude, envHelper.rootMesh];
537
+ }
538
+
539
+ // get bounding box of all visible meshes, this is the base for the autofocus algorithm
540
+ const boundingBox = await this.calculateBoundingBox(exclude);
541
+
542
+ const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
543
+ const center = boundingBox.getBoundingInfo().boundingSphere.center;
544
+ const diameter = radius * 2;
545
+
546
+ // set lower radius limit on edge of bounding sphere to make sure that we can't dive into the meshes
547
+ activeCamera.lowerRadiusLimit = radius;
548
+
549
+ // additional settings
550
+ // constants for division are taken directly from Babylon.js repository
551
+ activeCamera.minZ = Math.min(radius / Viewer._autofocusConstants.minZ, 1);
552
+ if (settings?.adjustWheelPrecision !== false) {
553
+ activeCamera.wheelPrecision = Viewer._autofocusConstants.wheelPrecision / radius;
554
+ }
555
+ if (settings?.adjustPanningSensibility !== false) {
556
+ activeCamera.panningSensibility = Viewer._autofocusConstants.panningSensibility / diameter;
557
+ }
558
+ if (settings?.adjustPinchPrecision !== false) {
559
+ activeCamera.pinchPrecision = Viewer._autofocusConstants.pinchPrecision / radius;
560
+ }
561
+
562
+ const radiusFactor = settings?.radiusFactor ?? 1.5;
563
+ const alpha = (settings?.alpha ?? -90) * (Math.PI / 180);
564
+ const beta = (settings?.beta ?? 90) * (Math.PI / 180);
565
+
566
+ const newCameraPosition = {
567
+ alpha: alpha,
568
+ beta: beta,
569
+ // this calculation is a bit "simplified", as it doesn't consider the viewport ratio or the frustum angle
570
+ // but it's also done this way in the Babylon.js repository, so it should be fine for us
571
+ radius: diameter * radiusFactor,
572
+ target: center,
573
+ };
574
+
575
+ await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation);
576
+ }
577
+
578
+ /**
579
+ * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
580
+ * environment
581
+ */
582
+ public async reset(tagManagerParameterValues: TagManagerParameterValue[]): Promise<Viewer> {
583
+ await this.destroy();
584
+ return this.bootstrap(tagManagerParameterValues);
585
+ }
586
+
587
+ /**
588
+ * Destroys
589
+ *
590
+ * * all {@link VariantInstance}s using {@link destroyVariantInstances}
591
+ * * calling `dispose` on the `Engine` and `Scene`
592
+ */
593
+ public destroy(): Viewer {
594
+ this.destroyVariantInstances();
595
+ this.engine.dispose();
596
+ SpecStorage.destroy();
597
+ return this;
598
+ }
599
+
600
+ /**
601
+ * Show coordinate system with given dimension (for debugging purpose).
602
+ */
603
+ public showWorldCoordinates(dimension: number) {
604
+ const scene = this.scene;
605
+ const makeTextPlane = function (text: string, color: string, size: number) {
606
+ const dynamicTexture = new DynamicTexture('DynamicTexture', 50, scene, true);
607
+ dynamicTexture.hasAlpha = true;
608
+ dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true);
609
+ const plane = Mesh.CreatePlane('TextPlane', size, scene, true);
610
+ plane.material = new StandardMaterial('TextPlaneMaterial', scene);
611
+ plane.material.backFaceCulling = false;
612
+ (plane.material as StandardMaterial).specularColor = new Color3(0, 0, 0);
613
+ (plane.material as StandardMaterial).diffuseTexture = dynamicTexture;
614
+ return plane;
615
+ };
616
+
617
+ const axisX = Mesh.CreateLines(
618
+ 'axisX',
619
+ [
620
+ Vector3.Zero(),
621
+ new Vector3(dimension, 0, 0),
622
+ new Vector3(dimension * 0.95, 0.05 * dimension, 0),
623
+ new Vector3(dimension, 0, 0),
624
+ new Vector3(dimension * 0.95, -0.05 * dimension, 0),
625
+ ],
626
+ scene,
627
+ false
628
+ );
629
+ axisX.color = new Color3(1, 0, 0);
630
+ const xChar = makeTextPlane('X', 'red', dimension / 10);
631
+ xChar.position = new Vector3(0.9 * dimension, -0.05 * dimension, 0);
632
+ const axisY = Mesh.CreateLines(
633
+ 'axisY',
634
+ [
635
+ Vector3.Zero(),
636
+ new Vector3(0, dimension, 0),
637
+ new Vector3(-0.05 * dimension, dimension * 0.95, 0),
638
+ new Vector3(0, dimension, 0),
639
+ new Vector3(0.05 * dimension, dimension * 0.95, 0),
640
+ ],
641
+ scene,
642
+ false
643
+ );
644
+ axisY.color = new Color3(0, 1, 0);
645
+ const yChar = makeTextPlane('Y', 'green', dimension / 10);
646
+ yChar.position = new Vector3(0, 0.9 * dimension, -0.05 * dimension);
647
+ const axisZ = Mesh.CreateLines(
648
+ 'axisZ',
649
+ [
650
+ Vector3.Zero(),
651
+ new Vector3(0, 0, dimension),
652
+ new Vector3(0, -0.05 * dimension, dimension * 0.95),
653
+ new Vector3(0, 0, dimension),
654
+ new Vector3(0, 0.05 * dimension, dimension * 0.95),
655
+ ],
656
+ scene,
657
+ false
658
+ );
659
+ axisZ.color = new Color3(0, 0, 1);
660
+ const zChar = makeTextPlane('Z', 'blue', dimension / 10);
661
+ zChar.position = new Vector3(0, 0.05 * dimension, 0.9 * dimension);
662
+ }
663
+
664
+ /**
665
+ * Pause render loop.
666
+ */
667
+ public pauseRendering() {
668
+ this._isRenderLoopPaused = true;
669
+ }
670
+
671
+ /**
672
+ * Resume render loop when paused.
673
+ */
674
+ public resumeRendering() {
675
+ this._isRenderLoopPaused = false;
676
+ }
677
+
678
+ /**
679
+ * Prints defined instances from SetupJson to the console.
680
+ */
681
+ protected printInstanceDefinitions(setupJson: SetupJson) {
682
+ console.info(
683
+ 'The following variant instances have been read from the given spec: ',
684
+ setupJson.instances.map(o => o.name)
685
+ );
686
+ }
687
+
688
+ /**
689
+ * @emits {@link Event.SCENE_PROCESSING_START}
690
+ * @emits {@link Event.SCENE_PROCESSING_END}
691
+ */
692
+ protected async initScene(): Promise<Scene> {
693
+ const sceneJson = SpecStorage.get<SceneJson>('scene');
694
+ this.broadcastEvent(Event.SCENE_PROCESSING_START, sceneJson);
695
+ const engine = new Engine(
696
+ this.canvas as HTMLCanvasElement,
697
+ sceneJson.engine?.antialiasing ?? false,
698
+ sceneJson.engine?.options
699
+ );
700
+ const scene = await sceneSetup(engine, sceneJson);
701
+ if (sceneJson.meshPicking) {
702
+ new HighlightLayer('default', scene);
703
+ scene.onPointerPick = (pointerEvent: IPointerEvent, pickInfo: PickingInfo) => {
704
+ if (!pickInfo.hit) {
705
+ return;
706
+ }
707
+ const mesh = pickInfo.pickedMesh;
708
+ this.broadcastEvent(Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant);
709
+ if (mesh?.metadata.element) {
710
+ this.broadcastEvent(Event.ELEMENT_PICKED, mesh.metadata.element);
711
+ }
712
+ if (mesh?.metadata.variant) {
713
+ if (mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
714
+ mesh.metadata.variant.toggleHighlight();
715
+ }
716
+ this.broadcastEvent(Event.VARIANT_PICKED, mesh.metadata.variant);
717
+ }
718
+ };
719
+ }
720
+ this._sceneManager = await SceneManager.create(scene);
721
+ this._animationManager = await AnimationManager.create(scene);
722
+ if (sceneJson.cloneMaterialsOnMutation !== undefined) {
723
+ this._cloneMaterialsOnMutation = sceneJson.cloneMaterialsOnMutation;
724
+ }
725
+ // register observers for tag manager
726
+ this.tagManager.registerNewTransformNodeObservers(scene);
727
+ this.broadcastEvent(Event.SCENE_PROCESSING_END, scene);
728
+ return scene;
729
+ }
730
+
731
+ /**
732
+ * Register custom file loader for babylon files which adds "missing-material" metadata to meshes which reference
733
+ * materials that are not present in the `materials` section of the given babylon file.
734
+ *
735
+ * Required for babylon files & materials loaded from "Combeenation configurator assets".
736
+ */
737
+ protected initCbnBabylonLoaderPlugin() {
738
+ const previousLoaderPlugin = SceneLoader.GetPluginForExtension('babylon') as ISceneLoaderPlugin;
739
+ const customLoaderPlugin = getCustomCbnBabylonLoaderPlugin(previousLoaderPlugin);
740
+ SceneLoader.RegisterPlugin(customLoaderPlugin);
741
+ }
742
+
743
+ /**
744
+ * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
745
+ */
746
+ protected async createVariantInstances(
747
+ tagManagerParameterValues?: TagManagerParameterValue[]
748
+ ): Promise<VariantInstance[]> {
749
+ const setupJson = SpecStorage.get<SetupJson>('setup');
750
+ const instances: VariantInstance[] = [];
751
+ for (const instanceDefinition of setupJson.instances) {
752
+ if (isArray(tagManagerParameterValues)) {
753
+ instanceDefinition.tagManagerParameterValues = tagManagerParameterValues;
754
+ }
755
+ // don't create the instance right away if `lazy` is set, register it for later creation (on first usage) instead
756
+ // however if the variant should be `visible` by default, `lazy` loading doesn't make sense and should therefore
757
+ // be overruled by the `visible` flag
758
+ if (instanceDefinition.lazy && instanceDefinition.parameters?.visible !== true) {
759
+ this.variantInstances.register(instanceDefinition);
760
+ continue;
761
+ }
762
+ const instance = await this.variantInstances.create(
763
+ instanceDefinition.variant,
764
+ instanceDefinition.name,
765
+ instanceDefinition.parameters,
766
+ instanceDefinition.tagManagerParameterValues
767
+ );
768
+ instances.push(instance);
769
+ }
770
+ return instances;
771
+ }
772
+ }