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

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