@combeenation/3d-viewer 4.0.0-alpha9 → 4.0.0-beta4

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 (105) hide show
  1. package/README.md +112 -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 -130
  7. package/dist/lib-cjs/api/classes/element.js +682 -739
  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 -326
  12. package/dist/lib-cjs/api/classes/event.js +357 -371
  13. package/dist/lib-cjs/api/classes/event.js.map +1 -1
  14. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  15. package/dist/lib-cjs/api/classes/eventBroadcaster.js +53 -53
  16. package/dist/lib-cjs/api/classes/parameter.d.ts +165 -259
  17. package/dist/lib-cjs/api/classes/parameter.js +267 -387
  18. package/dist/lib-cjs/api/classes/parameter.js.map +1 -1
  19. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  20. package/dist/lib-cjs/api/classes/parameterObservable.js +126 -101
  21. package/dist/lib-cjs/api/classes/parameterObservable.js.map +1 -1
  22. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  23. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  24. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +38 -38
  25. package/dist/lib-cjs/api/classes/placementAnimation.js +138 -138
  26. package/dist/lib-cjs/api/classes/variant.d.ts +190 -224
  27. package/dist/lib-cjs/api/classes/variant.js +873 -1137
  28. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  29. package/dist/lib-cjs/api/classes/variantInstance.d.ts +41 -45
  30. package/dist/lib-cjs/api/classes/variantInstance.js +98 -108
  31. package/dist/lib-cjs/api/classes/variantInstance.js.map +1 -1
  32. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  33. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  34. package/dist/lib-cjs/api/classes/viewer.d.ts +128 -131
  35. package/dist/lib-cjs/api/classes/viewer.js +486 -538
  36. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  37. package/dist/lib-cjs/api/classes/viewerLight.d.ts +65 -66
  38. package/dist/lib-cjs/api/classes/viewerLight.js +322 -389
  39. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  40. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  41. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  42. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  43. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  44. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +6 -10
  45. package/dist/lib-cjs/api/internal/sceneSetup.js +227 -231
  46. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  47. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  48. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  49. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  50. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  51. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  52. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  53. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  54. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  55. package/dist/lib-cjs/api/util/babylonHelper.d.ts +125 -175
  56. package/dist/lib-cjs/api/util/babylonHelper.js +368 -520
  57. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  58. package/dist/lib-cjs/api/util/globalTypes.d.ts +279 -321
  59. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  60. package/dist/lib-cjs/api/util/resourceHelper.d.ts +51 -26
  61. package/dist/lib-cjs/api/util/resourceHelper.js +243 -237
  62. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  63. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  64. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  65. package/dist/lib-cjs/buildinfo.json +3 -3
  66. package/dist/lib-cjs/index.d.ts +46 -48
  67. package/dist/lib-cjs/index.js +82 -86
  68. package/dist/lib-cjs/index.js.map +1 -1
  69. package/dist/webpack-stats.json +0 -0
  70. package/package.json +83 -83
  71. package/src/api/classes/animationInterface.ts +11 -11
  72. package/src/api/classes/dottedPath.ts +189 -189
  73. package/src/api/classes/element.ts +617 -635
  74. package/src/api/classes/{parameterizable.ts → elementParameterizable.ts} +78 -89
  75. package/src/api/classes/event.ts +355 -370
  76. package/src/api/classes/eventBroadcaster.ts +54 -54
  77. package/src/api/classes/parameter.ts +277 -408
  78. package/src/api/classes/parameterObservable.ts +121 -99
  79. package/src/api/classes/placementAnimation.ts +133 -133
  80. package/src/api/classes/variant.ts +670 -806
  81. package/src/api/classes/variantInstance.ts +81 -88
  82. package/src/api/classes/viewer.ts +421 -473
  83. package/src/api/internal/debugViewer.ts +81 -81
  84. package/src/api/internal/lensRendering.ts +10 -10
  85. package/src/api/internal/sceneSetup.ts +204 -194
  86. package/src/api/manager/animationManager.ts +116 -116
  87. package/src/api/manager/sceneManager.ts +105 -105
  88. package/src/api/manager/variantInstanceManager.ts +236 -236
  89. package/src/api/store/specStorage.ts +53 -53
  90. package/src/api/util/babylonHelper.ts +392 -553
  91. package/src/api/util/globalTypes.ts +318 -369
  92. package/src/api/util/resourceHelper.ts +187 -157
  93. package/src/buildinfo.json +2 -2
  94. package/src/commonjs.tsconfig.json +13 -13
  95. package/src/declaration.tsconfig.json +10 -10
  96. package/src/dev.ts +46 -44
  97. package/src/es6.tsconfig.json +13 -13
  98. package/src/index.ts +87 -91
  99. package/src/pagesconfig.json +57 -52
  100. package/src/tsconfig.json +43 -43
  101. package/src/tsconfig.types.json +9 -9
  102. package/src/types.d.ts +4 -4
  103. package/src/api/classes/variantParameterizable.ts +0 -73
  104. package/src/api/classes/viewerLight.ts +0 -330
  105. package/src/api/util/stringHelper.ts +0 -26
