@combeenation/3d-viewer 3.1.1-alpha7 → 3.1.2

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 (94) 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 +1 -1
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +190 -190
  6. package/dist/lib-cjs/api/classes/element.d.ts +125 -126
  7. package/dist/lib-cjs/api/classes/element.js +678 -674
  8. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/elementParameterizable.d.ts +14 -14
  10. package/dist/lib-cjs/api/classes/elementParameterizable.js +134 -134
  11. package/dist/lib-cjs/api/classes/event.d.ts +312 -312
  12. package/dist/lib-cjs/api/classes/event.js +357 -357
  13. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  14. package/dist/lib-cjs/api/classes/eventBroadcaster.js +53 -53
  15. package/dist/lib-cjs/api/classes/parameter.d.ts +165 -165
  16. package/dist/lib-cjs/api/classes/parameter.js +267 -267
  17. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  18. package/dist/lib-cjs/api/classes/parameterObservable.js +126 -126
  19. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  20. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  21. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +38 -38
  22. package/dist/lib-cjs/api/classes/placementAnimation.js +138 -138
  23. package/dist/lib-cjs/api/classes/variant.d.ts +180 -190
  24. package/dist/lib-cjs/api/classes/variant.js +863 -873
  25. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  26. package/dist/lib-cjs/api/classes/variantInstance.d.ts +41 -41
  27. package/dist/lib-cjs/api/classes/variantInstance.js +98 -98
  28. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  29. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  30. package/dist/lib-cjs/api/classes/viewer.d.ts +128 -128
  31. package/dist/lib-cjs/api/classes/viewer.js +486 -486
  32. package/dist/lib-cjs/api/classes/viewerLight.d.ts +65 -66
  33. package/dist/lib-cjs/api/classes/viewerLight.js +322 -389
  34. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  35. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  36. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  37. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  38. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  39. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +6 -6
  40. package/dist/lib-cjs/api/internal/sceneSetup.js +227 -227
  41. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  42. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  43. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  44. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  45. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  46. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  47. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  48. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  49. package/dist/lib-cjs/api/util/babylonHelper.d.ts +125 -125
  50. package/dist/lib-cjs/api/util/babylonHelper.js +368 -368
  51. package/dist/lib-cjs/api/util/globalTypes.d.ts +275 -275
  52. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  53. package/dist/lib-cjs/api/util/resourceHelper.d.ts +30 -30
  54. package/dist/lib-cjs/api/util/resourceHelper.js +247 -203
  55. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  56. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  57. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  58. package/dist/lib-cjs/buildinfo.json +3 -3
  59. package/dist/lib-cjs/index.d.ts +46 -46
  60. package/dist/lib-cjs/index.js +82 -82
  61. package/dist/webpack-stats.json +0 -0
  62. package/package.json +83 -83
  63. package/src/api/classes/animationInterface.ts +11 -11
  64. package/src/api/classes/dottedPath.ts +189 -189
  65. package/src/api/classes/element.ts +608 -606
  66. package/src/api/classes/elementParameterizable.ts +78 -78
  67. package/src/api/classes/event.ts +355 -355
  68. package/src/api/classes/eventBroadcaster.ts +54 -54
  69. package/src/api/classes/parameter.ts +277 -277
  70. package/src/api/classes/parameterObservable.ts +121 -121
  71. package/src/api/classes/placementAnimation.ts +133 -133
  72. package/src/api/classes/variant.ts +659 -670
  73. package/src/api/classes/variantInstance.ts +81 -81
  74. package/src/api/classes/viewer.ts +421 -421
  75. package/src/api/internal/debugViewer.ts +81 -81
  76. package/src/api/internal/lensRendering.ts +10 -10
  77. package/src/api/internal/sceneSetup.ts +203 -203
  78. package/src/api/manager/animationManager.ts +116 -116
  79. package/src/api/manager/sceneManager.ts +105 -105
  80. package/src/api/manager/variantInstanceManager.ts +236 -236
  81. package/src/api/store/specStorage.ts +53 -53
  82. package/src/api/util/babylonHelper.ts +392 -392
  83. package/src/api/util/globalTypes.ts +314 -314
  84. package/src/api/util/resourceHelper.ts +168 -155
  85. package/src/buildinfo.json +2 -2
  86. package/src/commonjs.tsconfig.json +13 -13
  87. package/src/declaration.tsconfig.json +10 -10
  88. package/src/dev.ts +44 -46
  89. package/src/es6.tsconfig.json +13 -13
  90. package/src/index.ts +87 -87
  91. package/src/pagesconfig.json +47 -47
  92. package/src/tsconfig.json +43 -43
  93. package/src/tsconfig.types.json +9 -9
  94. package/src/types.d.ts +4 -4
