@combeenation/3d-viewer 4.0.0-alpha9 → 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 (105) hide show
  1. package/README.md +112 -111
  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 -130
  7. package/dist/lib-cjs/api/classes/element.js +682 -739
  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 +312 -326
  12. package/dist/lib-cjs/api/classes/event.js +357 -371
  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 +165 -259
  17. package/dist/lib-cjs/api/classes/parameter.js +267 -387
  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 +126 -101
  21. package/dist/lib-cjs/api/classes/parameterObservable.js.map +1 -1
  22. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  23. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  24. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +38 -38
  25. package/dist/lib-cjs/api/classes/placementAnimation.js +138 -138
  26. package/dist/lib-cjs/api/classes/variant.d.ts +190 -224
  27. package/dist/lib-cjs/api/classes/variant.js +873 -1137
  28. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  29. package/dist/lib-cjs/api/classes/variantInstance.d.ts +41 -45
  30. package/dist/lib-cjs/api/classes/variantInstance.js +98 -108
  31. package/dist/lib-cjs/api/classes/variantInstance.js.map +1 -1
  32. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  33. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  34. package/dist/lib-cjs/api/classes/viewer.d.ts +128 -131
  35. package/dist/lib-cjs/api/classes/viewer.js +486 -538
  36. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  37. package/dist/lib-cjs/api/classes/viewerLight.d.ts +65 -66
  38. package/dist/lib-cjs/api/classes/viewerLight.js +322 -389
  39. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  40. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  41. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  42. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  43. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  44. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +6 -10
  45. package/dist/lib-cjs/api/internal/sceneSetup.js +227 -231
  46. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  47. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  48. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  49. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  50. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  51. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  52. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  53. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  54. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  55. package/dist/lib-cjs/api/util/babylonHelper.d.ts +125 -175
  56. package/dist/lib-cjs/api/util/babylonHelper.js +368 -520
  57. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  58. package/dist/lib-cjs/api/util/globalTypes.d.ts +279 -321
  59. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  60. package/dist/lib-cjs/api/util/resourceHelper.d.ts +51 -26
  61. package/dist/lib-cjs/api/util/resourceHelper.js +243 -237
  62. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  63. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  64. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  65. package/dist/lib-cjs/buildinfo.json +3 -3
  66. package/dist/lib-cjs/index.d.ts +46 -48
  67. package/dist/lib-cjs/index.js +82 -86
  68. package/dist/lib-cjs/index.js.map +1 -1
  69. package/dist/webpack-stats.json +0 -0
  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 +617 -635
  74. package/src/api/classes/{parameterizable.ts → elementParameterizable.ts} +78 -89
  75. package/src/api/classes/event.ts +355 -370
  76. package/src/api/classes/eventBroadcaster.ts +54 -54
  77. package/src/api/classes/parameter.ts +277 -408
  78. package/src/api/classes/parameterObservable.ts +121 -99
  79. package/src/api/classes/placementAnimation.ts +133 -133
  80. package/src/api/classes/variant.ts +670 -806
  81. package/src/api/classes/variantInstance.ts +81 -88
  82. package/src/api/classes/viewer.ts +421 -473
  83. package/src/api/internal/debugViewer.ts +81 -81
  84. package/src/api/internal/lensRendering.ts +10 -10
  85. package/src/api/internal/sceneSetup.ts +204 -194
  86. package/src/api/manager/animationManager.ts +116 -116
  87. package/src/api/manager/sceneManager.ts +105 -105
  88. package/src/api/manager/variantInstanceManager.ts +236 -236
  89. package/src/api/store/specStorage.ts +53 -53
  90. package/src/api/util/babylonHelper.ts +392 -553
  91. package/src/api/util/globalTypes.ts +318 -369
  92. package/src/api/util/resourceHelper.ts +187 -157
  93. package/src/buildinfo.json +2 -2
  94. package/src/commonjs.tsconfig.json +13 -13
  95. package/src/declaration.tsconfig.json +10 -10
  96. package/src/dev.ts +46 -44
  97. package/src/es6.tsconfig.json +13 -13
  98. package/src/index.ts +87 -91
  99. package/src/pagesconfig.json +57 -52
  100. package/src/tsconfig.json +43 -43
  101. package/src/tsconfig.types.json +9 -9
  102. package/src/types.d.ts +4 -4
  103. package/src/api/classes/variantParameterizable.ts +0 -73
  104. package/src/api/classes/viewerLight.ts +0 -330
  105. package/src/api/util/stringHelper.ts +0 -26
