@combeenation/3d-viewer 14.0.0 → 14.0.1-rc1

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 (65) hide show
  1. package/README.md +9 -9
  2. package/dist/lib-cjs/buildinfo.json +3 -3
  3. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  4. package/dist/lib-cjs/index.d.ts +62 -62
  5. package/dist/lib-cjs/index.js +94 -94
  6. package/dist/lib-cjs/internal/cbn-custom-babylon-loader-plugin.d.ts +10 -10
  7. package/dist/lib-cjs/internal/cbn-custom-babylon-loader-plugin.js +131 -131
  8. package/dist/lib-cjs/internal/cloning-helper.d.ts +19 -19
  9. package/dist/lib-cjs/internal/cloning-helper.js +163 -163
  10. package/dist/lib-cjs/internal/device-helper.d.ts +9 -9
  11. package/dist/lib-cjs/internal/device-helper.js +24 -24
  12. package/dist/lib-cjs/internal/geometry-helper.d.ts +21 -21
  13. package/dist/lib-cjs/internal/geometry-helper.js +145 -145
  14. package/dist/lib-cjs/internal/metadata-helper.d.ts +26 -26
  15. package/dist/lib-cjs/internal/metadata-helper.js +50 -50
  16. package/dist/lib-cjs/internal/paintable-helper.d.ts +40 -40
  17. package/dist/lib-cjs/internal/paintable-helper.js +286 -286
  18. package/dist/lib-cjs/internal/tags-helper.d.ts +12 -12
  19. package/dist/lib-cjs/internal/tags-helper.js +37 -37
  20. package/dist/lib-cjs/manager/camera-manager.d.ts +110 -110
  21. package/dist/lib-cjs/manager/camera-manager.js +206 -206
  22. package/dist/lib-cjs/manager/debug-manager.d.ts +60 -60
  23. package/dist/lib-cjs/manager/debug-manager.js +217 -217
  24. package/dist/lib-cjs/manager/event-manager.d.ts +52 -52
  25. package/dist/lib-cjs/manager/event-manager.js +71 -71
  26. package/dist/lib-cjs/manager/gltf-export-manager.d.ts +84 -75
  27. package/dist/lib-cjs/manager/gltf-export-manager.js +290 -278
  28. package/dist/lib-cjs/manager/gltf-export-manager.js.map +1 -1
  29. package/dist/lib-cjs/manager/material-manager.d.ts +35 -35
  30. package/dist/lib-cjs/manager/material-manager.js +125 -125
  31. package/dist/lib-cjs/manager/model-manager.d.ts +145 -145
  32. package/dist/lib-cjs/manager/model-manager.js +382 -382
  33. package/dist/lib-cjs/manager/parameter-manager.d.ts +210 -210
  34. package/dist/lib-cjs/manager/parameter-manager.js +514 -514
  35. package/dist/lib-cjs/manager/scene-manager.d.ts +45 -45
  36. package/dist/lib-cjs/manager/scene-manager.js +64 -64
  37. package/dist/lib-cjs/manager/texture-manager.d.ts +12 -12
  38. package/dist/lib-cjs/manager/texture-manager.js +43 -43
  39. package/dist/lib-cjs/viewer-error.d.ts +48 -48
  40. package/dist/lib-cjs/viewer-error.js +60 -60
  41. package/dist/lib-cjs/viewer.d.ts +115 -115
  42. package/dist/lib-cjs/viewer.js +217 -217
  43. package/package.json +91 -91
  44. package/src/buildinfo.json +3 -3
  45. package/src/dev.ts +47 -47
  46. package/src/global-types.d.ts +39 -39
  47. package/src/index.ts +81 -81
  48. package/src/internal/cbn-custom-babylon-loader-plugin.ts +159 -159
  49. package/src/internal/cloning-helper.ts +225 -225
  50. package/src/internal/device-helper.ts +25 -25
  51. package/src/internal/geometry-helper.ts +181 -181
  52. package/src/internal/metadata-helper.ts +63 -63
  53. package/src/internal/paintable-helper.ts +310 -310
  54. package/src/internal/tags-helper.ts +41 -41
  55. package/src/manager/camera-manager.ts +365 -365
  56. package/src/manager/debug-manager.ts +245 -245
  57. package/src/manager/event-manager.ts +72 -72
  58. package/src/manager/gltf-export-manager.ts +357 -341
  59. package/src/manager/material-manager.ts +135 -135
  60. package/src/manager/model-manager.ts +458 -458
  61. package/src/manager/parameter-manager.ts +652 -652
  62. package/src/manager/scene-manager.ts +101 -101
  63. package/src/manager/texture-manager.ts +32 -32
  64. package/src/viewer-error.ts +68 -68
  65. package/src/viewer.ts +290 -290