@@ -1,474 +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 { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
7
- import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
8
- import { Color3 } from '@babylonjs/core/Maths/math.color';
9
- import { Vector3 } from '@babylonjs/core/Maths/math.vector';
10
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
11
- import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
12
- import { Scene } from '@babylonjs/core/scene';
13
- import { isString } from 'lodash-es';
14
- import { version } from '../../buildinfo.json';
15
- import { sceneSetup } from '../internal/sceneSetup';
16
- import { AnimationManager } from '../manager/animationManager';
17
- import { SceneManager } from '../manager/sceneManager';
18
- import { VariantInstanceManager } from '../manager/variantInstanceManager';
19
- import { SpecStorage } from '../store/specStorage';
20
- import { debounce, loadJson } from '../util/resourceHelper';
21
- import { Event } from './event';
22
- import { EventBroadcaster } from './eventBroadcaster';
23
- import { Parameter } from './parameter';
24
- import { Variant } from './variant';
25
- import { VariantInstance } from './variantInstance';
26
-
27
-
28
- /**
29
- * The main exposed object. This is the entry point into the application
30
- *
31
- * ```js
32
- * const canvas = document.getElementById( 'babylon-canvas' );
33
- * const viewer = Viewer( canvas, '/path/to/index.json' );
34
- * ```
35
- * The class does nothing on its own and needs to {@link bootstrap}
36
- */
37
- 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
- // event broadcasting
151
- this.broadcastEvent( Event.BOOTSTRAP_END, this );
152
- return this;
153
- }
154
-
155
- // Disabled for now to decrease bundle size.
156
- // See https://github.com/Combeenation/3d-viewer/issues/37
157
- // /**
158
- // * Enables the BabylonJS DebugLayer. If you pass options, be sure to pass an Object of type `IInspectorOptions`.
159
- // */
160
- // public async enableDebugLayer(options?: any) {
161
- // // @ts-ignore
162
- // await import(/* webpackChunkName: "debug-inspector" */'@babylonjs/inspector');
163
- // await this.scene.debugLayer.show(options);
164
- // return this;
165
- // }
166
-
167
- /**
168
- * Destroys all registered {@link VariantInstance}s that are registered
169
- */
170
- public destroyVariantInstances(): Viewer {
171
- this.variantInstances.all.forEach( variantInstance => {
172
- this.variantInstances.destroy( variantInstance.name );
173
- } );
174
- return this;
175
- }
176
-
177
- /**
178
- * Trigger a resize event for the `Engine`
179
- */
180
- public resize(): Viewer {
181
- this.engine.resize();
182
- return this;
183
- }
184
-
185
- /**
186
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
187
- * {@link DottedPath}s.
188
- */
189
- public async getNode( variantInstanceName: string,
190
- elementDottedPath: DottedPathArgument,
191
- nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
192
- const variantInstance = await this.variantInstances.get(variantInstanceName);
193
- return variantInstance.getNode( elementDottedPath, nodeDottedPath );
194
- }
195
-
196
- /**
197
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
198
- * {@link DottedPath}s.
199
- */
200
- public async getMesh( variantInstanceName: string,
201
- elementDottedPath: DottedPathArgument,
202
- meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
203
- const variantInstance = await this.variantInstances.get(variantInstanceName);
204
- return variantInstance.getMesh( elementDottedPath, meshDottedPath );
205
- }
206
-
207
- /**
208
- * Switches the camera
209
- *
210
- * @emits {@link Event.CAMERA_SWITCHED}
211
- */
212
- public switchCamera( newCamera: string, reset: boolean = true ): Viewer {
213
- const camera = this.scene.getCameraByName( newCamera );
214
- if( camera ) {
215
- const activeCamera = this.scene.activeCamera;
216
- if( activeCamera ) {
217
- activeCamera.detachControl( this.engine.getRenderingCanvas()! );
218
- }
219
- if( reset ) {
220
- camera.restoreState();
221
- }
222
- this.scene.setActiveCameraByName( newCamera );
223
- camera.attachControl( this.engine.getRenderingCanvas()! );
224
- this.broadcastEvent( Event.CAMERA_SWITCHED, camera );
225
- } else {
226
- throw new Error( `Given camera "${newCamera}" not found.` );
227
- }
228
- // TODO: put traceable observers to new camera (@see element)
229
- return this;
230
- }
231
-
232
- /**
233
- * Moves or animates the active camera to given `placement`.
234
- */
235
- public async moveActiveCameraTo( placement: string | PlacementDefinition,
236
- animation?: string | AnimationDefinition ): Promise<AnimationInterface> {
237
- return this.animationManager.animateToPlacement( this.sceneManager.activeCamera, placement, animation );
238
- }
239
-
240
- /**
241
- * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
242
- */
243
- public screenshot( settings?: ScreenshotSettings ): Promise<string> {
244
- return new Promise( ( resolve, reject ) => {
245
- if( !this.engine ) {
246
- return reject( 'Engine is null' );
247
- }
248
- if( !this.scene ) {
249
- return reject( 'Scene is null' );
250
- }
251
- this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
252
- ScreenshotTools.CreateScreenshotUsingRenderTarget(
253
- this.engine,
254
- this.sceneManager.activeCamera,
255
- settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
256
- resolve,
257
- settings?.mimeType ?? 'image/png',
258
- settings?.samples ?? 1,
259
- settings?.antialiasing ?? false,
260
- settings?.fileName ?? 'screenshot.png',
261
- settings?.renderSprites ?? false
262
- );
263
- } );
264
- }
265
-
266
- /**
267
- * Calculates the bounding box from all visible meshes on the scene.
268
- */
269
- public calculateBoundingBox(): Mesh {
270
- if( this.scene.meshes.length === 0 ) {
271
- throw new Error( 'There are currently no meshes on the scene.' );
272
- }
273
- let max = new Vector3( 0, 0, 0 );
274
- let min = new Vector3( 0, 0, 0 );
275
- this.scene.meshes.filter( mesh => mesh.isVisible ).forEach( mesh => {
276
- max = Vector3.Maximize( max, mesh.getBoundingInfo().boundingBox.maximumWorld );
277
- min = Vector3.Minimize( min, mesh.getBoundingInfo().boundingBox.minimumWorld );
278
- } );
279
- let boundingBox = this.scene.getMeshByName( '__bounding_box__' ) as Mesh;
280
- if( !boundingBox ) {
281
- boundingBox = new Mesh( '__bounding_box__', this.scene );
282
- }
283
- boundingBox.setBoundingInfo( new BoundingInfo( min, max ) );
284
- //boundingBox.showBoundingBox = true;
285
- return boundingBox;
286
- }
287
-
288
- /**
289
- * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning.
290
- */
291
- public autofocusActiveCamera( settings?: AutofocusSettings ) {
292
- const activeCamera = this.scene.activeCamera;
293
- if( !activeCamera ) {
294
- throw new Error( 'No active camera found when using autofocus feature.' );
295
- }
296
- if( activeCamera instanceof ArcRotateCamera ) {
297
- // calculate some values
298
- const boundingBox = this.calculateBoundingBox();
299
- const size = boundingBox.getBoundingInfo().maximum.subtract( boundingBox.getBoundingInfo().minimum );
300
- let radius = size.length() * (settings?.radiusFactor ?? 1.5);
301
- if( !isFinite( radius ) ) {
302
- radius = 1;
303
- }
304
- // use helper camera to get some default values
305
- const helperCamera = new ArcRotateCamera(
306
- '__helper_camera__',
307
- Math.PI / -2,
308
- Math.PI / 2,
309
- radius,
310
- Vector3.Zero(),
311
- this.scene
312
- );
313
- helperCamera.useFramingBehavior = true;
314
- helperCamera.setTarget( boundingBox );
315
- // translate values from helper to active camera
316
- activeCamera.setTarget( Mesh.Center( [boundingBox] ) );
317
- activeCamera.alpha = helperCamera.alpha;
318
- activeCamera.beta = helperCamera.beta;
319
- activeCamera.minZ = helperCamera.minZ;
320
- activeCamera.maxZ = helperCamera.maxZ;
321
- activeCamera.radius = helperCamera.radius;
322
- activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
323
- activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
324
- if( settings?.adjustWheelPrecision !== false ) {
325
- activeCamera.wheelPrecision = helperCamera.wheelPrecision;
326
- }
327
- if( settings?.adjustPanningSensibility !== false ) {
328
- activeCamera.panningSensibility = helperCamera.panningSensibility;
329
- }
330
- if( settings?.adjustPinchPrecision !== false ) {
331
- activeCamera.pinchPrecision = helperCamera.pinchPrecision;
332
- }
333
- // remove the helper camera
334
- helperCamera.dispose();
335
- } else {
336
- const cameraClsName = activeCamera.getClassName();
337
- throw new Error( `Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.` );
338
- }
339
- }
340
-
341
- /**
342
- * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
343
- * environment
344
- */
345
- public async reset(): Promise<Viewer> {
346
- await this.destroy();
347
- return this.bootstrap();
348
- }
349
-
350
- /**
351
- * Destroys
352
- *
353
- * * all {@link VariantInstance}s using {@link destroyVariantInstances}
354
- * * calling `dispose` on the `Engine` and `Scene`
355
- */
356
- public destroy(): Viewer {
357
- this.destroyVariantInstances();
358
- this.scene.dispose();
359
- SpecStorage.destroy();
360
- return this;
361
- }
362
-
363
- /**
364
- * Show coordinate system with given dimension (for debugging purpose).
365
- */
366
- public showWorldCoordinates( dimension: number ) {
367
- const scene = this.scene;
368
- const makeTextPlane = function( text: string, color: string, size: number ) {
369
- const dynamicTexture = new DynamicTexture( 'DynamicTexture', 50, scene, true );
370
- dynamicTexture.hasAlpha = true;
371
- dynamicTexture.drawText( text, 5, 40, 'bold 36px Arial', color, 'transparent', true );
372
- const plane = Mesh.CreatePlane( 'TextPlane', size, scene, true );
373
- plane.material = new StandardMaterial( 'TextPlaneMaterial', scene );
374
- plane.material.backFaceCulling = false;
375
- // @ts-ignore
376
- plane.material.specularColor = new Color3( 0, 0, 0 );
377
- // @ts-ignore
378
- plane.material.diffuseTexture = dynamicTexture;
379
- return plane;
380
- };
381
- const axisX = Mesh.CreateLines( 'axisX', [
382
- Vector3.Zero(),
383
- new Vector3( dimension, 0, 0 ),
384
- new Vector3( dimension * 0.95, 0.05 * dimension, 0 ),
385
- new Vector3( dimension, 0, 0 ),
386
- new Vector3( dimension * 0.95, -0.05 * dimension, 0 )
387
- ], scene );
388
- axisX.color = new Color3( 1, 0, 0 );
389
- const xChar = makeTextPlane( 'X', 'red', dimension / 10 );
390
- xChar.position = new Vector3( 0.9 * dimension, -0.05 * dimension, 0 );
391
- const axisY = Mesh.CreateLines( 'axisY', [
392
- Vector3.Zero(),
393
- new Vector3( 0, dimension, 0 ),
394
- new Vector3( -0.05 * dimension, dimension * 0.95, 0 ),
395
- new Vector3( 0, dimension, 0 ),
396
- new Vector3( 0.05 * dimension, dimension * 0.95, 0 )
397
- ], scene );
398
- axisY.color = new Color3( 0, 1, 0 );
399
- const yChar = makeTextPlane( 'Y', 'green', dimension / 10 );
400
- yChar.position = new Vector3( 0, 0.9 * dimension, -0.05 * dimension );
401
- const axisZ = Mesh.CreateLines( 'axisZ', [
402
- Vector3.Zero(),
403
- new Vector3( 0, 0, dimension ),
404
- new Vector3( 0, -0.05 * dimension, dimension * 0.95 ),
405
- new Vector3( 0, 0, dimension ),
406
- new Vector3( 0, 0.05 * dimension, dimension * 0.95 )
407
- ], scene );
408
- axisZ.color = new Color3( 0, 0, 1 );
409
- const zChar = makeTextPlane( 'Z', 'blue', dimension / 10 );
410
- zChar.position = new Vector3( 0, 0.05 * dimension, 0.9 * dimension );
411
- }
412
-
413
- /**
414
- * @emits {@link Event.SCENE_PROCESSING_START}
415
- * @emits {@link Event.SCENE_PROCESSING_END}
416
- */
417
- protected async initScene(): Promise<Scene> {
418
- const sceneJson = SpecStorage.get<SceneJson>( 'scene' );
419
- this.broadcastEvent( Event.SCENE_PROCESSING_START, sceneJson );
420
- const engine = new Engine(
421
- this.canvas as HTMLCanvasElement,
422
- sceneJson.engine?.antialiasing ?? false,
423
- sceneJson.engine?.options
424
- );
425
- const scene = await sceneSetup( engine, sceneJson );
426
- if( sceneJson.meshPicking ) {
427
- new HighlightLayer( 'default', scene );
428
- scene.onPointerPick = ( pointerEvent: PointerEvent, pickInfo: PickingInfo ) => {
429
- if( !pickInfo.hit ) {
430
- return;
431
- }
432
- const mesh = pickInfo.pickedMesh;
433
- this.broadcastEvent( Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant );
434
- if( mesh?.metadata.element ) {
435
- this.broadcastEvent( Event.ELEMENT_PICKED, mesh.metadata.element );
436
- }
437
- if( mesh?.metadata.variant ) {
438
- if( mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
439
- mesh.metadata.variant.toggleHighlight();
440
- }
441
- this.broadcastEvent( Event.VARIANT_PICKED, mesh.metadata.variant );
442
- }
443
- };
444
- }
445
- this._sceneManager = await SceneManager.create( scene );
446
- this._animationManager = await AnimationManager.create( scene );
447
- this.broadcastEvent( Event.SCENE_PROCESSING_END, scene );
448
- engine.runRenderLoop( () => {
449
- scene.render();
450
- } );
451
- return scene;
452
- }
453
-
454
- /**
455
- * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
456
- */
457
- protected async createVariantInstances(): Promise<VariantInstance[]> {
458
- const setupJson = SpecStorage.get<SetupJson>( 'setup' );
459
- const instances = [];
460
- for( const instanceDefinition of setupJson.instances ) {
461
- if( instanceDefinition.lazy ) {
462
- this.variantInstances.register( instanceDefinition );
463
- continue;
464
- }
465
- instances.push( await this.variantInstances.create(
466
- instanceDefinition.variant,
467
- instanceDefinition.name,
468
- instanceDefinition.parameters
469
- ) );
470
- }
471
- return instances;
472
- }
473
-
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
+
474
422
  }