@combeenation/3d-viewer 4.2.0 → 5.0.0-alpha1

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 (95) hide show
  1. package/README.md +2 -2
  2. package/dist/lib-cjs/api/classes/dottedPath.js +2 -5
  3. package/dist/lib-cjs/api/classes/dottedPath.js.map +1 -1
  4. package/dist/lib-cjs/api/classes/element.d.ts +9 -0
  5. package/dist/lib-cjs/api/classes/element.js +114 -66
  6. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  7. package/dist/lib-cjs/api/classes/event.js.map +1 -1
  8. package/dist/lib-cjs/api/classes/eventBroadcaster.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/parameter.js +3 -2
  10. package/dist/lib-cjs/api/classes/parameter.js.map +1 -1
  11. package/dist/lib-cjs/api/classes/parameterObservable.js.map +1 -1
  12. package/dist/lib-cjs/api/classes/parameterizable.js.map +1 -1
  13. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +1 -0
  14. package/dist/lib-cjs/api/classes/placementAnimation.js +2 -2
  15. package/dist/lib-cjs/api/classes/placementAnimation.js.map +1 -1
  16. package/dist/lib-cjs/api/classes/variant.js +26 -19
  17. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  18. package/dist/lib-cjs/api/classes/variantInstance.js +19 -19
  19. package/dist/lib-cjs/api/classes/variantInstance.js.map +1 -1
  20. package/dist/lib-cjs/api/classes/variantParameterizable.js.map +1 -1
  21. package/dist/lib-cjs/api/classes/viewer.d.ts +40 -1
  22. package/dist/lib-cjs/api/classes/viewer.js +144 -48
  23. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  24. package/dist/lib-cjs/api/classes/viewerLight.js +25 -25
  25. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  26. package/dist/lib-cjs/api/internal/debugViewer.js +1 -2
  27. package/dist/lib-cjs/api/internal/debugViewer.js.map +1 -1
  28. package/dist/lib-cjs/api/internal/lensRendering.js.map +1 -1
  29. package/dist/lib-cjs/api/internal/sceneSetup.js +25 -22
  30. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  31. package/dist/lib-cjs/api/manager/animationManager.js +24 -15
  32. package/dist/lib-cjs/api/manager/animationManager.js.map +1 -1
  33. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +40 -10
  34. package/dist/lib-cjs/api/manager/gltfExportManager.js +135 -20
  35. package/dist/lib-cjs/api/manager/gltfExportManager.js.map +1 -1
  36. package/dist/lib-cjs/api/manager/sceneManager.js +3 -3
  37. package/dist/lib-cjs/api/manager/sceneManager.js.map +1 -1
  38. package/dist/lib-cjs/api/manager/variantInstanceManager.js +10 -7
  39. package/dist/lib-cjs/api/manager/variantInstanceManager.js.map +1 -1
  40. package/dist/lib-cjs/api/store/specStorage.js.map +1 -1
  41. package/dist/lib-cjs/api/util/babylonHelper.d.ts +1 -1
  42. package/dist/lib-cjs/api/util/babylonHelper.js +12 -15
  43. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  44. package/dist/lib-cjs/api/util/globalTypes.d.ts +41 -25
  45. package/dist/lib-cjs/api/util/resourceHelper.js +3 -1
  46. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  47. package/dist/lib-cjs/api/util/stringHelper.d.ts +1 -1
  48. package/dist/lib-cjs/api/util/stringHelper.js +2 -2
  49. package/dist/lib-cjs/api/util/stringHelper.js.map +1 -1
  50. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -0
  51. package/dist/lib-cjs/api/util/structureHelper.js +45 -0
  52. package/dist/lib-cjs/api/util/structureHelper.js.map +1 -0
  53. package/dist/lib-cjs/index.js +1 -0
  54. package/dist/lib-cjs/index.js.map +1 -1
  55. package/package.json +11 -7
  56. package/src/api/classes/animationInterface.ts +4 -6
  57. package/src/api/classes/dottedPath.ts +179 -187
  58. package/src/api/classes/element.ts +665 -621
  59. package/src/api/classes/event.ts +310 -313
  60. package/src/api/classes/eventBroadcaster.ts +47 -49
  61. package/src/api/classes/parameter.ts +394 -397
  62. package/src/api/classes/parameterObservable.ts +84 -83
  63. package/src/api/classes/parameterizable.ts +71 -73
  64. package/src/api/classes/placementAnimation.ts +130 -130
  65. package/src/api/classes/variant.ts +806 -778
  66. package/src/api/classes/variantInstance.ts +60 -52
  67. package/src/api/classes/variantParameterizable.ts +72 -67
  68. package/src/api/classes/viewer.ts +592 -490
  69. package/src/api/classes/viewerLight.ts +301 -301
  70. package/src/api/internal/debugViewer.ts +61 -53
  71. package/src/api/internal/lensRendering.ts +2 -3
  72. package/src/api/internal/sceneSetup.ts +144 -137
  73. package/src/api/manager/animationManager.ts +122 -97
  74. package/src/api/manager/gltfExportManager.ts +192 -0
  75. package/src/api/manager/sceneManager.ts +83 -86
  76. package/src/api/manager/variantInstanceManager.ts +234 -224
  77. package/src/api/store/specStorage.ts +48 -51
  78. package/src/api/util/babylonHelper.ts +329 -325
  79. package/src/api/util/globalTypes.ts +260 -246
  80. package/src/api/util/resourceHelper.ts +97 -109
  81. package/src/api/util/stringHelper.ts +13 -16
  82. package/src/api/util/structureHelper.ts +43 -0
  83. package/src/buildinfo.json +2 -2
  84. package/src/commonjs.tsconfig.json +8 -11
  85. package/src/declaration.tsconfig.json +6 -8
  86. package/src/dev.ts +28 -29
  87. package/src/es6.tsconfig.json +8 -11
  88. package/src/index.ts +40 -39
  89. package/src/pagesconfig.json +4 -0
  90. package/src/tsconfig.json +30 -41
  91. package/src/tsconfig.types.json +8 -9
  92. package/src/types.d.ts +0 -1
  93. package/dist/lib-cjs/api/classes/elementParameterizable.d.ts +0 -14
  94. package/dist/lib-cjs/api/classes/elementParameterizable.js +0 -135
  95. package/dist/lib-cjs/api/classes/elementParameterizable.js.map +0 -1
@@ -1,3 +1,4 @@
1
+ import { AbstractMesh, IPointerEvent } from '@babylonjs/core';
1
2
  import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
2
3
  import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
