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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +112 -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 +125 -125
  7. package/dist/lib-cjs/api/classes/element.js +682 -682
  8. package/dist/lib-cjs/api/classes/elementParameterizable.d.ts +14 -14
  9. package/dist/lib-cjs/api/classes/elementParameterizable.js +134 -134
  10. package/dist/lib-cjs/api/classes/event.d.ts +312 -312
  11. package/dist/lib-cjs/api/classes/event.js +357 -357
  12. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  13. package/dist/lib-cjs/api/classes/eventBroadcaster.js +53 -53
  14. package/dist/lib-cjs/api/classes/parameter.d.ts +165 -165
  15. package/dist/lib-cjs/api/classes/parameter.js +267 -267
  16. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  17. package/dist/lib-cjs/api/classes/parameterObservable.js +126 -126
  18. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  19. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  20. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +38 -38
  21. package/dist/lib-cjs/api/classes/placementAnimation.js +138 -138
  22. package/dist/lib-cjs/api/classes/variant.d.ts +190 -190
  23. package/dist/lib-cjs/api/classes/variant.js +873 -873
  24. package/dist/lib-cjs/api/classes/variantInstance.d.ts +41 -41
  25. package/dist/lib-cjs/api/classes/variantInstance.js +98 -98
  26. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  27. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  28. package/dist/lib-cjs/api/classes/viewer.d.ts +128 -128
  29. package/dist/lib-cjs/api/classes/viewer.js +486 -486
  30. package/dist/lib-cjs/api/classes/viewerLight.d.ts +65 -66
  31. package/dist/lib-cjs/api/classes/viewerLight.js +322 -389
  32. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  33. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  34. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  35. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  36. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  37. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +6 -6
  38. package/dist/lib-cjs/api/internal/sceneSetup.js +227 -227
  39. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  40. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  41. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  42. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  43. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  44. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  45. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  46. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  47. package/dist/lib-cjs/api/util/babylonHelper.d.ts +125 -125
  48. package/dist/lib-cjs/api/util/babylonHelper.js +368 -368
  49. package/dist/lib-cjs/api/util/globalTypes.d.ts +279 -279
  50. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  51. package/dist/lib-cjs/api/util/resourceHelper.d.ts +51 -48
  52. package/dist/lib-cjs/api/util/resourceHelper.js +243 -240
  53. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  54. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  55. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  56. package/dist/lib-cjs/buildinfo.json +3 -3
  57. package/dist/lib-cjs/index.d.ts +46 -46
  58. package/dist/lib-cjs/index.js +82 -82
  59. package/dist/webpack-stats.json +0 -0
  60. package/package.json +83 -83
  61. package/src/api/classes/animationInterface.ts +11 -11
  62. package/src/api/classes/dottedPath.ts +189 -189
  63. package/src/api/classes/element.ts +617 -617
  64. package/src/api/classes/elementParameterizable.ts +78 -78
  65. package/src/api/classes/event.ts +355 -355
  66. package/src/api/classes/eventBroadcaster.ts +54 -54
  67. package/src/api/classes/parameter.ts +277 -277
  68. package/src/api/classes/parameterObservable.ts +121 -121
  69. package/src/api/classes/placementAnimation.ts +133 -133
  70. package/src/api/classes/variant.ts +670 -670
  71. package/src/api/classes/variantInstance.ts +81 -81
  72. package/src/api/classes/viewer.ts +421 -421
  73. package/src/api/internal/debugViewer.ts +81 -81
  74. package/src/api/internal/lensRendering.ts +10 -10
  75. package/src/api/internal/sceneSetup.ts +203 -203
  76. package/src/api/manager/animationManager.ts +116 -116
  77. package/src/api/manager/sceneManager.ts +105 -105
  78. package/src/api/manager/variantInstanceManager.ts +236 -236
  79. package/src/api/store/specStorage.ts +53 -53
  80. package/src/api/util/babylonHelper.ts +392 -392
  81. package/src/api/util/globalTypes.ts +318 -318
  82. package/src/api/util/resourceHelper.ts +187 -184
  83. package/src/buildinfo.json +2 -2
  84. package/src/commonjs.tsconfig.json +13 -13
  85. package/src/declaration.tsconfig.json +10 -10
  86. package/src/dev.ts +46 -46
  87. package/src/es6.tsconfig.json +13 -13
  88. package/src/index.ts +87 -87
  89. package/src/pagesconfig.json +57 -57
  90. package/src/tsconfig.json +43 -43
  91. package/src/tsconfig.types.json +9 -9
  92. package/src/types.d.ts +4 -4
