@combeenation/3d-viewer 9.0.1 → 9.0.2-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 +111 -111
  2. package/dist/lib-cjs/api/classes/animationInterface.d.ts +8 -8
  3. package/dist/lib-cjs/api/classes/animationInterface.js +2 -2
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +166 -166
  6. package/dist/lib-cjs/api/classes/element.d.ts +153 -153
  7. package/dist/lib-cjs/api/classes/element.js +667 -667
  8. package/dist/lib-cjs/api/classes/event.d.ts +401 -401
  9. package/dist/lib-cjs/api/classes/event.js +424 -424
  10. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  11. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -49
  12. package/dist/lib-cjs/api/classes/fuzzyMap.d.ts +7 -7
  13. package/dist/lib-cjs/api/classes/fuzzyMap.js +21 -21
  14. package/dist/lib-cjs/api/classes/parameter.d.ts +410 -410
  15. package/dist/lib-cjs/api/classes/parameter.js +642 -642
  16. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  17. package/dist/lib-cjs/api/classes/parameterObservable.js +72 -72
  18. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  19. package/dist/lib-cjs/api/classes/parameterizable.js +102 -102
  20. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +45 -45
  21. package/dist/lib-cjs/api/classes/placementAnimation.js +176 -176
  22. package/dist/lib-cjs/api/classes/variant.d.ts +261 -261
  23. package/dist/lib-cjs/api/classes/variant.js +870 -870
  24. package/dist/lib-cjs/api/classes/variantInstance.d.ts +53 -53
  25. package/dist/lib-cjs/api/classes/variantInstance.js +125 -125
  26. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  27. package/dist/lib-cjs/api/classes/variantParameterizable.js +86 -86
  28. package/dist/lib-cjs/api/classes/viewer.d.ts +213 -213
  29. package/dist/lib-cjs/api/classes/viewer.js +717 -717
  30. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  31. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  32. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  33. package/dist/lib-cjs/api/classes/viewerLight.js +348 -348
  34. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  35. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  36. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  37. package/dist/lib-cjs/api/internal/sceneSetup.js +226 -226
  38. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  39. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  40. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +103 -103
  41. package/dist/lib-cjs/api/manager/gltfExportManager.js +325 -325
  42. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  43. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  44. package/dist/lib-cjs/api/manager/tagManager.d.ts +118 -118
  45. package/dist/lib-cjs/api/manager/tagManager.js +535 -522
  46. package/dist/lib-cjs/api/manager/tagManager.js.map +1 -1
  47. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  48. package/dist/lib-cjs/api/manager/textureLoadManager.js +97 -97
  49. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  50. package/dist/lib-cjs/api/manager/variantInstanceManager.js +290 -290
  51. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  52. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  53. package/dist/lib-cjs/api/util/babylonHelper.d.ts +237 -237
  54. package/dist/lib-cjs/api/util/babylonHelper.js +825 -825
  55. package/dist/lib-cjs/api/util/globalTypes.d.ts +479 -479
  56. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  57. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  58. package/dist/lib-cjs/api/util/resourceHelper.js +214 -211
  59. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  60. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  61. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  62. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  63. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  64. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  65. package/dist/lib-cjs/api/util/structureHelper.js +60 -60
  66. package/dist/lib-cjs/buildinfo.json +3 -3
  67. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  68. package/dist/lib-cjs/index.d.ts +54 -54
  69. package/dist/lib-cjs/index.js +117 -117
  70. package/package.json +82 -82
  71. package/src/api/classes/animationInterface.ts +10 -10
  72. package/src/api/classes/dottedPath.ts +181 -181
  73. package/src/api/classes/element.ts +723 -723
  74. package/src/api/classes/event.ts +457 -457
  75. package/src/api/classes/eventBroadcaster.ts +52 -52
  76. package/src/api/classes/fuzzyMap.ts +21 -21
  77. package/src/api/classes/parameter.ts +686 -686
  78. package/src/api/classes/parameterObservable.ts +73 -73
  79. package/src/api/classes/parameterizable.ts +87 -87
  80. package/src/api/classes/placementAnimation.ts +162 -162
  81. package/src/api/classes/variant.ts +963 -963
  82. package/src/api/classes/variantInstance.ts +123 -123
  83. package/src/api/classes/variantParameterizable.ts +83 -83
  84. package/src/api/classes/viewer.ts +770 -770
  85. package/src/api/classes/viewerError.ts +63 -63
  86. package/src/api/classes/viewerLight.ts +339 -339
  87. package/src/api/internal/debugViewer.ts +90 -90
  88. package/src/api/internal/lensRendering.ts +9 -9
  89. package/src/api/internal/sceneSetup.ts +205 -205
  90. package/src/api/manager/animationManager.ts +143 -143
  91. package/src/api/manager/gltfExportManager.ts +302 -302
  92. package/src/api/manager/sceneManager.ts +134 -134
  93. package/src/api/manager/tagManager.ts +576 -564
  94. package/src/api/manager/textureLoadManager.ts +95 -95
  95. package/src/api/manager/variantInstanceManager.ts +306 -306
  96. package/src/api/store/specStorage.ts +68 -68
  97. package/src/api/util/babylonHelper.ts +913 -913
  98. package/src/api/util/globalTypes.ts +555 -555
  99. package/src/api/util/resourceHelper.ts +201 -198
  100. package/src/api/util/sceneLoaderHelper.ts +170 -170
  101. package/src/api/util/stringHelper.ts +30 -30
  102. package/src/api/util/structureHelper.ts +60 -60
  103. package/src/buildinfo.json +3 -3
  104. package/src/dev.ts +62 -62
  105. package/src/index.ts +103 -103
  106. package/src/types.d.ts +38 -38
