@combeenation/3d-viewer 6.1.0 → 6.2.0

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