3
4
  import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
@@ -10,21 +11,23 @@ import { Vector3 } from '@babylonjs/core/Maths/math.vector';
10
11
  import { Mesh } from '@babylonjs/core/Meshes/mesh';
11
12
  import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
12
13
  import { Scene } from '@babylonjs/core/scene';
14
+ import { WebXRSessionManager } from '@babylonjs/core/XR/webXRSessionManager';
15
+ import { isMeshIncludedInExclusionList } from '../util/structureHelper';
13
16
  import { isString } from 'lodash-es';
14
17
  import { version } from '../../buildinfo.json';
15
18
  import { sceneSetup } from '../internal/sceneSetup';
16
19
  import { AnimationManager } from '../manager/animationManager';
20
+ import { GltfExportManager } from '../manager/gltfExportManager';
17
21
  import { SceneManager } from '../manager/sceneManager';
18
22
  import { VariantInstanceManager } from '../manager/variantInstanceManager';
19
23
  import { SpecStorage } from '../store/specStorage';
20
- import { debounce, loadJson, sleep } from '../util/resourceHelper';
24
+ import { debounce, loadJson } from '../util/resourceHelper';
21
25
  import { Event } from './event';
22
26
  import { EventBroadcaster } from './eventBroadcaster';
23
27
  import { Parameter } from './parameter';
24
28
  import { Variant } from './variant';
25
29
  import { VariantInstance } from './variantInstance';
26
30
 
27
-
28
31
  /**
29
32
  * The main exposed object. This is the entry point into the application
30
33
  *
@@ -35,491 +38,590 @@ import { VariantInstance } from './variantInstance';
35
38
  * The class does nothing on its own and needs to {@link bootstrap}
36
39
  */
