@combeenation/3d-viewer 4.0.0-beta4 → 4.0.1-alpha1

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