@@ -1,422 +1,422 @@
1
- import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
2
- import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
3
- import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
4
- import { Engine } from '@babylonjs/core/Engines/engine';
5
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
6
- import { Vector3 } from '@babylonjs/core/Maths/math.vector';
7
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
8
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
9
- import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
10
- import { Scene } from '@babylonjs/core/scene';
11
- import { isString } from 'lodash-es';
12
- import { version } from '../../buildinfo.json';
13
- import { sceneSetup } from '../internal/sceneSetup';
14
- import { AnimationManager } from '../manager/animationManager';
15
- import { SceneManager } from '../manager/sceneManager';
16
- import { VariantInstanceManager } from '../manager/variantInstanceManager';
17
- import { SpecStorage } from '../store/specStorage';
18
- import { debounce, loadJson } from '../util/resourceHelper';
19
- import { Event } from './event';
20
- import { EventBroadcaster } from './eventBroadcaster';
21
- import { Parameter } from './parameter';
22
- import { Variant } from './variant';
23
- import { VariantInstance } from './variantInstance';
24
-
25
-
26
- /**
27
- * The main exposed object. This is the entry point into the application
28
- *
29
- * ```js
30
- * const canvas = document.getElementById( 'babylon-canvas' );
31
- * const viewer = Viewer( canvas, '/path/to/index.json' );
32
- * ```
33
- * The class does nothing on its own and needs to {@link bootstrap}
34
- */
35
- export class Viewer extends EventBroadcaster {
36
-
37
- protected _scene: Scene | null = null;
38
-
39
- protected _animationManager: AnimationManager | null = null;
40
-
41
- protected _sceneManager: SceneManager | null = null;
42
-
43
- protected _variantInstances: VariantInstanceManager | null = null;
44
-
45
- static version = version;
46
-
47
- /**
48
- * Constructor
49
- */
50
- public constructor( public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson ) {
51
- super();
52
- }
53
-
54
- /**
55
- * Gets the BabylonJS Scene that is attached to the instance.
56
- *
57
- * @throws Error if the `scene` has not been initialized.
58
- */
59
- get scene(): Scene {
60
- if( !this._scene ) {
61
- throw new Error( `Scene has not been initialized.` );
62
- }
63
- return this._scene;
64
- }
65
-
66
- get sceneManager(): SceneManager {
67
- if( !this._sceneManager ) {
68
- throw new Error( `Environment has not been initialized.` );
69
- }
70
- return this._sceneManager;
71
- }
72
-
73
- /**
74
- * Gets the BabylonJS Engine that is attached to the viewer.
75
- */
76
- get engine(): Engine {
77
- return this.scene.getEngine();
78
- }
79
-
80
- /**
81
- * Gets the {@link VariantInstanceManager} attached to the viewer.
82
- *
83
- * @throws Error if the {@link VariantInstanceManager} has not been initialized.
84
- */
85
- get variantInstances(): VariantInstanceManager {
86
- if( !this._variantInstances ) {
87
- throw Error( `There is no variantInstanceManager.` );
88
- }
89
- return this._variantInstances;
90
- }
91
-
92
- /**
93
- * Gets the {@link AnimationManager} attached to the viewer.
94
- *
95
- * @throws Error if the {@link AnimationManager} has not been initialized.
96
- */
97
- get animationManager(): AnimationManager {
98
- if( !this._animationManager ) {
99
- throw new Error( `There is no animationManager instance.` );
100
- }
101
- return this._animationManager;
102
- }
103
-
104
- /**
105
- * Starts the application. This will
106
- * * load the given "index" JSON file
107
- * * setup the scene with the "scene" JSON file
108
- * * create an (optional) default setup with different variant settings
109
- * * sets up resizing by attaching a debounced version of {@link resize}
110
- *
111
- * @throws Error if any of the files is not found/valid
112
- *
113
- * @emits {@link Event.BOOTSTRAP_START}
114
- * @emits {@link Event.BOOTSTRAP_END}
115
- */
116
- public async bootstrap(): Promise<Viewer> {
117
- this.broadcastEvent( Event.BOOTSTRAP_START, this );
118
- let indexJson;
119
- if( isString( this.structureJson ) ) {
120
- indexJson = await loadJson<StructureJson>( this.structureJson );
121
- } else {
122
- indexJson = this.structureJson;
123
- }
124
- if( !indexJson.scene ) {
125
- throw new Error( `No "scene" property found for bootstrapping.` );
126
- }
127
- // fill spec store
128
- SpecStorage.createFromSpec( indexJson );
129
- // load scene
130
- if( isString( indexJson.scene ) ) {
131
- const sceneJson = await loadJson<SceneJson>( indexJson.scene );
132
- indexJson.scene = sceneJson;
133
- }
134
- this._scene = await this.initScene();
135
- // create instance manager
136
- const rootVariant = await Variant.create( '_', indexJson, this );
137
- this._variantInstances = await VariantInstanceManager.create( rootVariant );
138
- // create optional default instances
139
- if( indexJson.setup ) {
140
- if( isString( indexJson.setup ) ) {
141
- const setupJson = await loadJson<SetupJson>( indexJson.setup );
142
- indexJson.setup = setupJson;
143
- }
144
- await this.createVariantInstances();
145
- }
146
- // resize handler
147
- window.addEventListener( 'resize', debounce( this.resize.bind( this ), 100 ) );
148
- // event broadcasting
149
- this.broadcastEvent( Event.BOOTSTRAP_END, this );
150
- return this;
151
- }
152
-
153
- // Disabled for now to decrease bundle size.
154
- // See https://github.com/Combeenation/3d-viewer/issues/37
155
- // /**
156
- // * Enables the BabylonJS DebugLayer. If you pass options, be sure to pass an Object of type `IInspectorOptions`.
157
- // */
158
- // public async enableDebugLayer(options?: any) {
159
- // // @ts-ignore
160
- // await import(/* webpackChunkName: "debug-inspector" */'@babylonjs/inspector');
161
- // await this.scene.debugLayer.show(options);
162
- // return this;
163
- // }
164
-
165
- /**
166
- * Destroys all registered {@link VariantInstance}s that are registered
167
- */
168
- public destroyVariantInstances(): Viewer {
169
- this.variantInstances.all.forEach( variantInstance => {
170
- this.variantInstances.destroy( variantInstance.name );
171
- } );
172
- return this;
173
- }
174
-
175
- /**
176
- * Trigger a resize event for the `Engine`
177
- */
178
- public resize(): Viewer {
179
- this.engine.resize();
180
- return this;
181
- }
182
-
183
- /**
184
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
185
- * {@link DottedPath}s.
186
- */
187
- public async getNode( variantInstanceName: string,
188
- elementDottedPath: DottedPathArgument,
189
- nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
190
- const variantInstance = await this.variantInstances.get(variantInstanceName);
191
- return variantInstance.getNode( elementDottedPath, nodeDottedPath );
192
- }
193
-
194
- /**
195
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
196
- * {@link DottedPath}s.
197
- */
198
- public async getMesh( variantInstanceName: string,
199
- elementDottedPath: DottedPathArgument,
200
- meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
201
- const variantInstance = await this.variantInstances.get(variantInstanceName);
202
- return variantInstance.getMesh( elementDottedPath, meshDottedPath );
203
- }
204
-
205
- /**
206
- * Switches the camera
207
- *
208
- * @emits {@link Event.CAMERA_SWITCHED}
209
- */
210
- public switchCamera( newCamera: string, reset: boolean = true ): Viewer {
211
- const camera = this.scene.getCameraByName( newCamera );
212
- if( camera ) {
213
- const activeCamera = this.scene.activeCamera;
214
- if( activeCamera ) {
215
- activeCamera.detachControl( this.engine.getRenderingCanvas()! );
216
- }
217
- if( reset ) {
218
- camera.restoreState();
219
- }
220
- this.scene.setActiveCameraByName( newCamera );
221
- camera.attachControl( this.engine.getRenderingCanvas()! );
222
- this.broadcastEvent( Event.CAMERA_SWITCHED, camera );
223
- } else {
224
- throw new Error( `Given camera "${newCamera}" not found.` );
225
- }
226
- // TODO: put traceable observers to new camera (@see element)
227
- return this;
228
- }
229
-
230
- /**
231
- * Moves or animates the active camera to given `placement`.
232
- */
233
- public async moveActiveCameraTo( placement: string | PlacementDefinition,
234
- animation?: string | AnimationDefinition ): Promise<AnimationInterface> {
235
- return this.animationManager.animateToPlacement( this.sceneManager.activeCamera, placement, animation );
236
- }
237
-
238
- /**
239
- * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
240
- */
241
- public screenshot( settings?: ScreenshotSettings ): Promise<string> {
242
- return new Promise( ( resolve, reject ) => {
243
- if( !this.engine ) {
244
- return reject( 'Engine is null' );
245
- }
246
- if( !this.scene ) {
247
- return reject( 'Scene is null' );
248
- }
249
- this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
250
- ScreenshotTools.CreateScreenshotUsingRenderTarget(
251
- this.engine,
252
- this.sceneManager.activeCamera,
253
- settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
254
- resolve,
255
- settings?.mimeType ?? 'image/png',
256
- settings?.samples ?? 1,
257
- settings?.antialiasing ?? false,
258
- settings?.fileName ?? 'screenshot.png',
259
- settings?.renderSprites ?? false
260
- );
261
- } );
262
- }
263
-
264
- /**
265
- * Calculates the bounding box from all visible meshes on the scene.
266
- */
267
- public calculateBoundingBox(): Mesh {
268
- if( this.scene.meshes.length === 0 ) {
269
- throw new Error( 'There are currently no meshes on the scene.' );
270
- }
271
- let max = new Vector3( 0, 0, 0 );
272
- let min = new Vector3( 0, 0, 0 );
273
- this.scene.meshes.filter( mesh => mesh.isVisible ).forEach( mesh => {
274
- max = Vector3.Maximize( max, mesh.getBoundingInfo().boundingBox.maximumWorld );
275
- min = Vector3.Minimize( min, mesh.getBoundingInfo().boundingBox.minimumWorld );
276
- } );
277
- let boundingBox = this.scene.getMeshByName( '__bounding_box__' ) as Mesh;
278
- if( !boundingBox ) {
279
- boundingBox = new Mesh( '__bounding_box__', this.scene );
280
- }
281
- boundingBox.setBoundingInfo( new BoundingInfo( min, max ) );
282
- //boundingBox.showBoundingBox = true;
283
- return boundingBox;
284
- }
285
-
286
- /**
287
- * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning.
288
- */
289
- public autofocusActiveCamera( settings?: AutofocusSettings ) {
290
- const activeCamera = this.scene.activeCamera;
291
- if( !activeCamera ) {
292
- throw new Error( 'No active camera found when using autofocus feature.' );
293
- }
294
- if( activeCamera instanceof ArcRotateCamera ) {
295
- // calculate some values
296
- const boundingBox = this.calculateBoundingBox();
297
- const size = boundingBox.getBoundingInfo().maximum.subtract( boundingBox.getBoundingInfo().minimum );
298
- let radius = size.length() * (settings?.radiusFactor ?? 1.5);
299
- if( !isFinite( radius ) ) {
300
- radius = 1;
301
- }
302
- // use helper camera to get some default values
303
- const helperCamera = new ArcRotateCamera(
304
- '__helper_camera__',
305
- Math.PI / -2,
306
- Math.PI / 2,
307
- radius,
308
- Vector3.Zero(),
309
- this.scene
310
- );
311
- helperCamera.useFramingBehavior = true;
312
- helperCamera.setTarget( boundingBox );
313
- // translate values from helper to active camera
314
- activeCamera.setTarget( Mesh.Center( [boundingBox] ) );
315
- activeCamera.alpha = helperCamera.alpha;
316
- activeCamera.beta = helperCamera.beta;
317
- activeCamera.minZ = helperCamera.minZ;
318
- activeCamera.maxZ = helperCamera.maxZ;
319
- activeCamera.radius = helperCamera.radius;
320
- activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
321
- activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
322
- if( settings?.adjustWheelPrecision !== false ) {
323
- activeCamera.wheelPrecision = helperCamera.wheelPrecision;
324
- }
325
- if( settings?.adjustPanningSensibility !== false ) {
326
- activeCamera.panningSensibility = helperCamera.panningSensibility;
327
- }
328
- if( settings?.adjustPinchPrecision !== false ) {
329
- activeCamera.pinchPrecision = helperCamera.pinchPrecision;
330
- }
331
- // remove the helper camera
332
- helperCamera.dispose();
333
- } else {
334
- const cameraClsName = activeCamera.getClassName();
335
- throw new Error( `Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.` );
336
- }
337
- }
338
-
339
- /**
340
- * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
341
- * environment
342
- */
343
- public async reset(): Promise<Viewer> {
344
- await this.destroy();
345
- return this.bootstrap();
346
- }
347
-
348
- /**
349
- * Destroys
350
- *
351
- * * all {@link VariantInstance}s using {@link destroyVariantInstances}
352
- * * calling `dispose` on the `Engine` and `Scene`
353
- */
354
- public destroy(): Viewer {
355
- this.destroyVariantInstances();
356
- this.scene.dispose();
357
- SpecStorage.destroy();
358
- return this;
359
- }
360
-
361
- /**
362
- * @emits {@link Event.SCENE_PROCESSING_START}
363
- * @emits {@link Event.SCENE_PROCESSING_END}
364
- */
365
- protected async initScene(): Promise<Scene> {
366
- const sceneJson = SpecStorage.get<SceneJson>( 'scene' );
367
- this.broadcastEvent( Event.SCENE_PROCESSING_START, sceneJson );
368
- const engine = new Engine(
369
- this.canvas as HTMLCanvasElement,
370
- sceneJson.engine?.antialiasing ?? false,
371
- sceneJson.engine?.options
372
- );
373
- const scene = await sceneSetup( engine, sceneJson );
374
- if( sceneJson.meshPicking ) {
375
- new HighlightLayer( 'default', scene );
376
- scene.onPointerPick = ( pointerEvent: PointerEvent, pickInfo: PickingInfo ) => {
377
- if( !pickInfo.hit ) {
378
- return;
379
- }
380
- const mesh = pickInfo.pickedMesh;
381
- this.broadcastEvent( Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant );
382
- if( mesh?.metadata.element ) {
383
- this.broadcastEvent( Event.ELEMENT_PICKED, mesh.metadata.element );
384
- }
385
- if( mesh?.metadata.variant ) {
386
- if( mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
387
- mesh.metadata.variant.toggleHighlight();
388
- }
389
- this.broadcastEvent( Event.VARIANT_PICKED, mesh.metadata.variant );
390
- }
391
- };
392
- }
393
- this._sceneManager = await SceneManager.create( scene );
394
- this._animationManager = await AnimationManager.create( scene );
395
- this.broadcastEvent( Event.SCENE_PROCESSING_END, scene );
396
- engine.runRenderLoop( () => {
397
- scene.render();
398
- } );
399
- return scene;
400
- }
401
-
402
- /**
403
- * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
404
- */
405
- protected async createVariantInstances(): Promise<VariantInstance[]> {
406
- const setupJson = SpecStorage.get<SetupJson>( 'setup' );
407
- const instances = [];
408
- for( const instanceDefinition of setupJson.instances ) {
409
- if( instanceDefinition.lazy ) {
410
- this.variantInstances.register( instanceDefinition );
411
- continue;
412
- }
413
- instances.push( await this.variantInstances.create(
414
- instanceDefinition.variant,
415
- instanceDefinition.name,
416
- instanceDefinition.parameters
417
- ) );
418
- }
419
- return instances;
420
- }
421
-
1
+ import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
2
+ import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
3
+ import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
4
+ import { Engine } from '@babylonjs/core/Engines/engine';
5
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
6
+ import { Vector3 } from '@babylonjs/core/Maths/math.vector';
7
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
8
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
9
+ import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
10
+ import { Scene } from '@babylonjs/core/scene';
11
+ import { isString } from 'lodash-es';
12
+ import { version } from '../../buildinfo.json';
13
+ import { sceneSetup } from '../internal/sceneSetup';
14
+ import { AnimationManager } from '../manager/animationManager';
15
+ import { SceneManager } from '../manager/sceneManager';
16
+ import { VariantInstanceManager } from '../manager/variantInstanceManager';
17
+ import { SpecStorage } from '../store/specStorage';
18
+ import { debounce, loadJson } from '../util/resourceHelper';
19
+ import { Event } from './event';
20
+ import { EventBroadcaster } from './eventBroadcaster';
21
+ import { Parameter } from './parameter';
22
+ import { Variant } from './variant';
23
+ import { VariantInstance } from './variantInstance';
24
+
25
+
26
+ /**
27
+ * The main exposed object. This is the entry point into the application
28
+ *
29
+ * ```js
30
+ * const canvas = document.getElementById( 'babylon-canvas' );
31
+ * const viewer = Viewer( canvas, '/path/to/index.json' );
32
+ * ```
33
+ * The class does nothing on its own and needs to {@link bootstrap}
34
+ */
35
+ export class Viewer extends EventBroadcaster {
36
+
37
+ protected _scene: Scene | null = null;
38
+
39
+ protected _animationManager: AnimationManager | null = null;
40
+
41
+ protected _sceneManager: SceneManager | null = null;
42
+
43
+ protected _variantInstances: VariantInstanceManager | null = null;
44
+
45
+ static version = version;
46
+
47
+ /**
48
+ * Constructor
49
+ */
50
+ public constructor( public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson ) {
51
+ super();
52
+ }
53
+
54
+ /**
55
+ * Gets the BabylonJS Scene that is attached to the instance.
56
+ *
57
+ * @throws Error if the `scene` has not been initialized.
58
+ */
59
+ get scene(): Scene {
60
+ if( !this._scene ) {
61
+ throw new Error( `Scene has not been initialized.` );
62
+ }
63
+ return this._scene;
64
+ }
65
+
66
+ get sceneManager(): SceneManager {
67
+ if( !this._sceneManager ) {
68
+ throw new Error( `Environment has not been initialized.` );
69
+ }
70
+ return this._sceneManager;
71
+ }
72
+
73
+ /**
74
+ * Gets the BabylonJS Engine that is attached to the viewer.
75
+ */
76
+ get engine(): Engine {
77
+ return this.scene.getEngine();
78
+ }
79
+
80
+ /**
81
+ * Gets the {@link VariantInstanceManager} attached to the viewer.
82
+ *
83
+ * @throws Error if the {@link VariantInstanceManager} has not been initialized.
84
+ */
85
+ get variantInstances(): VariantInstanceManager {
86
+ if( !this._variantInstances ) {
87
+ throw Error( `There is no variantInstanceManager.` );
88
+ }
89
+ return this._variantInstances;
90
+ }
91
+
92
+ /**
93
+ * Gets the {@link AnimationManager} attached to the viewer.
94
+ *
95
+ * @throws Error if the {@link AnimationManager} has not been initialized.
96
+ */
97
+ get animationManager(): AnimationManager {
98
+ if( !this._animationManager ) {
99
+ throw new Error( `There is no animationManager instance.` );
100
+ }
101
+ return this._animationManager;
102
+ }
103
+
104
+ /**
105
+ * Starts the application. This will
106
+ * * load the given "index" JSON file
107
+ * * setup the scene with the "scene" JSON file
108
+ * * create an (optional) default setup with different variant settings
109
+ * * sets up resizing by attaching a debounced version of {@link resize}
110
+ *
111
+ * @throws Error if any of the files is not found/valid
112
+ *
113
+ * @emits {@link Event.BOOTSTRAP_START}
114
+ * @emits {@link Event.BOOTSTRAP_END}
115
+ */
116
+ public async bootstrap(): Promise<Viewer> {
117
+ this.broadcastEvent( Event.BOOTSTRAP_START, this );
118
+ let indexJson;
119
+ if( isString( this.structureJson ) ) {
120
+ indexJson = await loadJson<StructureJson>( this.structureJson );
121
+ } else {
122
+ indexJson = this.structureJson;
123
+ }
124
+ if( !indexJson.scene ) {
125
+ throw new Error( `No "scene" property found for bootstrapping.` );
126
+ }
127
+ // fill spec store
128
+ SpecStorage.createFromSpec( indexJson );
129
+ // load scene
130
+ if( isString( indexJson.scene ) ) {
131
+ const sceneJson = await loadJson<SceneJson>( indexJson.scene );
132
+ indexJson.scene = sceneJson;
133
+ }
134
+ this._scene = await this.initScene();
135
+ // create instance manager
136
+ const rootVariant = await Variant.create( '_', indexJson, this );
137
+ this._variantInstances = await VariantInstanceManager.create( rootVariant );
138
+ // create optional default instances
139
+ if( indexJson.setup ) {
140
+ if( isString( indexJson.setup ) ) {
141
+ const setupJson = await loadJson<SetupJson>( indexJson.setup );
142
+ indexJson.setup = setupJson;
143
+ }
144
+ await this.createVariantInstances();
145
+ }
146
+ // resize handler
147
+ window.addEventListener( 'resize', debounce( this.resize.bind( this ), 100 ) );
148
+ // event broadcasting
149
+ this.broadcastEvent( Event.BOOTSTRAP_END, this );
150
+ return this;
151
+ }
152
+
153
+ // Disabled for now to decrease bundle size.
154
+ // See https://github.com/Combeenation/3d-viewer/issues/37
155
+ // /**
156
+ // * Enables the BabylonJS DebugLayer. If you pass options, be sure to pass an Object of type `IInspectorOptions`.
157
+ // */
158
+ // public async enableDebugLayer(options?: any) {
159
+ // // @ts-ignore
160
+ // await import(/* webpackChunkName: "debug-inspector" */'@babylonjs/inspector');
161
+ // await this.scene.debugLayer.show(options);
162
+ // return this;
163
+ // }
164
+
165
+ /**
166
+ * Destroys all registered {@link VariantInstance}s that are registered
167
+ */
168
+ public destroyVariantInstances(): Viewer {
169
+ this.variantInstances.all.forEach( variantInstance => {
170
+ this.variantInstances.destroy( variantInstance.name );
171
+ } );
172
+ return this;
173
+ }
174
+
175
+ /**
176
+ * Trigger a resize event for the `Engine`
177
+ */
178
+ public resize(): Viewer {
179
+ this.engine.resize();
180
+ return this;
181
+ }
182
+
183
+ /**
184
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
185
+ * {@link DottedPath}s.
186
+ */
187
+ public async getNode( variantInstanceName: string,
188
+ elementDottedPath: DottedPathArgument,
189
+ nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
190
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
191
+ return variantInstance.getNode( elementDottedPath, nodeDottedPath );
192
+ }
193
+
194
+ /**
195
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
196
+ * {@link DottedPath}s.
197
+ */
198
+ public async getMesh( variantInstanceName: string,
199
+ elementDottedPath: DottedPathArgument,
200
+ meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
201
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
202
+ return variantInstance.getMesh( elementDottedPath, meshDottedPath );
203
+ }
204
+
205
+ /**
206
+ * Switches the camera
207
+ *
208
+ * @emits {@link Event.CAMERA_SWITCHED}
209
+ */
210
+ public switchCamera( newCamera: string, reset: boolean = true ): Viewer {
211
+ const camera = this.scene.getCameraByName( newCamera );
212
+ if( camera ) {
213
+ const activeCamera = this.scene.activeCamera;
214
+ if( activeCamera ) {
215
+ activeCamera.detachControl( this.engine.getRenderingCanvas()! );
216
+ }
217
+ if( reset ) {
218
+ camera.restoreState();
219
+ }
220
+ this.scene.setActiveCameraByName( newCamera );
221
+ camera.attachControl( this.engine.getRenderingCanvas()! );
222
+ this.broadcastEvent( Event.CAMERA_SWITCHED, camera );
223
+ } else {
224
+ throw new Error( `Given camera "${newCamera}" not found.` );
225
+ }
226
+ // TODO: put traceable observers to new camera (@see element)
227
+ return this;
228
+ }
229
+
230
+ /**
231
+ * Moves or animates the active camera to given `placement`.
232
+ */
233
+ public async moveActiveCameraTo( placement: string | PlacementDefinition,
234
+ animation?: string | AnimationDefinition ): Promise<AnimationInterface> {
235
+ return this.animationManager.animateToPlacement( this.sceneManager.activeCamera, placement, animation );
236
+ }
237
+
238
+ /**
239
+ * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
240
+ */
241
+ public screenshot( settings?: ScreenshotSettings ): Promise<string> {
242
+ return new Promise( ( resolve, reject ) => {
243
+ if( !this.engine ) {
244
+ return reject( 'Engine is null' );
245
+ }
246
+ if( !this.scene ) {
247
+ return reject( 'Scene is null' );
248
+ }
249
+ this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
250
+ ScreenshotTools.CreateScreenshotUsingRenderTarget(
251
+ this.engine,
252
+ this.sceneManager.activeCamera,
253
+ settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
254
+ resolve,
255
+ settings?.mimeType ?? 'image/png',
256
+ settings?.samples ?? 1,
257
+ settings?.antialiasing ?? false,
258
+ settings?.fileName ?? 'screenshot.png',
259
+ settings?.renderSprites ?? false
260
+ );
261
+ } );
262
+ }
263
+
264
+ /**
265
+ * Calculates the bounding box from all visible meshes on the scene.
266
+ */
267
+ public calculateBoundingBox(): Mesh {
268
+ if( this.scene.meshes.length === 0 ) {
269
+ throw new Error( 'There are currently no meshes on the scene.' );
270
+ }
271
+ let max = new Vector3( 0, 0, 0 );
272
+ let min = new Vector3( 0, 0, 0 );
273
+ this.scene.meshes.filter( mesh => mesh.isVisible ).forEach( mesh => {
274
+ max = Vector3.Maximize( max, mesh.getBoundingInfo().boundingBox.maximumWorld );
275
+ min = Vector3.Minimize( min, mesh.getBoundingInfo().boundingBox.minimumWorld );
276
+ } );
277
+ let boundingBox = this.scene.getMeshByName( '__bounding_box__' ) as Mesh;
278
+ if( !boundingBox ) {
279
+ boundingBox = new Mesh( '__bounding_box__', this.scene );
280
+ }
281
+ boundingBox.setBoundingInfo( new BoundingInfo( min, max ) );
282
+ //boundingBox.showBoundingBox = true;
283
+ return boundingBox;
284
+ }
285
+
286
+ /**
287
+ * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning.
288
+ */
289
+ public autofocusActiveCamera( settings?: AutofocusSettings ) {
290
+ const activeCamera = this.scene.activeCamera;
291
+ if( !activeCamera ) {
292
+ throw new Error( 'No active camera found when using autofocus feature.' );
293
+ }
294
+ if( activeCamera instanceof ArcRotateCamera ) {
295
+ // calculate some values
296
+ const boundingBox = this.calculateBoundingBox();
297
+ const size = boundingBox.getBoundingInfo().maximum.subtract( boundingBox.getBoundingInfo().minimum );
298
+ let radius = size.length() * (settings?.radiusFactor ?? 1.5);
299
+ if( !isFinite( radius ) ) {
300
+ radius = 1;
301
+ }
302
+ // use helper camera to get some default values
303
+ const helperCamera = new ArcRotateCamera(
304
+ '__helper_camera__',
305
+ Math.PI / -2,
306
+ Math.PI / 2,
307
+ radius,
308
+ Vector3.Zero(),
309
+ this.scene
310
+ );
311
+ helperCamera.useFramingBehavior = true;
312
+ helperCamera.setTarget( boundingBox );
313
+ // translate values from helper to active camera
314
+ activeCamera.setTarget( Mesh.Center( [boundingBox] ) );
315
+ activeCamera.alpha = helperCamera.alpha;
316
+ activeCamera.beta = helperCamera.beta;
317
+ activeCamera.minZ = helperCamera.minZ;
318
+ activeCamera.maxZ = helperCamera.maxZ;
319
+ activeCamera.radius = helperCamera.radius;
320
+ activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
321
+ activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
322
+ if( settings?.adjustWheelPrecision !== false ) {
323
+ activeCamera.wheelPrecision = helperCamera.wheelPrecision;
324
+ }
325
+ if( settings?.adjustPanningSensibility !== false ) {
326
+ activeCamera.panningSensibility = helperCamera.panningSensibility;
327
+ }
328
+ if( settings?.adjustPinchPrecision !== false ) {
329
+ activeCamera.pinchPrecision = helperCamera.pinchPrecision;
330
+ }
331
+ // remove the helper camera
332
+ helperCamera.dispose();
333
+ } else {
334
+ const cameraClsName = activeCamera.getClassName();
335
+ throw new Error( `Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.` );
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
341
+ * environment
342
+ */
343
+ public async reset(): Promise<Viewer> {
344
+ await this.destroy();
345
+ return this.bootstrap();
346
+ }
347
+
348
+ /**
349
+ * Destroys
350
+ *
351
+ * * all {@link VariantInstance}s using {@link destroyVariantInstances}
352
+ * * calling `dispose` on the `Engine` and `Scene`
353
+ */
354
+ public destroy(): Viewer {
355
+ this.destroyVariantInstances();
356
+ this.scene.dispose();
357
+ SpecStorage.destroy();
358
+ return this;
359
+ }
360
+
361
+ /**
362
+ * @emits {@link Event.SCENE_PROCESSING_START}
363
+ * @emits {@link Event.SCENE_PROCESSING_END}
364
+ */
365
+ protected async initScene(): Promise<Scene> {
366
+ const sceneJson = SpecStorage.get<SceneJson>( 'scene' );
367
+ this.broadcastEvent( Event.SCENE_PROCESSING_START, sceneJson );
368
+ const engine = new Engine(
369
+ this.canvas as HTMLCanvasElement,
370
+ sceneJson.engine?.antialiasing ?? false,
371
+ sceneJson.engine?.options
372
+ );
373
+ const scene = await sceneSetup( engine, sceneJson );
374
+ if( sceneJson.meshPicking ) {
375
+ new HighlightLayer( 'default', scene );
376
+ scene.onPointerPick = ( pointerEvent: PointerEvent, pickInfo: PickingInfo ) => {
377
+ if( !pickInfo.hit ) {
378
+ return;
379
+ }
380
+ const mesh = pickInfo.pickedMesh;
381
+ this.broadcastEvent( Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant );
382
+ if( mesh?.metadata.element ) {
383
+ this.broadcastEvent( Event.ELEMENT_PICKED, mesh.metadata.element );
384
+ }
385
+ if( mesh?.metadata.variant ) {
386
+ if( mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
387
+ mesh.metadata.variant.toggleHighlight();
388
+ }
389
+ this.broadcastEvent( Event.VARIANT_PICKED, mesh.metadata.variant );
390
+ }
391
+ };
392
+ }
393
+ this._sceneManager = await SceneManager.create( scene );
394
+ this._animationManager = await AnimationManager.create( scene );
395
+ this.broadcastEvent( Event.SCENE_PROCESSING_END, scene );
396
+ engine.runRenderLoop( () => {
397
+ scene.render();
398
+ } );
399
+ return scene;
400
+ }
401
+
402
+ /**
403
+ * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
404
+ */
405
+ protected async createVariantInstances(): Promise<VariantInstance[]> {
406
+ const setupJson = SpecStorage.get<SetupJson>( 'setup' );
407
+ const instances = [];
408
+ for( const instanceDefinition of setupJson.instances ) {
409
+ if( instanceDefinition.lazy ) {
410
+ this.variantInstances.register( instanceDefinition );
411
+ continue;
412
+ }
413
+ instances.push( await this.variantInstances.create(
414
+ instanceDefinition.variant,
415
+ instanceDefinition.name,
416
+ instanceDefinition.parameters
417
+ ) );
418
+ }
419
+ return instances;
420
+ }
421
+
422
422
  }