@@ -1,617 +1,617 @@
1
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
2
- import { Material } from '@babylonjs/core/Materials/material';
3
- import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
4
- import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
5
- import { Axis, Space } from '@babylonjs/core/Maths/math.axis';
6
- import { Color3 } from '@babylonjs/core/Maths/math.color';
7
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
8
- import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
9
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
10
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
11
- import { cloneDeep, concat, get, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
12
- import {
13
- activateTransformNode as activate,
14
- addToHighlightLayer,
15
- assertTransformNode,
16
- cloneTransformNode,
17
- cloneTransformNodeMaterial,
18
- deactivateTransformNode as deactivate,
19
- getClientRectFromMesh,
20
- injectTransformNodeMetadata,
21
- mapToDottedNodes,
22
- removeFromHighlightLayer,
23
- setMaterial,
24
- setMaterialColor,
25
- setMaterialMetallness,
26
- setMaterialRoughness,
27
- setMaterialTexture
28
- } from '../util/babylonHelper';
29
- import { createImageFromSvg, createImageFromImgSrc, mergeMaps } from '../util/resourceHelper';
30
- import { DottedPath } from './dottedPath';
31
- import { ElementParameterizable } from './elementParameterizable';
32
- import { Event } from './event';
33
- import { Parameter } from './parameter';
34
- import { Variant } from './variant';
35
-
36
- /**
37
- * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
38
- * {@link Variant}.
39
- *
40
- * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
41
- * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
42
- */
43
- export class Element extends ElementParameterizable {
44
-
45
- protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
46
-
47
- protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
48
-
49
- protected _highlightLayer?: HighlightLayer;
50
-
51
- public readonly nodes: TransformNode[] = [];
52
-
53
- /**
54
- * Constructor.
55
- */
56
- public constructor( public readonly variant: Variant,
57
- public readonly name: string ) {
58
- super();
59
- if ( process.env.NODE_ENV?.toLowerCase().includes('dev')) {
60
- this.assertPathDefinitions();
61
- }
62
- const nodes = this.variant.inheritedNodes.map(
63
- node => cloneTransformNode( node, this.filterNode.bind(this) )
64
- );
65
- this.nodes = nodes.filter( node => !!node ) as TransformNode[];
66
- this._dottedNodes = mapToDottedNodes<TransformNode>(
67
- this.nodes,
68
- node => node instanceof TransformNode
69
- );
70
- this.addParameterObservers();
71
- }
72
-
73
- /**
74
- * The {@link DottedPath} in the built tree of {@link Element}s.
75
- * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
76
- */
77
- get dottedPath(): DottedPath {
78
- return DottedPath.create( this.variant.dottedPath ).addPart( this.name );
79
- }
80
-
81
- /**
82
- * The id representing a {@link DottedPath}.
83
- */
84
- get id(): string {
85
- const dottedPath = DottedPath.create( this.dottedPath );
86
- dottedPath.shiftPart(); // remove root
87
- return dottedPath.path;
88
- }
89
-
90
- /**
91
- * The {@link ElementDefinition} of the {@link Element}.
92
- */
93
- get definition(): ElementDefinition {
94
- const definition = this.variant.structureJson.elements![this.name];
95
- if( isArray( definition ) ) {
96
- return {
97
- paths: {
98
- include: definition
99
- }
100
- } as ElementDefinition;
101
- }
102
- return definition as ElementDefinition;
103
- }
104
-
105
- /**
106
- * The {@link PathDefinitions} of the {@link Element}.
107
- */
108
- get pathDefinitions(): PathDefinitions {
109
- return this.definition.paths;
110
- }
111
-
112
- /**
113
- * The {@link TraceableDefinitions} of the {@link Element}.
114
- */
115
- get traceableDefinitions(): TraceableDefinitions {
116
- return this.definition.traceables || {};
117
- }
118
-
119
- /**
120
- * The {@link PaintableDefinition} of the {@link Element}.
121
- */
122
- get paintableDefinitions(): PaintableDefinitions {
123
- return this.definition.paintables || {};
124
- }
125
-
126
- /**
127
- * The inherited {@link ParameterBag}.
128
- * Merges the {@link Variant}'s parameters and those from the {@link Element}.
129
- */
130
- get inheritedParameters(): ParameterBag {
131
- return merge( {}, this.variant.inheritedParameters, this.parameters );
132
- }
133
-
134
- /**
135
- * @protected
136
- */
137
- set highlightLayer(layer: HighlightLayer | undefined) {
138
- this._highlightLayer = layer;
139
- }
140
-
141
- get highlightLayer(): HighlightLayer | undefined {
142
- return this._highlightLayer;
143
- }
144
-
145
- /**
146
- * Destroys this {@link Element} and dispose all nodes.
147
- */
148
- public destroy(): Element {
149
- this.nodes.forEach( node => {
150
- node.dispose();
151
- } );
152
- return this;
153
- }
154
-
155
- /**
156
- * Gets a node by its {@link DottedPath}.
157
- */
158
- public getNode( dottedPath: DottedPathArgument ): TransformNode {
159
- const _dottedPath = DottedPath.create( dottedPath );
160
- const keys = Array.from( this._dottedNodes.keys() ).map( dp => dp.path );
161
- const values = Array.from( this._dottedNodes.values() );
162
- const node = values[keys.indexOf( _dottedPath.path )];
163
- if( !node ) {
164
- throw new Error( `Node with path "${_dottedPath.path}" does not exist for element "${this.id}".` );
165
- }
166
- return node;
167
- }
168
-
169
- /**
170
- * Gets a mesh by its {@link DottedPath}.
171
- */
172
- public async getMesh( dottedPath: DottedPathArgument ): Promise<Mesh|null> {
173
- const node = await this.getNode( dottedPath );
174
- if( node instanceof Mesh ) {
175
- return node;
176
- }
177
- return null;
178
- }
179
-
180
- /**
181
- * Gets a {@link PaintableDefinition} by its name.
182
- */
183
- public getPaintableDefinition( name: string ): PaintableDefinition {
184
- if( !this.paintableDefinitions || !this.paintableDefinitions[name] ) {
185
- throw new Error( `No paintable "${name}" defined for element "${this.id}".` );
186
- }
187
- return this.paintableDefinitions[name];
188
- }
189
-
190
- /**
191
- * Gets a {@link TraceableDefinition} by its name.
192
- */
193
- public getTraceableDefinition( name: string ): TraceableDefinition {
194
- if( !this.traceableDefinitions || !this.traceableDefinitions[name] ) {
195
- throw new Error( `No traceable "${name}" defined to add observer in element "${this.id}".` );
196
- }
197
- return this.traceableDefinitions[name];
198
- }
199
-
200
- /**
201
- * Gets the paintable Node by its name.
202
- */
203
- public getPaintableNode( name: string ): TransformNode {
204
- return this.getNode( this.getPaintableDefinition( name ).path );
205
- }
206
-
207
- /**
208
- * Gets the traceable Node by its name.
209
- */
210
- public getTraceableNode( name: string ): TransformNode {
211
- return this.getNode( this.getTraceableDefinition( name ).path );
212
- }
213
-
214
- /**
215
- * Places the given {@link ParameterBag} in the {@link Element}'s parameters, replaces all patterns in the
216
- * {@link StructureJson} and broadcasts all {@link ParameterObserver}s.
217
- *
218
- * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
219
- */
220
- public async commitParameters( parameters?: ParameterBag ): Promise<Element> {
221
- if( !parameters ) {
222
- parameters = {};
223
- }
224
- const oldParameters = cloneDeep( this.parameters );
225
- merge( this.parameters, parameters );
226
- // handle parameter observers
227
- let observerPromises: Promise<void | ParameterObserver>[] = [];
228
- for( const parameter in this.parameters ) {
229
- const oldParameterValue = oldParameters[parameter];
230
- const newParameterValue = this.parameters[parameter];
231
- this.variant.assertParameter( this.variant.inheritedParameterDeclaration, parameter, newParameterValue );
232
- if( oldParameterValue === newParameterValue ) {
233
- continue;
234
- }
235
- // parameter changed
236
- const parameterObservers = mergeMaps( this._parameterObservers, this.parameterObservers );
237
- if( parameterObservers.has( parameter ) ) {
238
- const observers = parameterObservers.get( parameter )!;
239
- observerPromises = concat(observerPromises, observers.map( observer => {
240
- const observerResult = observer( this, oldParameterValue, newParameterValue );
241
- return Promise.resolve( observerResult ).then( () => {
242
- this.broadcastEvent( Event.ELEMENT_PARAMETER_COMMITTED,
243
- this, parameter, oldParameterValue, newParameterValue );
244
- } );
245
- } ) );
246
- }
247
- }
248
- await Promise.all( observerPromises );
249
- return this;
250
- }
251
-
252
- /**
253
- * Adds an observer function for camera matrix changes.
254
- * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
255
- */
256
- public addTraceableObserver( traceable: string, observer: CallableFunction, payload?: any ): Element {
257
- if( payload && !(payload instanceof HTMLElement) ) {
258
- throw new Error( `Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".` );
259
- }
260
- if( !this.traceableDefinitions || !this.traceableDefinitions[traceable] ) {
261
- throw new Error( `No traceable "${traceable}" defined to add observer in element "${this.id}".` );
262
- }
263
- const node = this.getTraceableNode( traceable );
264
- if( !(node instanceof AbstractMesh) ) {
265
- throw new Error( `The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".` );
266
- }
267
- this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add(
268
- ( eventData, eventState ) => {
269
- const position = getClientRectFromMesh( node, this.variant.viewer.scene, this.variant.viewer.canvas );
270
- if( payload ) {
271
- payload.style.top = `${position.top}px`;
272
- payload.style.left = `${position.left}px`;
273
- }
274
- observer( node, position );
275
- }
276
- );
277
- return this;
278
- }
279
-
280
- /**
281
- * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
282
- */
283
- public drawPaintable( paintable: string, imageSource: CanvasImageSource ): Element {
284
- // node and material checks and preperation
285
- const node = this.getPaintableNode( paintable );
286
- if( !(node instanceof AbstractMesh) ) {
287
- throw new Error( `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` +
288
- `in element "${this.id}".` );
289
- }
290
- if( node.material && !get( node.metadata, 'dirty.material' ) ) {
291
- cloneTransformNodeMaterial( node );
292
- }
293
- if( !node.material ) {
294
- node.material = new StandardMaterial( `${this.id}.${paintable}.material`, this.variant.viewer.scene );
295
- }
296
- node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
297
- if( !get( node.metadata, 'dirty.material.texture' ) ) {
298
- // inject initial value and mark as dirty
299
- injectTransformNodeMetadata( node, { dirty: { material: { texture: true } } } );
300
- }
301
-
302
- // consider width and height of the paintable
303
- const widthAndHeight = {
304
- width: imageSource.width,
305
- height: imageSource.height
306
- };
307
- const paintableDefinition = this.getPaintableDefinition( paintable );
308
- if( isNumber( paintableDefinition.textureOptions ) ) {
309
- widthAndHeight.width = paintableDefinition.textureOptions;
310
- widthAndHeight.height = paintableDefinition.textureOptions;
311
- } else if( isPlainObject( paintableDefinition.textureOptions ) ) {
312
- widthAndHeight.width = paintableDefinition.textureOptions.width;
313
- widthAndHeight.height = paintableDefinition.textureOptions.height;
314
- }
315
-
316
- // create dynamic texture on which the image can be drawn
317
- const texture = new DynamicTexture(
318
- `${this.id}.${paintable}.texture`,
319
- widthAndHeight,
320
- this.variant.viewer.scene,
321
- false
322
- );
323
-
324
- // draw image on texture
325
- const ctx = texture.getContext();
326
- ctx.drawImage( imageSource, 0, 0);
327
- texture.update( false );
328
-
329
- // finally apply the texture on the desired node material
330
- setMaterialTexture( node, texture, false );
331
-
332
- return this;
333
- }
334
-
335
- /**
336
- * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
337
- */
338
- public async drawPaintableFromSvg( paintable: string, svgSource: string ): Promise<Element> {
339
- const image = await createImageFromSvg( svgSource );
340
- return this.drawPaintable( paintable, image );
341
- }
342
-
343
- /**
344
- * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
345
- */
346
- public async drawPaintableFromImgSrc( paintable: string, imgSource: string ): Promise<Element> {
347
- const image = await createImageFromImgSrc( imgSource );
348
- return this.drawPaintable( paintable, image );
349
- }
350
-
351
- /**
352
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
353
- */
354
- protected addParameterObservers(): Element {
355
- this._parameterObservers.set( Parameter.VISIBLE, [
356
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
357
- let visible;
358
- try {
359
- visible = Parameter.parseBoolean( newValue );
360
- } catch( e ) {
361
- return;
362
- }
363
- if( visible === true ) {
364
- element.nodes.forEach( node => {
365
- injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
366
- activate( node );
367
- } );
368
- } else if( visible === false ) {
369
- element.nodes.forEach( node => {
370
- injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
371
- deactivate( node );
372
- } );
373
- }
374
- }
375
- ] );
376
- this._parameterObservers.set( Parameter.SCALING, [
377
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
378
- // we have to deal just with root nodes here due to relative impacts in a node tree
379
- element.nodes.forEach( node => node.scaling = Parameter.parseScaling( newValue ) );
380
- }
381
- ] );
382
- this._parameterObservers.set( Parameter.MATERIAL, [
383
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
384
- const material = element.variant.getMaterial( newValue.toString() );
385
- element.nodes.forEach( node => {
386
- assertTransformNode(node, (node: TransformNode) => {
387
- if( node instanceof InstancedMesh ) {
388
- throw new Error( `Changing parameter "${Parameter.MATERIAL}" ` +
389
- `of an InstancedMesh is not supported. ` +
390
- `Tried to change node "${node.id}" on element "${element.id}".` );
391
- }
392
- });
393
- setMaterial( node, material );
394
- } );
395
- }
396
- ] );
397
- this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
398
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
399
- const color = Parameter.parseColor( newValue );
400
- element.nodes.forEach( node => {
401
- assertTransformNode(node, (node: TransformNode) => {
402
- if( node instanceof InstancedMesh ) {
403
- throw new Error( `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
404
- `of an InstancedMesh is not supported. ` +
405
- `Tried to change node "${node.id}" on element "${element.id}".` );
406
- }
407
- });
408
- if( !get( node.metadata, 'dirty.material' ) ) {
409
- cloneTransformNodeMaterial( node );
410
- }
411
- if( !get( node.metadata, 'dirty.material.color' ) ) {
412
- // inject initial value and mark as dirty
413
- injectTransformNodeMetadata( node, { dirty: { material: { color: oldValue } } } );
414
- }
415
- setMaterialColor( node, color );
416
- } );
417
- }
418
- ] );
419
- this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
420
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
421
- const metallness = Parameter.parseNumber( newValue );
422
- element.nodes.forEach( node => {
423
- assertTransformNode(node, (node: TransformNode) => {
424
- if( node instanceof InstancedMesh ) {
425
- throw new Error( `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
426
- `of an InstancedMesh is not supported. ` +
427
- `Tried to change node "${node.id}" on element "${element.id}".` );
428
- }
429
- });
430
- if( !get( node.metadata, 'dirty.material' ) ) {
431
- cloneTransformNodeMaterial( node );
432
- }
433
- if( !get( node.metadata, 'dirty.material.metallness' ) ) {
434
- // inject initial value and mark as dirty
435
- injectTransformNodeMetadata( node, { dirty: { material: { metallness: oldValue } } } );
436
- }
437
- setMaterialMetallness( node, metallness );
438
- } );
439
- }
440
- ] );
441
- this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
442
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
443
- const roughness = Parameter.parseNumber( newValue );
444
- element.nodes.forEach( node => {
445
- assertTransformNode(node, (node: TransformNode) => {
446
- if( node instanceof InstancedMesh ) {
447
- throw new Error( `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
448
- `of an InstancedMesh is not supported. ` +
449
- `Tried to change node "${node.id}" on element "${element.id}".` );
450
- }
451
- });
452
- if( !get( node.metadata, 'dirty.material' ) ) {
453
- cloneTransformNodeMaterial( node );
454
- }
455
- if( !get( node.metadata, 'dirty.material.roughness' ) ) {
456
- // inject initial value and mark as dirty
457
- injectTransformNodeMetadata( node, { dirty: { material: { roughness: oldValue } } } );
458
- }
459
- setMaterialRoughness( node, roughness );
460
- } );
461
- }
462
- ] );
463
- this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
464
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
465
- // trigger Parameter.HIGHLIGHTED observers
466
- this._parameterObservers.get( Parameter.HIGHLIGHTED )?.forEach( observer => {
467
- observer( element, !!element.highlighted, !!element.highlighted );
468
- } );
469
- }
470
- ] );
471
- this._parameterObservers.set( Parameter.HIGHLIGHT_ENABLED, [
472
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
473
- let curr;
474
- try {
475
- curr = Parameter.parseBoolean( newValue );
476
- } catch( e ) {
477
- return;
478
- }
479
- switch( curr ) {
480
- case true:
481
- if( element._highlightLayer ) {
482
- break;
483
- }
484
- element.highlightLayer = new HighlightLayer(
485
- DottedPath.create( element.id ).addPart( 'highlight' ).path,
486
- element.variant.viewer.scene
487
- );
488
- break;
489
- case false:
490
- element.highlightLayer?.dispose();
491
- break;
492
- }
493
- }
494
- ] );
495
- this._parameterObservers.set( Parameter.HIGHLIGHTED, [
496
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
497
- if( !element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
498
- return;
499
- }
500
- // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
501
- this._parameterObservers.get( Parameter.HIGHLIGHT_ENABLED )?.forEach( observer => {
502
- observer( element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true );
503
- } );
504
- let highlighted;
505
- try {
506
- highlighted = Parameter.parseBoolean( newValue );
507
- } catch( e ) {
508
- return;
509
- }
510
- // Add/Remove meshes to previously created highlight layers.
511
- if( highlighted === true ) {
512
- element.nodes.forEach( node => {
513
- assertTransformNode(node, (node: TransformNode) => {
514
- if( node instanceof InstancedMesh ) {
515
- throw new Error( `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
516
- `of an InstancedMesh is not supported. ` +
517
- `Tried to change node "${node.id}" on element "${element.id}".` );
518
- }
519
- });
520
- let color = Color3.Green();
521
- if( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] ) {
522
- color = Parameter.parseColor( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] );
523
- }
524
- if ( typeof element._highlightLayer !== "undefined" ) {
525
- addToHighlightLayer( element._highlightLayer, color, node );
526
- }
527
- } );
528
- } else if( highlighted === false ) {
529
- element.nodes.forEach( node => {
530
- if ( typeof element._highlightLayer !== "undefined" ) {
531
- removeFromHighlightLayer( element._highlightLayer, node );
532
- }
533
- } );
534
- }
535
- }
536
- ] );
537
- this._parameterObservers.set( Parameter.POSITION, [
538
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
539
- // we have to deal just with root nodes here due to relative impacts in a node tree
540
- element.nodes.forEach( node => {
541
- // remember absolute position and reset it before translating
542
- if( !get( node.metadata, 'position' ) ) {
543
- node.metadata.position = node.absolutePosition.clone();
544
- }
545
- node.setAbsolutePosition( node.metadata.position );
546
- // move
547
- const distance = Parameter.parseVector( newValue );
548
- node.translate( Axis.X, distance.x, Space.WORLD );
549
- node.translate( Axis.Y, distance.y, Space.WORLD );
550
- node.translate( Axis.Z, distance.z, Space.WORLD );
551
- } );
552
- }
553
- ] );
554
- this._parameterObservers.set( Parameter.ROTATION, [
555
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
556
- // we have to deal just with root nodes here due to relative impacts in a node tree
557
- element.nodes.forEach( node => {
558
- // remember absolute rotation and reset it before translating
559
- if(!get( node.metadata, 'rotation' ) ) {
560
- node.metadata.rotation = node.rotation.clone();
561
- }
562
- node.rotation = node.metadata.rotation;
563
- // rotate
564
- const rotation = Parameter.parseRotation( newValue );
565
- node.rotate( Axis.X, rotation.x, Space.WORLD );
566
- node.rotate( Axis.Y, rotation.y, Space.WORLD );
567
- node.rotate( Axis.Z, rotation.z, Space.WORLD );
568
- } );
569
- }
570
- ] );
571
- return this;
572
- }
573
-
574
- /**
575
- * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
576
- */
577
- protected filterNode( node: TransformNode ): boolean {
578
- let includeTokens: string[] = [];
579
- this.pathDefinitions.include.forEach( dottedPath => {
580
- includeTokens = union( includeTokens, DottedPath.create( dottedPath ).leafTokens );
581
- } );
582
- const shallKeep = ( dp: DottedPath ) => {
583
- const isDirectlyIncluded = !!includeTokens.find( _dp => _dp === dp.path );
584
- const isSubOfIncluded = !!this.pathDefinitions.include.find( _dp => {
585
- return dp.path.startsWith( `${_dp}${DottedPath.DELIMITER}` );
586
- } );
587
- return isDirectlyIncluded || isSubOfIncluded;
588
- };
589
- const shallExclude = ( dp: DottedPath ) => {
590
- if( !this.pathDefinitions.exclude ) {
591
- return false;
592
- }
593
- return !!this.pathDefinitions.exclude.find( _dp => dp.path === _dp );
594
- };
595
- return shallKeep( node.metadata.dottedPath ) && !shallExclude( node.metadata.dottedPath );
596
- }
597
-
598
- /**
599
- * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
600
- * @protected
601
- */
602
- protected assertPathDefinitions() {
603
- const dottedNodes = this.variant.inheritedDottedNodes;
604
- if( dottedNodes.size === 0 ) {
605
- throw new Error( `There are no mapped nodes for element "${this.id}".` );
606
- }
607
- const include = this.pathDefinitions.include.map( path => DottedPath.create( path ).path );
608
- const exclude = this.pathDefinitions.exclude?.map( path => DottedPath.create( path ).path );
609
- const keys = Array.from( dottedNodes.keys() ).map( dottedPath => dottedPath.path );
610
- union<string>( include, exclude ).forEach( path => {
611
- if( keys.indexOf( path ) === -1 ) {
612
- throw new Error( `Node with path "${path}" does not exist for element "${this.id}".` );
613
- }
614
- } );
615
- }
616
-
617
- }
1
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
2
+ import { Material } from '@babylonjs/core/Materials/material';
3
+ import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
4
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
5
+ import { Axis, Space } from '@babylonjs/core/Maths/math.axis';
6
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
7
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
8
+ import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
9
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
10
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
11
+ import { cloneDeep, concat, get, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
12
+ import {
13
+ activateTransformNode as activate,
14
+ addToHighlightLayer,
15
+ assertTransformNode,
16
+ cloneTransformNode,
17
+ cloneTransformNodeMaterial,
18
+ deactivateTransformNode as deactivate,
19
+ getClientRectFromMesh,
20
+ injectTransformNodeMetadata,
21
+ mapToDottedNodes,
22
+ removeFromHighlightLayer,
23
+ setMaterial,
24
+ setMaterialColor,
25
+ setMaterialMetallness,
26
+ setMaterialRoughness,
27
+ setMaterialTexture
28
+ } from '../util/babylonHelper';
29
+ import { createImageFromSvg, createImageFromImgSrc, mergeMaps } from '../util/resourceHelper';
30
+ import { DottedPath } from './dottedPath';
31
+ import { ElementParameterizable } from './elementParameterizable';
32
+ import { Event } from './event';
33
+ import { Parameter } from './parameter';
34
+ import { Variant } from './variant';
35
+
36
+ /**
37
+ * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
38
+ * {@link Variant}.
39
+ *
40
+ * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
41
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
42
+ */
43
+ export class Element extends ElementParameterizable {
44
+
45
+ protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
46
+
47
+ protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
48
+
49
+ protected _highlightLayer?: HighlightLayer;
50
+
51
+ public readonly nodes: TransformNode[] = [];
52
+
53
+ /**
54
+ * Constructor.
55
+ */
56
+ public constructor( public readonly variant: Variant,
57
+ public readonly name: string ) {
58
+ super();
59
+ if ( process.env.NODE_ENV?.toLowerCase().includes('dev')) {
60
+ this.assertPathDefinitions();
61
+ }
62
+ const nodes = this.variant.inheritedNodes.map(
63
+ node => cloneTransformNode( node, this.filterNode.bind(this) )
64
+ );
65
+ this.nodes = nodes.filter( node => !!node ) as TransformNode[];
66
+ this._dottedNodes = mapToDottedNodes<TransformNode>(
67
+ this.nodes,
68
+ node => node instanceof TransformNode
69
+ );
70
+ this.addParameterObservers();
71
+ }
72
+
73
+ /**
74
+ * The {@link DottedPath} in the built tree of {@link Element}s.
75
+ * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
76
+ */
77
+ get dottedPath(): DottedPath {
78
+ return DottedPath.create( this.variant.dottedPath ).addPart( this.name );
79
+ }
80
+
81
+ /**
82
+ * The id representing a {@link DottedPath}.
83
+ */
84
+ get id(): string {
85
+ const dottedPath = DottedPath.create( this.dottedPath );
86
+ dottedPath.shiftPart(); // remove root
87
+ return dottedPath.path;
88
+ }
89
+
90
+ /**
91
+ * The {@link ElementDefinition} of the {@link Element}.
92
+ */
93
+ get definition(): ElementDefinition {
94
+ const definition = this.variant.structureJson.elements![this.name];
95
+ if( isArray( definition ) ) {
96
+ return {
97
+ paths: {
98
+ include: definition
99
+ }
100
+ } as ElementDefinition;
101
+ }
102
+ return definition as ElementDefinition;
103
+ }
104
+
105
+ /**
106
+ * The {@link PathDefinitions} of the {@link Element}.
107
+ */
108
+ get pathDefinitions(): PathDefinitions {
109
+ return this.definition.paths;
110
+ }
111
+
112
+ /**
113
+ * The {@link TraceableDefinitions} of the {@link Element}.
114
+ */
115
+ get traceableDefinitions(): TraceableDefinitions {
116
+ return this.definition.traceables || {};
117
+ }
118
+
119
+ /**
120
+ * The {@link PaintableDefinition} of the {@link Element}.
121
+ */
122
+ get paintableDefinitions(): PaintableDefinitions {
123
+ return this.definition.paintables || {};
124
+ }
125
+
126
+ /**
127
+ * The inherited {@link ParameterBag}.
128
+ * Merges the {@link Variant}'s parameters and those from the {@link Element}.
129
+ */
130
+ get inheritedParameters(): ParameterBag {
131
+ return merge( {}, this.variant.inheritedParameters, this.parameters );
132
+ }
133
+
134
+ /**
135
+ * @protected
136
+ */
137
+ set highlightLayer(layer: HighlightLayer | undefined) {
138
+ this._highlightLayer = layer;
139
+ }
140
+
141
+ get highlightLayer(): HighlightLayer | undefined {
142
+ return this._highlightLayer;
143
+ }
144
+
145
+ /**
146
+ * Destroys this {@link Element} and dispose all nodes.
147
+ */
148
+ public destroy(): Element {
149
+ this.nodes.forEach( node => {
150
+ node.dispose();
151
+ } );
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Gets a node by its {@link DottedPath}.
157
+ */
158
+ public getNode( dottedPath: DottedPathArgument ): TransformNode {
159
+ const _dottedPath = DottedPath.create( dottedPath );
160
+ const keys = Array.from( this._dottedNodes.keys() ).map( dp => dp.path );
161
+ const values = Array.from( this._dottedNodes.values() );
162
+ const node = values[keys.indexOf( _dottedPath.path )];
163
+ if( !node ) {
164
+ throw new Error( `Node with path "${_dottedPath.path}" does not exist for element "${this.id}".` );
165
+ }
166
+ return node;
167
+ }
168
+
169
+ /**
170
+ * Gets a mesh by its {@link DottedPath}.
171
+ */
172
+ public async getMesh( dottedPath: DottedPathArgument ): Promise<Mesh|null> {
173
+ const node = await this.getNode( dottedPath );
174
+ if( node instanceof Mesh ) {
175
+ return node;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /**
181
+ * Gets a {@link PaintableDefinition} by its name.
182
+ */
183
+ public getPaintableDefinition( name: string ): PaintableDefinition {
184
+ if( !this.paintableDefinitions || !this.paintableDefinitions[name] ) {
185
+ throw new Error( `No paintable "${name}" defined for element "${this.id}".` );
186
+ }
187
+ return this.paintableDefinitions[name];
188
+ }
189
+
190
+ /**
191
+ * Gets a {@link TraceableDefinition} by its name.
192
+ */
193
+ public getTraceableDefinition( name: string ): TraceableDefinition {
194
+ if( !this.traceableDefinitions || !this.traceableDefinitions[name] ) {
195
+ throw new Error( `No traceable "${name}" defined to add observer in element "${this.id}".` );
196
+ }
197
+ return this.traceableDefinitions[name];
198
+ }
199
+
200
+ /**
201
+ * Gets the paintable Node by its name.
202
+ */
203
+ public getPaintableNode( name: string ): TransformNode {
204
+ return this.getNode( this.getPaintableDefinition( name ).path );
205
+ }
206
+
207
+ /**
208
+ * Gets the traceable Node by its name.
209
+ */
210
+ public getTraceableNode( name: string ): TransformNode {
211
+ return this.getNode( this.getTraceableDefinition( name ).path );
212
+ }
213
+
214
+ /**
215
+ * Places the given {@link ParameterBag} in the {@link Element}'s parameters, replaces all patterns in the
216
+ * {@link StructureJson} and broadcasts all {@link ParameterObserver}s.
217
+ *
218
+ * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
219
+ */
220
+ public async commitParameters( parameters?: ParameterBag ): Promise<Element> {
221
+ if( !parameters ) {
222
+ parameters = {};
223
+ }
224
+ const oldParameters = cloneDeep( this.parameters );
225
+ merge( this.parameters, parameters );
226
+ // handle parameter observers
227
+ let observerPromises: Promise<void | ParameterObserver>[] = [];
228
+ for( const parameter in this.parameters ) {
229
+ const oldParameterValue = oldParameters[parameter];
230
+ const newParameterValue = this.parameters[parameter];
231
+ this.variant.assertParameter( this.variant.inheritedParameterDeclaration, parameter, newParameterValue );
232
+ if( oldParameterValue === newParameterValue ) {
233
+ continue;
234
+ }
235
+ // parameter changed
236
+ const parameterObservers = mergeMaps( this._parameterObservers, this.parameterObservers );
237
+ if( parameterObservers.has( parameter ) ) {
238
+ const observers = parameterObservers.get( parameter )!;
239
+ observerPromises = concat(observerPromises, observers.map( observer => {
240
+ const observerResult = observer( this, oldParameterValue, newParameterValue );
241
+ return Promise.resolve( observerResult ).then( () => {
242
+ this.broadcastEvent( Event.ELEMENT_PARAMETER_COMMITTED,
243
+ this, parameter, oldParameterValue, newParameterValue );
244
+ } );
245
+ } ) );
246
+ }
247
+ }
248
+ await Promise.all( observerPromises );
249
+ return this;
250
+ }
251
+
252
+ /**
253
+ * Adds an observer function for camera matrix changes.
254
+ * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
255
+ */
256
+ public addTraceableObserver( traceable: string, observer: CallableFunction, payload?: any ): Element {
257
+ if( payload && !(payload instanceof HTMLElement) ) {
258
+ throw new Error( `Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".` );
259
+ }
260
+ if( !this.traceableDefinitions || !this.traceableDefinitions[traceable] ) {
261
+ throw new Error( `No traceable "${traceable}" defined to add observer in element "${this.id}".` );
262
+ }
263
+ const node = this.getTraceableNode( traceable );
264
+ if( !(node instanceof AbstractMesh) ) {
265
+ throw new Error( `The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".` );
266
+ }
267
+ this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add(
268
+ ( eventData, eventState ) => {
269
+ const position = getClientRectFromMesh( node, this.variant.viewer.scene, this.variant.viewer.canvas );
270
+ if( payload ) {
271
+ payload.style.top = `${position.top}px`;
272
+ payload.style.left = `${position.left}px`;
273
+ }
274
+ observer( node, position );
275
+ }
276
+ );
277
+ return this;
278
+ }
279
+
280
+ /**
281
+ * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
282
+ */
283
+ public drawPaintable( paintable: string, imageSource: CanvasImageSource ): Element {
284
+ // node and material checks and preperation
285
+ const node = this.getPaintableNode( paintable );
286
+ if( !(node instanceof AbstractMesh) ) {
287
+ throw new Error( `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` +
288
+ `in element "${this.id}".` );
289
+ }
290
+ if( node.material && !get( node.metadata, 'dirty.material' ) ) {
291
+ cloneTransformNodeMaterial( node );
292
+ }
293
+ if( !node.material ) {
294
+ node.material = new StandardMaterial( `${this.id}.${paintable}.material`, this.variant.viewer.scene );
295
+ }
296
+ node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
297
+ if( !get( node.metadata, 'dirty.material.texture' ) ) {
298
+ // inject initial value and mark as dirty
299
+ injectTransformNodeMetadata( node, { dirty: { material: { texture: true } } } );
300
+ }
301
+
302
+ // consider width and height of the paintable
303
+ const widthAndHeight = {
304
+ width: imageSource.width,
305
+ height: imageSource.height
306
+ };
307
+ const paintableDefinition = this.getPaintableDefinition( paintable );
308
+ if( isNumber( paintableDefinition.textureOptions ) ) {
309
+ widthAndHeight.width = paintableDefinition.textureOptions;
310
+ widthAndHeight.height = paintableDefinition.textureOptions;
311
+ } else if( isPlainObject( paintableDefinition.textureOptions ) ) {
312
+ widthAndHeight.width = paintableDefinition.textureOptions.width;
313
+ widthAndHeight.height = paintableDefinition.textureOptions.height;
314
+ }
315
+
316
+ // create dynamic texture on which the image can be drawn
317
+ const texture = new DynamicTexture(
318
+ `${this.id}.${paintable}.texture`,
319
+ widthAndHeight,
320
+ this.variant.viewer.scene,
321
+ false
322
+ );
323
+
324
+ // draw image on texture
325
+ const ctx = texture.getContext();
326
+ ctx.drawImage( imageSource, 0, 0);
327
+ texture.update( false );
328
+
329
+ // finally apply the texture on the desired node material
330
+ setMaterialTexture( node, texture, false );
331
+
332
+ return this;
333
+ }
334
+
335
+ /**
336
+ * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
337
+ */
338
+ public async drawPaintableFromSvg( paintable: string, svgSource: string ): Promise<Element> {
339
+ const image = await createImageFromSvg( svgSource );
340
+ return this.drawPaintable( paintable, image );
341
+ }
342
+
343
+ /**
344
+ * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
345
+ */
346
+ public async drawPaintableFromImgSrc( paintable: string, imgSource: string ): Promise<Element> {
347
+ const image = await createImageFromImgSrc( imgSource );
348
+ return this.drawPaintable( paintable, image );
349
+ }
350
+
351
+ /**
352
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
353
+ */
354
+ protected addParameterObservers(): Element {
355
+ this._parameterObservers.set( Parameter.VISIBLE, [
356
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
357
+ let visible;
358
+ try {
359
+ visible = Parameter.parseBoolean( newValue );
360
+ } catch( e ) {
361
+ return;
362
+ }
363
+ if( visible === true ) {
364
+ element.nodes.forEach( node => {
365
+ injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
366
+ activate( node );
367
+ } );
368
+ } else if( visible === false ) {
369
+ element.nodes.forEach( node => {
370
+ injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
371
+ deactivate( node );
372
+ } );
373
+ }
374
+ }
375
+ ] );
376
+ this._parameterObservers.set( Parameter.SCALING, [
377
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
378
+ // we have to deal just with root nodes here due to relative impacts in a node tree
379
+ element.nodes.forEach( node => node.scaling = Parameter.parseScaling( newValue ) );
380
+ }
381
+ ] );
382
+ this._parameterObservers.set( Parameter.MATERIAL, [
383
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
384
+ const material = element.variant.getMaterial( newValue.toString() );
385
+ element.nodes.forEach( node => {
386
+ assertTransformNode(node, (node: TransformNode) => {
387
+ if( node instanceof InstancedMesh ) {
388
+ throw new Error( `Changing parameter "${Parameter.MATERIAL}" ` +
389
+ `of an InstancedMesh is not supported. ` +
390
+ `Tried to change node "${node.id}" on element "${element.id}".` );
391
+ }
392
+ });
393
+ setMaterial( node, material );
394
+ } );
395
+ }
396
+ ] );
397
+ this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
398
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
399
+ const color = Parameter.parseColor( newValue );
400
+ element.nodes.forEach( node => {
401
+ assertTransformNode(node, (node: TransformNode) => {
402
+ if( node instanceof InstancedMesh ) {
403
+ throw new Error( `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
404
+ `of an InstancedMesh is not supported. ` +
405
+ `Tried to change node "${node.id}" on element "${element.id}".` );
406
+ }
407
+ });
408
+ if( !get( node.metadata, 'dirty.material' ) ) {
409
+ cloneTransformNodeMaterial( node );
410
+ }
411
+ if( !get( node.metadata, 'dirty.material.color' ) ) {
412
+ // inject initial value and mark as dirty
413
+ injectTransformNodeMetadata( node, { dirty: { material: { color: oldValue } } } );
414
+ }
415
+ setMaterialColor( node, color );
416
+ } );
417
+ }
418
+ ] );
419
+ this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
420
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
421
+ const metallness = Parameter.parseNumber( newValue );
422
+ element.nodes.forEach( node => {
423
+ assertTransformNode(node, (node: TransformNode) => {
424
+ if( node instanceof InstancedMesh ) {
425
+ throw new Error( `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
426
+ `of an InstancedMesh is not supported. ` +
427
+ `Tried to change node "${node.id}" on element "${element.id}".` );
428
+ }
429
+ });
430
+ if( !get( node.metadata, 'dirty.material' ) ) {
431
+ cloneTransformNodeMaterial( node );
432
+ }
433
+ if( !get( node.metadata, 'dirty.material.metallness' ) ) {
434
+ // inject initial value and mark as dirty
435
+ injectTransformNodeMetadata( node, { dirty: { material: { metallness: oldValue } } } );
436
+ }
437
+ setMaterialMetallness( node, metallness );
438
+ } );
439
+ }
440
+ ] );
441
+ this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
442
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
443
+ const roughness = Parameter.parseNumber( newValue );
444
+ element.nodes.forEach( node => {
445
+ assertTransformNode(node, (node: TransformNode) => {
446
+ if( node instanceof InstancedMesh ) {
447
+ throw new Error( `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
448
+ `of an InstancedMesh is not supported. ` +
449
+ `Tried to change node "${node.id}" on element "${element.id}".` );
450
+ }
451
+ });
452
+ if( !get( node.metadata, 'dirty.material' ) ) {
453
+ cloneTransformNodeMaterial( node );
454
+ }
455
+ if( !get( node.metadata, 'dirty.material.roughness' ) ) {
456
+ // inject initial value and mark as dirty
457
+ injectTransformNodeMetadata( node, { dirty: { material: { roughness: oldValue } } } );
458
+ }
459
+ setMaterialRoughness( node, roughness );
460
+ } );
461
+ }
462
+ ] );
463
+ this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
464
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
465
+ // trigger Parameter.HIGHLIGHTED observers
466
+ this._parameterObservers.get( Parameter.HIGHLIGHTED )?.forEach( observer => {
467
+ observer( element, !!element.highlighted, !!element.highlighted );
468
+ } );
469
+ }
470
+ ] );
471
+ this._parameterObservers.set( Parameter.HIGHLIGHT_ENABLED, [
472
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
473
+ let curr;
474
+ try {
475
+ curr = Parameter.parseBoolean( newValue );
476
+ } catch( e ) {
477
+ return;
478
+ }
479
+ switch( curr ) {
480
+ case true:
481
+ if( element._highlightLayer ) {
482
+ break;
483
+ }
484
+ element.highlightLayer = new HighlightLayer(
485
+ DottedPath.create( element.id ).addPart( 'highlight' ).path,
486
+ element.variant.viewer.scene
487
+ );
488
+ break;
489
+ case false:
490
+ element.highlightLayer?.dispose();
491
+ break;
492
+ }
493
+ }
494
+ ] );
495
+ this._parameterObservers.set( Parameter.HIGHLIGHTED, [
496
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
497
+ if( !element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
498
+ return;
499
+ }
500
+ // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
501
+ this._parameterObservers.get( Parameter.HIGHLIGHT_ENABLED )?.forEach( observer => {
502
+ observer( element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true );
503
+ } );
504
+ let highlighted;
505
+ try {
506
+ highlighted = Parameter.parseBoolean( newValue );
507
+ } catch( e ) {
508
+ return;
509
+ }
510
+ // Add/Remove meshes to previously created highlight layers.
511
+ if( highlighted === true ) {
512
+ element.nodes.forEach( node => {
513
+ assertTransformNode(node, (node: TransformNode) => {
514
+ if( node instanceof InstancedMesh ) {
515
+ throw new Error( `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
516
+ `of an InstancedMesh is not supported. ` +
517
+ `Tried to change node "${node.id}" on element "${element.id}".` );
518
+ }
519
+ });
520
+ let color = Color3.Green();
521
+ if( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] ) {
522
+ color = Parameter.parseColor( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] );
523
+ }
524
+ if ( typeof element._highlightLayer !== "undefined" ) {
525
+ addToHighlightLayer( element._highlightLayer, color, node );
526
+ }
527
+ } );
528
+ } else if( highlighted === false ) {
529
+ element.nodes.forEach( node => {
530
+ if ( typeof element._highlightLayer !== "undefined" ) {
531
+ removeFromHighlightLayer( element._highlightLayer, node );
532
+ }
533
+ } );
534
+ }
535
+ }
536
+ ] );
537
+ this._parameterObservers.set( Parameter.POSITION, [
538
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
539
+ // we have to deal just with root nodes here due to relative impacts in a node tree
540
+ element.nodes.forEach( node => {
541
+ // remember absolute position and reset it before translating
542
+ if( !get( node.metadata, 'position' ) ) {
543
+ node.metadata.position = node.absolutePosition.clone();
544
+ }
545
+ node.setAbsolutePosition( node.metadata.position );
546
+ // move
547
+ const distance = Parameter.parseVector( newValue );
548
+ node.translate( Axis.X, distance.x, Space.WORLD );
549
+ node.translate( Axis.Y, distance.y, Space.WORLD );
550
+ node.translate( Axis.Z, distance.z, Space.WORLD );
551
+ } );
552
+ }
553
+ ] );
554
+ this._parameterObservers.set( Parameter.ROTATION, [
555
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
556
+ // we have to deal just with root nodes here due to relative impacts in a node tree
557
+ element.nodes.forEach( node => {
558
+ // remember absolute rotation and reset it before translating
559
+ if(!get( node.metadata, 'rotation' ) ) {
560
+ node.metadata.rotation = node.rotation.clone();
561
+ }
562
+ node.rotation = node.metadata.rotation;
563
+ // rotate
564
+ const rotation = Parameter.parseRotation( newValue );
565
+ node.rotate( Axis.X, rotation.x, Space.WORLD );
566
+ node.rotate( Axis.Y, rotation.y, Space.WORLD );
567
+ node.rotate( Axis.Z, rotation.z, Space.WORLD );
568
+ } );
569
+ }
570
+ ] );
571
+ return this;
572
+ }
573
+
574
+ /**
575
+ * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
576
+ */
577
+ protected filterNode( node: TransformNode ): boolean {
578
+ let includeTokens: string[] = [];
579
+ this.pathDefinitions.include.forEach( dottedPath => {
580
+ includeTokens = union( includeTokens, DottedPath.create( dottedPath ).leafTokens );
581
+ } );
582
+ const shallKeep = ( dp: DottedPath ) => {
583
+ const isDirectlyIncluded = !!includeTokens.find( _dp => _dp === dp.path );
584
+ const isSubOfIncluded = !!this.pathDefinitions.include.find( _dp => {
585
+ return dp.path.startsWith( `${_dp}${DottedPath.DELIMITER}` );
586
+ } );
587
+ return isDirectlyIncluded || isSubOfIncluded;
588
+ };
589
+ const shallExclude = ( dp: DottedPath ) => {
590
+ if( !this.pathDefinitions.exclude ) {
591
+ return false;
592
+ }
593
+ return !!this.pathDefinitions.exclude.find( _dp => dp.path === _dp );
594
+ };
595
+ return shallKeep( node.metadata.dottedPath ) && !shallExclude( node.metadata.dottedPath );
596
+ }
597
+
598
+ /**
599
+ * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
600
+ * @protected
601
+ */
602
+ protected assertPathDefinitions() {
603
+ const dottedNodes = this.variant.inheritedDottedNodes;
604
+ if( dottedNodes.size === 0 ) {
605
+ throw new Error( `There are no mapped nodes for element "${this.id}".` );
606
+ }
607
+ const include = this.pathDefinitions.include.map( path => DottedPath.create( path ).path );
608
+ const exclude = this.pathDefinitions.exclude?.map( path => DottedPath.create( path ).path );
609
+ const keys = Array.from( dottedNodes.keys() ).map( dottedPath => dottedPath.path );
610
+ union<string>( include, exclude ).forEach( path => {
611
+ if( keys.indexOf( path ) === -1 ) {
612
+ throw new Error( `Node with path "${path}" does not exist for element "${this.id}".` );
613
+ }
614
+ } );
615
+ }
616
+
617
+ }