@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,896 +1,910 @@
1
- import { deactivateTransformNode, getDottedPathForNode, injectNodeMetadata } from '../util/babylonHelper';
2
- import { loadJson, mergeMaps } from '../util/resourceHelper';
3
- import { createMaterialFromCbnAssets } from '../util/sceneLoaderHelper';
4
- import { DottedPath } from './dottedPath';
5
- import { Element } from './element';
6
- import { Event } from './event';
7
- import { Parameter } from './parameter';
8
- import { ParameterObservable } from './parameterObservable';
9
- import { Parameterizable } from './parameterizable';
10
- import { VariantParameterizable } from './variantParameterizable';
11
- import { Viewer } from './viewer';
12
- import { ViewerLight } from './viewerLight';
13
- import { Light } from '@babylonjs/core/Lights/light';
14
- import '@babylonjs/core/Loading/Plugins/babylonFileLoader';
15
- import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
16
- import { Material } from '@babylonjs/core/Materials/material';
17
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
18
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
19
- import { AssetContainer } from '@babylonjs/core/assetContainer';
20
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression';
21
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat';
22
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior';
23
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness';
24
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen';
25
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular';
26
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency';
27
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission';
28
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit';
29
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants';
30
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu';
31
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform';
32
- import '@babylonjs/loaders/glTF/2.0/glTFLoader';
33
- import { cloneDeep, concat, get, isEmpty, isEqual, isString, merge, set } from 'lodash-es';
34
-
35
- /**
36
- * A concrete "Variant". Most of these are handled by either the {@link Viewer} or {@link VariantInstance}.
37
- */
38
- export class Variant extends Parameterizable {
39
- public assetContainer: AssetContainer;
40
-
41
- public readonly elements: Element[] = [];
42
-
43
- public readonly viewerLights: ViewerLight[] = [];
44
-
45
- public structureJson: StructureJson;
46
-
47
- protected _dottedNodes: Map<DottedPath, TransformNode> | undefined;
48
-
49
- protected readonly _children: Map<string, Variant> = new Map();
50
-
51
- protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
52
-
53
- /**
54
- * @internal
55
- */
56
- private parametersInitialized: boolean = false;
57
-
58
- /**
59
- * Constructor.
60
- */
61
- protected constructor(
62
- public readonly name: string,
63
- protected readonly _structureJson: StructureJson,
64
- public readonly viewer: Viewer,
65
- public readonly parent?: Variant
66
- ) {
67
- super(cloneDeep(_structureJson.parameterDeclaration), cloneDeep(_structureJson.parameters));
68
- for (const parameter in _structureJson.parameterDeclaration) {
69
- if (!(parameter in (_structureJson.parameters || []))) {
70
- throw new Error(`No default value for parameter "${parameter}" defined.`);
71
- }
72
- }
73
- this.assetContainer = new AssetContainer(viewer.scene);
74
- this.structureJson = cloneDeep(_structureJson);
75
- }
76
-
77
- /**
78
- * Creates a {@link Variant} based on given parameters.
79
- *
80
- * @throws Error if "gltf" property is provided without a filename
81
- */
82
- public static async create(
83
- name: string,
84
- structureJson: StructureJson,
85
- viewer: Viewer,
86
- parent?: Variant
87
- ): Promise<Variant> {
88
- const variant = new Variant(name, structureJson, viewer, parent);
89
- await variant.loadAssets();
90
- return variant;
91
- }
92
-
93
- /**
94
- * The ancestor {@link Variant}s ordered from top to bottom in the built tree.
95
- */
96
- get ancestors(): Variant[] {
97
- const ancestors = [];
98
- let variant: Variant = this;
99
- while (variant.parent) {
100
- ancestors.unshift(variant.parent);
101
- variant = variant.parent;
102
- }
103
- return ancestors;
104
- }
105
-
106
- /**
107
- * The root {@link Variant}.
108
- */
109
- get root(): Variant {
110
- return this.ancestors[0] ?? this;
111
- }
112
-
113
- /**
114
- * The {@link DottedPath} in the built tree of {@link Variant}s.
115
- * E.g. "_.top-1.sub-2.sub-sub-3"
116
- */
117
- get dottedPath(): DottedPath {
118
- const parentIds = this.ancestors.map(ancestor => {
119
- return ancestor.name;
120
- });
121
- return DottedPath.createFromParts(parentIds).addPart(this.name);
122
- }
123
-
124
- /**
125
- * The id representing a {@link DottedPath}.
126
- */
127
- get id(): string {
128
- const dottedPath = DottedPath.create(this.dottedPath);
129
- dottedPath.shiftPart(); // remove root
130
- return dottedPath.path || '_';
131
- }
132
-
133
- /**
134
- * The defined glTF Asset.
135
- */
136
- get glTF(): Asset | undefined {
137
- if (this.structureJson.glTF) {
138
- if (isString(this.structureJson.glTF)) {
139
- return {
140
- rootUrl: this.structureJson.glTF,
141
- fileName: undefined,
142
- };
143
- }
144
- if (isEmpty(this.structureJson.glTF.rootUrl)) {
145
- throw new Error(`No "rootUrl" defined in "glTF" definition for variant "${this.id}".`);
146
- }
147
- return this.structureJson.glTF;
148
- }
149
- }
150
-
151
- /**
152
- * The defined glTF URI.
153
- */
154
- get glTFUri(): string | undefined {
155
- if (this.glTF) {
156
- return [this.glTF.rootUrl, this.glTF.fileName].join('');
157
- }
158
- }
159
-
160
- /**
161
- * The inherited defined glTF URI.
162
- */
163
- get inheritedGlTFUri(): string | undefined {
164
- if (!this.glTFUri && this.parent) {
165
- return this.parent.inheritedGlTFUri;
166
- }
167
- return this.glTFUri;
168
- }
169
-
170
- /**
171
- * The TransformNodes of the {@link Variant}.
172
- */
173
- get nodes(): TransformNode[] {
174
- const rootNodes = this.assetContainer
175
- .getNodes()
176
- .filter(n => n instanceof TransformNode && !n.parent) as TransformNode[];
177
- return rootNodes;
178
- }
179
-
180
- /**
181
- * The {@link ViewerLight}s of the {@link Variant}.
182
- */
183
- get lights(): Light[] {
184
- return this.assetContainer.lights;
185
- }
186
-
187
- /**
188
- * All TransformNodes of the {@link Variant} mapped flat with a {@link DottedPath}.
189
- */
190
- get dottedNodes(): Map<DottedPath, TransformNode> {
191
- if (!this._dottedNodes) {
192
- const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode);
193
- const dottedNodes = new Map();
194
- nodes.forEach(node => {
195
- dottedNodes.set(node.metadata.dottedPath, node);
196
- });
197
- this._dottedNodes = dottedNodes;
198
- }
199
- return this._dottedNodes;
200
- }
201
-
202
- /**
203
- * The Materials of the {@link Variant}.
204
- */
205
- get materials(): Material[] {
206
- return this.assetContainer.materials;
207
- }
208
-
209
- /**
210
- * All {@link Element}s from this {@link Variant}'s parents.
211
- */
212
- get inheritedElements(): Element[] {
213
- let elements: Element[] = [];
214
- this.ancestors.forEach(ancestor => {
215
- elements = concat(elements, ancestor.elements);
216
- });
217
- return concat(elements, this.elements);
218
- }
219
-
220
- /**
221
- * All {@link ViewerLight}s inherited from this {@link Variant}'s parents.
222
- */
223
- get inheritedViewerLights(): ViewerLight[] {
224
- let viewerLights: ViewerLight[] = [];
225
- this.ancestors.forEach(ancestor => {
226
- viewerLights = concat(viewerLights, ancestor.viewerLights);
227
- });
228
- return concat(viewerLights, this.viewerLights);
229
- }
230
-
231
- /**
232
- * All TransformNodes inherited from this {@link Variant}'s parents.
233
- */
234
- get inheritedNodes(): TransformNode[] {
235
- let nodes: TransformNode[] = [];
236
- this.ancestors.forEach(ancestor => {
237
- nodes = concat(nodes, ancestor.nodes);
238
- });
239
- return concat(nodes, this.nodes);
240
- }
241
-
242
- /**
243
- * All TransformNodes inherited from this {@link Variant}'s parents mapped flat with a {@link DottedPath}.
244
- */
245
- get inheritedDottedNodes(): Map<DottedPath, TransformNode> {
246
- let dottedNodes = this.dottedNodes;
247
- this.ancestors.forEach(ancestor => {
248
- dottedNodes = mergeMaps(dottedNodes, ancestor.dottedNodes);
249
- });
250
- return dottedNodes;
251
- }
252
-
253
- /**
254
- * All Lights inherited from this {@link Variant}'s parents.
255
- */
256
- get inheritedLights(): Light[] {
257
- let lights: Light[] = [];
258
- this.ancestors.forEach(ancestor => {
259
- lights = concat(lights, ancestor.lights);
260
- });
261
- return concat(lights, this.lights);
262
- }
263
-
264
- /**
265
- * The {@link ParameterDeclarations} inherited from this {@link Variant}'s parents.
266
- */
267
- get inheritedParameterDeclaration(): ParameterDeclarations {
268
- const declaration = {};
269
- this.ancestors.forEach(ancestor => {
270
- merge(declaration, ancestor.parameterDeclaration);
271
- });
272
- return merge(declaration, this.parameterDeclaration);
273
- }
274
-
275
- /**
276
- * The {@link ParameterBag} inherited from this {@link Variant}'s parents.
277
- */
278
- get inheritedParameters(): ParameterBag {
279
- const parameters = {};
280
- this.ancestors.forEach(ancestor => {
281
- merge(parameters, ancestor.parameters);
282
- });
283
- return merge(parameters, this.parameters);
284
- }
285
-
286
- /**
287
- * All Materials from this {@link Variant}'s parents.
288
- */
289
- get inheritedMaterials(): Material[] {
290
- let materials: Material[] = [];
291
- this.ancestors.forEach(ancestor => {
292
- materials = concat(materials, ancestor.materials);
293
- });
294
- return concat(materials, this.materials);
295
- }
296
-
297
- /**
298
- * Gets the direct children of the current {@link Variant}.
299
- */
300
- public async getChildren(): Promise<Variant[]> {
301
- const children: Variant[] = [];
302
- for (const name in this.structureJson.variants) {
303
- children.push(await this.getDescendant(name));
304
- }
305
- return children;
306
- }
307
-
308
- /**
309
- * Gets a descendant {@link Variant} of the current {@link Variant} relative to its {@link DottedPath}.
310
- * If you have the dotted path `_.product_x.variant_blue.with_yellow_highlight` in a tree and you operate on the
311
- * `product_x`, you can call `this.getDescendant('variant_blue.with_yellow_highlight')` to get the lowermost
312
- * {@link Variant}.
313
- */
314
- public async getDescendant(dottedPath: DottedPathArgument): Promise<Variant> {
315
- const _dottedPath = DottedPath.create(dottedPath);
316
- const [name, ...descendantParts] = _dottedPath.parts;
317
- let variant;
318
- if (this._children.has(name)) {
319
- variant = this._children.get(name);
320
- } else {
321
- if (!this.structureJson.variants) {
322
- throw new Error(`Missing key "variants" in JSON structure for variant "${this.id}".`);
323
- }
324
- if (!this.structureJson.variants[name]) {
325
- throw new Error(`Variant "${_dottedPath.path}" not defined in JSON structure for variant "${this.id}".`);
326
- }
327
- if (this.structureJson.variants[name].file) {
328
- const file = this.structureJson.variants[name].file as string;
329
- variant = await Variant.create(name, await loadJson<StructureJson>(file), this.viewer, this);
330
- } else {
331
- variant = await Variant.create(name, this.structureJson.variants[name], this.viewer, this);
332
- }
333
- this._children.set(name, variant);
334
- }
335
- if (!variant) {
336
- throw new Error(`Variant "${_dottedPath.path}" was not created.`);
337
- }
338
- if (descendantParts.length > 0) {
339
- return await variant.getDescendant(DottedPath.createFromParts(descendantParts));
340
- }
341
- return variant;
342
- }
343
-
344
- /**
345
- * Gets the desired {@link Element} of the current {@link Variant} relative to its {@link DottedPath}.
346
- * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
347
- */
348
- public async getElement(dottedPath: DottedPathArgument): Promise<Element> {
349
- const _dottedPath = DottedPath.create(dottedPath);
350
- const elementName = _dottedPath.popPart();
351
- let variant: Variant = this;
352
- if (_dottedPath.parts.length > 0) {
353
- variant = await this.getDescendant(_dottedPath);
354
- }
355
- if (variant.inheritedElements.length === 0) {
356
- throw new Error(
357
- `No elements for variant "${variant.id}" found. ` +
358
- `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
359
- );
360
- }
361
- let element;
362
- variant.inheritedElements.forEach(_element => {
363
- if (_element.name === elementName) {
364
- element = _element;
365
- }
366
- });
367
- if (!element) {
368
- throw new Error(`Element with name "${elementName}" does not exist for variant "${variant.id}".`);
369
- }
370
- return element;
371
- }
372
-
373
- /**
374
- * Gets the desired {@link ViewerLight} of the current {@link Variant} relative to its {@link DottedPath}.
375
- * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
376
- */
377
- public async getViewerLight(dottedPath: DottedPathArgument): Promise<ViewerLight> {
378
- const _dottedPath = DottedPath.create(dottedPath);
379
- const viewerLightName = _dottedPath.popPart();
380
- let variant: Variant = this;
381
- if (_dottedPath.parts.length > 0) {
382
- variant = await this.getDescendant(_dottedPath);
383
- }
384
- if (variant.inheritedViewerLights.length === 0) {
385
- throw new Error(
386
- `No viewerLights for variant "${variant.id}" found. ` +
387
- `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
388
- );
389
- }
390
- let viewerLight;
391
- variant.inheritedViewerLights.forEach(_viewerLight => {
392
- if (_viewerLight.name === viewerLightName) {
393
- viewerLight = _viewerLight;
394
- }
395
- });
396
- if (!viewerLight) {
397
- throw new Error(`ViewerLight with name "${viewerLightName}" does not exist for variant "${variant.id}".`);
398
- }
399
- return viewerLight;
400
- }
401
-
402
- /**
403
- * A proxy for directly getting a Node from an {@link Element} by its {@link DottedPath}s.
404
- */
405
- public async getNode(
406
- elementDottedPath: DottedPathArgument,
407
- nodeDottedPath: DottedPathArgument
408
- ): Promise<TransformNode> {
409
- const element = await this.getElement(elementDottedPath);
410
- return element.getNode(nodeDottedPath);
411
- }
412
-
413
- /**
414
- * A proxy for directly getting a Mesh from an {@link Element} by its {@link DottedPath}s.
415
- */
416
- public async getMesh(
417
- elementDottedPath: DottedPathArgument,
418
- meshDottedPath: DottedPathArgument
419
- ): Promise<Mesh | null> {
420
- const element = await this.getElement(elementDottedPath);
421
- return element.getMesh(meshDottedPath);
422
- }
423
-
424
- /**
425
- * Gets the Material defined in one of the variants glTFs by its id.
426
- */
427
- public getOrCreateMaterial(id: string): Material {
428
- const scene = this.viewer.scene;
429
-
430
- for (const material of this.inheritedMaterials) {
431
- if (material.id === id) {
432
- return material;
433
- }
434
- }
435
- // fallback to dynamically created materials on scene
436
- for (const material of scene.materials) {
437
- if (material.id === id) {
438
- return material;
439
- }
440
- }
441
- const cbnAssetMaterial = createMaterialFromCbnAssets(id, scene);
442
- if (cbnAssetMaterial) {
443
- return cbnAssetMaterial;
444
- }
445
-
446
- throw new Error(`Material with id "${id}" does not exist for variant "${this.id}".`);
447
- }
448
-
449
- /**
450
- * Creates a living clone of this {@link Variant}. Will clone all parent {@link Variant}s in tree.
451
- *
452
- * @emit {@link Event.VARIANT_CREATED}
453
- * @ignore
454
- */
455
- public async createLiving(parameters?: ParameterBag): Promise<Variant> {
456
- const parent = await this.parent?.createLiving();
457
- const variant = new Variant(this.name, this._structureJson, this.viewer, parent);
458
- parent?._children.set(variant.name, variant);
459
- variant.assetContainer = this.assetContainer;
460
- variant.parameterObservers = cloneDeep(this.parameterObservers);
461
- await variant.createElements();
462
- await variant.createViewerLights();
463
- variant.addParameterObservers();
464
- await variant.bootstrapParameters(parameters);
465
- this.broadcastEvent(Event.VARIANT_CREATED, variant);
466
- return variant;
467
- }
468
-
469
- /**
470
- * Destroys this {@link Variant}, all parents and destroy the {@link Element}s.
471
- */
472
- public destroy(): Variant {
473
- this.elements.forEach(element => element.destroy());
474
- if (this.parent) {
475
- this.parent.destroy();
476
- }
477
- this.broadcastEvent(Event.VARIANT_DESTROYED, this);
478
- return this;
479
- }
480
-
481
- /**
482
- * Places the given {@link ParameterBag} in the {@link Variant}'s parameters, replaces all patterns in the
483
- * {@link StructureJson}, broadcasts all {@link ParameterObserver}s and delegates them to its {@link Element}s.
484
- *
485
- * @emit {@link Event.VARIANT_PARAMETER_COMMITTED}
486
- */
487
- public async commitParameters(parameters?: ParameterBag): Promise<Variant> {
488
- parameters = merge({}, parameters);
489
-
490
- // remember old parameter values for later comparison
491
- const oldParameters = cloneDeep(this.inheritedParameters);
492
-
493
- // replace patterns in given parameters
494
- let _parameters = JSON.stringify(parameters);
495
- for (const parameter in this.inheritedParameters) {
496
- const value = this.inheritedParameters[parameter];
497
- const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
498
- _parameters = _parameters.replace(search, value.toString());
499
- }
500
- merge(parameters, JSON.parse(_parameters));
501
-
502
- // merge inherited parameters and replaced given parameters
503
- const mergedParameters = merge({}, this.inheritedParameters, parameters);
504
-
505
- // replace patterns in structure parameters
506
- const structureParameters = this._structureJson.parameters || {};
507
- let _structureParameters = JSON.stringify(structureParameters);
508
- for (const parameter in mergedParameters) {
509
- const value = mergedParameters[parameter];
510
- const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
511
- _structureParameters = _structureParameters.replace(search, value.toString());
512
- }
513
- const replacedStructureParameters = JSON.parse(_structureParameters);
514
-
515
- // calculate which replaced structure parameters have changed and should overload given parameters
516
- const differentStructureParameters: ParameterBag = {};
517
- for (const parameter in replacedStructureParameters) {
518
- if (!isEqual(structureParameters[parameter], replacedStructureParameters[parameter])) {
519
- differentStructureParameters[parameter] = replacedStructureParameters[parameter];
520
- }
521
- }
522
-
523
- // merge replaced structure parameters and given inherited parameters to structure parameters
524
- merge(this.parameters, mergedParameters, differentStructureParameters);
525
-
526
- // inherited parameters are now the new parameters to process
527
- const newParameters = this.inheritedParameters;
528
-
529
- // replace all parameter patterns in structure json
530
- let structure = JSON.stringify(this._structureJson);
531
- for (const parameter in newParameters) {
532
- const value = newParameters[parameter];
533
- const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
534
- structure = structure.replace(search, value.toString());
535
- }
536
- this.structureJson = JSON.parse(structure);
537
-
538
- // handle parameter observers
539
- let observerPromises: Promise<void | ParameterObserver>[] = [];
540
- for (const parameter in newParameters) {
541
- const oldParameterValue = oldParameters[parameter];
542
- const newParameterValue = newParameters[parameter];
543
- this.assertParameter(this.inheritedParameterDeclaration, parameter, newParameterValue);
544
- if (oldParameterValue === newParameterValue && this.parametersInitialized) {
545
- continue;
546
- }
547
- // parameter changed
548
- const parameterObservers = mergeMaps(this._parameterObservers, this.parameterObservers);
549
- if (parameterObservers.has(parameter)) {
550
- const observers = parameterObservers.get(parameter)!;
551
- observerPromises = concat(
552
- observerPromises,
553
- observers.map(observer => {
554
- const observerResult = observer(this, oldParameterValue, newParameterValue);
555
- return Promise.resolve(observerResult).then(() => {
556
- if (this.parametersInitialized) {
557
- this.broadcastEvent(
558
- Event.VARIANT_PARAMETER_COMMITTED,
559
- this,
560
- parameter,
561
- oldParameterValue,
562
- newParameterValue
563
- );
564
- }
565
- });
566
- })
567
- );
568
- }
569
- }
570
- await Promise.all(observerPromises);
571
-
572
- // broadcast that bag has been committed
573
- this.broadcastEvent(Event.VARIANT_PARAMETER_BAG_COMMITTED, this, oldParameters, newParameters);
574
-
575
- // commit parameters to elements
576
- await this.commitParametersToElements(newParameters);
577
-
578
- // commit parameters to lights
579
- await this.commitParametersToViewerLights(newParameters);
580
-
581
- // propagate parameters to parent
582
- if (this.parent) {
583
- await this.parent.commitParameters(this.parameters);
584
- }
585
-
586
- return this;
587
- }
588
-
589
- /**
590
- * Adds an observer function for camera matrix changes for given `dottedPath` representing the {@link Element}
591
- * and the `traceable`. The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
592
- */
593
- public async addTraceableObserver(
594
- dottedPath: DottedPathArgument,
595
- observer: CallableFunction,
596
- payload?: any
597
- ): Promise<Element> {
598
- const _dottedPath = DottedPath.create(dottedPath);
599
- const traceableName = _dottedPath.popPart();
600
- if (!traceableName) {
601
- throw new Error(
602
- `The dottedPath must consist of the element and the name of the defined corresponding ` +
603
- `traceable ("${_dottedPath.path}" given).`
604
- );
605
- }
606
- const element = await this.getElement(_dottedPath);
607
- return element.addTraceableObserver(traceableName, observer, payload);
608
- }
609
-
610
- /**
611
- * Loads {@link glTFUri} with assets, adds them to the {@link Variant}'s `assetContainer` and deactivates the meshes.
612
- * (for further processing).
613
- * @emits {@link Event.ASSET_LOADING_START}
614
- * @emits {@link Event.ASSET_LOADING_END}
615
- */
616
- protected async loadAssets(): Promise<Variant> {
617
- this.broadcastEvent(Event.ASSET_LOADING_START, this);
618
-
619
- const promisifiedLoader = new Promise<Variant>((resolve, reject) => {
620
- if (!this.structureJson) {
621
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
622
- return resolve(this);
623
- }
624
- if (!this.glTF) {
625
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
626
- return resolve(this);
627
- }
628
- SceneLoader.LoadAssetContainer(
629
- this.glTF.rootUrl,
630
- this.glTF.fileName,
631
- this.viewer.scene,
632
- // on success
633
- container => {
634
- this.assetContainer = container;
635
- const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode) as TransformNode[];
636
- nodes.forEach(node => {
637
- deactivateTransformNode(node, false);
638
- injectNodeMetadata(node, { dottedPath: getDottedPathForNode(node) }, false);
639
- });
640
- this.assetContainer.lights.forEach(light => {
641
- light.setEnabled(false);
642
- injectNodeMetadata(light, { dottedPath: getDottedPathForNode(light) }, false);
643
- this.viewer.scene.addLight(light);
644
- });
645
- this.assetContainer.cameras.forEach(camera => {
646
- camera.setEnabled(false);
647
- injectNodeMetadata(camera, { dottedPath: getDottedPathForNode(camera) }, false);
648
- this.viewer.scene.addCamera(camera);
649
- });
650
- this.assetContainer.materials.forEach(material => this.viewer.scene.materials.push(material));
651
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
652
- resolve(this);
653
- },
654
- // on progress
655
- undefined,
656
- // on error
657
- reason => {
658
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
659
- throw new Error(`Error loading assets for variant "${this.id}": ${reason}.`);
660
- }
661
- );
662
- });
663
- return await promisifiedLoader;
664
- }
665
-
666
- /**
667
- * Commits given parameters to all {@link Element}s.
668
- */
669
- protected async commitParametersToElements(parameters: ParameterBag) {
670
- await Promise.all(
671
- this.elements.map(element => this.commitParametersToVariantParameterizable(parameters, element, 'elements'))
672
- );
673
- }
674
-
675
- /**
676
- * Commits given parameters to all {@link ViewerLight}s.
677
- */
678
- protected async commitParametersToViewerLights(parameters: ParameterBag) {
679
- await Promise.all(
680
- this.viewerLights.map(viewerLight =>
681
- this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
682
- )
683
- );
684
- }
685
-
686
- /**
687
- * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
688
- * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
689
- * `this.structureJson.elements`.
690
- */
691
- protected async commitParametersToVariantParameterizable(
692
- parameters: ParameterBag,
693
- parameterizable: VariantParameterizable,
694
- definitionKey: string
695
- ): Promise<ParameterObservable> {
696
- const initialDefinition = get(this._structureJson, definitionKey)[parameterizable.name];
697
- let initialDefinitionStr = JSON.stringify(initialDefinition);
698
- const _parameters: ParameterBag = {};
699
- for (const parameter in parameters) {
700
- const dpp = DottedPath.create(parameter);
701
- if (dpp.shiftPart() !== parameterizable.name) {
702
- continue;
703
- }
704
- // we got a parameterizable ("element") parameter
705
- let parameterValue = parameters[parameter];
706
- const parameterizableParameter = dpp.path;
707
- // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
708
- // an exception for visibility to avoid overloading already applied element parameters with element parameters
709
- // defined in the variant spec ("dotted parameters").
710
- // @see https://github.com/Combeenation/3d-viewer/issues/44
711
- if (parameterizableParameter === Parameter.VISIBLE && parameters[Parameter.VISIBLE] === false) {
712
- parameterValue = false;
713
- }
714
- _parameters[parameterizableParameter] = parameterValue;
715
- const search = new RegExp(`\\$\\{${parameterizableParameter}\\}`, 'g');
716
- initialDefinitionStr = initialDefinitionStr.replace(search, parameterValue.toString());
717
- }
718
- const definition = get(this.structureJson, definitionKey);
719
- definition[this.name] = JSON.parse(initialDefinitionStr);
720
- set(this.structureJson, definitionKey, definition);
721
- return await parameterizable.commitParameters(_parameters);
722
- }
723
-
724
- /**
725
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
726
- */
727
- protected async commitParameterToElements(parameter: string, value: ParameterValue): Promise<Variant> {
728
- const promises = [];
729
- for (const element of this.elements) {
730
- const paramShowsVariant = Parameter.VISIBLE === parameter && value;
731
-
732
- // Fixes https://combeenation.youtrack.cloud/issue/CB-7773
733
- // Don't enable/show the variants element if it is explicitly hidden via its element parameters.
734
- // E.g. via spec:
735
- // ```
736
- // variants: {
737
- // theVariant: {
738
- // elements: {
739
- // Main: ['root.main'],
740
- // Secondary: ['root.secondary'],
741
- // },
742
- // parameters: {
743
- // // !!! The element `Secondary` should **not** be enabled when its containing variant is enabled !!!
744
- // 'Secondary.visible': false,
745
- // }
746
- // }
747
- // }
748
- // ```
749
- const elVisibleParamPath = DottedPath.create([element.name, Parameter.VISIBLE]).toString();
750
- const elVisibleParamValue = this.inheritedParameters[elVisibleParamPath];
751
- const elVisibleParamValueParsed = elVisibleParamValue && Parameter.parseBoolean(elVisibleParamValue);
752
- const elIsHiddenViaParams = elVisibleParamValueParsed === false;
753
- if (paramShowsVariant && elIsHiddenViaParams) continue;
754
-
755
- // Fixes https://combeenation.youtrack.cloud/issue/CB-7809
756
- // Apply element material before showing the element to prevent loading of the elements "original" material which
757
- // is never shown when "overwritten" by elements material param.
758
- const elMaterialParamPath = DottedPath.create([element.name, Parameter.MATERIAL]).toString();
759
- const elMaterialParamValue = this.inheritedParameters[elMaterialParamPath];
760
- if (paramShowsVariant && elMaterialParamValue) {
761
- await element.commitParameter(Parameter.MATERIAL, elMaterialParamValue);
762
- }
763
-
764
- promises.push(element.commitParameter(parameter, value));
765
- }
766
- await Promise.all(promises);
767
- return this;
768
- }
769
-
770
- /**
771
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
772
- */
773
- protected async commitParameterToViewerLights(parameter: string, value: ParameterValue): Promise<Variant> {
774
- const promises = [];
775
- for (const viewerLight of this.viewerLights) {
776
- promises.push(viewerLight.commitParameter(parameter, value));
777
- }
778
- await Promise.all(promises);
779
- return this;
780
- }
781
-
782
- /**
783
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
784
- */
785
- protected addParameterObservers(): Variant {
786
- this._parameterObservers.set(Parameter.VISIBLE, [
787
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
788
- await variant.commitParameterToElements(Parameter.VISIBLE, newValue);
789
- await variant.commitParameterToViewerLights(Parameter.VISIBLE, newValue);
790
- },
791
- ]);
792
- this._parameterObservers.set(Parameter.SCALING, [
793
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
794
- await variant.commitParameterToElements(Parameter.SCALING, newValue);
795
- await variant.commitParameterToViewerLights(Parameter.SCALING, newValue);
796
- },
797
- ]);
798
- this._parameterObservers.set(Parameter.MATERIAL, [
799
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
800
- await variant.commitParameterToElements(Parameter.MATERIAL, newValue);
801
- },
802
- ]);
803
- this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
804
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
805
- await variant.commitParameterToElements(Parameter.MATERIAL_COLOR, newValue);
806
- },
807
- ]);
808
- this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
809
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
810
- await variant.commitParameterToElements(Parameter.MATERIAL_METALLNESS, newValue);
811
- },
812
- ]);
813
- this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
814
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
815
- await variant.commitParameterToElements(Parameter.MATERIAL_ROUGHNESS, newValue);
816
- },
817
- ]);
818
- this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
819
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
820
- await variant.commitParameterToElements(Parameter.HIGHLIGHT_COLOR, newValue);
821
- },
822
- ]);
823
- this._parameterObservers.set(Parameter.HIGHLIGHTED, [
824
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
825
- await variant.commitParameterToElements(Parameter.HIGHLIGHTED, newValue);
826
- },
827
- ]);
828
- this._parameterObservers.set(Parameter.POSITION, [
829
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
830
- await variant.commitParameterToElements(Parameter.POSITION, newValue);
831
- await variant.commitParameterToViewerLights(Parameter.POSITION, newValue);
832
- },
833
- ]);
834
- this._parameterObservers.set(Parameter.ROTATION, [
835
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
836
- await variant.commitParameterToElements(Parameter.ROTATION, newValue);
837
- await variant.commitParameterToViewerLights(Parameter.ROTATION, newValue);
838
- },
839
- ]);
840
- this._parameterObservers.set(Parameter.CAST_SHADOW, [
841
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
842
- await variant.commitParameterToElements(Parameter.CAST_SHADOW, newValue);
843
- },
844
- ]);
845
- this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
846
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
847
- await variant.commitParameterToElements(Parameter.CAST_SHADOW_FROM_LIGHTS, newValue);
848
- },
849
- ]);
850
- this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
851
- async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
852
- await variant.commitParameterToElements(Parameter.RECEIVE_SHADOWS, newValue);
853
- },
854
- ]);
855
- return this;
856
- }
857
-
858
- /**
859
- * Creates {@link Element}s and clones nodes into them.
860
- */
861
- protected async createElements(): Promise<Variant> {
862
- for (const name in this.structureJson.elements || {}) {
863
- this.elements.push(await Element.create(this, name));
864
- }
865
- // inject node meta to all inherited elements
866
- // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
867
- this.inheritedElements.forEach(element => {
868
- element.nodes.forEach(node => {
869
- injectNodeMetadata(node, { variant: this, variantParameterizable: element });
870
- });
871
- });
872
- return this;
873
- }
874
-
875
- /**
876
- * Creates {@link ViewerLight}s.
877
- */
878
- protected async createViewerLights(): Promise<Variant> {
879
- for (const name in this.structureJson.lights || {}) {
880
- this.viewerLights.push(await ViewerLight.create(this, name));
881
- }
882
- this.inheritedViewerLights.forEach(viewerLight => {
883
- injectNodeMetadata(viewerLight.light, { variant: this, variantParameterizable: viewerLight });
884
- });
885
- return this;
886
- }
887
-
888
- /**
889
- * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
890
- */
891
- protected async bootstrapParameters(parameters?: ParameterBag): Promise<Variant> {
892
- await this.commitParameters(merge(cloneDeep(this.parameters), parameters));
893
- concat(this.ancestors, this).forEach(ancestor => (ancestor.parametersInitialized = true));
894
- return this;
895
- }
896
- }
1
+ import { deactivateTransformNode, getDottedPathForNode, injectNodeMetadata } from '../util/babylonHelper';
2
+ import { loadJson, mergeMaps } from '../util/resourceHelper';
3
+ import { createMaterialFromCbnAssets } from '../util/sceneLoaderHelper';
4
+ import { DottedPath } from './dottedPath';
5
+ import { Element } from './element';
6
+ import { Event } from './event';
7
+ import { Parameter } from './parameter';
8
+ import { ParameterObservable } from './parameterObservable';
9
+ import { Parameterizable } from './parameterizable';
10
+ import { VariantParameterizable } from './variantParameterizable';
11
+ import { Viewer } from './viewer';
12
+ import { ViewerLight } from './viewerLight';
13
+ import { Light } from '@babylonjs/core/Lights/light';
14
+ import '@babylonjs/core/Loading/Plugins/babylonFileLoader';
15
+ import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
16
+ import { Material } from '@babylonjs/core/Materials/material';
17
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
18
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
19
+ import { AssetContainer } from '@babylonjs/core/assetContainer';
20
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression';
21
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat';
22
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior';
23
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness';
24
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen';
25
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular';
26
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency';
27
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission';
28
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit';
29
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants';
30
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu';
31
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform';
32
+ import '@babylonjs/loaders/glTF/2.0/glTFLoader';
33
+ import { cloneDeep, concat, get, isEmpty, isEqual, isString, merge, set } from 'lodash-es';
34
+
35
+ /**
36
+ * A concrete "Variant". Most of these are handled by either the {@link Viewer} or {@link VariantInstance}.
37
+ */
38
+ export class Variant extends Parameterizable {
39
+ public assetContainer: AssetContainer;
40
+
41
+ public readonly elements: Element[] = [];
42
+
43
+ public readonly viewerLights: ViewerLight[] = [];
44
+
45
+ public structureJson: StructureJson;
46
+
47
+ protected _dottedNodes: Map<DottedPath, TransformNode> | undefined;
48
+
49
+ protected readonly _children: Map<string, Variant> = new Map();
50
+
51
+ protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
52
+
53
+ /**
54
+ * @internal
55
+ */
56
+ private parametersInitialized: boolean = false;
57
+
58
+ /**
59
+ * Constructor.
60
+ */
61
+ protected constructor(
62
+ public readonly name: string,
63
+ protected readonly _structureJson: StructureJson,
64
+ public readonly viewer: Viewer,
65
+ public readonly parent?: Variant
66
+ ) {
67
+ super(cloneDeep(_structureJson.parameterDeclaration), cloneDeep(_structureJson.parameters));
68
+ for (const parameter in _structureJson.parameterDeclaration) {
69
+ if (!(parameter in (_structureJson.parameters || []))) {
70
+ throw new Error(`No default value for parameter "${parameter}" defined.`);
71
+ }
72
+ }
73
+ this.assetContainer = new AssetContainer(viewer.scene);
74
+ this.structureJson = cloneDeep(_structureJson);
75
+ }
76
+
77
+ /**
78
+ * Creates a {@link Variant} based on given parameters.
79
+ *
80
+ * @throws Error if "gltf" property is provided without a filename
81
+ */
82
+ public static async create(
83
+ name: string,
84
+ structureJson: StructureJson,
85
+ viewer: Viewer,
86
+ parent?: Variant
87
+ ): Promise<Variant> {
88
+ const variant = new Variant(name, structureJson, viewer, parent);
89
+ await variant.loadAssets();
90
+ return variant;
91
+ }
92
+
93
+ /**
94
+ * The ancestor {@link Variant}s ordered from top to bottom in the built tree.
95
+ */
96
+ get ancestors(): Variant[] {
97
+ const ancestors = [];
98
+ let variant: Variant = this;
99
+ while (variant.parent) {
100
+ ancestors.unshift(variant.parent);
101
+ variant = variant.parent;
102
+ }
103
+ return ancestors;
104
+ }
105
+
106
+ /**
107
+ * The root {@link Variant}.
108
+ */
109
+ get root(): Variant {
110
+ return this.ancestors[0] ?? this;
111
+ }
112
+
113
+ /**
114
+ * The {@link DottedPath} in the built tree of {@link Variant}s.
115
+ * E.g. "_.top-1.sub-2.sub-sub-3"
116
+ */
117
+ get dottedPath(): DottedPath {
118
+ const parentIds = this.ancestors.map(ancestor => {
119
+ return ancestor.name;
120
+ });
121
+ return DottedPath.createFromParts(parentIds).addPart(this.name);
122
+ }
123
+
124
+ /**
125
+ * The id representing a {@link DottedPath}.
126
+ */
127
+ get id(): string {
128
+ const dottedPath = DottedPath.create(this.dottedPath);
129
+ dottedPath.shiftPart(); // remove root
130
+ return dottedPath.path || '_';
131
+ }
132
+
133
+ /**
134
+ * The defined glTF Asset.
135
+ */
136
+ get glTF(): Asset | undefined {
137
+ if (this.structureJson.glTF) {
138
+ if (isString(this.structureJson.glTF)) {
139
+ return {
140
+ rootUrl: this.structureJson.glTF,
141
+ fileName: undefined,
142
+ };
143
+ }
144
+ if (isEmpty(this.structureJson.glTF.rootUrl)) {
145
+ throw new Error(`No "rootUrl" defined in "glTF" definition for variant "${this.id}".`);
146
+ }
147
+ return this.structureJson.glTF;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * The defined glTF URI.
153
+ */
154
+ get glTFUri(): string | undefined {
155
+ if (this.glTF) {
156
+ return [this.glTF.rootUrl, this.glTF.fileName].join('');
157
+ }
158
+ }
159
+
160
+ /**
161
+ * The inherited defined glTF URI.
162
+ */
163
+ get inheritedGlTFUri(): string | undefined {
164
+ if (!this.glTFUri && this.parent) {
165
+ return this.parent.inheritedGlTFUri;
166
+ }
167
+ return this.glTFUri;
168
+ }
169
+
170
+ /**
171
+ * The TransformNodes of the {@link Variant}.
172
+ */
173
+ get nodes(): TransformNode[] {
174
+ const rootNodes = this.assetContainer
175
+ .getNodes()
176
+ .filter(n => n instanceof TransformNode && !n.parent) as TransformNode[];
177
+ return rootNodes;
178
+ }
179
+
180
+ /**
181
+ * The {@link ViewerLight}s of the {@link Variant}.
182
+ */
183
+ get lights(): Light[] {
184
+ return this.assetContainer.lights;
185
+ }
186
+
187
+ /**
188
+ * All TransformNodes of the {@link Variant} mapped flat with a {@link DottedPath}.
189
+ */
190
+ get dottedNodes(): Map<DottedPath, TransformNode> {
191
+ if (!this._dottedNodes) {
192
+ const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode);
193
+ const dottedNodes = new Map();
194
+ nodes.forEach(node => {
195
+ dottedNodes.set(node.metadata.dottedPath, node);
196
+ });
197
+ this._dottedNodes = dottedNodes;
198
+ }
199
+ return this._dottedNodes;
200
+ }
201
+
202
+ /**
203
+ * The Materials of the {@link Variant}.
204
+ */
205
+ get materials(): Material[] {
206
+ return this.assetContainer.materials;
207
+ }
208
+
209
+ /**
210
+ * All {@link Element}s from this {@link Variant}'s parents.
211
+ */
212
+ get inheritedElements(): Element[] {
213
+ let elements: Element[] = [];
214
+ this.ancestors.forEach(ancestor => {
215
+ elements = concat(elements, ancestor.elements);
216
+ });
217
+ return concat(elements, this.elements);
218
+ }
219
+
220
+ /**
221
+ * All {@link ViewerLight}s inherited from this {@link Variant}'s parents.
222
+ */
223
+ get inheritedViewerLights(): ViewerLight[] {
224
+ let viewerLights: ViewerLight[] = [];
225
+ this.ancestors.forEach(ancestor => {
226
+ viewerLights = concat(viewerLights, ancestor.viewerLights);
227
+ });
228
+ return concat(viewerLights, this.viewerLights);
229
+ }
230
+
231
+ /**
232
+ * All TransformNodes inherited from this {@link Variant}'s parents.
233
+ */
234
+ get inheritedNodes(): TransformNode[] {
235
+ let nodes: TransformNode[] = [];
236
+ this.ancestors.forEach(ancestor => {
237
+ nodes = concat(nodes, ancestor.nodes);
238
+ });
239
+ return concat(nodes, this.nodes);
240
+ }
241
+
242
+ /**
243
+ * All TransformNodes inherited from this {@link Variant}'s parents mapped flat with a {@link DottedPath}.
244
+ */
245
+ get inheritedDottedNodes(): Map<DottedPath, TransformNode> {
246
+ let dottedNodes = this.dottedNodes;
247
+ this.ancestors.forEach(ancestor => {
248
+ dottedNodes = mergeMaps(dottedNodes, ancestor.dottedNodes);
249
+ });
250
+ return dottedNodes;
251
+ }
252
+
253
+ /**
254
+ * All Lights inherited from this {@link Variant}'s parents.
255
+ */
256
+ get inheritedLights(): Light[] {
257
+ let lights: Light[] = [];
258
+ this.ancestors.forEach(ancestor => {
259
+ lights = concat(lights, ancestor.lights);
260
+ });
261
+ return concat(lights, this.lights);
262
+ }
263
+
264
+ /**
265
+ * The {@link ParameterDeclarations} inherited from this {@link Variant}'s parents.
266
+ */
267
+ get inheritedParameterDeclaration(): ParameterDeclarations {
268
+ const declaration = {};
269
+ this.ancestors.forEach(ancestor => {
270
+ merge(declaration, ancestor.parameterDeclaration);
271
+ });
272
+ return merge(declaration, this.parameterDeclaration);
273
+ }
274
+
275
+ /**
276
+ * The {@link ParameterBag} inherited from this {@link Variant}'s parents.
277
+ */
278
+ get inheritedParameters(): ParameterBag {
279
+ const parameters = {};
280
+ this.ancestors.forEach(ancestor => {
281
+ merge(parameters, ancestor.parameters);
282
+ });
283
+ return merge(parameters, this.parameters);
284
+ }
285
+
286
+ /**
287
+ * All Materials from this {@link Variant}'s parents.
288
+ */
289
+ get inheritedMaterials(): Material[] {
290
+ let materials: Material[] = [];
291
+ this.ancestors.forEach(ancestor => {
292
+ materials = concat(materials, ancestor.materials);
293
+ });
294
+ return concat(materials, this.materials);
295
+ }
296
+
297
+ /**
298
+ * Gets the direct children of the current {@link Variant}.
299
+ */
300
+ public async getChildren(): Promise<Variant[]> {
301
+ const children: Variant[] = [];
302
+ for (const name in this.structureJson.variants) {
303
+ children.push(await this.getDescendant(name));
304
+ }
305
+ return children;
306
+ }
307
+
308
+ /**
309
+ * Gets a descendant {@link Variant} of the current {@link Variant} relative to its {@link DottedPath}.
310
+ * If you have the dotted path `_.product_x.variant_blue.with_yellow_highlight` in a tree and you operate on the
311
+ * `product_x`, you can call `this.getDescendant('variant_blue.with_yellow_highlight')` to get the lowermost
312
+ * {@link Variant}.
313
+ */
314
+ public async getDescendant(dottedPath: DottedPathArgument): Promise<Variant> {
315
+ const _dottedPath = DottedPath.create(dottedPath);
316
+ const [name, ...descendantParts] = _dottedPath.parts;
317
+ let variant;
318
+ if (this._children.has(name)) {
319
+ variant = this._children.get(name);
320
+ } else {
321
+ if (!this.structureJson.variants) {
322
+ throw new Error(`Missing key "variants" in JSON structure for variant "${this.id}".`);
323
+ }
324
+ if (!this.structureJson.variants[name]) {
325
+ throw new Error(`Variant "${_dottedPath.path}" not defined in JSON structure for variant "${this.id}".`);
326
+ }
327
+ if (this.structureJson.variants[name].file) {
328
+ const file = this.structureJson.variants[name].file as string;
329
+ variant = await Variant.create(name, await loadJson<StructureJson>(file), this.viewer, this);
330
+ } else {
331
+ variant = await Variant.create(name, this.structureJson.variants[name], this.viewer, this);
332
+ }
333
+ this._children.set(name, variant);
334
+ }
335
+ if (!variant) {
336
+ throw new Error(`Variant "${_dottedPath.path}" was not created.`);
337
+ }
338
+ if (descendantParts.length > 0) {
339
+ return await variant.getDescendant(DottedPath.createFromParts(descendantParts));
340
+ }
341
+ return variant;
342
+ }
343
+
344
+ /**
345
+ * Gets the desired {@link Element} of the current {@link Variant} relative to its {@link DottedPath}.
346
+ * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
347
+ */
348
+ public async getElement(dottedPath: DottedPathArgument): Promise<Element> {
349
+ const _dottedPath = DottedPath.create(dottedPath);
350
+ const elementName = _dottedPath.popPart();
351
+ let variant: Variant = this;
352
+ if (_dottedPath.parts.length > 0) {
353
+ variant = await this.getDescendant(_dottedPath);
354
+ }
355
+ if (variant.inheritedElements.length === 0) {
356
+ throw new Error(
357
+ `No elements for variant "${variant.id}" found. ` +
358
+ `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
359
+ );
360
+ }
361
+ let element;
362
+ variant.inheritedElements.forEach(_element => {
363
+ if (_element.name === elementName) {
364
+ element = _element;
365
+ }
366
+ });
367
+ if (!element) {
368
+ throw new Error(`Element with name "${elementName}" does not exist for variant "${variant.id}".`);
369
+ }
370
+ return element;
371
+ }
372
+
373
+ /**
374
+ * Gets the desired {@link ViewerLight} of the current {@link Variant} relative to its {@link DottedPath}.
375
+ * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
376
+ */
377
+ public async getViewerLight(dottedPath: DottedPathArgument): Promise<ViewerLight> {
378
+ const _dottedPath = DottedPath.create(dottedPath);
379
+ const viewerLightName = _dottedPath.popPart();
380
+ let variant: Variant = this;
381
+ if (_dottedPath.parts.length > 0) {
382
+ variant = await this.getDescendant(_dottedPath);
383
+ }
384
+ if (variant.inheritedViewerLights.length === 0) {
385
+ throw new Error(
386
+ `No viewerLights for variant "${variant.id}" found. ` +
387
+ `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
388
+ );
389
+ }
390
+ let viewerLight;
391
+ variant.inheritedViewerLights.forEach(_viewerLight => {
392
+ if (_viewerLight.name === viewerLightName) {
393
+ viewerLight = _viewerLight;
394
+ }
395
+ });
396
+ if (!viewerLight) {
397
+ throw new Error(`ViewerLight with name "${viewerLightName}" does not exist for variant "${variant.id}".`);
398
+ }
399
+ return viewerLight;
400
+ }
401
+
402
+ /**
403
+ * A proxy for directly getting a Node from an {@link Element} by its {@link DottedPath}s.
404
+ */
405
+ public async getNode(
406
+ elementDottedPath: DottedPathArgument,
407
+ nodeDottedPath: DottedPathArgument
408
+ ): Promise<TransformNode> {
409
+ const element = await this.getElement(elementDottedPath);
410
+ return element.getNode(nodeDottedPath);
411
+ }
412
+
413
+ /**
414
+ * A proxy for directly getting a Mesh from an {@link Element} by its {@link DottedPath}s.
415
+ */
416
+ public async getMesh(
417
+ elementDottedPath: DottedPathArgument,
418
+ meshDottedPath: DottedPathArgument
419
+ ): Promise<Mesh | null> {
420
+ const element = await this.getElement(elementDottedPath);
421
+ return element.getMesh(meshDottedPath);
422
+ }
423
+
424
+ /**
425
+ * Gets the Material defined in one of the variants glTFs by its id.
426
+ */
427
+ public getOrCreateMaterial(id: string): Material {
428
+ const scene = this.viewer.scene;
429
+
430
+ for (const material of this.inheritedMaterials) {
431
+ if (material.id === id) {
432
+ return material;
433
+ }
434
+ }
435
+ // fallback to dynamically created materials on scene
436
+ for (const material of scene.materials) {
437
+ if (material.id === id) {
438
+ return material;
439
+ }
440
+ }
441
+ const cbnAssetMaterial = createMaterialFromCbnAssets(id, scene);
442
+ if (cbnAssetMaterial) {
443
+ return cbnAssetMaterial;
444
+ }
445
+
446
+ throw new Error(`Material with id "${id}" does not exist for variant "${this.id}".`);
447
+ }
448
+
449
+ /**
450
+ * Creates a living clone of this {@link Variant}. Will clone all parent {@link Variant}s in tree.
451
+ *
452
+ * @emit {@link Event.VARIANT_CREATED}
453
+ * @ignore
454
+ */
455
+ public async createLiving(parameters?: ParameterBag): Promise<Variant> {
456
+ const parent = await this.parent?.createLiving();
457
+ const variant = new Variant(this.name, this._structureJson, this.viewer, parent);
458
+ parent?._children.set(variant.name, variant);
459
+ variant.assetContainer = this.assetContainer;
460
+ variant.parameterObservers = cloneDeep(this.parameterObservers);
461
+ await variant.createElements();
462
+ await variant.createViewerLights();
463
+ variant.addParameterObservers();
464
+ await variant.bootstrapParameters(parameters);
465
+ this.broadcastEvent(Event.VARIANT_CREATED, variant);
466
+ return variant;
467
+ }
468
+
469
+ /**
470
+ * Destroys this {@link Variant}, all parents and destroy the {@link Element}s.
471
+ */
472
+ public destroy(): Variant {
473
+ this.elements.forEach(element => element.destroy());
474
+ if (this.parent) {
475
+ this.parent.destroy();
476
+ }
477
+ this.broadcastEvent(Event.VARIANT_DESTROYED, this);
478
+ return this;
479
+ }
480
+
481
+ /**
482
+ * Places the given {@link ParameterBag} in the {@link Variant}'s parameters, replaces all patterns in the
483
+ * {@link StructureJson}, broadcasts all {@link ParameterObserver}s and delegates them to its {@link Element}s.
484
+ *
485
+ * @emit {@link Event.VARIANT_PARAMETER_COMMITTED}
486
+ */
487
+ public async commitParameters(parameters?: ParameterBag): Promise<Variant> {
488
+ parameters = merge({}, parameters);
489
+
490
+ // remember old parameter values for later comparison
491
+ const oldParameters = cloneDeep(this.inheritedParameters);
492
+
493
+ // replace patterns in given parameters
494
+ let _parameters = JSON.stringify(parameters);
495
+ for (const parameter in this.inheritedParameters) {
496
+ const value = this.inheritedParameters[parameter];
497
+ const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
498
+ _parameters = _parameters.replace(search, value.toString());
499
+ }
500
+ merge(parameters, JSON.parse(_parameters));
501
+
502
+ // merge inherited parameters and replaced given parameters
503
+ const mergedParameters = merge({}, this.inheritedParameters, parameters);
504
+
505
+ // replace patterns in structure parameters
506
+ const structureParameters = this._structureJson.parameters || {};
507
+ let _structureParameters = JSON.stringify(structureParameters);
508
+ for (const parameter in mergedParameters) {
509
+ const value = mergedParameters[parameter];
510
+ const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
511
+ _structureParameters = _structureParameters.replace(search, value.toString());
512
+ }
513
+ const replacedStructureParameters = JSON.parse(_structureParameters);
514
+
515
+ // calculate which replaced structure parameters have changed and should overload given parameters
516
+ const differentStructureParameters: ParameterBag = {};
517
+ for (const parameter in replacedStructureParameters) {
518
+ if (!isEqual(structureParameters[parameter], replacedStructureParameters[parameter])) {
519
+ differentStructureParameters[parameter] = replacedStructureParameters[parameter];
520
+ }
521
+ }
522
+
523
+ // merge replaced structure parameters and given inherited parameters to structure parameters
524
+ merge(this.parameters, mergedParameters, differentStructureParameters);
525
+
526
+ // inherited parameters are now the new parameters to process
527
+ const newParameters = this.inheritedParameters;
528
+
529
+ // replace all parameter patterns in structure json
530
+ let structure = JSON.stringify(this._structureJson);
531
+ for (const parameter in newParameters) {
532
+ const value = newParameters[parameter];
533
+ const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
534
+ structure = structure.replace(search, value.toString());
535
+ }
536
+ this.structureJson = JSON.parse(structure);
537
+
538
+ // handle parameter observers
539
+ let observerPromises: Promise<void | ParameterObserver>[] = [];
540
+ for (const parameter in newParameters) {
541
+ const oldParameterValue = oldParameters[parameter];
542
+ const newParameterValue = newParameters[parameter];
543
+ this.assertParameter(this.inheritedParameterDeclaration, parameter, newParameterValue);
544
+ if (oldParameterValue === newParameterValue && this.parametersInitialized) {
545
+ continue;
546
+ }
547
+ // parameter changed
548
+ const parameterObservers = mergeMaps(this._parameterObservers, this.parameterObservers);
549
+ if (parameterObservers.has(parameter)) {
550
+ const observers = parameterObservers.get(parameter)!;
551
+ observerPromises = concat(
552
+ observerPromises,
553
+ observers.map(observer => {
554
+ const observerResult = observer(this, oldParameterValue, newParameterValue);
555
+ return Promise.resolve(observerResult).then(() => {
556
+ if (this.parametersInitialized) {
557
+ this.broadcastEvent(
558
+ Event.VARIANT_PARAMETER_COMMITTED,
559
+ this,
560
+ parameter,
561
+ oldParameterValue,
562
+ newParameterValue
563
+ );
564
+ }
565
+ });
566
+ })
567
+ );
568
+ }
569
+ }
570
+ await Promise.all(observerPromises);
571
+
572
+ // broadcast that bag has been committed
573
+ this.broadcastEvent(Event.VARIANT_PARAMETER_BAG_COMMITTED, this, oldParameters, newParameters);
574
+
575
+ // commit parameters to elements
576
+ await this.commitParametersToElements(newParameters);
577
+
578
+ // commit parameters to lights
579
+ await this.commitParametersToViewerLights(newParameters);
580
+
581
+ // propagate parameters to parent
582
+ if (this.parent) {
583
+ await this.parent.commitParameters(this.parameters);
584
+ }
585
+
586
+ return this;
587
+ }
588
+
589
+ /**
590
+ * Adds an observer function for camera matrix changes for given `dottedPath` representing the {@link Element}
591
+ * and the `traceable`. The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
592
+ */
593
+ public async addTraceableObserver(
594
+ dottedPath: DottedPathArgument,
595
+ observer: CallableFunction,
596
+ payload?: any
597
+ ): Promise<Element> {
598
+ const _dottedPath = DottedPath.create(dottedPath);
599
+ const traceableName = _dottedPath.popPart();
600
+ if (!traceableName) {
601
+ throw new Error(
602
+ `The dottedPath must consist of the element and the name of the defined corresponding ` +
603
+ `traceable ("${_dottedPath.path}" given).`
604
+ );
605
+ }
606
+ const element = await this.getElement(_dottedPath);
607
+ return element.addTraceableObserver(traceableName, observer, payload);
608
+ }
609
+
610
+ /**
611
+ * Loads {@link glTFUri} with assets, adds them to the {@link Variant}'s `assetContainer` and deactivates the meshes.
612
+ * (for further processing).
613
+ * @emits {@link Event.ASSET_LOADING_START}
614
+ * @emits {@link Event.ASSET_LOADING_END}
615
+ */
616
+ protected async loadAssets(): Promise<Variant> {
617
+ this.broadcastEvent(Event.ASSET_LOADING_START, this);
618
+
619
+ const promisifiedLoader = new Promise<Variant>((resolve, reject) => {
620
+ if (!this.structureJson) {
621
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
622
+ return resolve(this);
623
+ }
624
+ if (!this.glTF) {
625
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
626
+ return resolve(this);
627
+ }
628
+ SceneLoader.LoadAssetContainer(
629
+ this.glTF.rootUrl,
630
+ this.glTF.fileName,
631
+ this.viewer.scene,
632
+ // on success
633
+ container => {
634
+ this.assetContainer = container;
635
+ const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode) as TransformNode[];
636
+ nodes.forEach(node => {
637
+ deactivateTransformNode(node, false);
638
+ injectNodeMetadata(node, { dottedPath: getDottedPathForNode(node) }, false);
639
+ });
640
+ this.assetContainer.lights.forEach(light => {
641
+ light.setEnabled(false);
642
+ injectNodeMetadata(light, { dottedPath: getDottedPathForNode(light) }, false);
643
+ this.viewer.scene.addLight(light);
644
+ });
645
+ this.assetContainer.cameras.forEach(camera => {
646
+ camera.setEnabled(false);
647
+ injectNodeMetadata(camera, { dottedPath: getDottedPathForNode(camera) }, false);
648
+ this.viewer.scene.addCamera(camera);
649
+ });
650
+ this.assetContainer.materials.forEach(material => this.viewer.scene.materials.push(material));
651
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
652
+ resolve(this);
653
+ },
654
+ // on progress
655
+ undefined,
656
+ // on error
657
+ reason => {
658
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
659
+ throw new Error(`Error loading assets for variant "${this.id}": ${reason}.`);
660
+ }
661
+ );
662
+ });
663
+ return await promisifiedLoader;
664
+ }
665
+
666
+ /**
667
+ * Commits given parameters to all {@link Element}s.
668
+ */
669
+ protected async commitParametersToElements(parameters: ParameterBag) {
670
+ await Promise.all(
671
+ this.elements.map(element => this.commitParametersToVariantParameterizable(parameters, element, 'elements'))
672
+ );
673
+ }
674
+
675
+ /**
676
+ * Commits given parameters to all {@link ViewerLight}s.
677
+ */
678
+ protected async commitParametersToViewerLights(parameters: ParameterBag) {
679
+ await Promise.all(
680
+ this.viewerLights.map(viewerLight =>
681
+ this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
682
+ )
683
+ );
684
+ }
685
+
686
+ /**
687
+ * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
688
+ * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
689
+ * `this.structureJson.elements`.
690
+ */
691
+ protected async commitParametersToVariantParameterizable(
692
+ parameters: ParameterBag,
693
+ parameterizable: VariantParameterizable,
694
+ definitionKey: string
695
+ ): Promise<ParameterObservable> {
696
+ const initialDefinition = get(this._structureJson, definitionKey)[parameterizable.name];
697
+ let initialDefinitionStr = JSON.stringify(initialDefinition);
698
+ const _parameters: ParameterBag = {};
699
+ for (const parameter in parameters) {
700
+ const dpp = DottedPath.create(parameter);
701
+ if (dpp.shiftPart() !== parameterizable.name) {
702
+ continue;
703
+ }
704
+ // we got a parameterizable ("element") parameter
705
+ let parameterValue = parameters[parameter];
706
+ const parameterizableParameter = dpp.path;
707
+ // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
708
+ // an exception for visibility to avoid overloading already applied element parameters with element parameters
709
+ // defined in the variant spec ("dotted parameters").
710
+ // @see https://github.com/Combeenation/3d-viewer/issues/44
711
+ if (parameterizableParameter === Parameter.VISIBLE && parameters[Parameter.VISIBLE] === false) {
712
+ parameterValue = false;
713
+ }
714
+ _parameters[parameterizableParameter] = parameterValue;
715
+ const search = new RegExp(`\\$\\{${parameterizableParameter}\\}`, 'g');
716
+ initialDefinitionStr = initialDefinitionStr.replace(search, parameterValue.toString());
717
+ }
718
+ const definition = get(this.structureJson, definitionKey);
719
+ definition[this.name] = JSON.parse(initialDefinitionStr);
720
+ set(this.structureJson, definitionKey, definition);
721
+ return await parameterizable.commitParameters(_parameters);
722
+ }
723
+
724
+ /**
725
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
726
+ */
727
+ protected async commitParameterToElements(parameter: string, value: ParameterValue): Promise<Variant> {
728
+ const promises = [];
729
+ for (const element of this.elements) {
730
+ const paramShowsVariant = Parameter.VISIBLE === parameter && value;
731
+
732
+ // Fixes https://combeenation.youtrack.cloud/issue/CB-7773
733
+ // Don't enable/show the variants element if it is explicitly hidden via its element parameters.
734
+ // E.g. via spec:
735
+ // ```
736
+ // variants: {
737
+ // theVariant: {
738
+ // elements: {
739
+ // Main: ['root.main'],
740
+ // Secondary: ['root.secondary'],
741
+ // },
742
+ // parameters: {
743
+ // // !!! The element `Secondary` should **not** be enabled when its containing variant is enabled !!!
744
+ // 'Secondary.visible': false,
745
+ // }
746
+ // }
747
+ // }
748
+ // ```
749
+ const elVisibleParamPath = DottedPath.create([element.name, Parameter.VISIBLE]).toString();
750
+ const elVisibleParamValue = this.inheritedParameters[elVisibleParamPath];
751
+ const elVisibleParamValueParsed = elVisibleParamValue && Parameter.parseBoolean(elVisibleParamValue);
752
+ const elIsHiddenViaParams = elVisibleParamValueParsed === false;
753
+ if (paramShowsVariant && elIsHiddenViaParams) continue;
754
+
755
+ // Fixes https://combeenation.youtrack.cloud/issue/CB-7809
756
+ // Apply element material before showing the element to prevent loading of the elements "original" material which
757
+ // is never shown when "overwritten" by elements material param.
758
+ const elMaterialParamPath = DottedPath.create([element.name, Parameter.MATERIAL]).toString();
759
+ const elMaterialParamValue = this.inheritedParameters[elMaterialParamPath];
760
+ if (paramShowsVariant && elMaterialParamValue) {
761
+ await element.commitParameter(Parameter.MATERIAL, elMaterialParamValue);
762
+ }
763
+
764
+ promises.push(element.commitParameter(parameter, value));
765
+ }
766
+ await Promise.all(promises);
767
+ return this;
768
+ }
769
+
770
+ /**
771
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
772
+ */
773
+ protected async commitParameterToViewerLights(parameter: string, value: ParameterValue): Promise<Variant> {
774
+ const promises = [];
775
+ for (const viewerLight of this.viewerLights) {
776
+ promises.push(viewerLight.commitParameter(parameter, value));
777
+ }
778
+ await Promise.all(promises);
779
+ return this;
780
+ }
781
+
782
+ /**
783
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
784
+ */
785
+ protected addParameterObservers(): Variant {
786
+ this._parameterObservers.set(Parameter.VISIBLE, [
787
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
788
+ await variant.commitParameterToElements(Parameter.VISIBLE, newValue);
789
+ await variant.commitParameterToViewerLights(Parameter.VISIBLE, newValue);
790
+ },
791
+ ]);
792
+ this._parameterObservers.set(Parameter.SCALING, [
793
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
794
+ await variant.commitParameterToElements(Parameter.SCALING, newValue);
795
+ await variant.commitParameterToViewerLights(Parameter.SCALING, newValue);
796
+ },
797
+ ]);
798
+ this._parameterObservers.set(Parameter.MATERIAL, [
799
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
800
+ await variant.commitParameterToElements(Parameter.MATERIAL, newValue);
801
+ },
802
+ ]);
803
+ this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
804
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
805
+ await variant.commitParameterToElements(Parameter.MATERIAL_COLOR, newValue);
806
+ },
807
+ ]);
808
+ this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
809
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
810
+ await variant.commitParameterToElements(Parameter.MATERIAL_METALLNESS, newValue);
811
+ },
812
+ ]);
813
+ this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
814
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
815
+ await variant.commitParameterToElements(Parameter.MATERIAL_ROUGHNESS, newValue);
816
+ },
817
+ ]);
818
+ this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
819
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
820
+ await variant.commitParameterToElements(Parameter.HIGHLIGHT_COLOR, newValue);
821
+ },
822
+ ]);
823
+ this._parameterObservers.set(Parameter.HIGHLIGHTED, [
824
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
825
+ await variant.commitParameterToElements(Parameter.HIGHLIGHTED, newValue);
826
+ },
827
+ ]);
828
+ this._parameterObservers.set(Parameter.POSITION, [
829
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
830
+ await variant.commitParameterToElements(Parameter.POSITION, newValue);
831
+ await variant.commitParameterToViewerLights(Parameter.POSITION, newValue);
832
+ },
833
+ ]);
834
+ this._parameterObservers.set(Parameter.ROTATION, [
835
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
836
+ await variant.commitParameterToElements(Parameter.ROTATION, newValue);
837
+ await variant.commitParameterToViewerLights(Parameter.ROTATION, newValue);
838
+ },
839
+ ]);
840
+ this._parameterObservers.set(Parameter.CAST_SHADOW, [
841
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
842
+ await variant.commitParameterToElements(Parameter.CAST_SHADOW, newValue);
843
+ },
844
+ ]);
845
+ this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
846
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
847
+ await variant.commitParameterToElements(Parameter.CAST_SHADOW_FROM_LIGHTS, newValue);
848
+ },
849
+ ]);
850
+ this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
851
+ async (variant: Variant, oldValue: ParameterValue, newValue: ParameterValue) => {
852
+ await variant.commitParameterToElements(Parameter.RECEIVE_SHADOWS, newValue);
853
+ },
854
+ ]);
855
+ return this;
856
+ }
857
+
858
+ /**
859
+ * Creates {@link Element}s and clones nodes into them.
860
+ */
861
+ protected async createElements(): Promise<Variant> {
862
+ this.createElementDefinitionsIfNotExist();
863
+ for (const name in this.structureJson.elements || {}) {
864
+ this.elements.push(await Element.create(this, name));
865
+ }
866
+ // inject node meta to all inherited elements
867
+ // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
868
+ this.inheritedElements.forEach(element => {
869
+ element.nodes.forEach(node => {
870
+ injectNodeMetadata(node, { variant: this, variantParameterizable: element });
871
+ });
872
+ });
873
+ return this;
874
+ }
875
+
876
+ /**
877
+ * Creates {@link ViewerLight}s.
878
+ */
879
+ protected async createViewerLights(): Promise<Variant> {
880
+ for (const name in this.structureJson.lights || {}) {
881
+ this.viewerLights.push(await ViewerLight.create(this, name));
882
+ }
883
+ this.inheritedViewerLights.forEach(viewerLight => {
884
+ injectNodeMetadata(viewerLight.light, { variant: this, variantParameterizable: viewerLight });
885
+ });
886
+ return this;
887
+ }
888
+
889
+ /**
890
+ * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
891
+ */
892
+ protected async bootstrapParameters(parameters?: ParameterBag): Promise<Variant> {
893
+ await this.commitParameters(merge(cloneDeep(this.parameters), parameters));
894
+ concat(this.ancestors, this).forEach(ancestor => (ancestor.parametersInitialized = true));
895
+ return this;
896
+ }
897
+
898
+ /**
899
+ * Ensures there is at least one "Main" {@link Element} for the {@link Variant} with all "root nodes" defined in path.
900
+ */
901
+ protected createElementDefinitionsIfNotExist() {
902
+ if (this._structureJson.elements || this.inheritedNodes.length === 0) {
903
+ return;
904
+ }
905
+ this._structureJson.elements = {
906
+ Main: { paths: { include: this.inheritedNodes.map(node => node.metadata.dottedPath.path) } },
907
+ };
908
+ this.structureJson.elements = cloneDeep(this._structureJson.elements);
909
+ }
910
+ }