@@ -1,302 +1,302 @@
1
- import { Viewer } from '../classes/viewer';
2
- import { injectMetadata } from '../util/babylonHelper';
3
- import { isNodeIncludedInExclusionList } from '../util/structureHelper';
4
- import { Engine } from '@babylonjs/core/Engines/engine';
5
- import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
6
- import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
7
- import { Color3 } from '@babylonjs/core/Maths/math.color';
8
- import { Vector3 } from '@babylonjs/core/Maths/math.vector';
9
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
10
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
11
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
12
- import { SceneSerializer } from '@babylonjs/core/Misc/sceneSerializer';
13
- import { GLTF2Export, IExportOptions } from '@babylonjs/serializers/glTF/2.0';
14
- import { has, merge } from 'lodash-es';
15
-
16
- type MetadataMap = { [key: string]: any };
17
- export class GltfExportManager {
18
- protected static readonly _CLONED_FROM_MAT_METADATA_PROPERTY = 'clonedFrom';
19
- public static readonly NAME_BEFORE_EXPORT_METADATA_PROPERTY = 'nameBeforeExport';
20
-
21
- /**
22
- * Constructor.
23
- */
24
- protected constructor(protected viewer: Viewer) {}
25
-
26
- /**
27
- * Creates an {@link GltfExportManager}.
28
- */
29
- public static async create(viewer: Viewer): Promise<GltfExportManager> {
30
- return new GltfExportManager(viewer);
31
- }
32
-
33
- /**
34
- * Exports selected nodes to a file.
35
- * @param filename optional name of the exported .GLB file.
36
- * @param exportOptions export options to be merged with default options.\
37
- * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
38
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
39
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
40
- */
41
- public async exportGlb(
42
- filename = 'glb-export.glb',
43
- { exchangeRefractionMaterials = true, ...exportOptions }: IExportOptionsExtended = {},
44
- optimizeForAR: boolean = false,
45
- excluded?: ExcludedGeometryList
46
- ): Promise<File | undefined> {
47
- const { scene, sceneCopied } = await this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
48
- const glbData = await GLTF2Export.GLBAsync(scene, 'dummy', this.gltfExportOptions(exportOptions, excluded));
49
- this.exportPostProcess(scene, sceneCopied);
50
-
51
- const resBlob = glbData.glTFFiles['dummy.glb'];
52
- // check if result is valid, according to the typings this could also be a string
53
- if (resBlob instanceof Blob) {
54
- if (!filename.endsWith('.glb')) {
55
- filename += '.glb';
56
- }
57
- return new File([resBlob], filename);
58
- } else {
59
- // result was not a valid blob
60
- return undefined;
61
- }
62
- }
63
-
64
- /**
65
- * Exports selected nodes to GLTF. This may result in more than one file, since textures are exported separately.
66
- * @param filename name of the main (text-based) .GLTF file referring to separate texture files.
67
- * @param exportOptions export options to be merged with default options.\
68
- * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
69
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
70
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
71
- */
72
- public async exportGltfToFile(
73
- filename: string,
74
- { exchangeRefractionMaterials = true, ...exportOptions }: IExportOptionsExtended = {},
75
- optimizeForAR: boolean = false,
76
- excluded?: ExcludedGeometryList
77
- ) {
78
- const { scene, sceneCopied } = await this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
79
- const gltf = await GLTF2Export.GLTFAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
80
- gltf.downloadFiles();
81
- this.exportPostProcess(scene, sceneCopied);
82
- }
83
-
84
- /**
85
- * Exports selected nodes to GLB. This results in one binary file.
86
- * @param filename name of the .GLB file.
87
- * @param exportOptions export options to be merged with default options.\
88
- * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
89
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
90
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
91
- */
92
- public async exportGlbToFile(
93
- filename: string,
94
- { exchangeRefractionMaterials = true, ...exportOptions }: IExportOptionsExtended = {},
95
- optimizeForAR: boolean = false,
96
- excluded?: ExcludedGeometryList
97
- ) {
98
- const { scene, sceneCopied } = await this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
99
- const glb = await GLTF2Export.GLBAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
100
- glb.downloadFiles();
101
- this.exportPostProcess(scene, sceneCopied);
102
- }
103
-
104
- /**
105
- * Gets predefined {@link IExportOptions } merged with given ones.
106
- */
107
- protected gltfExportOptions(mergeWithOptions: IExportOptions = {}, excluded?: ExcludedGeometryList): IExportOptions {
108
- const defaultOptions: IExportOptions = {
109
- shouldExportNode: function (node: any) {
110
- if (!node.isEnabled()) {
111
- return false;
112
- }
113
- if ((node.name as string).startsWith(Viewer.BOUNDING_BOX_NAME)) {
114
- return false;
115
- }
116
- if (excluded && node instanceof TransformNode && isNodeIncludedInExclusionList(node, excluded)) {
117
- return false;
118
- }
119
- return true;
120
- },
121
- };
122
- return merge({}, defaultOptions, mergeWithOptions);
123
- }
124
-
125
- /**
126
- * Stuff to be done before exporting to GLTF
127
- *
128
- * @returns Either the original scene if no adjustments have been made or a copied scene (which can be disposed after
129
- * the export) if adjustments have been made
130
- */
131
- protected async exportPreProcess(
132
- exchangeRefractionMaterials: boolean,
133
- optimizeForAR: boolean
134
- ): Promise<{ scene: Scene; sceneCopied: boolean }> {
135
- if (!exchangeRefractionMaterials && !optimizeForAR) {
136
- // no need to copy the scene if no adjustments have to be made
137
- return { scene: this.viewer.scene, sceneCopied: false };
138
- }
139
-
140
- // copy the scene for the GLB export improvements, so that the original viewer scene remains untouched
141
- const copiedScene = await this.copyViewerScene();
142
-
143
- if (exchangeRefractionMaterials) {
144
- this.exchangeRefractionMaterials(copiedScene);
145
- }
146
-
147
- if (optimizeForAR) {
148
- this.setUniqueMeshNames(copiedScene);
149
- this.bakeTransformations(copiedScene);
150
- }
151
-
152
- return { scene: copiedScene, sceneCopied: true };
153
- }
154
-
155
- /**
156
- * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
157
- * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
158
- */
159
- protected async copyViewerScene(): Promise<Scene> {
160
- // required by the scene serializer
161
- await import(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent');
162
-
163
- // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
164
- // data structures in metadata
165
- // it basically does a `JSON.stringify` on the metadata
166
- // therefore the metadata has to be removed from the nodes before the copy process
167
- const metadataArr = this.extractMetadataOfAllNodes();
168
-
169
- // serialize the scene
170
- const serializedScene = await SceneSerializer.SerializeAsync(this.viewer.scene);
171
-
172
- // set the cropped metadata back to the viewer scene nodes
173
- this.restoreMetadataOfAllNodes(metadataArr);
174
-
175
- // load the scene into an invisible "dummy" canvas
176
- const offscreenCanvas = new OffscreenCanvas(0, 0);
177
- const engine = new Engine(offscreenCanvas);
178
-
179
- SceneLoader.ShowLoadingScreen = false;
180
- const newScene = await SceneLoader.LoadAsync('', 'data:' + JSON.stringify(serializedScene), engine);
181
- // this is required for offscreen canvas, otherwise the scene dispose code throws when trying to remove the cursor
182
- // events
183
- newScene.doNotHandleCursors = true;
184
-
185
- return newScene;
186
- }
187
-
188
- /**
189
- * Stuff to be done after the GLTF export
190
- */
191
- protected exportPostProcess(scene: Scene, disposeScene: boolean) {
192
- if (disposeScene) {
193
- // copied scene for GLB export is not needed anymore, therefore it can be removed
194
- scene.getEngine().dispose();
195
- }
196
- }
197
-
198
- /**
199
- * Remove all node metadata and return them in a map
200
- */
201
- protected extractMetadataOfAllNodes(): MetadataMap {
202
- return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
203
- const metadata = curNode.metadata;
204
- delete curNode.metadata;
205
- return { ...accMetadataObj, [curNode.uniqueId.toString()]: metadata };
206
- }, {});
207
- }
208
-
209
- /**
210
- * Restore node metadata from previously cropped metadata map
211
- */
212
- protected restoreMetadataOfAllNodes(metadataMap: MetadataMap) {
213
- this.viewer.scene.getNodes().forEach(node => {
214
- const metadata = metadataMap[node.uniqueId.toString()];
215
- if (metadata) {
216
- node.metadata = metadata;
217
- }
218
- });
219
- }
220
-
221
- /**
222
- * Materials with refraction set are not exported properly.
223
- * Exchange all such (relevant) materials with a more export-friendly version
224
- */
225
- protected exchangeRefractionMaterials(scene: Scene) {
226
- for (const n of scene.getNodes()) {
227
- if (!(n instanceof AbstractMesh)) continue;
228
- if (!(n.material instanceof PBRMaterial)) continue;
229
- if (!(n.material as PBRMaterial).subSurface.isRefractionEnabled) continue;
230
- if ((n.material as PBRMaterial).transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE) continue;
231
- // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
232
- // PBRMATERIAL_OPAQUE
233
- n.material = this.createRefractionMaterialReplacement(n.material);
234
- }
235
- }
236
-
237
- /**
238
- * Create an export-friendly replacement material for a material using refraction.
239
- * @param mat Material to be replaced
240
- */
241
- protected createRefractionMaterialReplacement(mat: PBRMaterial): PBRMaterial {
242
- // if we're dealing with a clone already, return it instead of cloning
243
- if (this.isMaterialClonedForExport(mat)) return mat;
244
-
245
- // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
246
- const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
247
- clonedMaterial.metadata = { ...mat.metadata, [GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY]: mat.uniqueId }; // create shallow copy of metadata on clone. see https://forum.babylonjs.com/t/the-metadata-of-the-mesh-cloned-by-the-instantiatemodelstoscene-method-is-a-shallow-copy/21563
248
- clonedMaterial.refractionTexture = null;
249
- clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
250
- clonedMaterial.alpha = 0.7;
251
- clonedMaterial.albedoColor = new Color3(0.3, 0.3, 0.3);
252
- clonedMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
253
- clonedMaterial.metallic = 0.65;
254
- clonedMaterial.roughness = 0.15;
255
-
256
- return clonedMaterial;
257
- }
258
-
259
- /**
260
- * Inspect if a material was temporarily cloned for GLB export
261
- * @param mat Material to be inspected
262
- */
263
- protected isMaterialClonedForExport(mat: PBRMaterial): boolean {
264
- return has(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
265
- }
266
-
267
- /**
268
- * Set unique mesh names for GLB export.
269
- * Duplicate names lead to problems in AR on iOS devices.
270
- */
271
- protected setUniqueMeshNames(scene: Scene): void {
272
- const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
273
- allNodes.forEach(currMesh => {
274
- injectMetadata(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
275
- currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
276
- });
277
- }
278
-
279
- /**
280
- * Stores the effect of all mesh transformations in their geometry and reset the transformation afterwards.
281
- * In this way negative scalings which lead to problems in AR on iOS devices can be eliminated.
282
- */
283
- protected bakeTransformations(scene: Scene): void {
284
- scene.meshes.forEach(mesh => {
285
- if (mesh instanceof Mesh && mesh.geometry) {
286
- // geometries can be shared across multiple meshes, first make them unique to avoid side-effects
287
- mesh.makeGeometryUnique();
288
- // this is the core functionality for storing the transformation data in the mesh geometry
289
- mesh.bakeCurrentTransformIntoVertices();
290
- }
291
- });
292
-
293
- // some nodes (mostly transform nodes), are not affected by the baking algorithm since they have no geometry
294
- // => reset their transformation manually
295
- const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
296
- allNodes.forEach(node => {
297
- node.position = new Vector3(0, 0, 0);
298
- node.rotation = new Vector3(0, 0, 0);
299
- node.scaling = new Vector3(1, 1, 1);
300
- });
301
- }
302
- }
1
+ import { Viewer } from '../classes/viewer';
2
+ import { injectMetadata } from '../util/babylonHelper';
3
+ import { isNodeIncludedInExclusionList } from '../util/structureHelper';
4
+ import { Engine } from '@babylonjs/core/Engines/engine';
5
+ import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
6
+ import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
7
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
8
+ import { Vector3 } from '@babylonjs/core/Maths/math.vector';
9
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
10
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
11
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
12
+ import { SceneSerializer } from '@babylonjs/core/Misc/sceneSerializer';
13
+ import { GLTF2Export, IExportOptions } from '@babylonjs/serializers/glTF/2.0';
14
+ import { has, merge } from 'lodash-es';
15
+
16
+ type MetadataMap = { [key: string]: any };
17
+ export class GltfExportManager {
18
+ protected static readonly _CLONED_FROM_MAT_METADATA_PROPERTY = 'clonedFrom';
19
+ public static readonly NAME_BEFORE_EXPORT_METADATA_PROPERTY = 'nameBeforeExport';
20
+
21
+ /**
22
+ * Constructor.
23
+ */
24
+ protected constructor(protected viewer: Viewer) {}
25
+
26
+ /**
27
+ * Creates an {@link GltfExportManager}.
28
+ */
29
+ public static async create(viewer: Viewer): Promise<GltfExportManager> {
30
+ return new GltfExportManager(viewer);
31
+ }
32
+
33
+ /**
34
+ * Exports selected nodes to a file.
35
+ * @param filename optional name of the exported .GLB file.
36
+ * @param exportOptions export options to be merged with default options.\
37
+ * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
38
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
39
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
40
+ */
41
+ public async exportGlb(
42
+ filename = 'glb-export.glb',
43
+ { exchangeRefractionMaterials = true, ...exportOptions }: IExportOptionsExtended = {},
44
+ optimizeForAR: boolean = false,
45
+ excluded?: ExcludedGeometryList
46
+ ): Promise<File | undefined> {
47
+ const { scene, sceneCopied } = await this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
48
+ const glbData = await GLTF2Export.GLBAsync(scene, 'dummy', this.gltfExportOptions(exportOptions, excluded));
49
+ this.exportPostProcess(scene, sceneCopied);
50
+
51
+ const resBlob = glbData.glTFFiles['dummy.glb'];
52
+ // check if result is valid, according to the typings this could also be a string
53
+ if (resBlob instanceof Blob) {
54
+ if (!filename.endsWith('.glb')) {
55
+ filename += '.glb';
56
+ }
57
+ return new File([resBlob], filename);
58
+ } else {
59
+ // result was not a valid blob
60
+ return undefined;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Exports selected nodes to GLTF. This may result in more than one file, since textures are exported separately.
66
+ * @param filename name of the main (text-based) .GLTF file referring to separate texture files.
67
+ * @param exportOptions export options to be merged with default options.\
68
+ * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
69
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
70
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
71
+ */
72
+ public async exportGltfToFile(
73
+ filename: string,
74
+ { exchangeRefractionMaterials = true, ...exportOptions }: IExportOptionsExtended = {},
75
+ optimizeForAR: boolean = false,
76
+ excluded?: ExcludedGeometryList
77
+ ) {
78
+ const { scene, sceneCopied } = await this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
79
+ const gltf = await GLTF2Export.GLTFAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
80
+ gltf.downloadFiles();
81
+ this.exportPostProcess(scene, sceneCopied);
82
+ }
83
+
84
+ /**
85
+ * Exports selected nodes to GLB. This results in one binary file.
86
+ * @param filename name of the .GLB file.
87
+ * @param exportOptions export options to be merged with default options.\
88
+ * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
89
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
90
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
91
+ */
92
+ public async exportGlbToFile(
93
+ filename: string,
94
+ { exchangeRefractionMaterials = true, ...exportOptions }: IExportOptionsExtended = {},
95
+ optimizeForAR: boolean = false,
96
+ excluded?: ExcludedGeometryList
97
+ ) {
98
+ const { scene, sceneCopied } = await this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
99
+ const glb = await GLTF2Export.GLBAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
100
+ glb.downloadFiles();
101
+ this.exportPostProcess(scene, sceneCopied);
102
+ }
103
+
104
+ /**
105
+ * Gets predefined {@link IExportOptions } merged with given ones.
106
+ */
107
+ protected gltfExportOptions(mergeWithOptions: IExportOptions = {}, excluded?: ExcludedGeometryList): IExportOptions {
108
+ const defaultOptions: IExportOptions = {
109
+ shouldExportNode: function (node: any) {
110
+ if (!node.isEnabled()) {
111
+ return false;
112
+ }
113
+ if ((node.name as string).startsWith(Viewer.BOUNDING_BOX_NAME)) {
114
+ return false;
115
+ }
116
+ if (excluded && node instanceof TransformNode && isNodeIncludedInExclusionList(node, excluded)) {
117
+ return false;
118
+ }
119
+ return true;
120
+ },
121
+ };
122
+ return merge({}, defaultOptions, mergeWithOptions);
123
+ }
124
+
125
+ /**
126
+ * Stuff to be done before exporting to GLTF
127
+ *
128
+ * @returns Either the original scene if no adjustments have been made or a copied scene (which can be disposed after
129
+ * the export) if adjustments have been made
130
+ */
131
+ protected async exportPreProcess(
132
+ exchangeRefractionMaterials: boolean,
133
+ optimizeForAR: boolean
134
+ ): Promise<{ scene: Scene; sceneCopied: boolean }> {
135
+ if (!exchangeRefractionMaterials && !optimizeForAR) {
136
+ // no need to copy the scene if no adjustments have to be made
137
+ return { scene: this.viewer.scene, sceneCopied: false };
138
+ }
139
+
140
+ // copy the scene for the GLB export improvements, so that the original viewer scene remains untouched
141
+ const copiedScene = await this.copyViewerScene();
142
+
143
+ if (exchangeRefractionMaterials) {
144
+ this.exchangeRefractionMaterials(copiedScene);
145
+ }
146
+
147
+ if (optimizeForAR) {
148
+ this.setUniqueMeshNames(copiedScene);
149
+ this.bakeTransformations(copiedScene);
150
+ }
151
+
152
+ return { scene: copiedScene, sceneCopied: true };
153
+ }
154
+
155
+ /**
156
+ * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
157
+ * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
158
+ */
159
+ protected async copyViewerScene(): Promise<Scene> {
160
+ // required by the scene serializer
161
+ await import(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent');
162
+
163
+ // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
164
+ // data structures in metadata
165
+ // it basically does a `JSON.stringify` on the metadata
166
+ // therefore the metadata has to be removed from the nodes before the copy process
167
+ const metadataArr = this.extractMetadataOfAllNodes();
168
+
169
+ // serialize the scene
170
+ const serializedScene = await SceneSerializer.SerializeAsync(this.viewer.scene);
171
+
172
+ // set the cropped metadata back to the viewer scene nodes
173
+ this.restoreMetadataOfAllNodes(metadataArr);
174
+
175
+ // load the scene into an invisible "dummy" canvas
176
+ const offscreenCanvas = new OffscreenCanvas(0, 0);
177
+ const engine = new Engine(offscreenCanvas);
178
+
179
+ SceneLoader.ShowLoadingScreen = false;
180
+ const newScene = await SceneLoader.LoadAsync('', 'data:' + JSON.stringify(serializedScene), engine);
181
+ // this is required for offscreen canvas, otherwise the scene dispose code throws when trying to remove the cursor
182
+ // events
183
+ newScene.doNotHandleCursors = true;
184
+
185
+ return newScene;
186
+ }
187
+
188
+ /**
189
+ * Stuff to be done after the GLTF export
190
+ */
191
+ protected exportPostProcess(scene: Scene, disposeScene: boolean) {
192
+ if (disposeScene) {
193
+ // copied scene for GLB export is not needed anymore, therefore it can be removed
194
+ scene.getEngine().dispose();
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Remove all node metadata and return them in a map
200
+ */
201
+ protected extractMetadataOfAllNodes(): MetadataMap {
202
+ return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
203
+ const metadata = curNode.metadata;
204
+ delete curNode.metadata;
205
+ return { ...accMetadataObj, [curNode.uniqueId.toString()]: metadata };
206
+ }, {});
207
+ }
208
+
209
+ /**
210
+ * Restore node metadata from previously cropped metadata map
211
+ */
212
+ protected restoreMetadataOfAllNodes(metadataMap: MetadataMap) {
213
+ this.viewer.scene.getNodes().forEach(node => {
214
+ const metadata = metadataMap[node.uniqueId.toString()];
215
+ if (metadata) {
216
+ node.metadata = metadata;
217
+ }
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Materials with refraction set are not exported properly.
223
+ * Exchange all such (relevant) materials with a more export-friendly version
224
+ */
225
+ protected exchangeRefractionMaterials(scene: Scene) {
226
+ for (const n of scene.getNodes()) {
227
+ if (!(n instanceof AbstractMesh)) continue;
228
+ if (!(n.material instanceof PBRMaterial)) continue;
229
+ if (!(n.material as PBRMaterial).subSurface.isRefractionEnabled) continue;
230
+ if ((n.material as PBRMaterial).transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE) continue;
231
+ // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
232
+ // PBRMATERIAL_OPAQUE
233
+ n.material = this.createRefractionMaterialReplacement(n.material);
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Create an export-friendly replacement material for a material using refraction.
239
+ * @param mat Material to be replaced
240
+ */
241
+ protected createRefractionMaterialReplacement(mat: PBRMaterial): PBRMaterial {
242
+ // if we're dealing with a clone already, return it instead of cloning
243
+ if (this.isMaterialClonedForExport(mat)) return mat;
244
+
245
+ // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
246
+ const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
247
+ clonedMaterial.metadata = { ...mat.metadata, [GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY]: mat.uniqueId }; // create shallow copy of metadata on clone. see https://forum.babylonjs.com/t/the-metadata-of-the-mesh-cloned-by-the-instantiatemodelstoscene-method-is-a-shallow-copy/21563
248
+ clonedMaterial.refractionTexture = null;
249
+ clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
250
+ clonedMaterial.alpha = 0.7;
251
+ clonedMaterial.albedoColor = new Color3(0.3, 0.3, 0.3);
252
+ clonedMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
253
+ clonedMaterial.metallic = 0.65;
254
+ clonedMaterial.roughness = 0.15;
255
+
256
+ return clonedMaterial;
257
+ }
258
+
259
+ /**
260
+ * Inspect if a material was temporarily cloned for GLB export
261
+ * @param mat Material to be inspected
262
+ */
263
+ protected isMaterialClonedForExport(mat: PBRMaterial): boolean {
264
+ return has(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
265
+ }
266
+
267
+ /**
268
+ * Set unique mesh names for GLB export.
269
+ * Duplicate names lead to problems in AR on iOS devices.
270
+ */
271
+ protected setUniqueMeshNames(scene: Scene): void {
272
+ const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
273
+ allNodes.forEach(currMesh => {
274
+ injectMetadata(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
275
+ currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
276
+ });
277
+ }
278
+
279
+ /**
280
+ * Stores the effect of all mesh transformations in their geometry and reset the transformation afterwards.
281
+ * In this way negative scalings which lead to problems in AR on iOS devices can be eliminated.
282
+ */
283
+ protected bakeTransformations(scene: Scene): void {
284
+ scene.meshes.forEach(mesh => {
285
+ if (mesh instanceof Mesh && mesh.geometry) {
286
+ // geometries can be shared across multiple meshes, first make them unique to avoid side-effects
287
+ mesh.makeGeometryUnique();
288
+ // this is the core functionality for storing the transformation data in the mesh geometry
289
+ mesh.bakeCurrentTransformIntoVertices();
290
+ }
291
+ });
292
+
293
+ // some nodes (mostly transform nodes), are not affected by the baking algorithm since they have no geometry
294
+ // => reset their transformation manually
295
+ const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
296
+ allNodes.forEach(node => {
297
+ node.position = new Vector3(0, 0, 0);
298
+ node.rotation = new Vector3(0, 0, 0);
299
+ node.scaling = new Vector3(1, 1, 1);
300
+ });
301
+ }
302
+ }