@@ -1,635 +1,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 { createImageBitmapFromImgSrc, createImageBitmapFromSvg } 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
- const paintableDefinition = this.getPaintableDefinition( paintable );
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
- const widthAndHeight = {
282
- width: imageSource.width,
283
- height: imageSource.height
284
- };
285
- if( isNumber( paintableDefinition.textureOptions ) ) {
286
- widthAndHeight.width = paintableDefinition.textureOptions;
287
- widthAndHeight.height = paintableDefinition.textureOptions;
288
- } else if( isPlainObject( paintableDefinition.textureOptions ) ) {
289
- widthAndHeight.width = paintableDefinition.textureOptions.width;
290
- widthAndHeight.height = paintableDefinition.textureOptions.height;
291
- }
292
- const texture = new DynamicTexture(
293
- `${this.id}.${paintable}.texture`,
294
- widthAndHeight,
295
- this.variant.viewer.scene,
296
- false
297
- );
298
- setMaterialTexture( node, texture, false );
299
- const ctx = texture.getContext();
300
- // flip texture context horizontal with translate and scale
301
- ctx.drawImage( imageSource, 0, 0);
302
- texture.update( false );
303
- return this;
304
- }
305
-
306
- /**
307
- * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
308
- */
309
- public async drawPaintableFromSvg( paintable: string, svgSource: string ): Promise<Element> {
310
- const source = await createImageBitmapFromSvg( svgSource );
311
- return this.drawPaintable( paintable, source );
312
- }
313
-
314
- /**
315
- * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
316
- */
317
- public async drawPaintableFromImgSrc( paintable: string, imgSource: string ): Promise<Element> {
318
- const source = await createImageBitmapFromImgSrc( imgSource );
319
- return this.drawPaintable( paintable, source );
320
- }
321
-
322
- /**
323
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
324
- */
325
- protected addParameterObservers(): Element {
326
- this._parameterObservers.set( Parameter.VISIBLE, [
327
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
328
- let visible;
329
- try {
330
- visible = Parameter.parseBoolean( newValue );
331
- } catch( e ) {
332
- return;
333
- }
334
- if( visible === true ) {
335
- element.nodes.forEach( node => {
336
- injectNodeMetadata( node, { visibility: node.isEnabled() } );
337
- activate( node );
338
- } );
339
- } else if( visible === false ) {
340
- element.nodes.forEach( node => {
341
- injectNodeMetadata( node, { visibility: node.isEnabled() } );
342
- deactivate( node );
343
- } );
344
- }
345
- }
346
- ] );
347
- this._parameterObservers.set( Parameter.SCALING, [
348
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
349
- // we have to deal just with root nodes here due to relative impacts in a node tree
350
- element.nodes.forEach( node => node.scaling = Parameter.parseScaling( newValue ) );
351
- }
352
- ] );
353
- this._parameterObservers.set( Parameter.MATERIAL, [
354
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
355
- const material = element.variant.getMaterial( newValue.toString() );
356
- element.nodes.forEach( node => {
357
- assertTransformNode(node, (node: AbstractMesh) => {
358
- if( node instanceof InstancedMesh ) {
359
- throw new Error( `Changing parameter "${Parameter.MATERIAL}" ` +
360
- `of an InstancedMesh is not supported. ` +
361
- `Tried to change node "${node.id}" on element "${element.id}".` );
362
- }
363
- });
364
- setMaterial( node, material );
365
- } );
366
- }
367
- ] );
368
- this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
369
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
370
- const color = Parameter.parseColor( newValue );
371
- element.nodes.forEach( node => {
372
- assertTransformNode(node, (node: AbstractMesh) => {
373
- if( node instanceof InstancedMesh ) {
374
- throw new Error( `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
375
- `of an InstancedMesh is not supported. ` +
376
- `Tried to change node "${node.id}" on element "${element.id}".` );
377
- }
378
- });
379
- if( !has( node.metadata, 'dirty.material' ) ) {
380
- cloneTransformNodeMaterial( node );
381
- }
382
- if( !has( node.metadata, 'dirty.material.color' ) ) {
383
- // inject initial value and mark as dirty
384
- injectNodeMetadata( node, { dirty: { material: { color: oldValue } } } );
385
- }
386
- setMaterialColor( node, color );
387
- } );
388
- }
389
- ] );
390
- this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
391
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
392
- const metallness = Parameter.parseNumber( newValue );
393
- element.nodes.forEach( node => {
394
- assertTransformNode(node, (node: AbstractMesh) => {
395
- if( node instanceof InstancedMesh ) {
396
- throw new Error( `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
397
- `of an InstancedMesh is not supported. ` +
398
- `Tried to change node "${node.id}" on element "${element.id}".` );
399
- }
400
- });
401
- if( !has( node.metadata, 'dirty.material' ) ) {
402
- cloneTransformNodeMaterial( node );
403
- }
404
- if( !has( node.metadata, 'dirty.material.metallness' ) ) {
405
- // inject initial value and mark as dirty
406
- injectNodeMetadata( node, { dirty: { material: { metallness: oldValue } } } );
407
- }
408
- setMaterialMetallness( node, metallness );
409
- } );
410
- }
411
- ] );
412
- this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
413
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
414
- const roughness = Parameter.parseNumber( newValue );
415
- element.nodes.forEach( node => {
416
- assertTransformNode(node, (node: AbstractMesh) => {
417
- if( node instanceof InstancedMesh ) {
418
- throw new Error( `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
419
- `of an InstancedMesh is not supported. ` +
420
- `Tried to change node "${node.id}" on element "${element.id}".` );
421
- }
422
- });
423
- if( !has( node.metadata, 'dirty.material' ) ) {
424
- cloneTransformNodeMaterial( node );
425
- }
426
- if( !has( node.metadata, 'dirty.material.roughness' ) ) {
427
- // inject initial value and mark as dirty
428
- injectNodeMetadata( node, { dirty: { material: { roughness: oldValue } } } );
429
- }
430
- setMaterialRoughness( node, roughness );
431
- } );
432
- }
433
- ] );
434
- this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
435
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
436
- // trigger Parameter.HIGHLIGHTED observers
437
- this._parameterObservers.get( Parameter.HIGHLIGHTED )?.forEach( observer => {
438
- observer( element, !!element.highlighted, !!element.highlighted );
439
- } );
440
- }
441
- ] );
442
- this._parameterObservers.set( Parameter.HIGHLIGHT_ENABLED, [
443
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
444
- let curr;
445
- try {
446
- curr = Parameter.parseBoolean( newValue );
447
- } catch( e ) {
448
- return;
449
- }
450
- switch( curr ) {
451
- case true:
452
- if( element._highlightLayer ) {
453
- break;
454
- }
455
- element.highlightLayer = new HighlightLayer(
456
- DottedPath.create( element.id ).addPart( 'highlight' ).path,
457
- element.variant.viewer.scene
458
- );
459
- break;
460
- case false:
461
- element.highlightLayer?.dispose();
462
- break;
463
- }
464
- }
465
- ] );
466
- this._parameterObservers.set( Parameter.HIGHLIGHTED, [
467
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
468
- if( !element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
469
- return;
470
- }
471
- // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
472
- this._parameterObservers.get( Parameter.HIGHLIGHT_ENABLED )?.forEach( observer => {
473
- observer( element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true );
474
- } );
475
- let highlighted;
476
- try {
477
- highlighted = Parameter.parseBoolean( newValue );
478
- } catch( e ) {
479
- return;
480
- }
481
- // Add/Remove meshes to previously created highlight layers.
482
- if( highlighted === true ) {
483
- element.nodes.forEach( node => {
484
- assertTransformNode(node, (node: AbstractMesh) => {
485
- if( node instanceof InstancedMesh ) {
486
- throw new Error( `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
487
- `of an InstancedMesh is not supported. ` +
488
- `Tried to change node "${node.id}" on element "${element.id}".` );
489
- }
490
- });
491
- let color = Color3.Green();
492
- if( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] ) {
493
- color = Parameter.parseColor( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] );
494
- }
495
- if ( typeof element._highlightLayer !== "undefined" ) {
496
- addToHighlightLayer( element._highlightLayer, color, node );
497
- }
498
- } );
499
- } else if( highlighted === false ) {
500
- element.nodes.forEach( node => {
501
- if ( typeof element._highlightLayer !== "undefined" ) {
502
- removeFromHighlightLayer( element._highlightLayer, node );
503
- }
504
- } );
505
- }
506
- }
507
- ] );
508
- this._parameterObservers.set( Parameter.POSITION, [
509
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
510
- // we have to deal just with root nodes here due to relative impacts in a node tree
511
- element.nodes.forEach( node => moveTransformNode( node, Parameter.parseVector( newValue ) ) );
512
- }
513
- ] );
514
- this._parameterObservers.set( Parameter.ROTATION, [
515
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
516
- // The current implementation (rotating around coordinates 0,0,0) implicitly mutates the position of a node.
517
- // Since a user expects the rotation after the positioning, we have to manually fire the position observers.
518
- // Without calling these observers, the pivot and the position of a node is initially the same before rotating,
519
- // so there is no rotation happening at all.
520
- if( Parameter.POSITION in element.inheritedParameters ) {
521
- await element.commitParameter( Parameter.POSITION, element.inheritedParameters[Parameter.POSITION] );
522
- }
523
- // we have to deal just with root nodes here due to relative impacts in a node tree
524
- element.nodes.forEach( node => rotateTransformNode( node, Parameter.parseRotation( newValue ) ) );
525
- }
526
- ] );
527
- this._parameterObservers.set( Parameter.CAST_SHADOW, [
528
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
529
- let castShadow;
530
- try {
531
- castShadow = Parameter.parseBoolean( newValue );
532
- } catch( e ) {
533
- return;
534
- }
535
- let lightCsl = element.inheritedParameters[Parameter.CAST_SHADOW_FROM_LIGHTS];
536
- if( ! lightCsl ) {
537
- lightCsl = element.variant.inheritedViewerLights.map( l => l.name ).join( ',' );
538
- }
539
- if( castShadow === true ) {
540
- await this.castShadowValueHandler( lightCsl, addToShadowGenerator );
541
- }
542
- if( castShadow === false ) {
543
- await this.castShadowValueHandler( lightCsl, removeFromShadowGenerator );
544
- }
545
- }
546
- ] );
547
- this._parameterObservers.set( Parameter.CAST_SHADOW_FROM_LIGHTS, [
548
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
549
- // TODO: Possible performance issue in combination with CAST_SHADOW, since both observers are initially called
550
- // when CAST_SHADOW and CAST_SHADOW_FROM_LIGHTS are defined in the spec.
551
- const lightCsl = element.variant.inheritedViewerLights.map( l => l.name ).join( ',' );
552
- // cleanup all shadow generators
553
- await this.castShadowValueHandler( lightCsl, removeFromShadowGenerator );
554
- if( element.castShadow === true ) {
555
- // if newValue is undefined or '' then set newValue to lightCsl (use all lights)
556
- if( !newValue ) {
557
- newValue = lightCsl;
558
- }
559
- await this.castShadowValueHandler( newValue, addToShadowGenerator );
560
- }
561
- }
562
- ] );
563
- this._parameterObservers.set( Parameter.RECEIVE_SHADOWS, [
564
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
565
- element.nodes.forEach( node => setReceiveShadows( node, Parameter.parseBoolean( newValue ) ) );
566
- }
567
- ] );
568
- return this;
569
- }
570
-
571
- /**
572
- * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
573
- */
574
- protected filterNode( node: TransformNode ): boolean {
575
- let includeTokens: string[] = [];
576
- this.pathDefinitions.include.forEach( dottedPath => {
577
- includeTokens = union( includeTokens, DottedPath.create( dottedPath ).leafTokens );
578
- } );
579
- const shallKeep = ( dp: DottedPath ) => {
580
- const isDirectlyIncluded = !!includeTokens.find( _dp => _dp === dp.path );
581
- const isSubOfIncluded = !!this.pathDefinitions.include.find( _dp => {
582
- return dp.path.startsWith( `${_dp}${DottedPath.DELIMITER}` );
583
- } );
584
- return isDirectlyIncluded || isSubOfIncluded;
585
- };
586
- const shallExclude = ( dp: DottedPath ) => {
587
- if( !this.pathDefinitions.exclude ) {
588
- return false;
589
- }
590
- return !!this.pathDefinitions.exclude.find( _dp => dp.path === _dp );
591
- };
592
- return shallKeep( node.metadata.dottedPath ) && !shallExclude( node.metadata.dottedPath );
593
- }
594
-
595
- /**
596
- * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
597
- * @protected
598
- */
599
- protected assertPathDefinitions() {
600
- const dottedNodes = this.variant.inheritedDottedNodes;
601
- if( dottedNodes.size === 0 ) {
602
- throw new Error( `There are no mapped nodes for element "${this.id}".` );
603
- }
604
- const include = this.pathDefinitions.include.map( path => DottedPath.create( path ).path );
605
- const exclude = this.pathDefinitions.exclude?.map( path => DottedPath.create( path ).path );
606
- const keys = Array.from( dottedNodes.keys() ).map( dottedPath => dottedPath.path );
607
- union<string>( include, exclude ).forEach( path => {
608
- if( keys.indexOf( path ) === -1 ) {
609
- throw new Error( `Node with path "${path}" does not exist for element "${this.id}".` );
610
- }
611
- } );
612
- }
613
-
614
- /**
615
- * Handles callback for given light parameter.
616
- */
617
- private async castShadowValueHandler( lightCsl: ParameterValue, mutator: CallableFunction ) {
618
- let lights: Light[] = [];
619
- for( const lightName of Parameter.parseCommaSeparatedList( lightCsl ) ) {
620
- const viewerLight = await this.variant.getViewerLight( lightName );
621
- if( viewerLight ) {
622
- lights.push( viewerLight.light );
623
- }
624
- }
625
- const shadowGenerators = lights
626
- .map( light => light?.getShadowGenerator() as ShadowGenerator )
627
- .filter( Boolean );
628
- shadowGenerators.forEach( generator => {
629
- this.nodes.forEach( node => {
630
- mutator( generator, node );
631
- } );
632
- } );
633
- }
634
-
635
- }
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
+ }