37
40
  export class Viewer extends EventBroadcaster {
38
-
39
- protected _scene: Scene | null = null;
40
-
41
- protected _animationManager: AnimationManager | null = null;
42
-
43
- protected _sceneManager: SceneManager | null = null;
44
-
45
- protected _variantInstances: VariantInstanceManager | null = null;
46
-
47
- static version = version;
48
-
49
- /**
50
- * Constructor
51
- */
52
- public constructor( public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson ) {
53
- super();
54
- }
55
-
56
- /**
57
- * Gets the BabylonJS Scene that is attached to the instance.
58
- *
59
- * @throws Error if the `scene` has not been initialized.
60
- */
61
- get scene(): Scene {
62
- if( !this._scene ) {
63
- throw new Error( `Scene has not been initialized.` );
64
- }
65
- return this._scene;
66
- }
67
-
68
- get sceneManager(): SceneManager {
69
- if( !this._sceneManager ) {
70
- throw new Error( `Environment has not been initialized.` );
71
- }
72
- return this._sceneManager;
73
- }
74
-
75
- /**
76
- * Gets the BabylonJS Engine that is attached to the viewer.
77
- */
78
- get engine(): Engine {
79
- return this.scene.getEngine();
80
- }
81
-
82
- /**
83
- * Gets the {@link VariantInstanceManager} attached to the viewer.
84
- *
85
- * @throws Error if the {@link VariantInstanceManager} has not been initialized.
86
- */
87
- get variantInstances(): VariantInstanceManager {
88
- if( !this._variantInstances ) {
89
- throw Error( `There is no variantInstanceManager.` );
90
- }
91
- return this._variantInstances;
92
- }
93
-
94
- /**
95
- * Gets the {@link AnimationManager} attached to the viewer.
96
- *
97
- * @throws Error if the {@link AnimationManager} has not been initialized.
98
- */
99
- get animationManager(): AnimationManager {
100
- if( !this._animationManager ) {
101
- throw new Error( `There is no animationManager instance.` );
102
- }
103
- return this._animationManager;
104
- }
105
-
106
- /**
107
- * Starts the application. This will
108
- * * load the given "index" JSON file
109
- * * setup the scene with the "scene" JSON file
110
- * * create an (optional) default setup with different variant settings
111
- * * sets up resizing by attaching a debounced version of {@link resize}
112
- *
113
- * @throws Error if any of the files is not found/valid
114
- *
115
- * @emits {@link Event.BOOTSTRAP_START}
116
- * @emits {@link Event.BOOTSTRAP_END}
117
- */
118
- public async bootstrap(): Promise<Viewer> {
119
- this.broadcastEvent( Event.BOOTSTRAP_START, this );
120
- let indexJson;
121
- if( isString( this.structureJson ) ) {
122
- indexJson = await loadJson<StructureJson>( this.structureJson );
123
- } else {
124
- indexJson = this.structureJson;
125
- }
126
- if( !indexJson.scene ) {
127
- throw new Error( `No "scene" property found for bootstrapping.` );
128
- }
129
- // fill spec store
130
- SpecStorage.createFromSpec( indexJson );
131
- // load scene
132
- if( isString( indexJson.scene ) ) {
133
- const sceneJson = await loadJson<SceneJson>( indexJson.scene );
134
- indexJson.scene = sceneJson;
135
- }
136
- this._scene = await this.initScene();
137
- // create instance manager
138
- const rootVariant = await Variant.create( '_', indexJson, this );
139
- this._variantInstances = await VariantInstanceManager.create( rootVariant );
140
- // create optional default instances
141
- if( indexJson.setup ) {
142
- if( isString( indexJson.setup ) ) {
143
- const setupJson = await loadJson<SetupJson>( indexJson.setup );
144
- indexJson.setup = setupJson;
145
- }
146
- await this.createVariantInstances();
147
- }
148
- // resize handler
149
- window.addEventListener( 'resize', debounce( this.resize.bind( this ), 100 ) );
150
- // wait until scene is completely ready
151
- await this.scene.whenReadyAsync();
152
- // event broadcasting
153
- this.broadcastEvent( Event.BOOTSTRAP_END, this );
154
- // render loop
155
- this.engine.runRenderLoop( () => {
156
- this.scene.render();
157
- } );
158
- return this;
159
- }
160
-
161
- // Disabled for now to decrease bundle size.
162
- // See https://github.com/Combeenation/3d-viewer/issues/37
163
- // /**
164
- // * Enables the BabylonJS DebugLayer. If you pass options, be sure to pass an Object of type `IInspectorOptions`.
165
- // */
166
- // public async enableDebugLayer(options?: any) {
167
- // // @ts-ignore
168
- // await import(/* webpackChunkName: "debug-inspector" */'@babylonjs/inspector');
169
- // await this.scene.debugLayer.show(options);
170
- // return this;
171
- // }
172
-
173
- /**
174
- * Destroys all registered {@link VariantInstance}s that are registered
175
- */
176
- public destroyVariantInstances(): Viewer {
177
- this.variantInstances.all.forEach( variantInstance => {
178
- this.variantInstances.destroy( variantInstance.name );
179
- } );
180
- return this;
181
- }
182
-
183
- /**
184
- * Trigger a resize event for the `Engine`
185
- */
186
- public resize(): Viewer {
187
- this.engine.resize();
188
- return this;
189
- }
190
-
191
- /**
192
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
193
- * {@link DottedPath}s.
194
- */
195
- public async getNode( variantInstanceName: string,
196
- elementDottedPath: DottedPathArgument,
197
- nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
198
- const variantInstance = await this.variantInstances.get(variantInstanceName);
199
- return variantInstance.getNode( elementDottedPath, nodeDottedPath );
200
- }
201
-
202
- /**
203
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
204
- * {@link DottedPath}s.
205
- */
206
- public async getMesh( variantInstanceName: string,
207
- elementDottedPath: DottedPathArgument,
208
- meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
209
- const variantInstance = await this.variantInstances.get(variantInstanceName);
210
- return variantInstance.getMesh( elementDottedPath, meshDottedPath );
211
- }
212
-
213
- /**
214
- * Switches the camera
215
- *
216
- * @emits {@link Event.CAMERA_SWITCHED}
217
- */
218
- public switchCamera( newCamera: string, reset: boolean = true ): Viewer {
219
- const camera = this.scene.getCameraByName( newCamera );
220
- if( camera ) {
221
- const activeCamera = this.scene.activeCamera;
222
- if( activeCamera ) {
223
- activeCamera.detachControl( this.engine.getRenderingCanvas()! );
224
- }
225
- if( reset ) {
226
- camera.restoreState();
227
- }
228
- this.scene.setActiveCameraByName( newCamera );
229
- camera.attachControl( this.engine.getRenderingCanvas()! );
230
- this.broadcastEvent( Event.CAMERA_SWITCHED, camera );
231
- } else {
232
- throw new Error( `Given camera "${newCamera}" not found.` );
233
- }
234
- // TODO: put traceable observers to new camera (@see element)
235
- return this;
236
- }
237
-
238
- /**
239
- * Moves or animates the active camera to given `placement`.
240
- */
241
- public async moveActiveCameraTo( placement: string | PlacementDefinition,
242
- animation?: string | AnimationDefinition ): Promise<AnimationInterface> {
243
- return this.animationManager.animateToPlacement( this.sceneManager.activeCamera, placement, animation );
244
- }
245
-
246
- /**
247
- * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
248
- */
249
- public screenshot( settings?: ScreenshotSettings ): Promise<string> {
250
- return new Promise( ( resolve, reject ) => {
251
- if( !this.engine ) {
252
- return reject( 'Engine is null' );
253
- }
254
- if( !this.scene ) {
255
- return reject( 'Scene is null' );
256
- }
257
- this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
258
- ScreenshotTools.CreateScreenshotUsingRenderTarget(
259
- this.engine,
260
- this.sceneManager.activeCamera,
261
- settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
262
- resolve,
263
- settings?.mimeType ?? 'image/png',
264
- settings?.samples ?? 1,
265
- settings?.antialiasing ?? false,
266
- settings?.fileName ?? 'screenshot.png',
267
- settings?.renderSprites ?? false
268
- );
269
- } );
270
- }
271
-
272
- /**
273
- * Calculates the bounding box from all visible meshes on the scene.
274
- */
275
- public async calculateBoundingBox(): Promise<Mesh> {
276
- if( this.scene.meshes.length === 0 ) {
277
- throw new Error( 'There are currently no meshes on the scene.' );
278
- }
279
- this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
280
- const bbName = '__bounding_box__';
281
-
282
- const { max, min } = this.scene.meshes.filter( mesh => {
283
- const isEnabled = mesh.isEnabled();
284
- // ignore the existing bounding box mesh for calculating the current one
285
- const isNotBBoxMesh = bbName !== mesh.id;
286
- // ignore meshes with invalid bounding infos
287
- const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
288
- return isEnabled && isNotBBoxMesh && hasValidBBoxInfo;
289
- } ).reduce( ( accBBoxMinMax, curMesh, idx ) => {
290
- const bBox = curMesh.getBoundingInfo().boundingBox;
291
- // use the first entry in the array as default value and get the resulting maximum/minimum values
292
- const max = ( idx === 0 ) ? bBox.maximumWorld : Vector3.Maximize( accBBoxMinMax.max, bBox.maximumWorld )
293
- const min = ( idx === 0 ) ? bBox.minimumWorld : Vector3.Minimize( accBBoxMinMax.min, bBox.minimumWorld )
294
- return { max, min }
295
- }, { max: new Vector3(), min: new Vector3() } );
296
-
297
- let boundingBox = this.scene.getMeshByName( bbName ) as Mesh;
298
- if( !boundingBox ) {
299
- boundingBox = new Mesh( bbName, this.scene );
300
- }
301
- boundingBox.setBoundingInfo( new BoundingInfo( min, max ) );
302
- return boundingBox;
303
- }
304
-
305
- public async autofocusActiveCamera( settings?: AutofocusSettings ) {
306
- // first check some preconditions
307
- const activeCamera = this.scene.activeCamera;
308
- if ( !activeCamera ) {
309
- throw new Error("No active camera found when using autofocus feature.");
310
- }
311
- if ( !( activeCamera instanceof ArcRotateCamera ) ) {
312
- const cameraClsName = activeCamera.getClassName();
313
- throw new Error( `Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.` );
314
- }
315
-
316
- // get bounding box of all visible meshes, this is the base for the autofocus algorithm
317
- const boundingBox = await this.calculateBoundingBox();
318
-
319
- // focus the helper camera and set the calculated camera data to the real camera
320
- const helperCamera = this.getFocusedHelperCamera( boundingBox, settings )
321
- await this.applyFocusedHelperCameraData( activeCamera, helperCamera, settings )
322
-
323
- // remove the helper camera
324
- helperCamera.dispose();
325
- }
326
-
327
- /**
328
- * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
329
- * environment
330
- */
331
- public async reset(): Promise<Viewer> {
332
- await this.destroy();
333
- return this.bootstrap();
334
- }
335
-
336
- /**
337
- * Destroys
338
- *
339
- * * all {@link VariantInstance}s using {@link destroyVariantInstances}
340
- * * calling `dispose` on the `Engine` and `Scene`
341
- */
342
- public destroy(): Viewer {
343
- this.destroyVariantInstances();
344
- this.scene.dispose();
345
- SpecStorage.destroy();
346
- return this;
347
- }
348
-
349
- /**
350
- * Show coordinate system with given dimension (for debugging purpose).
351
- */
352
- public showWorldCoordinates( dimension: number ) {
353
- const scene = this.scene;
354
- const makeTextPlane = function( text: string, color: string, size: number ) {
355
- const dynamicTexture = new DynamicTexture( 'DynamicTexture', 50, scene, true );
356
- dynamicTexture.hasAlpha = true;
357
- dynamicTexture.drawText( text, 5, 40, 'bold 36px Arial', color, 'transparent', true );
358
- const plane = Mesh.CreatePlane( 'TextPlane', size, scene, true );
359
- plane.material = new StandardMaterial( 'TextPlaneMaterial', scene );
360
- plane.material.backFaceCulling = false;
361
- // @ts-ignore
362
- plane.material.specularColor = new Color3( 0, 0, 0 );
363
- // @ts-ignore
364
- plane.material.diffuseTexture = dynamicTexture;
365
- return plane;
366
- };
367
- const axisX = Mesh.CreateLines( 'axisX', [
368
- Vector3.Zero(),
369
- new Vector3( dimension, 0, 0 ),
370
- new Vector3( dimension * 0.95, 0.05 * dimension, 0 ),
371
- new Vector3( dimension, 0, 0 ),
372
- new Vector3( dimension * 0.95, -0.05 * dimension, 0 )
373
- ], scene );
374
- axisX.color = new Color3( 1, 0, 0 );
375
- const xChar = makeTextPlane( 'X', 'red', dimension / 10 );
376
- xChar.position = new Vector3( 0.9 * dimension, -0.05 * dimension, 0 );
377
- const axisY = Mesh.CreateLines( 'axisY', [
378
- Vector3.Zero(),
379
- new Vector3( 0, dimension, 0 ),
380
- new Vector3( -0.05 * dimension, dimension * 0.95, 0 ),
381
- new Vector3( 0, dimension, 0 ),
382
- new Vector3( 0.05 * dimension, dimension * 0.95, 0 )
383
- ], scene );
384
- axisY.color = new Color3( 0, 1, 0 );
385
- const yChar = makeTextPlane( 'Y', 'green', dimension / 10 );
386
- yChar.position = new Vector3( 0, 0.9 * dimension, -0.05 * dimension );
387
- const axisZ = Mesh.CreateLines( 'axisZ', [
388
- Vector3.Zero(),
389
- new Vector3( 0, 0, dimension ),
390
- new Vector3( 0, -0.05 * dimension, dimension * 0.95 ),
391
- new Vector3( 0, 0, dimension ),
392
- new Vector3( 0, 0.05 * dimension, dimension * 0.95 )
393
- ], scene );
394
- axisZ.color = new Color3( 0, 0, 1 );
395
- const zChar = makeTextPlane( 'Z', 'blue', dimension / 10 );
396
- zChar.position = new Vector3( 0, 0.05 * dimension, 0.9 * dimension );
397
- }
398
-
399
- /**
400
- * @emits {@link Event.SCENE_PROCESSING_START}
401
- * @emits {@link Event.SCENE_PROCESSING_END}
402
- */
403
- protected async initScene(): Promise<Scene> {
404
- const sceneJson = SpecStorage.get<SceneJson>( 'scene' );
405
- this.broadcastEvent( Event.SCENE_PROCESSING_START, sceneJson );
406
- const engine = new Engine(
407
- this.canvas as HTMLCanvasElement,
408
- sceneJson.engine?.antialiasing ?? false,
409
- sceneJson.engine?.options
410
- );
411
- const scene = await sceneSetup( engine, sceneJson );
412
- if( sceneJson.meshPicking ) {
413
- new HighlightLayer( 'default', scene );
414
- scene.onPointerPick = ( pointerEvent: PointerEvent, pickInfo: PickingInfo ) => {
415
- if( !pickInfo.hit ) {
416
- return;
417
- }
418
- const mesh = pickInfo.pickedMesh;
419
- this.broadcastEvent( Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant );
420
- if( mesh?.metadata.element ) {
421
- this.broadcastEvent( Event.ELEMENT_PICKED, mesh.metadata.element );
422
- }
423
- if( mesh?.metadata.variant ) {
424
- if( mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
425
- mesh.metadata.variant.toggleHighlight();
426
- }
427
- this.broadcastEvent( Event.VARIANT_PICKED, mesh.metadata.variant );
428
- }
429
- };
430
- }
431
- this._sceneManager = await SceneManager.create( scene );
432
- this._animationManager = await AnimationManager.create( scene );
433
- this.broadcastEvent( Event.SCENE_PROCESSING_END, scene );
434
- return scene;
435
- }
436
-
437
- /**
438
- * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
439
- */
440
- protected async createVariantInstances(): Promise<VariantInstance[]> {
441
- const setupJson = SpecStorage.get<SetupJson>( 'setup' );
442
- const instances = [];
443
- for( const instanceDefinition of setupJson.instances ) {
444
- if( instanceDefinition.lazy ) {
445
- this.variantInstances.register( instanceDefinition );
446
- continue;
447
- }
448
- instances.push( await this.variantInstances.create(
449
- instanceDefinition.variant,
450
- instanceDefinition.name,
451
- instanceDefinition.parameters
452
- ) );
453
- }
454
- return instances;
455
- }
456
-
457
- /**
458
- * Help function for focusing a helper camera exactly onto the given bounding box
459
- */
460
- private getFocusedHelperCamera(boundingBox: Mesh, settings?: AutofocusSettings): ArcRotateCamera {
461
- // use helper camera to get some default values and set the values of the real camera accordingly
462
- const helperCamera = new ArcRotateCamera(
463
- "__helper_camera__",
464
- 0, // camera angles will be overwritten after the target has been set
465
- 0,
466
- 0, // radius will be calculated, so we can set to 0 here
467
- Vector3.Zero(),
468
- this.scene
469
- );
470
- // this is required for automatically calculating the `lowerRadiusLimit`, so that we don't "dive" into meshes
471
- // see https://doc.babylonjs.com/divingDeeper/behaviors/cameraBehaviors#framing-behavior
472
- helperCamera.useFramingBehavior = true;
473
-
474
- // `minZ` is the camera distance beyond which the mesh will be clipped
475
- // this should be very low, but can't be zero
476
- // a good value seems to be 1% of the bounding box size (= radius), whereas the value shouldn't go above 1, which is also the default value
477
- const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
478
- helperCamera.minZ = Math.min(radius/100, 1);
479
-
480
- // set desired camera data, these won't be changed by the autofocus function!
481
- // default values should focus the element exactly from the front (= XY Plane)
482
- helperCamera.setTarget(boundingBox, true);
483
- helperCamera.alpha = ( settings?.alpha ?? - 90 ) * ( Math.PI / 180 );
484
- helperCamera.beta = ( settings?.beta ?? 90 ) * ( Math.PI / 180 );
485
-
486
- // finally zoom to the bounding box
487
- // also apply a zoom factor, this adjusts the borders around the model in the viewport
488
- helperCamera.zoomOnFactor = settings?.radiusFactor || 1;
489
- helperCamera.zoomOn( [boundingBox], true );
490
-
491
- return helperCamera;
492
- }
493
-
494
- /**
495
- * Help function for applying the relevant data of the focused helper camera to the real camera
496
- */
497
- private async applyFocusedHelperCameraData(activeCamera: ArcRotateCamera, helperCamera: ArcRotateCamera, settings?: AutofocusSettings) {
498
- // limits
499
- activeCamera.minZ = helperCamera.minZ;
500
- activeCamera.maxZ = helperCamera.maxZ;
501
- activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
502
- activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
503
-
504
- // additional settings
505
- if( settings?.adjustWheelPrecision !== false ) {
506
- activeCamera.wheelPrecision = helperCamera.wheelPrecision;
507
- }
508
- if( settings?.adjustPanningSensibility !== false ) {
509
- activeCamera.panningSensibility = helperCamera.panningSensibility;
510
- }
511
- if( settings?.adjustPinchPrecision !== false ) {
512
- activeCamera.pinchPrecision = helperCamera.pinchPrecision;
513
- }
514
-
515
- // finally move the camera
516
- // do this at last, so that all camera settings are already considered
517
- const newCameraPosition: PlacementDefinition = {
518
- alpha: helperCamera.alpha,
519
- beta: helperCamera.beta,
520
- radius: helperCamera.radius,
521
- target: helperCamera.target
522
- }
523
- await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation)
524
- }
525
- }
41
+ protected _scene: Scene | null = null;
42
+
43
+ protected _animationManager: AnimationManager | null = null;
44
+
45
+ protected _sceneManager: SceneManager | null = null;
46
+
47
+ protected _gltfExportManager: GltfExportManager | null = null;
48
+
49
+ protected _variantInstances: VariantInstanceManager | null = null;
50
+
51
+ // default value is `true` ATM for compatibility reasons
52
+ // in the future material cloning should be the edge case
53
+ protected _cloneMaterialsOnMutation: boolean = true;
54
+
55
+ protected _isRenderLoopPaused: boolean = false;
56
+
57
+ static version = version;
58
+
59
+ /**
60
+ * Constructor
61
+ */
62
+ public constructor(public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson) {
63
+ super();
64
+ }
65
+
66
+ /**
67
+ * Gets the BabylonJS Scene that is attached to the instance.
68
+ *
69
+ * @throws Error if the `scene` has not been initialized.
70
+ */
71
+ get scene(): Scene {
72
+ if (!this._scene) {
73
+ throw new Error(`Scene has not been initialized.`);
74
+ }
75
+ return this._scene;
76
+ }
77
+
78
+ /**
79
+ * Gets the {@link SceneManager} attached to the viewer.
80
+ *
81
+ * @throws Error if the {@link SceneManager} has not been initialized.
82
+ */
83
+ get sceneManager(): SceneManager {
84
+ if (!this._sceneManager) {
85
+ throw new Error(`SceneManager has not been initialized.`);
86
+ }
87
+ return this._sceneManager;
88
+ }
89
+
90
+ /**
91
+ * Gets the {@link GltfExportManager} attached to the viewer.
92
+ *
93
+ * @throws Error if the {@link GltfExportManager} has not been initialized.
94
+ */
95
+ get gltfExportManager(): GltfExportManager {
96
+ if (!this._gltfExportManager) {
97
+ throw new Error(`GltfExportManager has not been initialized.`);
98
+ }
99
+ return this._gltfExportManager;
100
+ }
101
+
102
+ /**
103
+ * Gets the BabylonJS Engine that is attached to the viewer.
104
+ */
105
+ get engine(): Engine {
106
+ return this.scene.getEngine();
107
+ }
108
+
109
+ /**
110
+ * Gets the {@link VariantInstanceManager} attached to the viewer.
111
+ *
112
+ * @throws Error if the {@link VariantInstanceManager} has not been initialized.
113
+ */
114
+ get variantInstances(): VariantInstanceManager {
115
+ if (!this._variantInstances) {
116
+ throw Error(`There is no variantInstanceManager.`);
117
+ }
118
+ return this._variantInstances;
119
+ }
120
+
121
+ /**
122
+ * Gets the {@link AnimationManager} attached to the viewer.
123
+ *
124
+ * @throws Error if the {@link AnimationManager} has not been initialized.
125
+ */
126
+ get animationManager(): AnimationManager {
127
+ if (!this._animationManager) {
128
+ throw new Error(`There is no animationManager instance.`);
129
+ }
130
+ return this._animationManager;
131
+ }
132
+
133
+ /**
134
+ * Gets the `cloneMaterialsOnMutation` flag, as defined in the spec
135
+ */
136
+ get cloneMaterialsOnMutation(): boolean {
137
+ return this._cloneMaterialsOnMutation;
138
+ }
139
+
140
+ /**
141
+ * Starts the application. This will
142
+ * * load the given "index" JSON file
143
+ * * setup the scene with the "scene" JSON file
144
+ * * create an (optional) default setup with different variant settings
145
+ * * sets up resizing by attaching a debounced version of {@link resize}
146
+ *
147
+ * @throws Error if any of the files is not found/valid
148
+ *
149
+ * @emits {@link Event.BOOTSTRAP_START}
150
+ * @emits {@link Event.BOOTSTRAP_END}
151
+ */
152
+ public async bootstrap(): Promise<Viewer> {
153
+ this.broadcastEvent(Event.BOOTSTRAP_START, this);
154
+ let indexJson;
155
+ if (isString(this.structureJson)) {
156
+ indexJson = await loadJson<StructureJson>(this.structureJson);
157
+ } else {
158
+ indexJson = this.structureJson;
159
+ }
160
+ if (!indexJson.scene) {
161
+ throw new Error(`No "scene" property found for bootstrapping.`);
162
+ }
163
+ // fill spec store
164
+ SpecStorage.createFromSpec(indexJson);
165
+ // load scene
166
+ if (isString(indexJson.scene)) {
167
+ const sceneJson = await loadJson<SceneJson>(indexJson.scene);
168
+ indexJson.scene = sceneJson;
169
+ }
170
+ this._scene = await this.initScene();
171
+ // create instance manager
172
+ const rootVariant = await Variant.create('_', indexJson, this);
173
+ this._variantInstances = await VariantInstanceManager.create(rootVariant);
174
+ // create optional default instances
175
+ if (indexJson.setup) {
176
+ if (isString(indexJson.setup)) {
177
+ const setupJson = await loadJson<SetupJson>(indexJson.setup);
178
+ indexJson.setup = setupJson;
179
+ }
180
+ await this.createVariantInstances();
181
+ }
182
+ // create gltf export manager
183
+ this._gltfExportManager = await GltfExportManager.create(this);
184
+ // resize handler
185
+ window.addEventListener('resize', debounce(this.resize.bind(this), 100));
186
+ // wait until scene is completely ready
187
+ await this.scene.whenReadyAsync();
188
+ // event broadcasting
189
+ this.broadcastEvent(Event.BOOTSTRAP_END, this);
190
+ // render loop
191
+ this.engine.runRenderLoop(() => {
192
+ if (!this._isRenderLoopPaused) this.scene.render();
193
+ });
194
+ return this;
195
+ }
196
+
197
+ /**
198
+ * Enables the BabylonJS [Inspector](https://doc.babylonjs.com/toolsAndResources/tools/inspector).\
199
+ * Due to the enormous additional package size of the inspector, this feature is only available in development builds.
200
+ */
201
+ public async enableDebugLayer(options?: IInspectorOptions) {
202
+ if (process.env.NODE_ENV?.toLowerCase().includes('dev')) {
203
+ await import(/* webpackChunkName: "debug-inspector" */ '@babylonjs/inspector');
204
+ await this.scene.debugLayer.show(options);
205
+ } else {
206
+ console.warn('BabylonJS inspector is not supported in production builds!');
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Destroys all registered {@link VariantInstance}s that are registered
212
+ */
213
+ public destroyVariantInstances(): Viewer {
214
+ this.variantInstances.all.forEach(variantInstance => {
215
+ this.variantInstances.destroy(variantInstance.name);
216
+ });
217
+ return this;
218
+ }
219
+
220
+ /**
221
+ * Trigger a resize event for the `Engine`
222
+ */
223
+ public resize(): Viewer {
224
+ this.engine.resize();
225
+ return this;
226
+ }
227
+
228
+ /**
229
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
230
+ * {@link DottedPath}s.
231
+ */
232
+ public async getNode(
233
+ variantInstanceName: string,
234
+ elementDottedPath: DottedPathArgument,
235
+ nodeDottedPath: DottedPathArgument
236
+ ): Promise<TransformNode> {
237
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
238
+ return variantInstance.getNode(elementDottedPath, nodeDottedPath);
239
+ }
240
+
241
+ /**
242
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
243
+ * {@link DottedPath}s.
244
+ */
245
+ public async getMesh(
246
+ variantInstanceName: string,
247
+ elementDottedPath: DottedPathArgument,
248
+ meshDottedPath: DottedPathArgument
249
+ ): Promise<Mesh | null> {
250
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
251
+ return variantInstance.getMesh(elementDottedPath, meshDottedPath);
252
+ }
253
+
254
+ /**
255
+ * Switches the camera
256
+ *
257
+ * @emits {@link Event.CAMERA_SWITCHED}
258
+ */
259
+ public switchCamera(newCamera: string, reset: boolean = true): Viewer {
260
+ const camera = this.scene.getCameraByName(newCamera);
261
+ if (camera) {
262
+ const activeCamera = this.scene.activeCamera;
263
+ if (activeCamera) {
264
+ activeCamera.detachControl(this.engine.getRenderingCanvas()!);
265
+ }
266
+ if (reset) {
267
+ camera.restoreState();
268
+ }
269
+ this.scene.setActiveCameraByName(newCamera);
270
+ camera.attachControl(this.engine.getRenderingCanvas()!);
271
+ this.broadcastEvent(Event.CAMERA_SWITCHED, camera);
272
+ } else {
273
+ throw new Error(`Given camera "${newCamera}" not found.`);
274
+ }
275
+ // TODO: put traceable observers to new camera (@see element)
276
+ return this;
277
+ }
278
+
279
+ /**
280
+ * Moves or animates the active camera to given `placement`.
281
+ */
282
+ public async moveActiveCameraTo(
283
+ placement: string | PlacementDefinition,
284
+ animation?: string | AnimationDefinition
285
+ ): Promise<AnimationInterface> {
286
+ return this.animationManager.animateToPlacement(this.sceneManager.activeCamera, placement, animation);
287
+ }
288
+
289
+ /**
290
+ * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
291
+ */
292
+ public screenshot(settings?: ScreenshotSettings): Promise<string> {
293
+ return new Promise((resolve, reject) => {
294
+ if (!this.engine) {
295
+ return reject('Engine is null');
296
+ }
297
+ if (!this.scene) {
298
+ return reject('Scene is null');
299
+ }
300
+ this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
301
+ ScreenshotTools.CreateScreenshotUsingRenderTarget(
302
+ this.engine,
303
+ this.sceneManager.activeCamera,
304
+ settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
305
+ resolve,
306
+ settings?.mimeType ?? 'image/png',
307
+ settings?.samples ?? 1,
308
+ settings?.antialiasing ?? false,
309
+ settings?.fileName ?? 'screenshot.png',
310
+ settings?.renderSprites ?? false
311
+ );
312
+ });
313
+ }
314
+
315
+ /**
316
+ * Checks whether the browser is capable of handling XR.
317
+ */
318
+ public async isBrowserARCapable(): Promise<boolean> {
319
+ return await WebXRSessionManager.IsSessionSupportedAsync('immersive-ar');
320
+ }
321
+
322
+ /**
323
+ * Calculates the bounding box from all visible meshes on the scene.
324
+ */
325
+ public async calculateBoundingBox(excludeGeometry?: ExcludedGeometry): Promise<Mesh> {
326
+ if (this.scene.meshes.length === 0) {
327
+ throw new Error('There are currently no meshes on the scene.');
328
+ }
329
+ this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
330
+ const bbName = '__bounding_box__';
331
+
332
+ const { max, min } = this.scene.meshes
333
+ .filter(mesh => {
334
+ const isEnabled = mesh.isEnabled();
335
+ // ignore the existing bounding box mesh for calculating the current one
336
+ const isNotBBoxMesh = bbName !== mesh.id;
337
+ // ignore meshes with invalid bounding infos
338
+ const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
339
+ // ignore excluded meshes
340
+ const isExcluded = excludeGeometry ? isMeshIncludedInExclusionList(mesh as Mesh, excludeGeometry) : false;
341
+ return isEnabled && isNotBBoxMesh && hasValidBBoxInfo && !isExcluded;
342
+ })
343
+ .reduce(
344
+ (accBBoxMinMax, curMesh, idx) => {
345
+ const bBox = curMesh.getBoundingInfo().boundingBox;
346
+ // use the first entry in the array as default value and get the resulting maximum/minimum values
347
+ const max = idx === 0 ? bBox.maximumWorld : Vector3.Maximize(accBBoxMinMax.max, bBox.maximumWorld);
348
+ const min = idx === 0 ? bBox.minimumWorld : Vector3.Minimize(accBBoxMinMax.min, bBox.minimumWorld);
349
+ return { max, min };
350
+ },
351
+ { max: new Vector3(), min: new Vector3() }
352
+ );
353
+
354
+ let boundingBox = this.scene.getMeshByName(bbName) as Mesh;
355
+ if (!boundingBox) {
356
+ boundingBox = new Mesh(bbName, this.scene);
357
+ }
358
+ boundingBox.setBoundingInfo(new BoundingInfo(min, max));
359
+ return boundingBox;
360
+ }
361
+
362
+ /**
363
+ * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning
364
+ */
365
+ public async autofocusActiveCamera(settings?: AutofocusSettings) {
366
+ // first check some preconditions
367
+ const activeCamera = this.scene.activeCamera;
368
+ if (!activeCamera) {
369
+ throw new Error('No active camera found when using autofocus feature.');
370
+ }
371
+ if (!(activeCamera instanceof ArcRotateCamera)) {
372
+ const cameraClsName = activeCamera.getClassName();
373
+ throw new Error(`Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.`);
374
+ }
375
+
376
+ // get bounding box of all visible meshes, this is the base for the autofocus algorithm
377
+ const boundingBox = await this.calculateBoundingBox(settings?.exclude);
378
+
379
+ // focus the helper camera and set the calculated camera data to the real camera
380
+ const helperCamera = this.getFocusedHelperCamera(boundingBox, settings);
381
+ await this.applyFocusedHelperCameraData(activeCamera, helperCamera, settings);
382
+
383
+ // remove the helper camera
384
+ helperCamera.dispose();
385
+ }
386
+
387
+ /**
388
+ * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
389
+ * environment
390
+ */
391
+ public async reset(): Promise<Viewer> {
392
+ await this.destroy();
393
+ return this.bootstrap();
394
+ }
395
+
396
+ /**
397
+ * Destroys
398
+ *
399
+ * * all {@link VariantInstance}s using {@link destroyVariantInstances}
400
+ * * calling `dispose` on the `Engine` and `Scene`
401
+ */
402
+ public destroy(): Viewer {
403
+ this.destroyVariantInstances();
404
+ this.scene.dispose();
405
+ SpecStorage.destroy();
406
+ return this;
407
+ }
408
+
409
+ /**
410
+ * Show coordinate system with given dimension (for debugging purpose).
411
+ */
412
+ public showWorldCoordinates(dimension: number) {
413
+ const scene = this.scene;
414
+ const makeTextPlane = function (text: string, color: string, size: number) {
415
+ const dynamicTexture = new DynamicTexture('DynamicTexture', 50, scene, true);
416
+ dynamicTexture.hasAlpha = true;
417
+ dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true);
418
+ const plane = Mesh.CreatePlane('TextPlane', size, scene, true);
419
+ plane.material = new StandardMaterial('TextPlaneMaterial', scene);
420
+ plane.material.backFaceCulling = false;
421
+ // @ts-ignore
422
+ plane.material.specularColor = new Color3(0, 0, 0);
423
+ // @ts-ignore
424
+ plane.material.diffuseTexture = dynamicTexture;
425
+ return plane;
426
+ };
427
+
428
+ const axisX = Mesh.CreateLines(
429
+ 'axisX',
430
+ [
431
+ Vector3.Zero(),
432
+ new Vector3(dimension, 0, 0),
433
+ new Vector3(dimension * 0.95, 0.05 * dimension, 0),
434
+ new Vector3(dimension, 0, 0),
435
+ new Vector3(dimension * 0.95, -0.05 * dimension, 0),
436
+ ],
437
+ scene,
438
+ false
439
+ );
440
+ axisX.color = new Color3(1, 0, 0);
441
+ const xChar = makeTextPlane('X', 'red', dimension / 10);
442
+ xChar.position = new Vector3(0.9 * dimension, -0.05 * dimension, 0);
443
+ const axisY = Mesh.CreateLines(
444
+ 'axisY',
445
+ [
446
+ Vector3.Zero(),
447
+ new Vector3(0, dimension, 0),
448
+ new Vector3(-0.05 * dimension, dimension * 0.95, 0),
449
+ new Vector3(0, dimension, 0),
450
+ new Vector3(0.05 * dimension, dimension * 0.95, 0),
451
+ ],
452
+ scene,
453
+ false
454
+ );
455
+ axisY.color = new Color3(0, 1, 0);
456
+ const yChar = makeTextPlane('Y', 'green', dimension / 10);
457
+ yChar.position = new Vector3(0, 0.9 * dimension, -0.05 * dimension);
458
+ const axisZ = Mesh.CreateLines(
459
+ 'axisZ',
460
+ [
461
+ Vector3.Zero(),
462
+ new Vector3(0, 0, dimension),
463
+ new Vector3(0, -0.05 * dimension, dimension * 0.95),
464
+ new Vector3(0, 0, dimension),
465
+ new Vector3(0, 0.05 * dimension, dimension * 0.95),
466
+ ],
467
+ scene,
468
+ false
469
+ );
470
+ axisZ.color = new Color3(0, 0, 1);
471
+ const zChar = makeTextPlane('Z', 'blue', dimension / 10);
472
+ zChar.position = new Vector3(0, 0.05 * dimension, 0.9 * dimension);
473
+ }
474
+
475
+ /**
476
+ * Pause render loop.
477
+ */
478
+ public pauseRendering() {
479
+ this._isRenderLoopPaused = true;
480
+ }
481
+
482
+ /**
483
+ * Resume render loop when paused.
484
+ */
485
+ public resumeRendering() {
486
+ this._isRenderLoopPaused = false;
487
+ }
488
+
489
+ /**
490
+ * @emits {@link Event.SCENE_PROCESSING_START}
491
+ * @emits {@link Event.SCENE_PROCESSING_END}
492
+ */
493
+ protected async initScene(): Promise<Scene> {
494
+ const sceneJson = SpecStorage.get<SceneJson>('scene');
495
+ this.broadcastEvent(Event.SCENE_PROCESSING_START, sceneJson);
496
+ const engine = new Engine(
497
+ this.canvas as HTMLCanvasElement,
498
+ sceneJson.engine?.antialiasing ?? false,
499
+ sceneJson.engine?.options
500
+ );
501
+ const scene = await sceneSetup(engine, sceneJson);
502
+ if (sceneJson.meshPicking) {
503
+ new HighlightLayer('default', scene);
504
+ scene.onPointerPick = (pointerEvent: IPointerEvent, pickInfo: PickingInfo) => {
505
+ if (!pickInfo.hit) {
506
+ return;
507
+ }
508
+ const mesh = pickInfo.pickedMesh;
509
+ this.broadcastEvent(Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant);
510
+ if (mesh?.metadata.element) {
511
+ this.broadcastEvent(Event.ELEMENT_PICKED, mesh.metadata.element);
512
+ }
513
+ if (mesh?.metadata.variant) {
514
+ if (mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
515
+ mesh.metadata.variant.toggleHighlight();
516
+ }
517
+ this.broadcastEvent(Event.VARIANT_PICKED, mesh.metadata.variant);
518
+ }
519
+ };
520
+ }
521
+ this._sceneManager = await SceneManager.create(scene);
522
+ this._animationManager = await AnimationManager.create(scene);
523
+ if (sceneJson.cloneMaterialsOnMutation !== undefined) {
524
+ this._cloneMaterialsOnMutation = sceneJson.cloneMaterialsOnMutation;
525
+ }
526
+ if (sceneJson.useRightHandedSystem !== undefined) {
527
+ scene.useRightHandedSystem = sceneJson.useRightHandedSystem;
528
+ }
529
+ this.broadcastEvent(Event.SCENE_PROCESSING_END, scene);
530
+ return scene;
531
+ }
532
+
533
+ /**
534
+ * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
535
+ */
536
+ protected async createVariantInstances(): Promise<VariantInstance[]> {
537
+ const setupJson = SpecStorage.get<SetupJson>('setup');
538
+ const instances = [];
539
+ for (const instanceDefinition of setupJson.instances) {
540
+ if (instanceDefinition.lazy) {
541
+ this.variantInstances.register(instanceDefinition);
542
+ continue;
543
+ }
544
+ instances.push(
545
+ await this.variantInstances.create(
546
+ instanceDefinition.variant,
547
+ instanceDefinition.name,
548
+ instanceDefinition.parameters
549
+ )
550
+ );
551
+ }
552
+ return instances;
553
+ }
554
+
555
+ /**
556
+ * Help function for focusing a helper camera exactly onto the given bounding box
557
+ */
558
+ private getFocusedHelperCamera(boundingBox: Mesh, settings?: AutofocusSettings): ArcRotateCamera {
559
+ // use helper camera to get some default values and set the values of the real camera accordingly
560
+ const helperCamera = new ArcRotateCamera(
561
+ '__helper_camera__',
562
+ 0, // camera angles will be overwritten after the target has been set
563
+ 0,
564
+ 0, // radius will be calculated, so we can set to 0 here
565
+ Vector3.Zero(),
566
+ this.scene
567
+ );
568
+ // this is required for automatically calculating the `lowerRadiusLimit`, so that we don't "dive" into meshes
569
+ // see https://doc.babylonjs.com/divingDeeper/behaviors/cameraBehaviors#framing-behavior
570
+ helperCamera.useFramingBehavior = true;
571
+
572
+ // `minZ` is the camera distance beyond which the mesh will be clipped
573
+ // this should be very low, but can't be zero
574
+ // a good value seems to be 1% of the bounding box size (= radius), whereas the value shouldn't go above 1, which is also the default value
575
+ const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
576
+ helperCamera.minZ = Math.min(radius / 100, 1);
577
+
578
+ // set desired camera data, these won't be changed by the autofocus function!
579
+ // default values should focus the element exactly from the front (= XY Plane)
580
+ helperCamera.setTarget(boundingBox, true);
581
+ helperCamera.alpha = (settings?.alpha ?? -90) * (Math.PI / 180);
582
+ helperCamera.beta = (settings?.beta ?? 90) * (Math.PI / 180);
583
+
584
+ // finally zoom to the bounding box
585
+ // also apply a zoom factor, this adjusts the borders around the model in the viewport
586
+ helperCamera.zoomOnFactor = settings?.radiusFactor || 1;
587
+ helperCamera.zoomOn([boundingBox], true);
588
+
589
+ return helperCamera;
590
+ }
591
+
592
+ /**
593
+ * Help function for applying the relevant data of the focused helper camera to the real camera
594
+ */
595
+ private async applyFocusedHelperCameraData(
596
+ activeCamera: ArcRotateCamera,
597
+ helperCamera: ArcRotateCamera,
598
+ settings?: AutofocusSettings
599
+ ) {
600
+ // limits
601
+ activeCamera.minZ = helperCamera.minZ;
602
+ activeCamera.maxZ = helperCamera.maxZ;
603
+ activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
604
+ activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
605
+
606
+ // additional settings
607
+ if (settings?.adjustWheelPrecision !== false) {
608
+ activeCamera.wheelPrecision = helperCamera.wheelPrecision;
609
+ }
610
+ if (settings?.adjustPanningSensibility !== false) {
611
+ activeCamera.panningSensibility = helperCamera.panningSensibility;
612
+ }
613
+ if (settings?.adjustPinchPrecision !== false) {
614
+ activeCamera.pinchPrecision = helperCamera.pinchPrecision;
615
+ }
616
+
617
+ // finally move the camera
618
+ // do this at last, so that all camera settings are already considered
619
+ const newCameraPosition: PlacementDefinition = {
620
+ alpha: helperCamera.alpha,
621
+ beta: helperCamera.beta,
622
+ radius: helperCamera.radius,
623
+ target: helperCamera.target,
624
+ };
625
+ await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation);
626
+ }
627
+ }