@@ -1,458 +1,458 @@
1
- import {
2
- AssetContainer,
3
- BuiltInParameter,
4
- MaterialManager,
5
- MeshBuilder,
6
- ParameterManager,
7
- SceneLoader,
8
- TransformNode,
9
- Viewer,
10
- ViewerError,
11
- ViewerErrorIds,
12
- } from '../index';
13
- import { cloneModelAssetContainer } from '../internal/cloning-helper';
14
- import { getInternalMetadataValue } from '../internal/metadata-helper';
15
- import { isArray } from 'lodash-es';
16
-
17
- export type ModelAssetDefinition = {
18
- name: string;
19
- url: string;
20
- };
21
-
22
- export type ModelVisibilityEntry = {
23
- name: string;
24
- visible: boolean;
25
- };
26
-
27
- /**
28
- * Callback for renaming nodes when cloning nodes in a model
29
- */
30
- export type NodeNamingStrategy = (node: TransformNode, newModelName: string) => string;
31
- /**
32
- * Callback for renaming tags when cloning nodes in a model
33
- */
34
- export type TagNamingStrategy = (tag: string, newModelName: string) => string;
35
-
36
- export type ModelCloneOptions = {
37
- nodeNamingStrategy: NodeNamingStrategy;
38
- tagNamingStrategy: TagNamingStrategy;
39
- };
40
-
41
- type Model = {
42
- name: string;
43
- url: string;
44
- state: ModelAssetState;
45
- assetContainer: AssetContainer;
46
- isClone: boolean;
47
- visibilityCallId?: number;
48
- };
49
-
50
- type ModelAssetState = 'notLoaded' | 'loading' | 'loaded' | 'inScene';
51
-
52
- /**
53
- * Manager for handling 3d models.\
54
- * Responsible for loading models and handling their visibility.\
55
- * Also contains advanced features like model cloning.
56
- */
57
- export class ModelManager {
58
- /**
59
- * CAUTION: this has to be in sync with the Combeenation backend!
60
- * @internal
61
- */
62
- public static readonly CBN_FALLBACK_MODEL_ASSET_NAME = '$fallback';
63
-
64
- protected _modelAssets: {
65
- [name: string]: Model;
66
- } = {};
67
- protected _fallbackModelAsset: Model = {
68
- name: ModelManager.CBN_FALLBACK_MODEL_ASSET_NAME,
69
- url: '',
70
- state: 'loaded',
71
- assetContainer: new AssetContainer(),
72
- isClone: false,
73
- };
74
- protected _loadModelPromises: { [modelName: string]: Promise<void> } = {};
75
-
76
- get modelNames(): string[] {
77
- return Object.keys(this._modelAssets);
78
- }
79
-
80
- /**
81
- * Nested models were targeted with slash notation previously, as Spec couldn't work with dots.
82
- * Dots were interpreted as inherited model.
83
- * Now the Hive viewer parameters are returning slash notated asset names, whereas the asset names from the
84
- * prepacked asset manager are dot notated.
85
- * This function converts slash to dot notation, so that models can be target with slash and dot notation alike.
86
- */
87
- protected static _replaceSlashes(inputStr: string): string {
88
- return inputStr.split('/').join('.');
89
- }
90
-
91
- public constructor(protected viewer: Viewer) {}
92
-
93
- /**
94
- * Creates content for the fallback model, which is actually just a black cube.
95
- * This is used for 3d assets that are linked in a data source but not available (yet).
96
- * The Combeenation backend exchanges the missing 3d asset name with "$fallback", which indicates that we shouldn't
97
- * throw an error but just show the fallback model instead.
98
- *
99
- * @internal
100
- */
101
- public createFallbackModel(): void {
102
- const fallbackCube = MeshBuilder.CreateBox('$fallbackCube', { size: 1 }, this.viewer.scene);
103
- fallbackCube._parentContainer = this._fallbackModelAsset.assetContainer;
104
- this._fallbackModelAsset.assetContainer.meshes.push(fallbackCube);
105
- // NOTE: this is theoretically async, but in reality it's not when getting the material description from the CBN
106
- // server
107
- // also this is just a fallback that shouldn't be relevant in productive configurators
108
- this.viewer.materialManager.setMaterialOnMesh(MaterialManager.CBN_FALLBACK_MATERIAL_NAME, fallbackCube);
109
-
110
- this._fallbackModelAsset.assetContainer.removeFromScene();
111
- }
112
-
113
- /**
114
- * Register models for 3d viewer, this is required for each model before it can be loaded/shown.\
115
- * The "viewer control" inside the Combeenation framework calls this function automatically with all assigned
116
- * 3d assets.
117
- */
118
- public registerModels(modelAssets: ModelAssetDefinition[]): void {
119
- for (const { name, url } of modelAssets) {
120
- const existingModel = this._modelAssets[name];
121
- if (existingModel) {
122
- console.warn(`Model ${name} is already registered`);
123
- return;
124
- }
125
-
126
- const model: Model = { name, url, state: 'notLoaded', assetContainer: new AssetContainer(), isClone: false };
127
- this._modelAssets[name] = model;
128
- }
129
- }
130
-
131
- /**
132
- * Loads the model and all it's assigned materials.\
133
- * This function should be used for "eager loading" of models, so that model switching will be instant in the
134
- * process.\
135
- * If you don't plan to do this, just use {@link setModelVisibility} as this function will load the model under the
136
- * hood the first time the model gets visible.
137
- */
138
- public async loadModel(name: string): Promise<void> {
139
- const model = this._getModel(name);
140
- if (!model) {
141
- throw new ViewerError({
142
- id: ViewerErrorIds.ModelNotRegistered,
143
- message: `Can't load model "${name}" as model is not registered`,
144
- });
145
- }
146
-
147
- if (model.state !== 'notLoaded') {
148
- console.warn(`Model ${name} is already loaded or currently loading`);
149
- return;
150
- }
151
-
152
- await this._loadModel(model);
153
- await this._prepareModelForScene(model);
154
- }
155
-
156
- /**
157
- * Enables/disables multiple one or multiple models simultaniously.\
158
- * All required models are loaded before adjusting the visibility to avoid flashing in the 3d scene.
159
- *
160
- * @returns Array of changed visibility status, combined with the corresponding model name
161
- */
162
- public async setModelVisibility(
163
- modelVisibility: ModelVisibilityEntry | ModelVisibilityEntry[]
164
- ): Promise<ModelVisibilityEntry[]> {
165
- const showModels: Model[] = [];
166
- const hideModels: Model[] = [];
167
-
168
- if (!isArray(modelVisibility)) {
169
- modelVisibility = [modelVisibility];
170
- }
171
-
172
- for (const entry of modelVisibility) {
173
- const model = this._getModel(entry.name);
174
- if (!model) {
175
- throw new ViewerError({
176
- id: ViewerErrorIds.ModelNotRegistered,
177
- message: `Can't set visibility of model "${entry.name}" as model is not registered`,
178
- });
179
- }
180
-
181
- // there can be multiple "setModelVisibility" calls while the model is loading
182
- // loading can be awaited, but it has to be ensured, that the last call of "setModelVisibility" has priority
183
- // therefore we store the id of the call in the model
184
- const curVisibilityCallId = (model.visibilityCallId ?? 0) + 1;
185
- model.visibilityCallId = curVisibilityCallId;
186
-
187
- if (entry.visible) {
188
- if (model.state === 'notLoaded') {
189
- await this._loadModel(model);
190
-
191
- // check if this is still the latest visibility call
192
- if (model.visibilityCallId === curVisibilityCallId) {
193
- showModels.push(model);
194
- }
195
- } else if (model.state === 'loading') {
196
- await this._loadModelPromises[model.name];
197
-
198
- if (model.visibilityCallId === curVisibilityCallId) {
199
- showModels.push(model);
200
- }
201
- } else if (model.state === 'loaded') {
202
- showModels.push(model);
203
- }
204
- } else {
205
- if (model.state === 'loading') {
206
- await this._loadModelPromises[model.name];
207
-
208
- if (model.visibilityCallId === curVisibilityCallId) {
209
- hideModels.push(model);
210
- }
211
- } else if (model.state === 'inScene') {
212
- hideModels.push(model);
213
- }
214
- }
215
- }
216
-
217
- for (const showModel of showModels) {
218
- await this._prepareModelForScene(showModel);
219
- }
220
-
221
- for (const showModel of showModels) {
222
- await this._showModel(showModel, true);
223
- }
224
-
225
- for (const hideModel of hideModels) {
226
- this._hideModel(hideModel);
227
- }
228
-
229
- const returnVal: ModelVisibilityEntry[] = [];
230
- showModels.forEach(showModel => returnVal.push({ name: showModel.name, visible: true }));
231
- hideModels.forEach(hideModel => returnVal.push({ name: hideModel.name, visible: false }));
232
-
233
- return returnVal;
234
- }
235
-
236
- /**
237
- * Create a clone of an existing model.\
238
- * Only the geometry (meshes, transform nodes) gets cloned, as materials are typically shared across the whole scene.
239
- *
240
- * @param show show model immediately after cloning
241
- * @param options additional options for the cloning procedure, like renaming algorithms
242
- */
243
- public async cloneModel(
244
- name: string,
245
- newModelName: string,
246
- show: boolean = true,
247
- options?: ModelCloneOptions
248
- ): Promise<void> {
249
- const sourceModel = this._getModel(name);
250
- if (!sourceModel) {
251
- throw new ViewerError({
252
- id: ViewerErrorIds.ModelNotRegistered,
253
- message: `Can't clone model "${name}" as model is not registered`,
254
- });
255
- }
256
-
257
- const existingModel = this._getModel(newModelName);
258
- if (existingModel) {
259
- throw new ViewerError({
260
- id: ViewerErrorIds.ModelAlreadyExists,
261
- message: `Can't create clone as model "${newModelName}" already exists`,
262
- });
263
- }
264
-
265
- if (sourceModel.state === 'notLoaded') {
266
- await this._loadModel(sourceModel);
267
- } else if (sourceModel.state === 'loading') {
268
- await this._loadModelPromises[sourceModel.name];
269
- }
270
-
271
- const clonedModel: Model = {
272
- name: newModelName,
273
- url: sourceModel.url,
274
- state: 'loaded',
275
- assetContainer: cloneModelAssetContainer(
276
- sourceModel.assetContainer,
277
- newModelName,
278
- {
279
- nodeNamingStrategy: options?.nodeNamingStrategy,
280
- tagNamingStrategy: options?.tagNamingStrategy,
281
- },
282
- this.viewer.scene
283
- ),
284
- isClone: true,
285
- };
286
- this._modelAssets[newModelName] = clonedModel;
287
-
288
- if (show) {
289
- await this._showModel(clonedModel);
290
- }
291
- }
292
-
293
- /**
294
- * Removes a cloned model from the scene and from the internal model storage.\
295
- * Deleted clones can not be shown again.
296
- */
297
- public deleteClonedModel(name: string): void {
298
- const model = this._getModel(name);
299
- if (!model) {
300
- throw new ViewerError({
301
- id: ViewerErrorIds.ModelNotRegistered,
302
- message: `Can't delete cloned model "${name}" as model is not registered`,
303
- });
304
- }
305
-
306
- if (!model.isClone) {
307
- throw new ViewerError({
308
- id: ViewerErrorIds.ModelIsNotAClone,
309
- message: `Can't delete model "${name}" as model is not a clone`,
310
- });
311
- }
312
-
313
- model.assetContainer.dispose();
314
-
315
- delete this._modelAssets[name];
316
- }
317
-
318
- /**
319
- * Removes all cloned models from the scene and the internal model storage.
320
- */
321
- public deleteAllClonedModels(): void {
322
- const clonedModelNames = Object.values(this._modelAssets)
323
- .filter(model => model.isClone)
324
- .map(model => model.name);
325
-
326
- clonedModelNames.forEach(modelName => this.deleteClonedModel(modelName));
327
- }
328
-
329
- /**
330
- * Loads and returns the asset container of a certain model.\
331
- * This can be used to access the models content without having to add it to the scene.\
332
- * A typical use case is to clone or instantiate a node from a "library" model.
333
- */
334
- public async getAssetContainerOfModel(name: string): Promise<AssetContainer> {
335
- const model = this._getModel(name);
336
- if (!model) {
337
- throw new ViewerError({
338
- id: ViewerErrorIds.ModelNotRegistered,
339
- message: `Can't get asset container of model "${name}" as model is not registered`,
340
- });
341
- }
342
-
343
- if (model.state === 'notLoaded') {
344
- await this._loadModel(model);
345
- } else if (model.state === 'loading') {
346
- await this._loadModelPromises[model.name];
347
- }
348
-
349
- if (model.state !== 'inScene') {
350
- await this._prepareModelForScene(model);
351
- }
352
-
353
- return model.assetContainer;
354
- }
355
-
356
- /**
357
- * Get model by name
358
- */
359
- protected _getModel(name: string): Model | undefined {
360
- if (name === '$fallback') {
361
- return this._fallbackModelAsset;
362
- }
363
-
364
- const replacedName = ModelManager._replaceSlashes(name);
365
- const model = this._modelAssets[replacedName];
366
-
367
- return model;
368
- }
369
-
370
- /**
371
- * Load model into scene, but don't show it immediately
372
- */
373
- protected async _loadModel(model: Model): Promise<void> {
374
- const loadModelPromise = async (): Promise<void> => {
375
- model.state = 'loading';
376
- const curEnvTexture = this.viewer.scene.environmentTexture;
377
- const curEnvIntensity = this.viewer.scene.environmentIntensity;
378
-
379
- let assetContainer;
380
- try {
381
- assetContainer = await SceneLoader.LoadAssetContainerAsync('', model.url, this.viewer.scene);
382
- } catch (e) {
383
- throw new ViewerError({
384
- id: ViewerErrorIds.AssetLoadingFailed,
385
- message: `Error loading model "${model.name}" from url "${model.url}":\n${(e as Error).message}`,
386
- });
387
- }
388
-
389
- // remove all lights and cameras from the asset, as this data should be handled globally in the scene instead of
390
- // being in a model context
391
- [...assetContainer.lights].forEach(light => light.dispose());
392
- [...assetContainer.cameras].forEach(camera => camera.dispose());
393
-
394
- // environment texture and intensity has been overwritten by load asset container function
395
- this.viewer.scene.environmentTexture = curEnvTexture;
396
- this.viewer.scene.environmentIntensity = curEnvIntensity;
397
-
398
- model.assetContainer = assetContainer;
399
- model.state = 'loaded';
400
-
401
- delete this._loadModelPromises[model.name];
402
- };
403
-
404
- this._loadModelPromises[model.name] = loadModelPromise();
405
- return this._loadModelPromises[model.name];
406
- }
407
-
408
- /**
409
- * Apply parameter to the model in the asset container.
410
- * This is typically done before the model is added to the scene to avoid changes on the visible model, which ensures
411
- * a smooth model switch behaviour.
412
- */
413
- protected async _prepareModelForScene(model: Model): Promise<void> {
414
- await this.viewer.parameterManager.applyAllParameterValuesToModel(model.assetContainer);
415
- // parameter manager did his job, now apply the deferred materials to all meshes that are not explicitely hidden by
416
- // the parameter manager
417
- await this._applyDeferredMaterialsForAllVisibleMeshes(model);
418
- }
419
-
420
- /**
421
- * Add assets of asset container to scene, do the scene preparation if required.
422
- * CAUTION: model is expected to be in the correct loading state already.
423
- *
424
- * @param skipPreparation optionally skip applying parameter values to model before showing it
425
- * (see {@link _prepareModelForScene})
426
- */
427
- protected async _showModel(model: Model, skipPreparation?: boolean): Promise<void> {
428
- if (!skipPreparation) {
429
- await this._prepareModelForScene(model);
430
- }
431
-
432
- model.assetContainer.addToScene();
433
- model.state = 'inScene';
434
- }
435
-
436
- /**
437
- * Remove assets of asset container from scene
438
- */
439
- protected _hideModel(model: Model): void {
440
- model.assetContainer.removeFromScene();
441
- model.state = 'loaded';
442
- }
443
-
444
- /**
445
- * Creates and assigns each "deferred" material to the corresponding mesh, if the mesh is visible.
446
- * Model should be ready to use immediately after this function has done it's job.
447
- */
448
- protected async _applyDeferredMaterialsForAllVisibleMeshes(model: Model): Promise<void> {
449
- for (const mesh of model.assetContainer.meshes) {
450
- const deferredMaterial = getInternalMetadataValue(mesh, 'deferredMaterial');
451
- const rawVisibleValue = this.viewer.parameterManager.getParameterValueOfNode(mesh, BuiltInParameter.Visible);
452
- const visible = rawVisibleValue === undefined || ParameterManager.parseBoolean(rawVisibleValue) === true;
453
- if (deferredMaterial && visible) {
454
- await this.viewer.materialManager.setMaterialOnMesh(deferredMaterial as string, mesh);
455
- }
456
- }
457
- }
458
- }
1
+ import {
2
+ AssetContainer,
3
+ BuiltInParameter,
4
+ MaterialManager,
5
+ MeshBuilder,
6
+ ParameterManager,
7
+ SceneLoader,
8
+ TransformNode,
9
+ Viewer,
10
+ ViewerError,
11
+ ViewerErrorIds,
12
+ } from '../index';
13
+ import { cloneModelAssetContainer } from '../internal/cloning-helper';
14
+ import { getInternalMetadataValue } from '../internal/metadata-helper';
15
+ import { isArray } from 'lodash-es';
16
+
17
+ export type ModelAssetDefinition = {
18
+ name: string;
19
+ url: string;
20
+ };
21
+
22
+ export type ModelVisibilityEntry = {
23
+ name: string;
24
+ visible: boolean;
25
+ };
26
+
27
+ /**
28
+ * Callback for renaming nodes when cloning nodes in a model
29
+ */
30
+ export type NodeNamingStrategy = (node: TransformNode, newModelName: string) => string;
31
+ /**
32
+ * Callback for renaming tags when cloning nodes in a model
33
+ */
34
+ export type TagNamingStrategy = (tag: string, newModelName: string) => string;
35
+
36
+ export type ModelCloneOptions = {
37
+ nodeNamingStrategy: NodeNamingStrategy;
38
+ tagNamingStrategy: TagNamingStrategy;
39
+ };
40
+
41
+ type Model = {
42
+ name: string;
43
+ url: string;
44
+ state: ModelAssetState;
45
+ assetContainer: AssetContainer;
46
+ isClone: boolean;
47
+ visibilityCallId?: number;
48
+ };
49
+
50
+ type ModelAssetState = 'notLoaded' | 'loading' | 'loaded' | 'inScene';
51
+
52
+ /**
53
+ * Manager for handling 3d models.\
54
+ * Responsible for loading models and handling their visibility.\
55
+ * Also contains advanced features like model cloning.
56
+ */
57
+ export class ModelManager {
58
+ /**
59
+ * CAUTION: this has to be in sync with the Combeenation backend!
60
+ * @internal
61
+ */
62
+ public static readonly CBN_FALLBACK_MODEL_ASSET_NAME = '$fallback';
63
+
64
+ protected _modelAssets: {
65
+ [name: string]: Model;
66
+ } = {};
67
+ protected _fallbackModelAsset: Model = {
68
+ name: ModelManager.CBN_FALLBACK_MODEL_ASSET_NAME,
69
+ url: '',
70
+ state: 'loaded',
71
+ assetContainer: new AssetContainer(),
72
+ isClone: false,
73
+ };
74
+ protected _loadModelPromises: { [modelName: string]: Promise<void> } = {};
75
+
76
+ get modelNames(): string[] {
77
+ return Object.keys(this._modelAssets);
78
+ }
79
+
80
+ /**
81
+ * Nested models were targeted with slash notation previously, as Spec couldn't work with dots.
82
+ * Dots were interpreted as inherited model.
83
+ * Now the Hive viewer parameters are returning slash notated asset names, whereas the asset names from the
84
+ * prepacked asset manager are dot notated.
85
+ * This function converts slash to dot notation, so that models can be target with slash and dot notation alike.
86
+ */
87
+ protected static _replaceSlashes(inputStr: string): string {
88
+ return inputStr.split('/').join('.');
89
+ }
90
+
91
+ public constructor(protected viewer: Viewer) {}
92
+
93
+ /**
94
+ * Creates content for the fallback model, which is actually just a black cube.
95
+ * This is used for 3d assets that are linked in a data source but not available (yet).
96
+ * The Combeenation backend exchanges the missing 3d asset name with "$fallback", which indicates that we shouldn't
97
+ * throw an error but just show the fallback model instead.
98
+ *
99
+ * @internal
100
+ */
101
+ public createFallbackModel(): void {
102
+ const fallbackCube = MeshBuilder.CreateBox('$fallbackCube', { size: 1 }, this.viewer.scene);
103
+ fallbackCube._parentContainer = this._fallbackModelAsset.assetContainer;
104
+ this._fallbackModelAsset.assetContainer.meshes.push(fallbackCube);
105
+ // NOTE: this is theoretically async, but in reality it's not when getting the material description from the CBN
106
+ // server
107
+ // also this is just a fallback that shouldn't be relevant in productive configurators
108
+ this.viewer.materialManager.setMaterialOnMesh(MaterialManager.CBN_FALLBACK_MATERIAL_NAME, fallbackCube);
109
+
110
+ this._fallbackModelAsset.assetContainer.removeFromScene();
111
+ }
112
+
113
+ /**
114
+ * Register models for 3d viewer, this is required for each model before it can be loaded/shown.\
115
+ * The "viewer control" inside the Combeenation framework calls this function automatically with all assigned
116
+ * 3d assets.
117
+ */
118
+ public registerModels(modelAssets: ModelAssetDefinition[]): void {
119
+ for (const { name, url } of modelAssets) {
120
+ const existingModel = this._modelAssets[name];
121
+ if (existingModel) {
122
+ console.warn(`Model ${name} is already registered`);
123
+ return;
124
+ }
125
+
126
+ const model: Model = { name, url, state: 'notLoaded', assetContainer: new AssetContainer(), isClone: false };
127
+ this._modelAssets[name] = model;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Loads the model and all it's assigned materials.\
133
+ * This function should be used for "eager loading" of models, so that model switching will be instant in the
134
+ * process.\
135
+ * If you don't plan to do this, just use {@link setModelVisibility} as this function will load the model under the
136
+ * hood the first time the model gets visible.
137
+ */
138
+ public async loadModel(name: string): Promise<void> {
139
+ const model = this._getModel(name);
140
+ if (!model) {
141
+ throw new ViewerError({
142
+ id: ViewerErrorIds.ModelNotRegistered,
143
+ message: `Can't load model "${name}" as model is not registered`,
144
+ });
145
+ }
146
+
147
+ if (model.state !== 'notLoaded') {
148
+ console.warn(`Model ${name} is already loaded or currently loading`);
149
+ return;
150
+ }
151
+
152
+ await this._loadModel(model);
153
+ await this._prepareModelForScene(model);
154
+ }
155
+
156
+ /**
157
+ * Enables/disables multiple one or multiple models simultaniously.\
158
+ * All required models are loaded before adjusting the visibility to avoid flashing in the 3d scene.
159
+ *
160
+ * @returns Array of changed visibility status, combined with the corresponding model name
161
+ */
162
+ public async setModelVisibility(
163
+ modelVisibility: ModelVisibilityEntry | ModelVisibilityEntry[]
164
+ ): Promise<ModelVisibilityEntry[]> {
165
+ const showModels: Model[] = [];
166
+ const hideModels: Model[] = [];
167
+
168
+ if (!isArray(modelVisibility)) {
169
+ modelVisibility = [modelVisibility];
170
+ }
171
+
172
+ for (const entry of modelVisibility) {
173
+ const model = this._getModel(entry.name);
174
+ if (!model) {
175
+ throw new ViewerError({
176
+ id: ViewerErrorIds.ModelNotRegistered,
177
+ message: `Can't set visibility of model "${entry.name}" as model is not registered`,
178
+ });
179
+ }
180
+
181
+ // there can be multiple "setModelVisibility" calls while the model is loading
182
+ // loading can be awaited, but it has to be ensured, that the last call of "setModelVisibility" has priority
183
+ // therefore we store the id of the call in the model
184
+ const curVisibilityCallId = (model.visibilityCallId ?? 0) + 1;
185
+ model.visibilityCallId = curVisibilityCallId;
186
+
187
+ if (entry.visible) {
188
+ if (model.state === 'notLoaded') {
189
+ await this._loadModel(model);
190
+
191
+ // check if this is still the latest visibility call
192
+ if (model.visibilityCallId === curVisibilityCallId) {
193
+ showModels.push(model);
194
+ }
195
+ } else if (model.state === 'loading') {
196
+ await this._loadModelPromises[model.name];
197
+
198
+ if (model.visibilityCallId === curVisibilityCallId) {
199
+ showModels.push(model);
200
+ }
201
+ } else if (model.state === 'loaded') {
202
+ showModels.push(model);
203
+ }
204
+ } else {
205
+ if (model.state === 'loading') {
206
+ await this._loadModelPromises[model.name];
207
+
208
+ if (model.visibilityCallId === curVisibilityCallId) {
209
+ hideModels.push(model);
210
+ }
211
+ } else if (model.state === 'inScene') {
212
+ hideModels.push(model);
213
+ }
214
+ }
215
+ }
216
+
217
+ for (const showModel of showModels) {
218
+ await this._prepareModelForScene(showModel);
219
+ }
220
+
221
+ for (const showModel of showModels) {
222
+ await this._showModel(showModel, true);
223
+ }
224
+
225
+ for (const hideModel of hideModels) {
226
+ this._hideModel(hideModel);
227
+ }
228
+
229
+ const returnVal: ModelVisibilityEntry[] = [];
230
+ showModels.forEach(showModel => returnVal.push({ name: showModel.name, visible: true }));
231
+ hideModels.forEach(hideModel => returnVal.push({ name: hideModel.name, visible: false }));
232
+
233
+ return returnVal;
234
+ }
235
+
236
+ /**
237
+ * Create a clone of an existing model.\
238
+ * Only the geometry (meshes, transform nodes) gets cloned, as materials are typically shared across the whole scene.
239
+ *
240
+ * @param show show model immediately after cloning
241
+ * @param options additional options for the cloning procedure, like renaming algorithms
242
+ */
243
+ public async cloneModel(
244
+ name: string,
245
+ newModelName: string,
246
+ show: boolean = true,
247
+ options?: ModelCloneOptions
248
+ ): Promise<void> {
249
+ const sourceModel = this._getModel(name);
250
+ if (!sourceModel) {
251
+ throw new ViewerError({
252
+ id: ViewerErrorIds.ModelNotRegistered,
253
+ message: `Can't clone model "${name}" as model is not registered`,
254
+ });
255
+ }
256
+
257
+ const existingModel = this._getModel(newModelName);
258
+ if (existingModel) {
259
+ throw new ViewerError({
260
+ id: ViewerErrorIds.ModelAlreadyExists,
261
+ message: `Can't create clone as model "${newModelName}" already exists`,
262
+ });
263
+ }
264
+
265
+ if (sourceModel.state === 'notLoaded') {
266
+ await this._loadModel(sourceModel);
267
+ } else if (sourceModel.state === 'loading') {
268
+ await this._loadModelPromises[sourceModel.name];
269
+ }
270
+
271
+ const clonedModel: Model = {
272
+ name: newModelName,
273
+ url: sourceModel.url,
274
+ state: 'loaded',
275
+ assetContainer: cloneModelAssetContainer(
276
+ sourceModel.assetContainer,
277
+ newModelName,
278
+ {
279
+ nodeNamingStrategy: options?.nodeNamingStrategy,
280
+ tagNamingStrategy: options?.tagNamingStrategy,
281
+ },
282
+ this.viewer.scene
283
+ ),
284
+ isClone: true,
285
+ };
286
+ this._modelAssets[newModelName] = clonedModel;
287
+
288
+ if (show) {
289
+ await this._showModel(clonedModel);
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Removes a cloned model from the scene and from the internal model storage.\
295
+ * Deleted clones can not be shown again.
296
+ */
297
+ public deleteClonedModel(name: string): void {
298
+ const model = this._getModel(name);
299
+ if (!model) {
300
+ throw new ViewerError({
301
+ id: ViewerErrorIds.ModelNotRegistered,
302
+ message: `Can't delete cloned model "${name}" as model is not registered`,
303
+ });
304
+ }
305
+
306
+ if (!model.isClone) {
307
+ throw new ViewerError({
308
+ id: ViewerErrorIds.ModelIsNotAClone,
309
+ message: `Can't delete model "${name}" as model is not a clone`,
310
+ });
311
+ }
312
+
313
+ model.assetContainer.dispose();
314
+
315
+ delete this._modelAssets[name];
316
+ }
317
+
318
+ /**
319
+ * Removes all cloned models from the scene and the internal model storage.
320
+ */
321
+ public deleteAllClonedModels(): void {
322
+ const clonedModelNames = Object.values(this._modelAssets)
323
+ .filter(model => model.isClone)
324
+ .map(model => model.name);
325
+
326
+ clonedModelNames.forEach(modelName => this.deleteClonedModel(modelName));
327
+ }
328
+
329
+ /**
330
+ * Loads and returns the asset container of a certain model.\
331
+ * This can be used to access the models content without having to add it to the scene.\
332
+ * A typical use case is to clone or instantiate a node from a "library" model.
333
+ */
334
+ public async getAssetContainerOfModel(name: string): Promise<AssetContainer> {
335
+ const model = this._getModel(name);
336
+ if (!model) {
337
+ throw new ViewerError({
338
+ id: ViewerErrorIds.ModelNotRegistered,
339
+ message: `Can't get asset container of model "${name}" as model is not registered`,
340
+ });
341
+ }
342
+
343
+ if (model.state === 'notLoaded') {
344
+ await this._loadModel(model);
345
+ } else if (model.state === 'loading') {
346
+ await this._loadModelPromises[model.name];
347
+ }
348
+
349
+ if (model.state !== 'inScene') {
350
+ await this._prepareModelForScene(model);
351
+ }
352
+
353
+ return model.assetContainer;
354
+ }
355
+
356
+ /**
357
+ * Get model by name
358
+ */
359
+ protected _getModel(name: string): Model | undefined {
360
+ if (name === '$fallback') {
361
+ return this._fallbackModelAsset;
362
+ }
363
+
364
+ const replacedName = ModelManager._replaceSlashes(name);
365
+ const model = this._modelAssets[replacedName];
366
+
367
+ return model;
368
+ }
369
+
370
+ /**
371
+ * Load model into scene, but don't show it immediately
372
+ */
373
+ protected async _loadModel(model: Model): Promise<void> {
374
+ const loadModelPromise = async (): Promise<void> => {
375
+ model.state = 'loading';
376
+ const curEnvTexture = this.viewer.scene.environmentTexture;
377
+ const curEnvIntensity = this.viewer.scene.environmentIntensity;
378
+
379
+ let assetContainer;
380
+ try {
381
+ assetContainer = await SceneLoader.LoadAssetContainerAsync('', model.url, this.viewer.scene);
382
+ } catch (e) {
383
+ throw new ViewerError({
384
+ id: ViewerErrorIds.AssetLoadingFailed,
385
+ message: `Error loading model "${model.name}" from url "${model.url}":\n${(e as Error).message}`,
386
+ });
387
+ }
388
+
389
+ // remove all lights and cameras from the asset, as this data should be handled globally in the scene instead of
390
+ // being in a model context
391
+ [...assetContainer.lights].forEach(light => light.dispose());
392
+ [...assetContainer.cameras].forEach(camera => camera.dispose());
393
+
394
+ // environment texture and intensity has been overwritten by load asset container function
395
+ this.viewer.scene.environmentTexture = curEnvTexture;
396
+ this.viewer.scene.environmentIntensity = curEnvIntensity;
397
+
398
+ model.assetContainer = assetContainer;
399
+ model.state = 'loaded';
400
+
401
+ delete this._loadModelPromises[model.name];
402
+ };
403
+
404
+ this._loadModelPromises[model.name] = loadModelPromise();
405
+ return this._loadModelPromises[model.name];
406
+ }
407
+
408
+ /**
409
+ * Apply parameter to the model in the asset container.
410
+ * This is typically done before the model is added to the scene to avoid changes on the visible model, which ensures
411
+ * a smooth model switch behaviour.
412
+ */
413
+ protected async _prepareModelForScene(model: Model): Promise<void> {
414
+ await this.viewer.parameterManager.applyAllParameterValuesToModel(model.assetContainer);
415
+ // parameter manager did his job, now apply the deferred materials to all meshes that are not explicitely hidden by
416
+ // the parameter manager
417
+ await this._applyDeferredMaterialsForAllVisibleMeshes(model);
418
+ }
419
+
420
+ /**
421
+ * Add assets of asset container to scene, do the scene preparation if required.
422
+ * CAUTION: model is expected to be in the correct loading state already.
423
+ *
424
+ * @param skipPreparation optionally skip applying parameter values to model before showing it
425
+ * (see {@link _prepareModelForScene})
426
+ */
427
+ protected async _showModel(model: Model, skipPreparation?: boolean): Promise<void> {
428
+ if (!skipPreparation) {
429
+ await this._prepareModelForScene(model);
430
+ }
431
+
432
+ model.assetContainer.addToScene();
433
+ model.state = 'inScene';
434
+ }
435
+
436
+ /**
437
+ * Remove assets of asset container from scene
438
+ */
439
+ protected _hideModel(model: Model): void {
440
+ model.assetContainer.removeFromScene();
441
+ model.state = 'loaded';
442
+ }
443
+
444
+ /**
445
+ * Creates and assigns each "deferred" material to the corresponding mesh, if the mesh is visible.
446
+ * Model should be ready to use immediately after this function has done it's job.
447
+ */
448
+ protected async _applyDeferredMaterialsForAllVisibleMeshes(model: Model): Promise<void> {
449
+ for (const mesh of model.assetContainer.meshes) {
450
+ const deferredMaterial = getInternalMetadataValue(mesh, 'deferredMaterial');
451
+ const rawVisibleValue = this.viewer.parameterManager.getParameterValueOfNode(mesh, BuiltInParameter.Visible);
452
+ const visible = rawVisibleValue === undefined || ParameterManager.parseBoolean(rawVisibleValue) === true;
453
+ if (deferredMaterial && visible) {
454
+ await this.viewer.materialManager.setMaterialOnMesh(deferredMaterial as string, mesh);
455
+ }
456
+ }
457
+ }
458
+ }